-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Dialect: Add support for asyncpg
and psycopg3
drivers
#11
Draft
amotl
wants to merge
1
commit into
main
Choose a base branch
from
amo/postgresql-async
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
# -*- coding: utf-8; -*- | ||
# | ||
# Licensed to CRATE Technology GmbH ("Crate") under one or more contributor | ||
# license agreements. See the NOTICE file distributed with this work for | ||
# additional information regarding copyright ownership. Crate licenses | ||
# this file to you under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. You may | ||
# obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | ||
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the | ||
# License for the specific language governing permissions and limitations | ||
# under the License. | ||
# | ||
# However, if you have executed another commercial license agreement | ||
# with Crate these terms will supersede the license and you may use the | ||
# software solely pursuant to the terms of the relevant commercial agreement. | ||
from sqlalchemy.engine.reflection import Inspector | ||
from sqlalchemy_postgresql_relaxed.asyncpg import PGDialect_asyncpg_relaxed | ||
from sqlalchemy_postgresql_relaxed.base import PGDialect_relaxed | ||
from sqlalchemy_postgresql_relaxed.psycopg import ( | ||
PGDialect_psycopg_relaxed, | ||
PGDialectAsync_psycopg_relaxed, | ||
) | ||
|
||
from sqlalchemy_cratedb import dialect | ||
|
||
|
||
class CrateDialectPostgresAdapter(PGDialect_relaxed, dialect): | ||
""" | ||
Provide a dialect on top of the relaxed PostgreSQL dialect. | ||
""" | ||
|
||
inspector = Inspector | ||
|
||
# Need to manually override some methods because of polymorphic inheritance woes. | ||
# TODO: Investigate if this can be solved using metaprogramming or other techniques. | ||
has_schema = dialect.has_schema | ||
has_table = dialect.has_table | ||
get_schema_names = dialect.get_schema_names | ||
get_table_names = dialect.get_table_names | ||
get_view_names = dialect.get_view_names | ||
get_columns = dialect.get_columns | ||
get_pk_constraint = dialect.get_pk_constraint | ||
get_foreign_keys = dialect.get_foreign_keys | ||
get_indexes = dialect.get_indexes | ||
|
||
get_multi_columns = dialect.get_multi_columns | ||
get_multi_pk_constraint = dialect.get_multi_pk_constraint | ||
get_multi_foreign_keys = dialect.get_multi_foreign_keys | ||
|
||
# TODO: Those may want to go to dialect instead? | ||
def get_multi_indexes(self, *args, **kwargs): | ||
return [] | ||
|
||
def get_multi_unique_constraints(self, *args, **kwargs): | ||
return [] | ||
|
||
def get_multi_check_constraints(self, *args, **kwargs): | ||
return [] | ||
|
||
def get_multi_table_comment(self, *args, **kwargs): | ||
return [] | ||
|
||
|
||
class CrateDialect_psycopg(PGDialect_psycopg_relaxed, CrateDialectPostgresAdapter): | ||
driver = "psycopg" | ||
|
||
@classmethod | ||
def get_async_dialect_cls(cls, url): | ||
return CrateDialectAsync_psycopg | ||
|
||
@classmethod | ||
def import_dbapi(cls): | ||
import psycopg | ||
|
||
return psycopg | ||
|
||
|
||
class CrateDialectAsync_psycopg(PGDialectAsync_psycopg_relaxed, CrateDialectPostgresAdapter): | ||
driver = "psycopg_async" | ||
is_async = True | ||
|
||
|
||
class CrateDialect_asyncpg(PGDialect_asyncpg_relaxed, CrateDialectPostgresAdapter): | ||
driver = "asyncpg" | ||
|
||
# TODO: asyncpg may have `paramstyle="numeric_dollar"`. Review this! | ||
|
||
# TODO: AttributeError: module 'asyncpg' has no attribute 'paramstyle' | ||
""" | ||
@classmethod | ||
def import_dbapi(cls): | ||
import asyncpg | ||
|
||
return asyncpg | ||
""" | ||
|
||
|
||
dialect_urllib3 = dialect | ||
dialect_psycopg = CrateDialect_psycopg | ||
dialect_psycopg_async = CrateDialectAsync_psycopg | ||
dialect_asyncpg = CrateDialect_asyncpg |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
import pytest | ||
import sqlalchemy as sa | ||
from sqlalchemy.dialects import registry as dialect_registry | ||
|
||
from sqlalchemy_cratedb.sa_version import SA_2_0, SA_VERSION | ||
|
||
if SA_VERSION < SA_2_0: | ||
raise pytest.skip("Only supported on SQLAlchemy 2.0 and higher", allow_module_level=True) | ||
|
||
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine | ||
|
||
# Registering the additional dialects manually seems to be needed when running | ||
# under tests. Apparently, manual registration is not needed under regular | ||
# circumstances, as this is wired through the `sqlalchemy.dialects` entrypoint | ||
# registrations in `pyproject.toml`. It is definitively weird, but c'est la vie. | ||
dialect_registry.register("crate.urllib3", "sqlalchemy_cratedb.dialect_more", "dialect_urllib3") | ||
dialect_registry.register("crate.asyncpg", "sqlalchemy_cratedb.dialect_more", "dialect_asyncpg") | ||
dialect_registry.register("crate.psycopg", "sqlalchemy_cratedb.dialect_more", "dialect_psycopg") | ||
|
||
|
||
QUERY = sa.text("SELECT mountain, coordinates FROM sys.summits ORDER BY mountain LIMIT 3;") | ||
|
||
|
||
def test_engine_sync_vanilla(cratedb_service): | ||
""" | ||
crate:// -- Verify connectivity and data transport with vanilla HTTP-based driver. | ||
""" | ||
port4200 = cratedb_service.cratedb.get_exposed_port(4200) | ||
engine = sa.create_engine(f"crate://crate@localhost:{port4200}/", echo=True) | ||
assert isinstance(engine, sa.engine.Engine) | ||
with engine.connect() as connection: | ||
result = connection.execute(QUERY) | ||
assert result.mappings().fetchone() == { | ||
"mountain": "Acherkogel", | ||
"coordinates": [10.95667, 47.18917], | ||
} | ||
|
||
|
||
def test_engine_sync_urllib3(cratedb_service): | ||
""" | ||
crate+urllib3:// -- Verify connectivity and data transport *explicitly* selecting the HTTP driver. | ||
""" # noqa: E501 | ||
port4200 = cratedb_service.cratedb.get_exposed_port(4200) | ||
engine = sa.create_engine( | ||
f"crate+urllib3://crate@localhost:{port4200}/", isolation_level="AUTOCOMMIT", echo=True | ||
) | ||
assert isinstance(engine, sa.engine.Engine) | ||
with engine.connect() as connection: | ||
result = connection.execute(QUERY) | ||
assert result.mappings().fetchone() == { | ||
"mountain": "Acherkogel", | ||
"coordinates": [10.95667, 47.18917], | ||
} | ||
|
||
|
||
def test_engine_sync_psycopg(cratedb_service): | ||
""" | ||
crate+psycopg:// -- Verify connectivity and data transport using the psycopg driver (version 3). | ||
""" | ||
port5432 = cratedb_service.cratedb.get_exposed_port(5432) | ||
engine = sa.create_engine( | ||
f"crate+psycopg://crate@localhost:{port5432}/", isolation_level="AUTOCOMMIT", echo=True | ||
) | ||
assert isinstance(engine, sa.engine.Engine) | ||
with engine.connect() as connection: | ||
result = connection.execute(QUERY) | ||
assert result.mappings().fetchone() == { | ||
"mountain": "Acherkogel", | ||
"coordinates": "(10.95667,47.18917)", | ||
} | ||
|
||
|
||
@pytest.mark.asyncio | ||
async def test_engine_async_psycopg(cratedb_service): | ||
""" | ||
crate+psycopg:// -- Verify connectivity and data transport using the psycopg driver (version 3). | ||
This time, in asynchronous mode. | ||
""" | ||
port5432 = cratedb_service.cratedb.get_exposed_port(5432) | ||
engine = create_async_engine( | ||
f"crate+psycopg://crate@localhost:{port5432}/", isolation_level="AUTOCOMMIT", echo=True | ||
) | ||
assert isinstance(engine, AsyncEngine) | ||
async with engine.begin() as conn: | ||
result = await conn.execute(QUERY) | ||
assert result.mappings().fetchone() == { | ||
"mountain": "Acherkogel", | ||
"coordinates": "(10.95667,47.18917)", | ||
} | ||
|
||
|
||
@pytest.mark.asyncio | ||
async def test_engine_async_asyncpg(cratedb_service): | ||
""" | ||
crate+asyncpg:// -- Verify connectivity and data transport using the asyncpg driver. | ||
This exclusively uses asynchronous mode. | ||
""" | ||
port5432 = cratedb_service.cratedb.get_exposed_port(5432) | ||
from asyncpg.pgproto.types import Point | ||
|
||
engine = create_async_engine( | ||
f"crate+asyncpg://crate@localhost:{port5432}/", isolation_level="AUTOCOMMIT", echo=True | ||
) | ||
assert isinstance(engine, AsyncEngine) | ||
async with engine.begin() as conn: | ||
result = await conn.execute(QUERY) | ||
assert result.mappings().fetchone() == { | ||
"mountain": "Acherkogel", | ||
"coordinates": Point(10.95667, 47.18917), | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am not quite following. I assume we would want to use server side binding (i.e. qmark)?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is probably the reason for needing the workaround at all: Because PostgreSQL drivers psycopg and asyncpg, or the SA dialect, use
pyformat
, but CrateDB usesqmark
, we may need to adjust, iirc.At least, the patch in its current shape needs it. Maybe there are alternatives to implement it, possibly even easier ones. We will be happy to learn about them.