|
| 1 | +""" |
| 2 | +About |
| 3 | +===== |
| 4 | +
|
| 5 | +Example program to demonstrate how to connect to CrateDB using its SQLAlchemy |
| 6 | +dialect, and exercise a few basic examples using the low-level table API, this |
| 7 | +time in asynchronous mode. |
| 8 | +
|
| 9 | +Both the PostgreSQL drivers based on `psycopg` and `asyncpg` are exercised. |
| 10 | +The corresponding SQLAlchemy dialect identifiers are:: |
| 11 | +
|
| 12 | + # PostgreSQL protocol on port 5432, using `psycopg` |
| 13 | + crate+psycopg://crate@localhost:5432/doc |
| 14 | +
|
| 15 | + # PostgreSQL protocol on port 5432, using `asyncpg` |
| 16 | + crate+asyncpg://crate@localhost:5432/doc |
| 17 | +
|
| 18 | +Synopsis |
| 19 | +======== |
| 20 | +:: |
| 21 | +
|
| 22 | + # Run CrateDB |
| 23 | + docker run --rm -it --publish=4200:4200 --publish=5432:5432 crate |
| 24 | +
|
| 25 | + # Use PostgreSQL protocol, with asynchronous support of `psycopg` |
| 26 | + python examples/async_table.py psycopg |
| 27 | +
|
| 28 | + # Use PostgreSQL protocol, with `asyncpg` |
| 29 | + python examples/async_table.py asyncpg |
| 30 | +
|
| 31 | + # Use with both variants |
| 32 | + python examples/async_table.py psycopg asyncpg |
| 33 | +
|
| 34 | +""" |
| 35 | +import asyncio |
| 36 | +import sys |
| 37 | +import typing as t |
| 38 | +from functools import lru_cache |
| 39 | + |
| 40 | +import sqlalchemy as sa |
| 41 | +from sqlalchemy.ext.asyncio import create_async_engine |
| 42 | + |
| 43 | + |
| 44 | +class AsynchronousTableExample: |
| 45 | + """ |
| 46 | + Demonstrate the CrateDB SQLAlchemy dialect in asynchronous mode with the `psycopg` and `asyncpg` drivers. |
| 47 | + """ |
| 48 | + |
| 49 | + def __init__(self, dsn: str): |
| 50 | + self.dsn = dsn |
| 51 | + |
| 52 | + @property |
| 53 | + @lru_cache |
| 54 | + def engine(self): |
| 55 | + """ |
| 56 | + Provide an SQLAlchemy engine object. |
| 57 | + """ |
| 58 | + return create_async_engine(self.dsn, isolation_level="AUTOCOMMIT", echo=True) |
| 59 | + |
| 60 | + @property |
| 61 | + @lru_cache |
| 62 | + def table(self): |
| 63 | + """ |
| 64 | + Provide an SQLAlchemy table object. |
| 65 | + """ |
| 66 | + metadata = sa.MetaData() |
| 67 | + return sa.Table( |
| 68 | + "testdrive", |
| 69 | + metadata, |
| 70 | + sa.Column("x", sa.Integer, primary_key=True, autoincrement=False), |
| 71 | + sa.Column("y", sa.Integer), |
| 72 | + ) |
| 73 | + |
| 74 | + async def conn_run_sync(self, func: t.Callable, *args, **kwargs): |
| 75 | + """ |
| 76 | + To support SQLAlchemy DDL methods as well as legacy functions, the |
| 77 | + AsyncConnection.run_sync() awaitable method will pass a "sync" |
| 78 | + version of the AsyncConnection object to any synchronous method, |
| 79 | + where synchronous IO calls will be transparently translated for |
| 80 | + await. |
| 81 | +
|
| 82 | + https://docs.sqlalchemy.org/en/20/_modules/examples/asyncio/basic.html |
| 83 | + """ |
| 84 | + # `conn` is an instance of `AsyncConnection` |
| 85 | + async with self.engine.begin() as conn: |
| 86 | + return await conn.run_sync(func, *args, **kwargs) |
| 87 | + |
| 88 | + async def run(self): |
| 89 | + """ |
| 90 | + Run the whole recipe, returning the result from the "read" step. |
| 91 | + """ |
| 92 | + await self.create() |
| 93 | + await self.insert(sync=True) |
| 94 | + return await self.read() |
| 95 | + |
| 96 | + async def create(self): |
| 97 | + """ |
| 98 | + Create table schema, completely dropping it upfront. |
| 99 | + """ |
| 100 | + await self.conn_run_sync(self.table.drop, checkfirst=True) |
| 101 | + await self.conn_run_sync(self.table.create) |
| 102 | + |
| 103 | + async def insert(self, sync: bool = False): |
| 104 | + """ |
| 105 | + Write data from the database, taking CrateDB-specific `REFRESH TABLE` into account. |
| 106 | + """ |
| 107 | + async with self.engine.begin() as conn: |
| 108 | + stmt = self.table.insert().values(x=1, y=42) |
| 109 | + await conn.execute(stmt) |
| 110 | + stmt = self.table.insert().values(x=2, y=42) |
| 111 | + await conn.execute(stmt) |
| 112 | + if sync and self.dsn.startswith("crate"): |
| 113 | + await conn.execute(sa.text("REFRESH TABLE testdrive;")) |
| 114 | + |
| 115 | + async def read(self): |
| 116 | + """ |
| 117 | + Read data from the database. |
| 118 | + """ |
| 119 | + async with self.engine.begin() as conn: |
| 120 | + cursor = await conn.execute(sa.text("SELECT * FROM testdrive;")) |
| 121 | + return cursor.fetchall() |
| 122 | + |
| 123 | + async def reflect(self): |
| 124 | + """ |
| 125 | + Reflect the table schema from the database. |
| 126 | + """ |
| 127 | + |
| 128 | + # Debugging. |
| 129 | + # self.trace() |
| 130 | + |
| 131 | + def reflect(session): |
| 132 | + """ |
| 133 | + A function written in "synchronous" style that will be invoked |
| 134 | + within the asyncio event loop. |
| 135 | +
|
| 136 | + The session object passed is a traditional orm.Session object with |
| 137 | + synchronous interface. |
| 138 | +
|
| 139 | + https://docs.sqlalchemy.org/en/20/_modules/examples/asyncio/greenlet_orm.html |
| 140 | + """ |
| 141 | + meta = sa.MetaData() |
| 142 | + reflected_table = sa.Table("testdrive", meta, autoload_with=session) |
| 143 | + print("Table information:") |
| 144 | + print(f"Table: {reflected_table}") |
| 145 | + print(f"Columns: {reflected_table.columns}") |
| 146 | + print(f"Constraints: {reflected_table.constraints}") |
| 147 | + print(f"Primary key: {reflected_table.primary_key}") |
| 148 | + |
| 149 | + return await self.conn_run_sync(reflect) |
| 150 | + |
| 151 | + @staticmethod |
| 152 | + def trace(): |
| 153 | + """ |
| 154 | + Trace execution flow through SQLAlchemy. |
| 155 | +
|
| 156 | + pip install hunter |
| 157 | + """ |
| 158 | + from hunter import Q, trace |
| 159 | + |
| 160 | + constraint = Q(module_startswith="sqlalchemy") |
| 161 | + trace(constraint) |
| 162 | + |
| 163 | + |
| 164 | +async def run_example(dsn: str): |
| 165 | + example = AsynchronousTableExample(dsn) |
| 166 | + |
| 167 | + # Run a basic conversation. |
| 168 | + # It also includes a catalog inquiry at `table.drop(checkfirst=True)`. |
| 169 | + result = await example.run() |
| 170 | + print(result) |
| 171 | + |
| 172 | + # Reflect the table schema. |
| 173 | + await example.reflect() |
| 174 | + |
| 175 | + |
| 176 | +def run_drivers(drivers: t.List[str]): |
| 177 | + for driver in drivers: |
| 178 | + if driver == "psycopg": |
| 179 | + dsn = "crate+psycopg://crate@localhost:5432/doc" |
| 180 | + elif driver == "asyncpg": |
| 181 | + dsn = "crate+asyncpg://crate@localhost:5432/doc" |
| 182 | + else: |
| 183 | + raise ValueError(f"Unknown driver: {driver}") |
| 184 | + |
| 185 | + asyncio.run(run_example(dsn)) |
| 186 | + |
| 187 | + |
| 188 | +if __name__ == "__main__": |
| 189 | + |
| 190 | + drivers = sys.argv[1:] |
| 191 | + run_drivers(drivers) |
0 commit comments