Skip to content

Dialect: Add sync and asyncio dialects over the PostgreSQL wire protocol (crate+psycopg://) - #340

Open
bgunebakan wants to merge 17 commits into
mainfrom
bilal/63-dialect-add-sync-and-asyncio-dialects-over-the-pgwire
Open

bgunebakan wants to merge 17 commits into
mainfrom
bilal/63-dialect-add-sync-and-asyncio-dialects-over-the-pgwire

Conversation

@bgunebakan

Copy link
Copy Markdown
Contributor

Summary of the changes / Why this is an improvement

Checklist

@bgunebakan bgunebakan self-assigned this Nov 23, 2026
@bgunebakan bgunebakan added the enhancement New feature or request label Nov 23, 2026
@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Explain Change →

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: fab7cf5e-be7b-4a24-986c-7b21629b3c30

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review

Walkthrough

The package adds synchronous and asynchronous psycopg dialects, async refresh utilities, and tests and workflow configuration for HTTP and psycopg drivers.

Changes

Psycopg and async SQLAlchemy support

Layer / File(s) Summary
Synchronous psycopg dialect
pyproject.toml, src/sqlalchemy_cratedb/compiler.py, src/sqlalchemy_cratedb/dialect.py, src/sqlalchemy_cratedb/dialect_psycopg.py, tests/psycopg_test.py
Registers the synchronous psycopg dialect and adds connection handling, type processing, execution, and reflection behavior. Tests cover connection arguments, SQL operations, values, errors, reflection, and ORM updates.
Async refresh utilities
src/sqlalchemy_cratedb/support/*, tests/test_support_polyfill.py, tests/test_support_util.py, CHANGES.md, docs/support.md
Adds async targets to refresh_after_dml and exports arefresh_table as an asynchronous counterpart to refresh_table. Tests and documentation describe their supported inputs and behavior.
Async psycopg dialect
src/sqlalchemy_cratedb/dialect_psycopg.py, tests/psycopg_async_test.py
Adds async dialect selection and DBAPI loading. Tests cover connections, pooling, reflection, queries, values, errors, and ORM operations.
Driver test workflow
.github/workflows/tests.yml, pyproject.toml, tests/conftest.py, tests/datetime_test.py, tests/test_error_handling.py, tests/test_support_pandas.py, tests/util.py
Adds HTTP and psycopg workflow jobs, passes the selected driver to tests, and skips http_only tests for psycopg runs. Test utilities select the connection URL for the configured driver.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant SQLAlchemy
  participant CrateDialectAsync_psycopg
  participant PsycopgAsyncDBAPI
  participant CrateDB
  SQLAlchemy->>CrateDialectAsync_psycopg: Select dialect from async URL
  CrateDialectAsync_psycopg->>PsycopgAsyncDBAPI: Load async DBAPI
  SQLAlchemy->>PsycopgAsyncDBAPI: Execute query
  PsycopgAsyncDBAPI->>CrateDB: Send query
  CrateDB-->>PsycopgAsyncDBAPI: Return result
  PsycopgAsyncDBAPI-->>SQLAlchemy: Return result
Loading

Suggested reviewers: amotl, florinutz

Merge Risk: Moderate · previous review 5cdbe

This PR adds psycopg and asyncio dialects for CrateDB. As written, numeric results through psycopg can silently lose precision, and one CI job on CrateDB 5.10.16 fails on a native UUID test. The async refresh helpers also mishandle schema-qualified mapped classes and callable session factories. Fix these before merging.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: adding sync and asyncio SQLAlchemy dialects over the PostgreSQL wire protocol via the crate+psycopg:// URL scheme. The raw summary confirms the changeset adds CrateDia…
Description check Passed The description is a template stub with an empty summary section and only a checklist entry linking to issue 63 (crate/ecosystem). It does not describe any part of the changeset, but it is not off-top…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: adding sync and asyncio SQLAlchemy dialects over the PostgreSQL wire protocol via the crate+psycopg:// URL scheme. The raw summary confirms the changeset adds CrateDialect_psycopg and CrateDialectAsync_psycopg in dialect_psycopg.py, plus related tests, dependencies, and docs. The title is concise and specific, though it is long at 91 characters.

Full details: Description check

Explanation

The description is a template stub with an empty summary section and only a checklist entry linking to issue 63 (crate/ecosystem). It does not describe any part of the changeset, but it is not off-topic: the linked issue concerns the same psycopg dialect work. Under the lenient criteria, the description is related to the changeset in some way.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
Fix failing CI checks

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

A rabbit checks the driver’s trail,
Through async paths and queries pale.
A refresh waits, then runs with care,
While psycopg brings results there.
I thump beside the test-runner’s chair.

@bgunebakan

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

Major · Keep the schema when refreshing mapped classes in the shared helper. · util.py:43

src/sqlalchemy_cratedb/support/util.py:43
Major · Functional Correctness · Quick win

Keep the schema when refreshing mapped classes in the shared helper.

_refresh_table_statement builds the statement for a mapped class from __tablename__ alone. The schema set in __table_args__ is dropped. For __tablename__ = "sensor_readings" with schema "iot", the statement is REFRESH TABLE sensor_readings, which targets the default schema.

This branch predates the PR. The sync refresh_table and the refresh_dirty after-flush handler reach it too. The new arefresh_table inherits it through the shared helper. Fix the shared helper so that all three paths benefit.

The failing case can refresh a different table or raise an error. In an after-flush handler, that error can propagate from the flush.

Read the schema from the mapped class's __table__. Keep unqualified names as they are, so schema-less tables keep their current statement:

Suggested fix

     elif hasattr(target, "__tablename__"):
         full_table_name = target.__tablename__
+        table = getattr(target, "__table__", None)
+        if table is not None and table.schema is not None:
+            full_table_name = f'"{table.schema}".' + full_table_name
Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 072f3b23-a47c-490b-883b-9a7e3fe44a21
Commits

Reviewing files that changed from the base of the PR and between 127f905 and 5cdbe20.

Files selected for processing: 19

  • .github/workflows/tests.yml
  • CHANGES.md
  • docs/support.md
  • pyproject.toml
  • src/sqlalchemy_cratedb/compiler.py
  • src/sqlalchemy_cratedb/dialect.py
  • src/sqlalchemy_cratedb/dialect_psycopg.py
  • src/sqlalchemy_cratedb/support/__init__.py
  • src/sqlalchemy_cratedb/support/polyfill.py
  • src/sqlalchemy_cratedb/support/util.py
  • tests/conftest.py
  • tests/datetime_test.py
  • tests/psycopg_async_test.py
  • tests/psycopg_test.py
  • tests/test_error_handling.py
  • tests/test_support_pandas.py
  • tests/test_support_polyfill.py
  • tests/test_support_util.py
  • tests/util.py

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

driver = "psycopg"
default_paramstyle = "pyformat"
supports_statement_cache = True
colspecs = colspecs

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Data Integrity & Integration · Quick win

Declare native Decimal support for psycopg.

This class inherits supports_native_decimal=False. Psycopg returns Decimal for NUMERIC, but the inherited SQLAlchemy processor applies float-style formatting. For Numeric(20, 2), this can change 9007199254740993.00 to 9007199254740992.00. With asdecimal=False, the processor instead returns a Decimal, not a float. (raw.githubusercontent.com)

Set supports_native_decimal=True on CrateDialect_psycopg. The async subclass will inherit the correction. Add high-precision and asdecimal=False coverage.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed in aae9f24

Comment on lines +166 to +168
refreshing_session_class = type(
"RefreshingSession", (sync_session_class,), {"_crate_refresh_after_dml": True}
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Quick win

Preserve callable synchronous session factories.

SQLAlchemy 2.0.44 supports async_sessionmaker(sync_session_class=sessionmaker()). In that configuration, sync_session_class is a factory instance, not a class. These lines use that instance as a base class, so refresh_after_dml(factory) raises TypeError before it registers the listener. (raw.githubusercontent.com)

Handle callable session factories without subclassing the callable. Preserve their configuration and keep refresh listeners local to the supplied async factory.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3393849

Comment thread tests/psycopg_test.py Outdated
Comment on lines +277 to +278
sa.Column("firmware_id", sa.UUID),
sa.Column("firmware_name", sa.UUID(as_uuid=False)),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Functional Correctness · Quick win

Gate native UUID coverage on server support.

The workflow includes CrateDB 5.10.16, but these columns require native UUID support. The supplied pipeline fails at Line 306 with Cannot find data type: uuid. This blocks the required test job.

Keep portable sa.Uuid columns in this shared test. Move the native sa.UUID columns into a separate test that skips unsupported server versions.

Source: Pipeline failures

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9ced01d

@coderabbitai

coderabbitai Bot commented Nov 23, 2026

Copy link
Copy Markdown

Add Carrot credits or activate Agent usage billing to use Autofix

@bgunebakan
bgunebakan requested a review from florinutz November 24, 2026 12:16
Comment thread CHANGES.md Outdated
- Support: `refresh_after_dml()` accepts an `AsyncEngine`, an `AsyncSession`
or an `async_sessionmaker`, with SQLAlchemy 2.0 and later. Added
`arefresh_table()`, the awaitable counterpart of `refresh_table()`
- Dialect: Added the experimental `crate+psycopg://` dialect over the PostgreSQL

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it landed wrong location while fixing conflicts, move it to unreleased tag.

@florinutz florinutz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ran this against 6.5.1 next to crate://, types, ORM flushes, schemas and lost connections all match.

two inline comments, and a few small things:

  • insert_bulk on crate+psycopg:// fails with TypeError: Cursor.execute() got an unexpected keyword argument 'sql', until ecosystem#64 it could raise a message that names method="multi"
  • not sure about this, but the [W1], [W3], [W4], [W15] tags in the comments seem to be pointing at a list that is not in the repo. the crate issue links next to them are enough
  • new source files here go without the license header since 2024
  • the body could link the thread on ecosystem#54 where this direction was agreed, and name what is left for #64 to #67
  • cratedb-examples has three skipped tests waiting for this dialect (sync_table, async_table, async_streaming), written for the URLs of #11, and the SQLAlchemy page in cratedb-guide still says HTTP only; both could use a ticket under the epic


def setup(dbapi_connection):
self.set_isolation_level(dbapi_connection, "AUTOCOMMIT")
self.get_driver_connection(dbapi_connection).adapters.register_dumper(dict, JsonDumper)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

a dict that holds a datetime, date, Decimal or UUID fails here with TypeError: Object of type ... is not JSON serializable, while crate:// stores it (dates as epoch milliseconds, Decimal and UUID as strings), so this needs a dumper with the same conversions and one such dict in test_values_match_http

opts["prepare_threshold"] = _parse_prepare_threshold(opts.get("prepare_threshold"))
opts.setdefault("connect_timeout", 10)

if opts.get("sslmode") in ("verify-ca", "verify-full") and "sslrootcert" not in opts:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this also replaces a CA set the libpq way (PGSSLROOTCERT, or ~/.postgresql/root.crt), because an explicit sslrootcert wins over both. certifi should apply only when neither of them is there

@bgunebakan
bgunebakan requested a review from florinutz November 26, 2026 16:22

@florinutz florinutz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants