diffdb-core 0.1.2__py3-none-any.whl → 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
diffdb/__init__.py CHANGED
@@ -17,7 +17,7 @@ from .geometry import Vector
17
17
  from .telemetry import QueryTracker
18
18
  from .types import DbPath
19
19
 
20
- __version__ = "0.1.2"
20
+ __version__ = "0.2.0"
21
21
 
22
22
 
23
23
  def connect_to_table(
@@ -12,7 +12,7 @@ from operator import attrgetter, methodcaller
12
12
  from ..concurrency import ThreadedYielder
13
13
  from ..geometry import Vector, create_mesh_from_points
14
14
  from ..telemetry import InfoTree, QueryTracker, SegmentInfo
15
- from ..types import Decimal, IKey
15
+ from ..types import IKey
16
16
  from ..utils import dataclass, field, strict_zip
17
17
  from .differ import DiffResult, DiffResultWrapper
18
18
  from .segment import EmptyTable, TableSegment
@@ -225,17 +225,6 @@ class HashDiffer:
225
225
  table1 = table1.replace(_schema=dict(table1._schema))
226
226
  table2 = table2.replace(_schema=dict(table2._schema))
227
227
  for c1, c2 in strict_zip(table1.relevant_columns, table2.relevant_columns):
228
- # Unscaled numbers (no declared scale, precision=None) are compared as whole numbers
229
- for segment, col_name in ((table1, c1), (table2, c2)):
230
- ctype = segment._schema[col_name]
231
- if isinstance(ctype, Decimal) and ctype.precision is None:
232
- logger.warning(
233
- f"[{segment.database.name}] Column '{'.'.join(segment.table_path)}.{col_name}' has no declared "
234
- "scale; comparing it as a whole number, so fractional differences won't be detected. "
235
- "Declare a scale in its datatype on both sides (e.g. NUMBER(12,2) / numeric(12,2)) to compare decimals."
236
- )
237
- segment._schema[col_name] = ctype.replace(precision=0)
238
-
239
228
  # Check compatibility and reconcile to a mutually comparable form (e.g. minimal precision).
240
229
  # The rules live on the ColType classes (compat_accepts / reconcile in diffdb/types.py).
241
230
  col1 = table1._schema[c1]
diffdb/core/segment.py CHANGED
@@ -14,6 +14,7 @@ from ..geometry import (
14
14
  from ..telemetry import QueryTracker
15
15
  from ..types import (
16
16
  ColType,
17
+ Decimal,
17
18
  String_UUID,
18
19
  String_VaryingAlphanum,
19
20
  Text,
@@ -51,10 +52,15 @@ class TableSegment:
51
52
  columns (dict): Every column to compare, in order, including the bisection columns:
52
53
  ``{name: {"datatype": "NUMBER(12,2)", "transform_rule": "<sql>"}}``
53
54
 
54
- * ``datatype`` (required): native type of the value that is hashed, e.g. ``NUMBER(10,0)``,
55
+ * ``datatype`` (optional): native type of the value that is hashed, e.g. ``NUMBER(10,0)``,
55
56
  ``VARCHAR2(100)``, ``TIMESTAMP(3)``, ``numeric(12,2)``. When a transform_rule changes the
56
- type, give the result's type (``LENGTH("NOTE")`` -> ``NUMBER(10,0)``). Must be a basic type
57
- mapped in the dialect's ``type_classes``; LOB/binary types are rejected.
57
+ type, give the result's type (``LENGTH("NOTE")`` -> ``NUMBER(10,0)``). Left out, the type the
58
+ database reports for the column or transform_rule is used: one query returning no rows
59
+ (``SELECT ... WHERE 1=0``), read from the driver's result metadata, never the catalog. Either way
60
+ it must be a basic type mapped in the dialect's ``type_classes`` (LOB/binary types are rejected),
61
+ and decimals need a scale: plain ``NUMBER`` / ``numeric`` is rejected (use ``NUMBER(*,0)`` for
62
+ whole numbers). Oracle reports most computed numbers without a scale, so declare those, or
63
+ CAST them in the transform_rule. See :attr:`datatypes` for the types used.
58
64
  * ``transform_rule`` (optional): SQL expression used instead of the column, e.g.
59
65
  ``TRUNC("HIRE_DT")``. It is wrapped in parentheses.
60
66
 
@@ -87,6 +93,8 @@ class TableSegment:
87
93
  query_tracker: QueryTracker | None = None
88
94
  # Internal: column name -> ColType, built from `columns` by __post_init__. Not for callers.
89
95
  _schema: dict[str, ColType] | None = None
96
+ # Internal: column name -> native type name used for it (declared, or reported by the database)
97
+ _datatypes: dict[str, str] | None = None
90
98
 
91
99
  def __post_init__(self):
92
100
  if self.min_key is not None and self.max_key is not None and self.min_key >= self.max_key:
@@ -95,15 +103,24 @@ class TableSegment:
95
103
  self.bisection_columns = tuple(self.bisection_columns)
96
104
  self.key_columns = tuple(self.key_columns) or self.bisection_columns
97
105
  if self._schema is None:
98
- self._schema = self._build_schema()
106
+ self._schema, self._datatypes = self._build_schema()
99
107
 
100
- def _build_schema(self) -> dict[str, ColType]:
101
- """Validate `columns` / `bisection_columns` and turn each datatype into a ColType."""
108
+ @property
109
+ def datatypes(self) -> dict[str, str]:
110
+ """Native type name of each column, as declared in `columns` or, without one, as reported by the database."""
111
+ return dict(self._datatypes or {})
112
+
113
+ def _build_schema(self) -> tuple[dict[str, ColType], dict[str, str]]:
114
+ """Validate `columns` / `bisection_columns` and turn each column's datatype into a ColType.
115
+
116
+ A column without a 'datatype' takes the type the database reports for it (`_report_datatypes`).
117
+ Returns the schema and the native type name used for each column.
118
+ """
102
119
  table_name = ".".join(self.table_path)
103
120
  if not isinstance(self.columns, dict) or not self.columns:
104
121
  raise ValueError(
105
122
  f"Invalid TableSegment for {table_name}: `columns` must be a non-empty dict like "
106
- "{'ID': {'datatype': 'NUMBER(10,0)'}}"
123
+ "{'ID': {'datatype': 'NUMBER(10,0)'}} or {'ID': {}}"
107
124
  )
108
125
 
109
126
  errors = []
@@ -116,12 +133,10 @@ class TableSegment:
116
133
  if missing_keys:
117
134
  errors.append(f"key column(s) {missing_keys} are not in `columns`")
118
135
 
119
- dialect = self.database.dialect
120
- schema = {}
136
+ declared, undeclared = {}, []
121
137
  for name, spec in self.columns.items():
122
- datatype = spec.get("datatype") if isinstance(spec, dict) else None
123
- if not isinstance(datatype, str) or not datatype.strip():
124
- errors.append(f"{name}: needs a 'datatype' string, e.g. {{'datatype': 'NUMBER(10,0)'}}")
138
+ if not isinstance(spec, dict):
139
+ errors.append(f"{name}: must be a dict, e.g. {{'datatype': 'NUMBER(10,0)'}} or {{}}")
125
140
  continue
126
141
  unknown = set(spec) - _COLUMN_KEYS
127
142
  if unknown:
@@ -129,20 +144,91 @@ class TableSegment:
129
144
  rule = spec.get("transform_rule")
130
145
  if rule is not None and not (isinstance(rule, str) and rule.strip()):
131
146
  errors.append(f"{name}: 'transform_rule' must be a non-empty SQL string")
147
+ datatype = spec.get("datatype")
148
+ if datatype is None:
149
+ undeclared.append(name)
150
+ elif isinstance(datatype, str) and datatype.strip():
151
+ declared[name] = datatype
152
+ else:
153
+ errors.append(f"{name}: 'datatype' must be a non-empty string such as 'NUMBER(10,0)', or left out")
154
+
155
+ reported = {}
156
+ if undeclared and not errors:
157
+ reported = self._report_datatypes(undeclared, errors)
158
+
159
+ dialect = self.database.dialect
160
+ schema, datatypes = {}, {}
161
+ for name in self.columns:
162
+ if name in declared:
163
+ datatype = declared[name]
164
+ unsupported = (
165
+ f"unsupported datatype {datatype!r} for {dialect.name}; reduce it to a basic type with a "
166
+ "'transform_rule' and declare the result's datatype (e.g. LENGTH(...) as NUMBER(10,0))"
167
+ )
168
+ unscaled = f"datatype {datatype!r} has no scale"
169
+ fix_scale = "; declare one (NUMBER(12,2) / numeric(12,2), or NUMBER(*,0) / numeric(38,0) for whole numbers)"
170
+ elif name in reported:
171
+ datatype = reported[name]
172
+ expr = self._column_sql(name)
173
+ if datatype is None:
174
+ errors.append(
175
+ f"{name}: {self.database.name} doesn't report enough to name the exact type of {expr} "
176
+ "(e.g. a timestamp's fractional precision); declare 'datatype'"
177
+ )
178
+ continue
179
+ unsupported = (
180
+ f"unsupported type {datatype!r} reported by {self.database.name} for {expr}; reduce it to a "
181
+ "basic type with a 'transform_rule' (e.g. a length)"
182
+ )
183
+ unscaled = f"{self.database.name} reports {datatype!r} (no scale) for {expr}"
184
+ cast_of = self.columns[name].get("transform_rule") or expr
185
+ fix_scale = f"; declare 'datatype' with a scale, or CAST it in the 'transform_rule': CAST({cast_of} AS NUMBER(12,2))"
186
+ else:
187
+ continue # not reported: an error is already listed
132
188
  coltype = dialect.parse_type(datatype)
133
189
  if isinstance(coltype, Text):
134
190
  # Strings are a basic type: hashed as-is (same normalization) and usable as bisection keys
135
191
  coltype = String_VaryingAlphanum()
136
192
  if isinstance(coltype, UnknownColType):
137
- errors.append(
138
- f"{name}: unsupported datatype {datatype!r} for {dialect.name}; reduce it to a basic type with "
139
- "a 'transform_rule' and declare the result's datatype (e.g. LENGTH(...) as NUMBER(10,0))"
140
- )
193
+ errors.append(f"{name}: {unsupported}")
194
+ elif isinstance(coltype, Decimal) and coltype.precision is None:
195
+ errors.append(f"{name}: {unscaled}, so its fractional digits are unknown{fix_scale}")
141
196
  schema[name] = coltype
197
+ datatypes[name] = datatype
142
198
 
143
199
  if errors:
144
200
  raise ValueError(f"Invalid TableSegment for {table_name}:\n - " + "\n - ".join(errors))
145
- return schema
201
+ return schema, datatypes
202
+
203
+ def _report_datatypes(self, names: list[str], errors: list[str]) -> dict[str, str | None]:
204
+ """Native types of `names` as reported by the database for a query returning no rows (no catalog read).
205
+
206
+ Types already reported for this table (kept by `new()` while `columns` and `database` don't change)
207
+ are reused. Problems are appended to `errors`.
208
+ """
209
+ known = self._datatypes or {}
210
+ reported = {n: known[n] for n in names if n in known}
211
+ names = [n for n in names if n not in known]
212
+ if not names:
213
+ return reported
214
+
215
+ q = sql.describe(self.database.dialect, self.table_path, [self._column_sql(n) for n in names])
216
+ start = time.monotonic()
217
+ try:
218
+ types = self.database.describe(q)
219
+ except NotImplementedError:
220
+ errors.append(f"{names}: no 'datatype' given, and {self.database.name} can't report column types yet")
221
+ return reported
222
+ except Exception as e:
223
+ errors.append(f"could not get the types of {names} from the database ({type(e).__name__}: {e}); query: {q}")
224
+ return reported
225
+ self._record_query("describe", q, 0, None, time.monotonic() - start)
226
+
227
+ table_name = ".".join(self.table_path)
228
+ for name, datatype in strict_zip(names, types):
229
+ logger.info(f"[{self.database.name}] {table_name}.{name}: type reported by the database: {datatype}")
230
+ reported[name] = datatype
231
+ return reported
146
232
 
147
233
  def _cast_col_value(self, col, value):
148
234
  """Cast the value to the right type, based on the type of the column.
@@ -286,6 +372,8 @@ class TableSegment:
286
372
  kwargs["key_columns"] = () # the key defaulted to the bisection columns: follow the new ones
287
373
  if {"columns", "bisection_columns", "key_columns", "database"} & kwargs.keys() and "_schema" not in kwargs:
288
374
  kwargs["_schema"] = None # rebuild (and re-validate) the schema from the new definitions
375
+ if {"columns", "database"} & kwargs.keys():
376
+ kwargs["_datatypes"] = None # types reported by the database no longer apply
289
377
  return self.replace(**kwargs)
290
378
 
291
379
  def new_key_bounds(self, min_key: Vector, max_key: Vector) -> "TableSegment":
diffdb/core/sql.py CHANGED
@@ -7,6 +7,10 @@ There are only four queries per segment (see TableSegment):
7
7
  query_key_range SELECT min(k1), max(k1), ... FROM t WHERE <filters>
8
8
  get_values SELECT <normalized columns> FROM t WHERE <filters>
9
9
 
10
+ plus, once per table and only when some columns have no declared datatype, a probe that returns no rows:
11
+
12
+ describe SELECT <column or (transform_rule)>, ... FROM t WHERE 1=0
13
+
10
14
  Everything database-specific (quoting, NULL handling, concatenation, hashing, value formatting) comes from the
11
15
  YAML dialect. The output is pinned byte-for-byte for every dialect by tests/golden/query_sql.json.
12
16
  """
@@ -74,6 +78,15 @@ def checksum(dialect: YamlDialect, normalized_columns: list[str]) -> str:
74
78
  return f"sum({dialect.md5_as_int(row)})"
75
79
 
76
80
 
81
+ def describe(dialect: YamlDialect, path: tuple[str, ...], columns: list[str]) -> str:
82
+ """A query returning no rows, whose result metadata gives each column's native type (Database.describe).
83
+
84
+ `WHERE 1=0` is portable and lets the planner skip reading the table. The caller's `where` and key range
85
+ are left out: they don't change the result types.
86
+ """
87
+ return select(dialect, path, columns, ["1=0"])
88
+
89
+
77
90
  def select(dialect: YamlDialect, path: tuple[str, ...], columns: list[str], filters: list[str]) -> str:
78
91
  sql = f"SELECT {', '.join(columns)} FROM {table_sql(dialect, path)}"
79
92
  if filters:
diffdb/databases/base.py CHANGED
@@ -194,12 +194,34 @@ class Database(ABC):
194
194
  def _query(self, sql_code: str) -> list:
195
195
  "Send a query to the database and return the result"
196
196
 
197
+ def describe(self, sql_code: str) -> list[str | None]:
198
+ """Native type name of each column of a query's result, e.g. ['NUMBER(10,0)', 'VARCHAR2'].
199
+
200
+ Read from the driver's result metadata (`cursor.description`) after running the query, which should
201
+ return no rows (see core/sql.py `describe`). The catalog is never read. An entry is None when the
202
+ driver doesn't report enough to name the type exactly (e.g. a timestamp without its precision).
203
+ Raises NotImplementedError when the driver has no `_native_type` mapping.
204
+ """
205
+ if type(self)._native_type is Database._native_type:
206
+ raise NotImplementedError(f"{self.name} can't report column types yet")
207
+ return self._describe(sql_code)
208
+
209
+ def _native_type(self, column: Sequence) -> str | None:
210
+ """Native type name for one `cursor.description` entry. Driver-specific: override to support `describe`."""
211
+ raise NotImplementedError
212
+
213
+ def _describe(self, sql_code: str) -> list[str | None]:
214
+ """Run `sql_code` and map its result metadata with `_native_type` (drivers override to pick a connection)."""
215
+ raise NotImplementedError(f"{self.name} can't report column types yet")
216
+
197
217
  def parse_table_name(self, name: str) -> DbPath:
198
218
  return parse_table_name(name)
199
219
 
200
220
  def _query_cursor(self, c, sql_code: str) -> QueryResult | None:
201
221
  logger.debug(f"{self.name} Executing SQL: {sql_code}")
202
- c.execute(sql_code, ()) # empty parameter tuple, as before (the diff never binds parameters)
222
+ # No parameter argument: the diff never binds parameters, and drivers with %-style placeholders
223
+ # (psycopg2, MySQL, ...) would read every '%' in the SQL (a modulo, LIKE 'A%') as one, even for ()
224
+ c.execute(sql_code)
203
225
  if sql_code.lstrip().lower().startswith(("select", "explain", "show", "with")):
204
226
  columns = c.description and [col[0] for col in c.description]
205
227
  return QueryResult(c.fetchall(), columns)
@@ -213,6 +235,20 @@ class Database(ABC):
213
235
  with suppress(Exception):
214
236
  c.close()
215
237
 
238
+ def _describe_cursor(self, c, sql_code: str) -> list[str | None]:
239
+ logger.debug(f"{self.name} Describing SQL: {sql_code}")
240
+ c.execute(sql_code)
241
+ c.fetchall() # no rows; consumed so the cursor is complete on every driver
242
+ return [self._native_type(col) for col in c.description]
243
+
244
+ def _describe_conn(self, conn, sql_code: str) -> list[str | None]:
245
+ c = conn.cursor()
246
+ try:
247
+ return self._describe_cursor(c, sql_code)
248
+ finally:
249
+ with suppress(Exception):
250
+ c.close()
251
+
216
252
  def close(self):
217
253
  self.is_closed = True
218
254
 
@@ -247,6 +283,14 @@ class ThreadedDatabase(Database):
247
283
  raise self._init_error
248
284
  return self._query_conn(self.thread_local.conn, sql_code)
249
285
 
286
+ def _describe(self, sql_code: str) -> list[str | None]:
287
+ return self._queue.submit(self._describe_in_worker, sql_code).result()
288
+
289
+ def _describe_in_worker(self, sql_code: str):
290
+ if self._init_error:
291
+ raise self._init_error
292
+ return self._describe_conn(self.thread_local.conn, sql_code)
293
+
250
294
  @abstractmethod
251
295
  def create_connection(self):
252
296
  """Return a connection instance that supports the .cursor() method."""
@@ -35,6 +35,13 @@ class DuckDB(Database):
35
35
  def _query(self, sql_code: str):
36
36
  return self._query_conn(self._conn, sql_code)
37
37
 
38
+ def _describe(self, sql_code: str):
39
+ return self._describe_conn(self._conn, sql_code)
40
+
41
+ def _native_type(self, column):
42
+ # DuckDB reports the complete type, scale included: 'BIGINT', 'DECIMAL(14,3)', 'TIMESTAMP WITH TIME ZONE'
43
+ return str(column[1])
44
+
38
45
  def close(self):
39
46
  super().close()
40
47
  self._conn.close()
@@ -17,6 +17,33 @@ def _with_hash_charset(dialect: YamlDialect, charset: str | None) -> YamlDialect
17
17
  return configured
18
18
 
19
19
 
20
+ # oracledb DbType names (without "DB_TYPE_") whose Oracle type name differs; others are used as they are
21
+ _ORACLE_TYPE_NAMES = {"VARCHAR": "VARCHAR2", "NVARCHAR": "NVARCHAR2", "LONG_VARCHAR": "LONG", "LONG_RAW": "LONG RAW"}
22
+ _ORACLE_TIMESTAMP_SUFFIX = {"TIMESTAMP": "", "TIMESTAMP_TZ": " WITH TIME ZONE", "TIMESTAMP_LTZ": " WITH LOCAL TIME ZONE"}
23
+
24
+
25
+ def oracle_native_type(column) -> str | None:
26
+ """Oracle type name for one oracledb `cursor.description` entry (name, type, display_size, internal_size,
27
+ precision, scale, null_ok).
28
+
29
+ NUMBER: precision p / scale s -> NUMBER(p,s); scale -127 marks a floating type: FLOAT(p), or a plain
30
+ NUMBER (no scale) when p is 0. Computed numbers (LENGTH, ROUND, arithmetic) report no precision or scale
31
+ at all (None), also a plain NUMBER. TIMESTAMP: the scale is the fractional-second precision; when it isn't
32
+ reported (as for TIMESTAMP(0)) the type can't be named exactly, so None is returned.
33
+ """
34
+ dbtype, precision, scale = column[1], column[4], column[5]
35
+ name = (getattr(dbtype, "name", None) or str(dbtype)).removeprefix("DB_TYPE_")
36
+ if name == "NUMBER":
37
+ if scale == -127 or scale is None:
38
+ return f"FLOAT({precision})" if precision else "NUMBER"
39
+ return f"NUMBER({precision},{scale})" if precision else "NUMBER"
40
+ if name in _ORACLE_TIMESTAMP_SUFFIX:
41
+ if scale is None:
42
+ return None
43
+ return f"TIMESTAMP({scale}){_ORACLE_TIMESTAMP_SUFFIX[name]}"
44
+ return _ORACLE_TYPE_NAMES.get(name, name)
45
+
46
+
20
47
  @import_helper("oracle")
21
48
  def import_oracle():
22
49
  try:
@@ -93,7 +120,20 @@ class Oracle(ThreadedDatabase):
93
120
  try:
94
121
  return super()._query_cursor(c, sql_code)
95
122
  except Exception as e:
96
- oracle_mod = getattr(self, "_oracle", None) or import_oracle()
97
- if hasattr(oracle_mod, "DatabaseError") and isinstance(e, oracle_mod.DatabaseError):
98
- raise QueryError(e) from e
123
+ self._raise_query_error(e)
99
124
  raise
125
+
126
+ def _describe_cursor(self, c, sql_code):
127
+ try:
128
+ return super()._describe_cursor(c, sql_code)
129
+ except Exception as e:
130
+ self._raise_query_error(e)
131
+ raise
132
+
133
+ def _raise_query_error(self, e: Exception) -> None:
134
+ oracle_mod = getattr(self, "_oracle", None) or import_oracle()
135
+ if hasattr(oracle_mod, "DatabaseError") and isinstance(e, oracle_mod.DatabaseError):
136
+ raise QueryError(e) from e
137
+
138
+ def _native_type(self, column):
139
+ return oracle_native_type(column)
@@ -6,6 +6,33 @@ from .yaml_dialect import YamlDialect
6
6
 
7
7
  logger = logging.getLogger(__name__)
8
8
 
9
+ # Built-in type OIDs (fixed in PostgreSQL's pg_type.dat) -> type names. Unmapped OIDs (extensions, domains,
10
+ # user types) are reported as "oid <n>" and rejected as unsupported.
11
+ _PG_TYPE_NAMES = {
12
+ 16: "boolean", 17: "bytea", 20: "bigint", 21: "smallint", 23: "integer", 25: "text", 114: "json",
13
+ 142: "xml", 700: "real", 701: "double precision", 790: "money", 1042: "character", 1043: "character varying",
14
+ 1082: "date", 1083: "time", 1114: "timestamp", 1184: "timestamp with time zone", 1186: "interval",
15
+ 1266: "time with time zone", 1700: "numeric", 2950: "uuid", 3802: "jsonb",
16
+ }
17
+ # psycopg2 reports a numeric without type modifier (plain numeric, round(), arithmetic) as 65535 / 65535
18
+ _PG_NO_TYPMOD = 65535
19
+
20
+
21
+ def postgresql_native_type(column) -> str:
22
+ """PostgreSQL type name for one psycopg2 `cursor.description` entry (name, type_code, display_size,
23
+ internal_size, precision, scale, null_ok); type_code is the type OID.
24
+
25
+ numeric: precision / scale come from the type modifier -> numeric(p,s); without one (plain numeric and
26
+ computed values such as round() or arithmetic) -> numeric, which has no scale. Timestamps: psycopg2 doesn't
27
+ report their precision, so they are named without one and take the default of 6, PostgreSQL's maximum:
28
+ that can only overstate the precision, and reconcile lowers it to the other side's.
29
+ """
30
+ oid, precision, scale = column[1], column[4], column[5]
31
+ name = _PG_TYPE_NAMES.get(oid, f"oid {oid}")
32
+ if name == "numeric" and precision not in (None, _PG_NO_TYPMOD) and scale not in (None, _PG_NO_TYPMOD):
33
+ return f"numeric({precision},{scale})"
34
+ return name
35
+
9
36
 
10
37
  @import_helper("postgresql")
11
38
  def import_postgresql():
@@ -29,6 +56,15 @@ class PostgreSQL(ThreadedDatabase):
29
56
  self._args["host"] = None
30
57
  pg = import_postgresql()
31
58
  try:
32
- return pg.connect(**self._args)
59
+ conn = pg.connect(**self._args)
33
60
  except pg.OperationalError as e:
34
61
  raise ConnectError(*e.args) from e
62
+ # The diff only reads. Without autocommit psycopg2 opens a transaction on the first SELECT and keeps it
63
+ # for the life of the connection ("idle in transaction"): a lock on every table read, which blocks
64
+ # ALTER / TRUNCATE / DROP on them, and an old snapshot that holds back vacuum. Under the default READ
65
+ # COMMITTED each statement sees fresh data either way, so results don't change.
66
+ conn.autocommit = True
67
+ return conn
68
+
69
+ def _native_type(self, column):
70
+ return postgresql_native_type(column)
@@ -1,6 +1,7 @@
1
1
  # diffdb/databases/redshift.py
2
2
  import logging
3
3
 
4
+ from .base import Database
4
5
  from .postgresql import PostgreSQL
5
6
  from .yaml_dialect import YamlDialect
6
7
 
@@ -9,4 +10,6 @@ logger = logging.getLogger(__name__)
9
10
 
10
11
  class Redshift(PostgreSQL):
11
12
  dialect = YamlDialect.load("redshift")
13
+ # Type reporting is PostgreSQL's (psycopg2 OIDs) but untested on Redshift: datatype stays required
14
+ _native_type = Database._native_type
12
15
  CONNECT_URI_HELP = "redshift://<user>:<password>@<host>/<database>"
@@ -392,7 +392,7 @@ class YamlDialect:
392
392
  """'I.P': at least one integer digit, exactly coltype.precision fractional digits, no dot if 0."""
393
393
  precision = getattr(coltype, "precision", 0)
394
394
  if precision is None:
395
- precision = 0 # unscaled Decimal; HashDiffer warns about these before hashing
395
+ precision = 0 # unscaled Decimal; TableSegment rejects these, so only reached by direct calls
396
396
  tmpl = self.norm_templates.get("number")
397
397
  if tmpl:
398
398
  format_str = ""
diffdb/types.py CHANGED
@@ -202,8 +202,8 @@ class Decimal(FractionalType, IKey): # Snowflake may use Decimal as a key
202
202
  """Fixed-point number. `precision` is the number of fractional digits compared.
203
203
 
204
204
  precision=None marks an unscaled column (datatype Oracle NUMBER / PostgreSQL numeric without a
205
- declared scale). It is a marker only: HashDiffer warns and compares it with 0 fractional digits. To
206
- compare decimals, declare a scale in the datatype on both sides (NUMBER(12,2) / numeric(12,2)).
205
+ declared scale). TableSegment rejects it: the number of fractional digits to compare must be declared,
206
+ e.g. NUMBER(12,2) / numeric(12,2), or NUMBER(*,0) for whole numbers.
207
207
  """
208
208
 
209
209
  precision: int | None
@@ -216,8 +216,8 @@ class Decimal(FractionalType, IKey): # Snowflake may use Decimal as a key
216
216
 
217
217
  @classmethod
218
218
  def from_type_args(cls, dialect, args=()):
219
- # NUMBER(12,2) -> scale 2; NUMBER(10) / NUMBER(*,0) -> 0; plain NUMBER / numeric -> None (unscaled)
220
- if not args:
219
+ # NUMBER(12,2) -> scale 2; NUMBER(10) / NUMBER(*,0) -> 0; plain NUMBER / NUMBER(*) / numeric -> None
220
+ if not args or args == (None,):
221
221
  return cls(precision=None)
222
222
  if len(args) == 1:
223
223
  return cls(precision=0)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: diffdb-core
3
- Version: 0.1.2
3
+ Version: 0.2.0
4
4
  Summary: Cross-database table diffing by recursive checksum bisection, with declarative YAML SQL dialects
5
5
  Author: Sarath Mohan
6
6
  License: MIT
@@ -60,16 +60,26 @@ engines and a `FULL OUTER JOIN` isn't possible.
60
60
  - **12 databases** through declarative YAML dialects: PostgreSQL, Oracle, MySQL, Snowflake, BigQuery, Redshift,
61
61
  Databricks, DuckDB, Trino, Presto, ClickHouse, Vertica.
62
62
  - **Any pair**: the source and target can be different engines; each side renders values to the same text before hashing.
63
- - **No metadata reads**: you pass the columns, their native types and optional SQL transform rules, so the
64
- engine sends only four read-only query shapes and never touches the catalog. (The one exception: an Oracle
65
- connection reads `NLS_CHARACTERSET` once when it opens, unless `hash_charset` is given.)
63
+ - **Just name the columns**: on PostgreSQL, Oracle and DuckDB the column types come from the database. Declare a
64
+ type or compare an SQL expression only when you need to.
65
+ - **No catalog reads**: no `information_schema`, primary-key or table-list queries. The engine sends a handful of
66
+ read-only query shapes (see [How it works](#how-it-works)).
66
67
  - **Non-unique keys** work: bisection columns need only be selective, and duplicate rows are counted.
67
68
  - **Per-key summary**: changed rows with their differing columns, source-only and target-only rows, duplicate keys.
68
69
  - **Telemetry**: every query, row count, checksum and duration can be captured for auditing.
69
70
 
70
- diffdb-core is the third iteration of this tooling, after `simple-dv-tool` and `ibis-dv-tool`, and is built on
71
- reladiff's algorithm. See [Background](#background-from-aggregate-fingerprints-to-checksum-bisection) for how it got
72
- here and [How diffdb-core differs from reladiff](#how-diffdb-core-differs-from-reladiff) for what changed.
71
+ **Contents**
72
+
73
+ - Getting started: [Install](#install) · [Quick start](#quick-start-no-database-server-needed) ·
74
+ [Compare two real databases](#compare-two-real-databases) · [Reading the results](#reading-the-results)
75
+ - Going further: [When to declare a datatype](#when-to-declare-a-datatype) ·
76
+ [Comparing expressions](#comparing-expressions-transform_rule) · [Filtering](#filtering-and-incremental-runs) ·
77
+ [Performance](#performance) · [Auditing](#auditing-queries-raw-rows-and-stats) · [Common errors](#common-errors)
78
+ - Reference: [Arguments](#reference) · [How it works](#how-it-works) ·
79
+ [Keys and the per-key summary](#keys-and-the-per-key-summary) · [Known limitations](#known-limitations)
80
+ - Background: [From fingerprints to bisection](#background-from-aggregate-fingerprints-to-checksum-bisection) ·
81
+ [How diffdb-core differs from reladiff](#how-diffdb-core-differs-from-reladiff) ·
82
+ [Adding a database](#adding-a-database) · [Development](#development)
73
83
 
74
84
  ## Install
75
85
 
@@ -80,62 +90,98 @@ pip install "diffdb-core[postgresql,oracle]" # pick the extras for your databa
80
90
  Extras: `oracle`, `postgresql`, `redshift`, `mysql`, `snowflake`, `bigquery`, `databricks`, `duckdb`, `trino`,
81
91
  `presto`, `clickhouse`, `vertica`. The package is imported as `diffdb`. Python ≥ 3.12.
82
92
 
83
- ## Quick start
93
+ ## Quick start (no database server needed)
94
+
95
+ This runs as is after `pip install "diffdb-core[duckdb]"`. It builds two small tables in a local DuckDB file, with
96
+ three differences between them, and finds them:
97
+
98
+ ```python
99
+ import diffdb
100
+
101
+ db = diffdb.connect("duckdb://demo@demo.duckdb") # a local file; created if missing
102
+
103
+ # Two copies of a table, with a few differences in the new one
104
+ db.query("""CREATE OR REPLACE TABLE customers_old AS
105
+ SELECT i AS id, 'user' || i || '@example.com' AS email, CAST(i * 1.5 AS DECIMAL(10,2)) AS balance
106
+ FROM range(1, 10001) t(i)""")
107
+ db.query("CREATE OR REPLACE TABLE customers_new AS SELECT * FROM customers_old")
108
+ db.query("UPDATE customers_new SET balance = balance + 1 WHERE id = 42")
109
+ db.query("DELETE FROM customers_new WHERE id = 7")
110
+ db.query("INSERT INTO customers_new VALUES (10001, 'new@example.com', 0)")
111
+
112
+ columns = {"id": {}, "email": {}, "balance": {}} # just the names; types come from the database
113
+
114
+ src = diffdb.connect_to_table(db, "customers_old", "id", columns) # "id" splits the table into key ranges
115
+ tgt = diffdb.connect_to_table(db, "customers_new", "id", columns)
116
+
117
+ with diffdb.diff_tables(src, tgt) as diff:
118
+ summary = diff.summarize()
119
+
120
+ print(f"changed rows: {summary.changed}")
121
+ print(f"only in source: {summary.source_only}")
122
+ print(f"only in target: {summary.target_only}")
123
+
124
+ for kd in summary.key_diffs:
125
+ if kd.kind == "changed":
126
+ for cd in kd.column_diffs:
127
+ print(f"id {kd.key[0]}: {cd.source_column} changed from {cd.source_value} to {cd.target_value}")
128
+ else:
129
+ print(f"id {kd.key[0]}: {kd.kind}")
130
+ ```
131
+
132
+ ```text
133
+ changed rows: 1
134
+ only in source: 1
135
+ only in target: 1
136
+ id 10001: target_only
137
+ id 42: balance changed from 63.00 to 64.00
138
+ id 7: source_only
139
+ ```
140
+
141
+ The three things you always give are the table, the **bisection column** (`"id"`: the column used to split the
142
+ table into ranges, ideally the indexed primary key) and the **columns to compare**.
143
+
144
+ ## Compare two real databases
145
+
146
+ The same call, one connection per side. Here an Oracle table is checked against its PostgreSQL copy:
84
147
 
85
148
  ```python
86
149
  from diffdb import connect_to_table, diff_tables
87
150
 
88
- # Every compared column with its native datatype. Source and target are paired by position,
89
- # so both dicts list the columns in the same order (bisection columns first).
90
151
  src = connect_to_table(
91
- "oracle://app_user:pwd@oracle-host:1521/ORCL",
152
+ "oracle://app_user:pwd@oracle-host:1521/ORCLPDB1",
92
153
  "SALES.CUSTOMER",
93
- bisection_columns=("CUSTOMER_ID",),
94
- columns={
95
- "CUSTOMER_ID": {"datatype": "NUMBER(10,0)"},
96
- "EMAIL": {"datatype": "VARCHAR2(200)"},
97
- "BALANCE": {"datatype": "NUMBER(12,2)"},
98
- "NOTES": {"datatype": "NUMBER(10,0)", "transform_rule": 'DBMS_LOB.GETLENGTH("NOTES")'}, # CLOB -> length
99
- },
154
+ bisection_columns="CUSTOMER_ID",
155
+ columns={"CUSTOMER_ID": {}, "EMAIL": {}, "BALANCE": {}, "CREATED_AT": {}},
100
156
  )
101
157
  tgt = connect_to_table(
102
158
  "postgresql://app_user:pwd@pg-host:5432/sales",
103
159
  "sales.customer",
104
- bisection_columns=("customer_id",),
105
- columns={
106
- "customer_id": {"datatype": "bigint"},
107
- "email": {"datatype": "varchar(200)"},
108
- "balance": {"datatype": "numeric(12,2)"},
109
- "notes": {"datatype": "integer", "transform_rule": 'LENGTH("notes")'},
110
- },
160
+ bisection_columns="customer_id",
161
+ columns={"customer_id": {}, "email": {}, "balance": {}, "created_at": {}},
111
162
  )
112
163
 
113
- diff = diff_tables(src, tgt)
114
- try:
115
- summary = diff.summarize(limit=1000) # stop after 1000 differing keys
116
- finally:
117
- diff.close()
164
+ with diff_tables(src, tgt) as diff:
165
+ summary = diff.summarize(limit=1000) # stop after 1000 differing keys
118
166
 
119
- print(summary.changed, summary.source_only, summary.target_only, summary.limit_reached)
120
- for kd in summary.key_diffs: # kind: changed | source_only | target_only | duplicate_key
121
- if kd.kind == "changed":
122
- for cd in kd.column_diffs:
123
- print(kd.key, cd.target_column, cd.source_value, "->", cd.target_value)
124
- else: # source_only | target_only | duplicate_key: the unpaired rows
125
- print(kd.key, kd.kind, kd.source_rows, kd.target_rows)
167
+ print(f"changed rows: {summary.changed}")
168
+ print(f"only in Oracle: {summary.source_only}")
169
+ print(f"only in PG: {summary.target_only}")
170
+ if summary.limit_reached:
171
+ print("stopped at 1000 differing keys: the counts above are partial")
126
172
  ```
127
173
 
128
- Rows are paired into `changed` results by `key_columns`, which default to the bisection columns; see
129
- [Keys and the per-key summary](#keys-and-the-per-key-summary).
174
+ Two rules to know from the start:
130
175
 
131
- You can also iterate the raw stream (`for sign, row in diff_tables(...)`, with `-` = source only and `+` = target
132
- only), get counts with `get_stats_dict()`, and capture every query with `track_queries=True, return_queries=True`.
133
- See [ARCHITECTURE.md](https://github.com/sarath-mec/diffdb-core/blob/main/ARCHITECTURE.md#6-python-api-reference--practical-recipes) for these recipes.
176
+ - **Columns are paired by position, not by name.** The first source column is compared with the first target
177
+ column, and so on, so list both sides in the same order. Names may differ (`CUSTOMER_ID` ↔ `customer_id`).
178
+ - **The bisection column is always compared first**, whatever its place in the dict.
134
179
 
135
- ### Connections
180
+ That's all a typical migration check needs. If a column can't be compared as is (a plain Oracle `NUMBER`, a
181
+ `CLOB`, a database without type reporting), `connect_to_table` raises one `ValueError` that lists every such
182
+ column and how to fix it; the next sections explain the fixes.
136
183
 
137
- `connect()` / `connect_to_table()` take a URI (`postgresql://user:pwd@host:5432/db`) or a dict whose `driver` is
138
- one of the schemes above and whose other keys go to that database's Python driver:
184
+ Connections take a URI or a dict whose other keys go to that database's Python driver:
139
185
 
140
186
  ```python
141
187
  import diffdb
@@ -146,7 +192,180 @@ ora = diffdb.connect({"driver": "oracle", "user": "app_user", "password": "...",
146
192
  "dsn": "oracle-host:1521/ORCLPDB1"}, thread_count=4)
147
193
  ```
148
194
 
149
- An existing `Database` can be passed to `connect_to_table()` instead of a URI, so one connection pool serves many tables.
195
+ Pass a connected `Database` to `connect_to_table()` instead of a URI so one connection pool serves many tables.
196
+
197
+ ## Reading the results
198
+
199
+ `summarize()` returns a `DiffSummary`:
200
+
201
+ | Field | Meaning |
202
+ | :--- | :--- |
203
+ | `changed` | keys present on both sides with different values |
204
+ | `source_only` / `target_only` | rows found on one side only |
205
+ | `source_scanned` / `target_scanned` | rows covered on each side |
206
+ | `limit_reached` | `True` if `limit` stopped the run early (the counts are then partial) |
207
+ | `duplicate_keys` | `True` if some key had several differing rows on one side |
208
+ | `key_diffs` | one `KeyDiff` per differing key: `key`, `kind` (`changed`, `source_only`, `target_only`, `duplicate_key`), `column_diffs` for changed rows, `source_rows` / `target_rows` otherwise |
209
+
210
+ Each `ColumnDiff` holds `source_column`, `target_column`, `source_value` and `target_value`. Values are the
211
+ normalized text that was compared (`'63.00'`, `'2024-01-01 12:57:00.777000'`, `'<null>'` for NULL).
212
+ `summary.as_dict()` gives the whole result as JSON-ready data.
213
+
214
+ ```python
215
+ for kd in summary.key_diffs:
216
+ if kd.kind == "changed":
217
+ for cd in kd.column_diffs:
218
+ print(kd.key, cd.target_column, cd.source_value, "->", cd.target_value)
219
+ else: # source_only | target_only | duplicate_key: the unpaired rows
220
+ print(kd.key, kd.kind, kd.source_rows, kd.target_rows)
221
+ ```
222
+
223
+ ## Going further
224
+
225
+ ### When to declare a datatype
226
+
227
+ Each entry in `columns` takes two optional keys: `{"datatype": "<native type>", "transform_rule": "<sql>"}`. With
228
+ neither, diffdb asks the database for the type: when the table is opened it sends one query that returns no
229
+ rows (`SELECT "CUSTOMER_ID", "EMAIL", … FROM "SALES"."CUSTOMER" WHERE 1=0`) and reads each column's type from the
230
+ driver's result metadata. `src.datatypes` shows the type used for every column.
231
+
232
+ Declare `datatype` yourself when:
233
+
234
+ | Situation | Example | Why |
235
+ | :--- | :--- | :--- |
236
+ | A plain decimal with no scale | Oracle `NUMBER`, PostgreSQL `numeric` | The number of decimals to compare is unknown, so it's rejected. Declare it: `{"datatype": "NUMBER(12,2)"}` / `{"datatype": "numeric(12,2)"}`, or `NUMBER(*,0)` / `numeric(38,0)` for whole numbers. |
237
+ | The database can't report types | MySQL, Snowflake, BigQuery, Redshift, Databricks, Trino, Presto, ClickHouse, Vertica | Type reporting is available on PostgreSQL, Oracle and DuckDB only. |
238
+ | An Oracle `TIMESTAMP(0)` | | Oracle reports no precision for it. |
239
+ | The bisection column is a plain `NUMBER` | `"ID": {"datatype": "NUMBER(12,0)"}` | Better than a `CAST` in a `transform_rule`, which would stop the database from using the column's index. |
240
+
241
+ A declared `datatype` always wins and isn't probed, so you can mix both styles in one dict:
242
+
243
+ ```python
244
+ columns={
245
+ "ID": {"datatype": "NUMBER(12,0)"}, # plain NUMBER key: declared
246
+ "EMAIL": {}, # VARCHAR2, reported
247
+ "AMOUNT": {}, # NUMBER(12,2), reported
248
+ }
249
+ ```
250
+
251
+ `datatype` is the native type name as the database spells it (`VARCHAR2(100)`, `TIMESTAMP(3)`, `numeric(12,2)`,
252
+ `bigint`). Only basic types compare: numbers, strings, timestamps/dates and booleans; see [Types](#types).
253
+
254
+ ### Comparing expressions: `transform_rule`
255
+
256
+ A `transform_rule` is an SQL expression used instead of the column, on that side only. Use it to reduce a type
257
+ that can't be compared (LOBs, binary), to clean values, or to make both engines agree:
258
+
259
+ ```python
260
+ oracle_columns = {
261
+ "ID": {},
262
+ "NOTES": {"transform_rule": 'CAST(DBMS_LOB.GETLENGTH("NOTES") AS NUMBER(10,0))'}, # CLOB -> its length
263
+ "NAME": {"transform_rule": 'TRIM("NAME")'},
264
+ "CREATED": {"transform_rule": 'TRUNC("CREATED")'}, # drop the time of day
265
+ }
266
+ postgres_columns = {
267
+ "id": {},
268
+ "notes": {"transform_rule": 'length("notes")'},
269
+ "name": {"transform_rule": 'trim("name")'},
270
+ "created": {"transform_rule": "date_trunc('day', \"created\")"},
271
+ }
272
+ ```
273
+
274
+ - The rule is wrapped in parentheses and used **everywhere** the column appears: the checksum, the key-range
275
+ `MIN`/`MAX`, the downloaded rows and, for a bisection column, the key-range `WHERE` clauses.
276
+ - The type of the rule's result is reported like a column's, but engines often can't name it exactly. Oracle
277
+ reports `LENGTH`, `ROUND` and arithmetic as a plain `NUMBER`, and PostgreSQL reports `round()` and arithmetic as a
278
+ plain `numeric`. Both are rejected, so `CAST` the result (as above) or declare `datatype` for the result:
279
+ `{"datatype": "NUMBER(10,0)", "transform_rule": 'DBMS_LOB.GETLENGTH("NOTES")'}`.
280
+ - PostgreSQL's `length()` returns `integer`, so it needs no cast.
281
+
282
+ ### Filtering and incremental runs
283
+
284
+ `where` adds an SQL filter to every query on that side, e.g. to check only recent changes (CDC windows):
285
+
286
+ ```python
287
+ src = connect_to_table(ora, "SALES.ORDERS", "ORDER_ID", cols,
288
+ where="\"UPDATED_AT\" >= TIMESTAMP '2026-10-01 00:00:00'")
289
+ ```
290
+
291
+ `diff_tables(..., where=...)` sets the same filter on both sides, and `min_key` / `max_key` restrict the
292
+ bisection key range.
293
+
294
+ ### Performance
295
+
296
+ - **Bisect on an indexed, selective column**, usually the primary key. Every checksum query filters on it.
297
+ - **Threads**: `connect(..., thread_count=N)` opens N connections per database, and
298
+ `diff_tables(..., max_threadpool_size=M)` sets how many queries run at once; make M at least 2 × N.
299
+ - **`bisection_factor`** (default 32): how many ranges each mismatching range is split into.
300
+ **`bisection_threshold`** (default 16,384): ranges with fewer rows are downloaded and compared in memory.
301
+ - **Mostly identical tables are fast**: matching ranges cost one checksum query each and nothing is downloaded.
302
+ - `summarize(limit=N)` stops after N differing keys and cancels the remaining queries.
303
+
304
+ ### Auditing: queries, raw rows and stats
305
+
306
+ - `diff.get_queries_and_checksums()` lists every query sent, with row counts, checksums and durations
307
+ (`diff_tables(..., return_queries=True)` also returns the `QueryTracker`).
308
+ - `for sign, row in diff_tables(src, tgt)` streams the raw differences: `'-'` = source only, `'+'` = target only.
309
+ - `diff.get_stats_dict()` returns counts only.
310
+ - Logging goes through the `diffdb` logger (`logging.getLogger("diffdb").setLevel(logging.INFO)` shows each
311
+ reported column type).
312
+
313
+ See [ARCHITECTURE.md](https://github.com/sarath-mec/diffdb-core/blob/main/ARCHITECTURE.md#6-python-api-reference--practical-recipes)
314
+ for more recipes.
315
+
316
+ ### Common errors
317
+
318
+ All problems with `columns` are reported together in one `ValueError` when the table is opened.
319
+
320
+ | Error says | Fix |
321
+ | :--- | :--- |
322
+ | `datatype 'NUMBER' has no scale` / `reports 'NUMBER' (no scale)` | Declare the scale (`NUMBER(12,2)`, `NUMBER(*,0)`) or `CAST` the rule. |
323
+ | `unsupported type 'CLOB'` (or `BLOB`, `bytea`, …) | Reduce it with a `transform_rule`, e.g. its length. |
324
+ | `can't report column types yet` | That database has no type reporting: declare `datatype` for each column. |
325
+ | `doesn't report enough to name the exact type` | Declare `datatype` (e.g. an Oracle `TIMESTAMP(0)`). |
326
+ | `bisection column(s) [...] are not in columns` | Add the bisection column to `columns`. |
327
+ | `Incompatible types for column` | The paired columns have different kinds (e.g. a string and a number). Check the column order, or cast one side. |
328
+ | `key_columns must sit at the same positions on both sides` | List the columns in the same order on both sides. |
329
+ | `EmptyTable` | A side has no rows in range: pass `allow_empty_tables=True` if that's expected. |
330
+ | `ORA-01489` | The Oracle row string is longer than 4000 bytes: compare wide text columns through `LENGTH(...)`. |
331
+
332
+ ## Reference
333
+
334
+ `TableSegment` (or `connect_to_table`) takes:
335
+
336
+ | Argument | Meaning |
337
+ | :--- | :--- |
338
+ | `bisection_columns` | Columns that split the table into key ranges. Need not be unique, but should be selective and indexed: one value holding more rows than `bisection_threshold` can't be split and is downloaded whole (with a warning). Integers, decimals, timestamps, UUIDs and alphanumeric strings are supported. |
339
+ | `columns` | `{name: {"datatype": "<native type>", "transform_rule": "<sql>"}}` for every compared column, bisection columns included. Both keys are optional (see [When to declare a datatype](#when-to-declare-a-datatype) and [Comparing expressions](#comparing-expressions-transform_rule)). Paired with the other side by position. |
340
+ | `key_columns` | Columns identifying a logical row in the summary (default: `bisection_columns`). Used only to report differences; see [Keys and the per-key summary](#keys-and-the-per-key-summary). |
341
+ | `where` | Optional SQL filter added to every query, e.g. a time window. |
342
+
343
+ `diff_tables(src, tgt, ...)` options:
344
+
345
+ | Option | Default | Meaning |
346
+ | :--- | :--- | :--- |
347
+ | `bisection_columns`, `key_columns`, `where`, `min_key`, `max_key` | from the tables | override these on both sides |
348
+ | `bisection_factor` | 32 | ranges per split |
349
+ | `bisection_threshold` | 16384 | rows below which a range is downloaded |
350
+ | `threaded` / `max_threadpool_size` | `True` / 1 | run queries concurrently |
351
+ | `duplicate_rows_support` | `True` | count identical duplicate rows (needed when keys repeat) |
352
+ | `allow_empty_tables` | `False` | don't raise `EmptyTable` for empty sides |
353
+ | `skip_sort_results` | `False` | skip sorting the raw stream |
354
+ | `track_queries` / `return_queries` | `True` / `False` | record queries; also return the `QueryTracker` |
355
+
356
+ ### Types
357
+
358
+ The engine compares numbers, strings, timestamps/dates and booleans (hashed as `1`/`0`); `NULL` is `'<null>'` on
359
+ every side. LOB and binary types (`CLOB`, `BLOB`, `RAW`, `bytea`, …) are rejected on purpose: reduce them with a
360
+ `transform_rule`. When the two sides have different precisions (`TIMESTAMP(3)` vs `timestamp(6)`, `NUMBER(12,4)`
361
+ vs `numeric(12,2)`), both are compared at the lower one.
362
+
363
+ A decimal must have a scale, declared or reported: a plain Oracle `NUMBER` / `NUMBER(*)` or PostgreSQL `numeric`
364
+ (or any dialect's decimal type without arguments) is rejected, because the number of fractional digits to compare
365
+ is unknown. An engine that can't name the exact type of a column or expression makes it fail the same way,
366
+ instead of comparing it at a guessed precision. One exception is safe: psycopg2 doesn't report a PostgreSQL
367
+ timestamp's precision, so it takes 6, PostgreSQL's maximum. That never understates it, and the other side's lower
368
+ precision still wins.
150
369
 
151
370
  ## How it works
152
371
 
@@ -158,6 +377,9 @@ An existing `Database` can be passed to `connect_to_table()` instead of a URI, s
158
377
  4. **Download & compare**: only those small ranges are downloaded and compared in memory.
159
378
  5. **Summarize**: `summarize()` pairs the differing rows by `key_columns` (default: the bisection columns).
160
379
 
380
+ Before that, once per table and only for columns without a declared `datatype`, one query that returns no rows
381
+ (`SELECT <columns> FROM t WHERE 1=0`) reads their types from the driver's result metadata.
382
+
161
383
  For a table bisected on `(ORDER_ID, LINE_CODE)`, with columns `ORDER_ID NUMBER(12,0)` / `bigint`,
162
384
  `LINE_CODE VARCHAR2(20)` / `varchar(20)`, `UPDATED_AT TIMESTAMP(6)` / `timestamp(6)` and
163
385
  `UPDATED_BY VARCHAR2(30)` / `varchar(30)`, the checksum queries look like this. Oracle (database character set
@@ -194,25 +416,7 @@ WHERE ("order_id" >= 1405) AND (("line_code" COLLATE "C") >= 'A-001')
194
416
  AND ("order_id" < 2662) AND (("line_code" COLLATE "C") < 'K-250')
195
417
  ```
196
418
 
197
- ## Defining columns
198
-
199
- `TableSegment` (or `connect_to_table`) takes:
200
-
201
- | Argument | Meaning |
202
- | :--- | :--- |
203
- | `bisection_columns` | Columns that split the table into key ranges. Need not be unique, but should be selective and indexed: one value holding more rows than `bisection_threshold` can't be split and is downloaded whole (with a warning). Integers, decimals, timestamps, UUIDs and alphanumeric strings are supported. |
204
- | `columns` | `{name: {"datatype": "<native type>", "transform_rule": "<sql>"}}` for every compared column, bisection columns included. `transform_rule` replaces the column (wrapped in parentheses); `datatype` is then the type of the expression's result. |
205
- | `key_columns` | Columns identifying a logical row in the summary (default: `bisection_columns`). Used only to report differences; see [Keys and the per-key summary](#keys-and-the-per-key-summary). |
206
- | `where` | Optional SQL filter added to every query, e.g. a time window. |
207
-
208
- All problems with `columns` (missing datatype, unknown or unsupported type, bisection column not listed) are
209
- reported together in one `ValueError`.
210
-
211
- **Types.** The engine compares numbers, strings, timestamps/dates and booleans (hashed as `1`/`0`); `NULL` is
212
- `'<null>'` on every side. LOB and binary types (`CLOB`, `BLOB`, `RAW`, `bytea`, …) are rejected on purpose: reduce
213
- them with a `transform_rule` (e.g. a length). When the two sides declare different precisions, both are compared
214
- at the lower one. An unscaled decimal (Oracle `NUMBER`, PostgreSQL `numeric`) is compared as a whole number, with a
215
- warning; declare a scale on both sides (`NUMBER(12,2)` / `numeric(12,2)`) to compare decimals.
419
+ The only other query is Oracle's `NLS_CHARACTERSET` lookup, once per connection, unless `hash_charset` is given.
216
420
 
217
421
  ## Keys and the per-key summary
218
422
 
@@ -292,8 +496,8 @@ entries and `duplicate_keys` as the signal to look at the rows yourself.
292
496
 
293
497
  ## Background: from aggregate fingerprints to checksum bisection
294
498
 
295
- diffdb-core is the third iteration of my migration data-validation tooling. The first two are archived and kept
296
- for reference.
499
+ diffdb-core is the third iteration of my migration data-validation tooling, after `simple-dv-tool` and
500
+ `ibis-dv-tool`, and is built on reladiff's algorithm. The first two are archived and kept for reference.
297
501
 
298
502
  ### 1. simple-dv-tool: hand-written aggregate SQL
299
503
 
@@ -347,10 +551,11 @@ diffdb-core adapts reladiff's bisection engine (`HashDiffer`, segments, key-spac
347
551
 
348
552
  | | reladiff | diffdb-core |
349
553
  | :--- | :--- | :--- |
350
- | Column definitions | column **names** (`key_columns`, `extra_columns`); types read from the database | `columns={name: {"datatype", "transform_rule"}}` per side; nothing read from the database |
351
- | Metadata queries | reads `information_schema` and samples rows to refine types | none (except Oracle `NLS_CHARACTERSET`, once per connection) |
554
+ | Column definitions | column **names** (`key_columns`, `extra_columns`); types read from the database | column names per side, paired by position; types from the result metadata of a zero-row query, or declared; optional `transform_rule` per column |
555
+ | Metadata queries | reads `information_schema` and samples rows to refine types | no catalog reads: one `WHERE 1=0` probe per table for columns without a declared type, plus Oracle `NLS_CHARACTERSET` once per connection |
352
556
  | Compare an SQL expression | not supported (create a view) | `transform_rule` on any column, bisection columns included |
353
557
  | LOB / binary / unknown types | compared anyway, with a "may result in false positives" warning | rejected up front; reduce them with a `transform_rule` |
558
+ | Types an engine can't name exactly | sampled / guessed | rejected with the fix (declare the type, or `CAST`), never compared at a guessed precision |
354
559
  | Dialects | Python classes and mixins from [sqeleton](https://github.com/erezsh/sqeleton), SQL built by its query builder | one validated YAML file per database; SQL built as plain strings in `core/sql.py` |
355
560
  | Result | `+`/`-` row stream; `get_stats_dict()` counts | the same stream, plus `summarize()`: per-key, per-column results |
356
561
  | Duplicate keys in stats | a key with two differing rows on the same side fails an `assert` | reported as `duplicate_key`, with `duplicate_keys=True` |
@@ -362,28 +567,19 @@ diffdb-core adapts reladiff's bisection engine (`HashDiffer`, segments, key-spac
362
567
  ### `transform_rule`: comparing expressions, not just columns
363
568
 
364
569
  In reladiff a compared column is a name that must exist in the table's schema. To compare `TRIM(name)`, a CLOB's
365
- length, or a string key under binary collation, you have to create a view on each side first.
366
-
367
- In diffdb-core each column entry can carry a `transform_rule`, an SQL expression used instead of the column, and a
368
- `datatype` that describes the expression's result:
369
-
370
- ```python
371
- "NOTES": {"datatype": "NUMBER(10,0)", "transform_rule": 'DBMS_LOB.GETLENGTH("NOTES")'}, # Oracle CLOB
372
- "notes": {"datatype": "integer", "transform_rule": 'LENGTH("notes")'}, # PostgreSQL text
373
- "line_code": {"datatype": "varchar(20)", "transform_rule": '"line_code" COLLATE "C"'}, # byte-order bisection
374
- ```
570
+ length, or a string key under binary collation, you have to create a view on each side first. In diffdb-core each
571
+ column entry can carry a `transform_rule` (see [Comparing expressions](#comparing-expressions-transform_rule)):
375
572
 
376
- - The rule is wrapped in parentheses and used **everywhere** the column appears: in the checksum, the key-range
377
- `MIN`/`MAX`, the downloaded rows, and the key-range `WHERE` clauses when it's a bisection column (see the
378
- PostgreSQL query in [How it works](#how-it-works)).
573
+ - The rule is used **everywhere** the column appears, including the key-range `WHERE` clauses when it's a
574
+ bisection column (see the PostgreSQL query in [How it works](#how-it-works)).
379
575
  - Each side has its own rule, so the two sides can use different SQL to reach the same value.
380
- - The declared `datatype` drives normalization and precision reconciliation, so the result is hashed as the type
381
- you declared, not the column's original type.
576
+ - The result's type (declared, or reported by the database for the rule) drives normalization and precision
577
+ reconciliation, so the result is hashed as the expression's type, not the column's original type.
382
578
  - This is how unsupported types are handled: LOB and binary columns are rejected unless a rule reduces them to a
383
579
  number, string or timestamp. reladiff instead hashes them with a warning, which can report false differences.
384
580
 
385
581
  This is the same idea as ibis-dv-tool's editable `src_matched_cols` (where a source "column" could be a cast), now
386
- applied inside the hash, on both sides, with a declared type.
582
+ applied inside the hash, on both sides, with a known type.
387
583
 
388
584
  ### YAML dialect declarations
389
585
 
@@ -401,12 +597,12 @@ diffdb-core declares each dialect in one YAML file (`src/databases/dialects/<db>
401
597
  - **Validated when it loads**: unknown keys, unknown type classes and unknown template placeholders raise
402
598
  `DialectConfigError`, rather than producing wrong SQL at run time.
403
599
  - Engine-specific behaviour lives in YAML, not in `if name == ...` branches. The only Python per database is a small
404
- driver class (import and connection).
600
+ driver class (import, connection and, optionally, naming the types in the driver's result metadata).
405
601
  - Every dialect's generated SQL is pinned by golden snapshots (`tests/golden/`), so a YAML change that alters a
406
602
  query shows up as a test diff.
407
603
 
408
- Columns are also declared, not discovered: you pass the native `datatype` of each column, and the dialect's
409
- `type_classes` turn it into a diffdb type. That replaces reladiff's `information_schema` query and row sampling.
604
+ A column's native type (reported by the database, or declared) is turned into a diffdb type by the dialect's
605
+ `type_classes`. That replaces reladiff's `information_schema` query and row sampling.
410
606
 
411
607
  (This YAML is a dialect definition. It is different from reladiff's TOML file, which describes runs, and from
412
608
  ibis-dv-tool's YAML, which described the table mapping. diffdb-core has no run-config file.)
@@ -440,7 +636,8 @@ tables into memory: only the rows of mismatching segments are ever downloaded.
440
636
  fragments, type mapping and normalization templates. `_base.yaml` documents every key; unknown keys, type
441
637
  classes and template placeholders are rejected when the dialect loads.
442
638
  2. A small driver class in `src/databases/<db>.py` (driver import and connection creation), registered in
443
- `DATABASE_BY_SCHEME` (`src/databases/_connect.py`).
639
+ `DATABASE_BY_SCHEME` (`src/databases/_connect.py`). Optionally a `_native_type()` hook that names the type of
640
+ a `cursor.description` entry, so `datatype` can be left out on that database.
444
641
 
445
642
  The new dialect must render every value byte-identically to its counterpart. See
446
643
  [ARCHITECTURE.md](https://github.com/sarath-mec/diffdb-core/blob/main/ARCHITECTURE.md#4-declarative-yaml-dialect-framework).
@@ -1,31 +1,31 @@
1
- diffdb/__init__.py,sha256=IxU_8MgJW0ycl1sOrMSSqzxj3Nrr3OaQr-r7vuRv6j4,7599
2
- diffdb/types.py,sha256=oYGHaVCbaFpE3cLvITDgPIOm7XD9Bgy48ljBG4VhsMA,9927
1
+ diffdb/__init__.py,sha256=4jR4ECHD3zvaafHlgZNU07ZXo5uqvGk7zmEy2-z21iI,7599
2
+ diffdb/types.py,sha256=I_s8YY9JlNdBGb_2qrlTR-flrT_qOrA7bjky6lIm19Q,9923
3
3
  diffdb/utils.py,sha256=ia_5f2ZC9tUl0oR89fFexjyU9SMKKSfFPx7slsazmfo,2911
4
4
  diffdb/concurrency/__init__.py,sha256=R3quisr2f23EPhe0IgkldEwrbGgymG3nCbwGpj2sIJo,194
5
5
  diffdb/concurrency/pool.py,sha256=FGMeIB6XmN4WK5tXNLtHTPgmYsdHyBKR8G-sLJQxDKM,2909
6
6
  diffdb/concurrency/stream.py,sha256=_qffVEuhZS5JmVdP_xhtqU3NlG7L350i8bdydHOtUo4,3775
7
7
  diffdb/core/__init__.py,sha256=xdHLxcF-PUgxdNDn8zQzOtodmODt7mBZchrmlk69FGA,789
8
8
  diffdb/core/differ.py,sha256=MErq-JGiahiO3oBNsyHrVaduuatHNuia17F5Ht7_OF4,5412
9
- diffdb/core/hash_differ.py,sha256=aoi5Ae4SAwpdNxwGUT9TUsg9g_b_aKJBi2_XQfSI6wc,18336
10
- diffdb/core/segment.py,sha256=-lnHIOezd0f2WQ2d4ySIIc8DKhqX1hPzqHMtI8IFXX8,14904
11
- diffdb/core/sql.py,sha256=UThlUTr37917hsfzyubMG0eGAInsyGdnJREwfkKWacU,3342
9
+ diffdb/core/hash_differ.py,sha256=rqXCK_eOlZFawFmmrd0yvWv6mF5X73_7hBU7JMjd3uA,17543
10
+ diffdb/core/segment.py,sha256=paw1esBUWcerZkC8vgNU7yiwFdOvyIHN59i1_cnUbfI,19803
11
+ diffdb/core/sql.py,sha256=kYSJzUMNTlqkqUQ7D9bLfCUKTLshjIFKanjn00rpmEo,3950
12
12
  diffdb/core/summary.py,sha256=nDozOCpBybrMcHzGcgyVn_D8nozcP8pMZ0JbNclixY8,6922
13
13
  diffdb/databases/__init__.py,sha256=uzzoY2Q93X6vEPdniCsj7_pWoxVc7GeBgOGtLyuFgCE,1201
14
14
  diffdb/databases/_connect.py,sha256=beHHv3sNcuU4r8kSMsFpDjwaE_hCEUS2mkkJ8z7id_M,6854
15
- diffdb/databases/base.py,sha256=-vEGzFX12NcZlnbMWY_Fqidxnfdt-yIGyJ8vruSJ3Lw,8666
15
+ diffdb/databases/base.py,sha256=GoEFlkfGCSJRopRGxANecxx9AVtolZCtYSV97HjPrfE,10912
16
16
  diffdb/databases/bigquery.py,sha256=mDk_C2PJGu1avVl_hj0r95xYiVTT2PsJaAJrvvVzLVk,1464
17
17
  diffdb/databases/clickhouse.py,sha256=rbcqZMmbK0SNhklcAnWmIDQ18aMpXERJVERM0IiT7ws,1014
18
18
  diffdb/databases/databricks.py,sha256=Kq15SnUFaYFMGNU9LwiQqbnW1AwrM-rYMN7KQ4AgAEY,1040
19
- diffdb/databases/duckdb.py,sha256=BjbsiSEAEC1HuxQ0VgGuweE80Y2N4EIWI4E1lholxcc,922
19
+ diffdb/databases/duckdb.py,sha256=IFVCAY2D5J4AvA8e8oD9xgoeqP881PKW3teBkPtcV2c,1201
20
20
  diffdb/databases/mysql.py,sha256=TOi00N1ZHaeINEufwXUX8_egckdksvBfYuGD3-PJh4I,1075
21
- diffdb/databases/oracle.py,sha256=qJGfyiv7sgtWbW3jhX-45FZ2gN2YOzFA70TO1Hb-t7I,4132
22
- diffdb/databases/postgresql.py,sha256=OdpgKVgGp5CFg_dFc0k1TRHZ-QXF40hJRq5IvYrj8YA,948
21
+ diffdb/databases/oracle.py,sha256=QANDB-ha3nX45_fUNIXIpMuSNIzit-rxg38mNiN3ZOc,6020
22
+ diffdb/databases/postgresql.py,sha256=RvXXziNZ7OHn5FHzQXtos12OGVy-0UhEqiMr1iN_E9s,3149
23
23
  diffdb/databases/presto.py,sha256=-7fiFR4B5Bu0J2VgAHlv9btU_l1FMV0T4GnQ3UuHDiw,977
24
- diffdb/databases/redshift.py,sha256=uiVP9Qw5KEA2Rm2qdo6nZOiTUWn-SNZsprOdj_oTfaw,303
24
+ diffdb/databases/redshift.py,sha256=VSxZnzJT0Ya7WtVclyuFQugJZ6c0qi92ZONF-J5050c,474
25
25
  diffdb/databases/snowflake.py,sha256=Cpb_EyjbfmVIBbzr0BMtWU4mwHiqEQmJznnj_DFTB7Y,2074
26
26
  diffdb/databases/trino.py,sha256=UxI7MQWFiBAEHv3VCkxdgiERQLeeJZqPUXoBguTSLxU,956
27
27
  diffdb/databases/vertica.py,sha256=uOql6twPLBv3gDKXqL5V1SmWBzjMGMweOyDZUdD-P_c,1106
28
- diffdb/databases/yaml_dialect.py,sha256=0wS4HpFx5RePCoq5BouyBZGszLwo7LWZgMEJMVB35ac,18891
28
+ diffdb/databases/yaml_dialect.py,sha256=HgESHZjK7b2TgyA0sirXYffnQ1HfOCKMCYQbhW3tlPk,18907
29
29
  diffdb/databases/dialects/_base.yaml,sha256=r6w0QBYtmpBa7tKMNWx2vU6Tjt6-C9KqZu77aGXyMwY,10508
30
30
  diffdb/databases/dialects/bigquery.yaml,sha256=Oy0VRenuvrGvEQgZgFM3TW6hvtD96WwQMAymKMyWiXA,1185
31
31
  diffdb/databases/dialects/clickhouse.yaml,sha256=2PG-lrgh0UFq6bWj-hCxjfD4O6Ts7eD-HGMSmgSIvHY,960
@@ -46,8 +46,8 @@ diffdb/geometry/vector.py,sha256=27ok3tu-DpnOQXs8HfVWBMSKWl3HI9W9KSk3AuHrMuE,151
46
46
  diffdb/telemetry/__init__.py,sha256=LQDy9L2cF3WqZkQbGE12HHXcMNpNIirplzxZKWJMqrQ,239
47
47
  diffdb/telemetry/info_tree.py,sha256=nqt9IGLdy0x3WLevhYd8AsTiflIH26hsuLNF2Sm4BzE,1521
48
48
  diffdb/telemetry/query_tracker.py,sha256=wK4Q3ERcCudkJsjpkaONqS-UEjEEAPuobHOupJS_nKs,1692
49
- diffdb_core-0.1.2.dist-info/licenses/LICENSE.md,sha256=BhpQu7Vh18Qd-5AmNYVqaeUSvHWTk1n_9atj9r4kRhs,3701
50
- diffdb_core-0.1.2.dist-info/METADATA,sha256=0eSttn01MUjUI_oXzXkzdXGzRtenm0yJ--_t43xOIrU,27545
51
- diffdb_core-0.1.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
52
- diffdb_core-0.1.2.dist-info/top_level.txt,sha256=34BdAwNkIALSU7RVEmtdtebfvtoIdf1ruWC7ByXO2H4,7
53
- diffdb_core-0.1.2.dist-info/RECORD,,
49
+ diffdb_core-0.2.0.dist-info/licenses/LICENSE.md,sha256=BhpQu7Vh18Qd-5AmNYVqaeUSvHWTk1n_9atj9r4kRhs,3701
50
+ diffdb_core-0.2.0.dist-info/METADATA,sha256=gN21oJsLcUnN_WENDF0szJBSBoraZ7kQX37YAsa_IFQ,38656
51
+ diffdb_core-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
52
+ diffdb_core-0.2.0.dist-info/top_level.txt,sha256=34BdAwNkIALSU7RVEmtdtebfvtoIdf1ruWC7ByXO2H4,7
53
+ diffdb_core-0.2.0.dist-info/RECORD,,