Skip to content

Dialect: Reflect the precision and scale of NUMERIC columns - #341

Open
olpa wants to merge 2 commits into
crate:mainfrom
olpa:olpa/313-reflect-numeric-precision-scale
Open

olpa wants to merge 2 commits into
crate:mainfrom
olpa:olpa/313-reflect-numeric-precision-scale

Conversation

@olpa

@olpa olpa commented Nov 24, 2026

Copy link
Copy Markdown

Fixes #313.

Before and after

The script in the appendix reflects this table on CrateDB 6.4.6:

CREATE TABLE doc.prices (id INTEGER PRIMARY KEY, amount NUMERIC(10, 2), rate NUMERIC(5));
INSERT INTO doc.prices (id, amount, rate) VALUES (1, 1.25, 7);

Before, on main:

1) reflected types
   id       INTEGER()
   amount   NUMERIC()
   rate     NUMERIC()
2) read a stored 1.25
   Decimal('1.2500000000')
3) CREATE TABLE from the reflected table
   CompileError: (in table 'prices_copy', column 'amount'): CrateDB stores a NUMERIC column only with a precision, as in Numeric(precision=10, scale=2)

After, with this change:

1) reflected types
   id       INTEGER()
   amount   NUMERIC(precision=10, scale=2)
   rate     NUMERIC(precision=5, scale=0)
2) read a stored 1.25
   Decimal('1.25')
3) CREATE TABLE from the reflected table

CREATE TABLE doc.prices_copy (
	id INT NOT NULL, 
	amount NUMERIC(10, 2), 
	rate NUMERIC(5, 0), 
	CONSTRAINT "PRIMARY KEY" PRIMARY KEY (id)
)

The change

get_columns() now also reads numeric_precision and numeric_scale from information_schema.columns. A numeric column uses them only when both are present.

Integer and float types ignore the reported values: their precision is a bit width fixed by the type, not a value the user declared.

Tests

  • A column reported with precision 10 and scale 2 renders as NUMERIC(10, 2) in the DDL.
  • The server reports a column declared NUMERIC(5) with a scale of zero, and it renders as NUMERIC(5, 0), as in SQLAlchemy's PostgreSQL dialect.
  • A column with a precision but no scale, as older servers report it, stays a bare NUMERIC.
  • A column with neither value stays a bare NUMERIC.
  • An integer column ignores the precision the server reports for it and still renders as INT.
  • An integration test reflects a real table from CrateDB. The table renders NUMERIC(10, 2) and NUMERIC(5, 0) and reads its value at the column's scale. On a server before 6.4.6, its columns stay a bare NUMERIC.

Follow-ups

  • Incompatibility with SQLAlchemy's generic Numeric() and with standard SQL: CrateDB rejects a NUMERIC column without a precision (NUMERIC storage is only supported if precision and scale are specified), while PostgreSQL, for example, stores it as an unconstrained decimal. The dialect therefore refuses such DDL, and the tests for a bare NUMERIC check the rendered type instead.
  • Arrays of NUMERIC still reflect without precision.
  • CREATE TABLE from a reflected table with a primary key fails: reflection marks every column as nullable, the primary key included.

Appendix

repro_313.py, the script that produced the output in "Before and after".

"""Reproduce sqlalchemy-cratedb#313: reflected NUMERIC columns lose precision and scale."""
import argparse
import logging

from sqlalchemy import MetaData, Table, create_engine, select
from sqlalchemy.exc import CompileError
from sqlalchemy.schema import CreateTable

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("url", nargs="?", default="crate://localhost:4200")
parser.add_argument("schema", nargs="?", default="doc")
parser.add_argument(
    "--trace",
    action="store_true",
    help="log the traffic to the database: for crate:// the driver's HTTP/JSON payloads, "
    "for other dialects SQLAlchemy's statement log",
)
args = parser.parse_args()

if args.trace:
    logging.basicConfig(format="   [trace] %(name)s: %(message)s")
    # The crate driver logs whole requests and responses; other drivers have no such log,
    # so for them fall back to SQLAlchemy's statement log.
    if args.url.startswith("crate"):
        logging.getLogger("crate.client.http").setLevel(logging.DEBUG)
    else:
        logging.getLogger("sqlalchemy.engine").setLevel(logging.INFO)

engine = create_engine(args.url)
prices = Table("prices", MetaData(), autoload_with=engine, schema=args.schema)

print("1) reflected types")
for col in prices.columns:
    print(f"   {col.name:8} {col.type!r}")

print("2) read a stored 1.25")
with engine.connect() as conn:
    print("  ", repr(conn.execute(select(prices.c.amount)).scalar()))

print("3) CREATE TABLE from the reflected table")
copy = prices.to_metadata(MetaData(), name="prices_copy")
# Unrelated to #313: the dialect reflects every column as nullable, also the PK.
copy.c.id.nullable = False
try:
    print(CreateTable(copy).compile(engine))
except CompileError as e:
    print("   CompileError:", e)

olpa and others added 2 commits November 24, 2026 13:51
`get_columns()` read only `data_type` from `information_schema.columns`,
so a `NUMERIC(10, 2)` column was reflected as a bare `NUMERIC`. A table
created from it raised `CompileError`, and values read back with ten
decimal places instead of the column's scale.

Read `numeric_precision` and `numeric_scale` too, and use them for a
`numeric` column when both are present. CrateDB reports the scale since
6.4.6. Older servers report the precision with a NULL scale, which means
unknown rather than zero, so such columns stay a bare `NUMERIC` instead
of silently becoming `NUMERIC(p)`. Other types report a fixed bit width
and ignore the values. Arrays of `NUMERIC` report neither and stay
unchanged.

Fixes crate#313

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Follow the file's convention and assert the `CREATE TABLE` that a
reflected column renders, instead of the type's attributes. The new
helper `render_row_ddl` passes an `information_schema` row through
`_create_column_info()`; the string-length test uses it too.

A bare `NUMERIC` has no valid DDL, because `CrateDDLCompiler` refuses
it, so the tests for a column without both values check the type
compiler's output instead of DDL or the refusal.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 24, 2026

Copy link
Copy Markdown

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: daf2b6f8-7d94-40d1-ae0d-c28dc52b4153

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
  • 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

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Reflected NUMERIC columns lose their precision and scale

1 participant