datadouble-postgres 0.0.3__tar.gz → 0.0.5__tar.gz

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.
Files changed (20) hide show
  1. {datadouble_postgres-0.0.3 → datadouble_postgres-0.0.5}/PKG-INFO +45 -1
  2. {datadouble_postgres-0.0.3 → datadouble_postgres-0.0.5}/README.md +44 -0
  3. {datadouble_postgres-0.0.3 → datadouble_postgres-0.0.5}/pyproject.toml +16 -4
  4. {datadouble_postgres-0.0.3 → datadouble_postgres-0.0.5}/src/datadouble_postgres/__init__.py +1 -0
  5. {datadouble_postgres-0.0.3 → datadouble_postgres-0.0.5}/src/datadouble_postgres/errors.py +71 -4
  6. {datadouble_postgres-0.0.3 → datadouble_postgres-0.0.5}/src/datadouble_postgres/introspect.py +70 -8
  7. datadouble_postgres-0.0.5/src/datadouble_postgres/profile.py +205 -0
  8. {datadouble_postgres-0.0.3 → datadouble_postgres-0.0.5}/src/datadouble_postgres/render.py +20 -5
  9. {datadouble_postgres-0.0.3 → datadouble_postgres-0.0.5}/src/datadouble_postgres/source.py +44 -7
  10. {datadouble_postgres-0.0.3 → datadouble_postgres-0.0.5}/src/datadouble_postgres/working.py +239 -56
  11. {datadouble_postgres-0.0.3 → datadouble_postgres-0.0.5}/tests/test_cluster.py +32 -1
  12. {datadouble_postgres-0.0.3 → datadouble_postgres-0.0.5}/tests/test_conformance.py +1 -0
  13. {datadouble_postgres-0.0.3 → datadouble_postgres-0.0.5}/tests/test_postgres.py +368 -6
  14. datadouble_postgres-0.0.5/tests/test_profile.py +168 -0
  15. {datadouble_postgres-0.0.3 → datadouble_postgres-0.0.5}/tests/test_render.py +13 -0
  16. {datadouble_postgres-0.0.3 → datadouble_postgres-0.0.5}/.gitignore +0 -0
  17. {datadouble_postgres-0.0.3 → datadouble_postgres-0.0.5}/LICENSE +0 -0
  18. {datadouble_postgres-0.0.3 → datadouble_postgres-0.0.5}/src/datadouble_postgres/cluster.py +0 -0
  19. {datadouble_postgres-0.0.3 → datadouble_postgres-0.0.5}/src/datadouble_postgres/py.typed +0 -0
  20. {datadouble_postgres-0.0.3 → datadouble_postgres-0.0.5}/tests/test_sources.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: datadouble-postgres
3
- Version: 0.0.3
3
+ Version: 0.0.5
4
4
  Summary: PostgreSQL engine adapter for Datadouble
5
5
  Project-URL: Homepage, https://datadouble.tightlinesoftware.com/
6
6
  Project-URL: Source, https://github.com/datadouble/datadouble
@@ -31,6 +31,14 @@ PostgreSQL image of the source's exact version, through the spec's container
31
31
  runtime; a source that uses extensions names an image that has them in
32
32
  `sources.<name>.image`.
33
33
 
34
+ A physical image is the data directory of a fresh cluster that each
35
+ database's dump was restored into, never the working cluster's own files,
36
+ whose old row versions and write-ahead log still hold replaced values. The
37
+ fresh cluster gets each extension at the working cluster's version and its
38
+ `ALTER SYSTEM` settings (`postgresql.auto.conf`); roles, and `ALTER DATABASE ... SET` and
39
+ `ALTER ROLE ... SET` settings, don't come along. See
40
+ [what a physical image holds](https://datadouble.tightlinesoftware.com/architecture/#what-a-physical-image-holds).
41
+
34
42
  ## Accounts
35
43
 
36
44
  A physical image carries no account that logs in over the network, so a
@@ -187,6 +195,19 @@ requirement at the version the source runs (`pg_extension.extversion`).
187
195
  - **A managed service's own extensions** (`aws_s3`, `aws_commons`,
188
196
  `rds_tools`, `google_ml_integration`, `azure`) are in no public image.
189
197
  Leave them out with `sources.<name>.omit`, and exclude whatever uses them.
198
+ - **Configuration tables are copied.** An extension's configuration tables
199
+ (`pg_extension.extconfig`, such as `pg_cron`'s `cron.job`) are in the
200
+ catalog, so seeds, `exclude`, `structure_only` and `anonymize` rules apply
201
+ to them. Rows are read through the extension's `extcondition`, which keeps
202
+ out the rows the extension inserts itself, and loaded into the tables
203
+ `CREATE EXTENSION` made. A sequence in `extconfig` is set past the rows of
204
+ the column whose default uses it. An excluded configuration table keeps
205
+ only the extension's own rows. When you omit an extension, exclude its
206
+ configuration tables too, or the plan fails naming them. `cron.job.command` can hold credentials, and its
207
+ `database` and `username` columns name the source's database and roles, so
208
+ anonymize them, and set `active` to false unless copies should run the
209
+ jobs. A source role without superuser or `BYPASSRLS` reads only its own
210
+ jobs through `cron.job`'s row-level security.
190
211
  - **Logical images** restore with `pg_restore`, which creates extensions at
191
212
  the restoring server's default version.
192
213
 
@@ -208,6 +229,16 @@ sources:
208
229
  `sources.<name>.server` takes `shared_preload_libraries`, a list of library names.
209
230
  Nothing else.
210
231
 
232
+ ## Anonymizing
233
+
234
+ `transform` runs each table's rules as one `UPDATE`, in
235
+ [chunks](https://datadouble.tightlinesoftware.com/anonymization/#large-tables)
236
+ of `transform.chunk_rows` rows when the table's primary key is a single
237
+ integer column that no rule changes. Every statement commits on its own. The
238
+ session runs with `session_replication_role = replica`, so triggers and
239
+ foreign key checks stay off. Temporary tables of replacements for value rules
240
+ last across a table's chunks and are dropped when it is done.
241
+
211
242
  ## Objects
212
243
 
213
244
  The catalog lists functions and procedures (by name and argument types),
@@ -247,3 +278,16 @@ function in the group's `objects` keeps it. A trigger is dropped on the
247
278
  table or view the database says it is on, and one already gone with its
248
279
  table or view is skipped. Foreign keys into a pulled-in table without rows are
249
280
  left out. Schemas stay, even when nothing in them is kept.
281
+
282
+ ## Discover
283
+
284
+ `datadouble discover` profiles a PostgreSQL source with read-only queries,
285
+ each limited by `statement_timeout`, in a session set to UTC with ISO dates. Row and size estimates come from
286
+ `pg_class`, summed over a partitioned table's partitions; a table never
287
+ analyzed has no row estimate. A table estimated at over 100,000 rows is
288
+ sampled by page with `TABLESAMPLE SYSTEM`; a smaller one is read whole. The
289
+ rows are then picked at random. Window counts and newest values are read
290
+ only for columns that lead a valid, non-partial B-tree index, and newest
291
+ values ignore `infinity`. PostgreSQL has no last-write time, and can't check an inferred
292
+ reference between two databases, so neither is reported. See
293
+ [discovering what to copy](https://datadouble.tightlinesoftware.com/using/discover/).
@@ -10,6 +10,14 @@ PostgreSQL image of the source's exact version, through the spec's container
10
10
  runtime; a source that uses extensions names an image that has them in
11
11
  `sources.<name>.image`.
12
12
 
13
+ A physical image is the data directory of a fresh cluster that each
14
+ database's dump was restored into, never the working cluster's own files,
15
+ whose old row versions and write-ahead log still hold replaced values. The
16
+ fresh cluster gets each extension at the working cluster's version and its
17
+ `ALTER SYSTEM` settings (`postgresql.auto.conf`); roles, and `ALTER DATABASE ... SET` and
18
+ `ALTER ROLE ... SET` settings, don't come along. See
19
+ [what a physical image holds](https://datadouble.tightlinesoftware.com/architecture/#what-a-physical-image-holds).
20
+
13
21
  ## Accounts
14
22
 
15
23
  A physical image carries no account that logs in over the network, so a
@@ -166,6 +174,19 @@ requirement at the version the source runs (`pg_extension.extversion`).
166
174
  - **A managed service's own extensions** (`aws_s3`, `aws_commons`,
167
175
  `rds_tools`, `google_ml_integration`, `azure`) are in no public image.
168
176
  Leave them out with `sources.<name>.omit`, and exclude whatever uses them.
177
+ - **Configuration tables are copied.** An extension's configuration tables
178
+ (`pg_extension.extconfig`, such as `pg_cron`'s `cron.job`) are in the
179
+ catalog, so seeds, `exclude`, `structure_only` and `anonymize` rules apply
180
+ to them. Rows are read through the extension's `extcondition`, which keeps
181
+ out the rows the extension inserts itself, and loaded into the tables
182
+ `CREATE EXTENSION` made. A sequence in `extconfig` is set past the rows of
183
+ the column whose default uses it. An excluded configuration table keeps
184
+ only the extension's own rows. When you omit an extension, exclude its
185
+ configuration tables too, or the plan fails naming them. `cron.job.command` can hold credentials, and its
186
+ `database` and `username` columns name the source's database and roles, so
187
+ anonymize them, and set `active` to false unless copies should run the
188
+ jobs. A source role without superuser or `BYPASSRLS` reads only its own
189
+ jobs through `cron.job`'s row-level security.
169
190
  - **Logical images** restore with `pg_restore`, which creates extensions at
170
191
  the restoring server's default version.
171
192
 
@@ -187,6 +208,16 @@ sources:
187
208
  `sources.<name>.server` takes `shared_preload_libraries`, a list of library names.
188
209
  Nothing else.
189
210
 
211
+ ## Anonymizing
212
+
213
+ `transform` runs each table's rules as one `UPDATE`, in
214
+ [chunks](https://datadouble.tightlinesoftware.com/anonymization/#large-tables)
215
+ of `transform.chunk_rows` rows when the table's primary key is a single
216
+ integer column that no rule changes. Every statement commits on its own. The
217
+ session runs with `session_replication_role = replica`, so triggers and
218
+ foreign key checks stay off. Temporary tables of replacements for value rules
219
+ last across a table's chunks and are dropped when it is done.
220
+
190
221
  ## Objects
191
222
 
192
223
  The catalog lists functions and procedures (by name and argument types),
@@ -226,3 +257,16 @@ function in the group's `objects` keeps it. A trigger is dropped on the
226
257
  table or view the database says it is on, and one already gone with its
227
258
  table or view is skipped. Foreign keys into a pulled-in table without rows are
228
259
  left out. Schemas stay, even when nothing in them is kept.
260
+
261
+ ## Discover
262
+
263
+ `datadouble discover` profiles a PostgreSQL source with read-only queries,
264
+ each limited by `statement_timeout`, in a session set to UTC with ISO dates. Row and size estimates come from
265
+ `pg_class`, summed over a partitioned table's partitions; a table never
266
+ analyzed has no row estimate. A table estimated at over 100,000 rows is
267
+ sampled by page with `TABLESAMPLE SYSTEM`; a smaller one is read whole. The
268
+ rows are then picked at random. Window counts and newest values are read
269
+ only for columns that lead a valid, non-partial B-tree index, and newest
270
+ values ignore `infinity`. PostgreSQL has no last-write time, and can't check an inferred
271
+ reference between two databases, so neither is reported. See
272
+ [discovering what to copy](https://datadouble.tightlinesoftware.com/using/discover/).
@@ -3,9 +3,8 @@
3
3
 
4
4
  [project]
5
5
  name = "datadouble-postgres"
6
- # All packages share one version until 1.0 (decision 38); scripts/make_tag.py
7
- # sets it at release time.
8
- version = "0.0.3"
6
+ # Every package takes its version from the release tag (decision 165).
7
+ dynamic = ["version"]
9
8
  description = "PostgreSQL engine adapter for Datadouble"
10
9
  readme = "README.md"
11
10
  license = "MIT"
@@ -31,8 +30,21 @@ Source = "https://github.com/datadouble/datadouble"
31
30
  postgres = "datadouble_postgres:engine"
32
31
 
33
32
  [build-system]
34
- requires = ["hatchling>=1.33.0"]
33
+ requires = ["hatchling>=1.33.0", "hatch-vcs>=0.5.0"]
35
34
  build-backend = "hatchling.build"
36
35
 
36
+ # The version comes from `git describe`: the tag's on a tagged commit, and a
37
+ # development version such as 0.0.5.dev3+gabc1234 anywhere else. A build with
38
+ # no Git history (a Docker build) gets 0.0.0.dev0 unless the build sets
39
+ # SETUPTOOLS_SCM_PRETEND_VERSION.
40
+ [tool.hatch.version]
41
+ source = "vcs"
42
+ fallback-version = "0.0.0.dev0"
43
+ raw-options = { search_parent_directories = true }
44
+
45
+ # Reinstall when the commit or tags change, so the installed version follows.
46
+ [tool.uv]
47
+ cache-keys = [{ file = "pyproject.toml" }, { git = { commit = true, tags = true } }]
48
+
37
49
  [tool.hatch.build.targets.wheel]
38
50
  packages = ["src/datadouble_postgres"]
@@ -115,6 +115,7 @@ class PostgresEngine:
115
115
  return Capabilities(
116
116
  formats=(ImageFormat.PHYSICAL, ImageFormat.LOGICAL),
117
117
  expressions=True,
118
+ json_text=True,
118
119
  nested=True,
119
120
  accounts=AccountNames(
120
121
  max_bytes=63,
@@ -6,13 +6,15 @@
6
6
  PostgreSQL messages can quote the data that caused them (a duplicate key, a
7
7
  value that does not parse). Messages leaving this adapter keep the SQLSTATE,
8
8
  the primary message with data values hidden, and the names of the objects
9
- involved, which are identifiers rather than data (decisions 54 and 139).
9
+ involved, which are identifiers rather than data (decisions 54 and 139). The
10
+ SQLSTATE comes with its condition name and a plain explanation where the
11
+ adapter knows them (decision 158).
10
12
  """
11
13
 
12
14
  import psycopg
13
15
 
14
16
  from datadouble.engine import EngineError
15
- from datadouble.redaction import Redactor, kinds
17
+ from datadouble.redaction import Meaning, Redactor, kinds, labelled
16
18
  from datadouble.runtime import runtime_failure
17
19
 
18
20
  _NOISE = ("DETAIL:", "CONTEXT:", "HINT:", "LINE ", "QUERY:", "STATEMENT:")
@@ -66,6 +68,68 @@ _NAMES = (
66
68
  # language (``PL/Python function "f"``), and psql and pg_restore print it.
67
69
  _RAISED = (r"\bP0001\b", r"\bPL/\w+")
68
70
 
71
+ # What the common SQLSTATEs mean: the condition name PL/pgSQL uses for each,
72
+ # and a plain explanation, added to the message.
73
+ _MEANINGS = {
74
+ "0A000": Meaning(
75
+ "the server does not support what the statement asks", "feature_not_supported"
76
+ ),
77
+ "08006": Meaning("the connection to the server failed", "connection_failure"),
78
+ "22001": Meaning("a value is longer than the column allows", "string_data_right_truncation"),
79
+ "22003": Meaning("a value is outside the range of its type", "numeric_value_out_of_range"),
80
+ "22007": Meaning(
81
+ "a date or time is not in a format the server reads", "invalid_datetime_format"
82
+ ),
83
+ "22008": Meaning("a date or time field is out of range", "datetime_field_overflow"),
84
+ "22012": Meaning("an expression divided by zero", "division_by_zero"),
85
+ "22021": Meaning(
86
+ "a string's bytes are not valid in the database's encoding", "character_not_in_repertoire"
87
+ ),
88
+ "22P02": Meaning("a value does not convert to its type", "invalid_text_representation"),
89
+ "23502": Meaning("a NOT NULL column was given NULL", "not_null_violation"),
90
+ "23503": Meaning(
91
+ "a row refers to a missing parent row, or a referenced row was removed",
92
+ "foreign_key_violation",
93
+ ),
94
+ "23505": Meaning("a row repeats the value of a unique key", "unique_violation"),
95
+ "23514": Meaning("a row fails a CHECK constraint", "check_violation"),
96
+ "25P02": Meaning(
97
+ "an earlier statement in the transaction failed, so the server refuses the rest",
98
+ "in_failed_sql_transaction",
99
+ ),
100
+ "28P01": Meaning("the server refused the user name or password", "invalid_password"),
101
+ "2BP01": Meaning(
102
+ "other objects depend on the object being dropped", "dependent_objects_still_exist"
103
+ ),
104
+ "3D000": Meaning("no database has that name", "invalid_catalog_name"),
105
+ "40P01": Meaning(
106
+ "two sessions waited for each other's locks; the server cancelled this one",
107
+ "deadlock_detected",
108
+ ),
109
+ "428C9": Meaning(
110
+ "a statement gave a value to a generated column, which the server computes from"
111
+ " other columns; an anonymization rule cannot name one, so anonymize the columns"
112
+ " it is computed from",
113
+ "generated_always",
114
+ ),
115
+ "42501": Meaning("the role lacks a privilege the statement needs", "insufficient_privilege"),
116
+ "42601": Meaning("the server could not parse a statement", "syntax_error"),
117
+ "42701": Meaning("a definition names a column twice", "duplicate_column"),
118
+ "42703": Meaning("no column has that name", "undefined_column"),
119
+ "42704": Meaning("no object of that kind has that name", "undefined_object"),
120
+ "42710": Meaning("an object of that name exists already", "duplicate_object"),
121
+ "42804": Meaning("an expression's type does not match the column's", "datatype_mismatch"),
122
+ "42883": Meaning("no function or operator takes those argument types", "undefined_function"),
123
+ "42P01": Meaning("no table or view has that name", "undefined_table"),
124
+ "42P07": Meaning("a table of that name exists already", "duplicate_table"),
125
+ "53100": Meaning("the server's disk is full", "disk_full"),
126
+ "53200": Meaning("the server ran out of memory", "out_of_memory"),
127
+ "55P03": Meaning("a lock another session holds was not granted in time", "lock_not_available"),
128
+ "57014": Meaning("the statement was cancelled, by a timeout or an operator", "query_canceled"),
129
+ "57P01": Meaning("the server is shutting down", "admin_shutdown"),
130
+ }
131
+ _USER_RAISED = Meaning("a function or trigger raised this error itself")
132
+
69
133
  redact = Redactor(values=_VALUES, names=_NAMES, marks="\"'", raised=_RAISED)
70
134
  """Hide the data values in a PostgreSQL message, keeping the objects it names."""
71
135
 
@@ -86,8 +150,11 @@ def database_error(error: psycopg.Error, action: str) -> EngineError:
86
150
  if value
87
151
  ]
88
152
  where = f" ({', '.join(names)})" if names else ""
89
- code = f"[{diag.sqlstate}] " if diag.sqlstate else ""
90
- return EngineError(f"{action} failed: {code}{primary}{where}")
153
+ # A raised error's SQLSTATE is whatever its author chose, so it means only that.
154
+ meaning = _USER_RAISED if raised else _MEANINGS.get(diag.sqlstate or "")
155
+ if not diag.sqlstate:
156
+ return EngineError(f"{action} failed: {primary}{where}")
157
+ return EngineError(f"{action} failed: {labelled(diag.sqlstate, primary + where, meaning)}")
91
158
 
92
159
 
93
160
  def tool_error(tool: str, status: int, stderr: str) -> EngineError:
@@ -6,9 +6,14 @@
6
6
  Each database is read on its own connection, and its tables are named
7
7
  ``database.schema.table``. Tables are ordinary and partitioned tables outside the system schemas;
8
8
  partitions are represented by their partitioned root (a reference to a
9
- partition becomes a reference to its root), and tables owned by extensions are
10
- left out. Types are spelled with ``format_type`` under an
11
- empty search path, so user-defined types come out schema-qualified.
9
+ partition becomes a reference to its root). Tables owned by extensions are
10
+ left out, except their configuration tables: those an extension marks with
11
+ ``pg_extension_config_dump``, listed in ``pg_extension.extconfig``, such as
12
+ ``cron.job``. They hold the database's own settings, so they are tables like
13
+ any other, read through the condition the extension gave (``extcondition``),
14
+ which keeps out the rows the extension inserts itself. Types are spelled
15
+ with ``format_type`` under an empty search path, so user-defined types come
16
+ out schema-qualified.
12
17
 
13
18
  Every extension except ``plpgsql``, which every database has, is a
14
19
  requirement at the version the source runs.
@@ -32,7 +37,7 @@ own, so no edge crosses databases.
32
37
  """
33
38
 
34
39
  from collections import defaultdict
35
- from dataclasses import dataclass
40
+ from dataclasses import dataclass, field
36
41
 
37
42
  import psycopg
38
43
  from pydantic import BaseModel, ConfigDict
@@ -65,16 +70,43 @@ WHERE c.relkind IN ('r', 'p')
65
70
  AND n.nspname NOT IN ('pg_catalog', 'information_schema')
66
71
  AND n.nspname NOT LIKE 'pg\\_toast%'
67
72
  AND n.nspname NOT LIKE 'pg\\_temp%'
68
- AND NOT EXISTS (
73
+ AND (NOT EXISTS (
69
74
  SELECT 1 FROM pg_catalog.pg_depend d
70
75
  WHERE d.classid = 'pg_catalog.pg_class'::regclass AND d.objid = c.oid AND d.deptype = 'e'
71
- )
76
+ ) OR EXISTS (SELECT 1 FROM pg_catalog.pg_extension x WHERE c.oid = ANY(x.extconfig)))
72
77
  ORDER BY n.nspname, c.relname
73
78
  """
74
79
 
80
+ _CONFIGURATION = """
81
+ SELECT n.nspname, c.relname, x.extname, coalesce(u.condition, '')
82
+ FROM pg_catalog.pg_extension x
83
+ CROSS JOIN LATERAL unnest(x.extconfig, x.extcondition) AS u(relid, condition)
84
+ JOIN pg_catalog.pg_class c ON c.oid = u.relid
85
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
86
+ WHERE c.relkind IN ('r', 'p')
87
+ ORDER BY 1, 2
88
+ """
89
+ """Extensions' configuration tables, with the condition that picks the rows to copy."""
90
+
75
91
  _COLUMNS = """
76
92
  SELECT a.attrelid, a.attname, pg_catalog.format_type(a.atttypid, a.atttypmod),
77
- a.attnotnull, a.attgenerated <> '', bt.typname, bt.typcategory
93
+ a.attnotnull, a.attgenerated <> '', bt.typname, bt.typcategory,
94
+ -- A generated column depends on the columns its expression reads: the
95
+ -- column itself does on recent servers, its default entry on older ones.
96
+ CASE WHEN a.attgenerated <> '' THEN ARRAY(
97
+ SELECT ra.attname
98
+ FROM pg_catalog.pg_depend d
99
+ JOIN pg_catalog.pg_attribute ra
100
+ ON ra.attrelid = d.refobjid AND ra.attnum = d.refobjsubid
101
+ WHERE d.refclassid = 'pg_catalog.pg_class'::regclass AND d.refobjid = a.attrelid
102
+ AND d.refobjsubid > 0 AND d.refobjsubid <> a.attnum
103
+ AND ((d.classid = 'pg_catalog.pg_class'::regclass
104
+ AND d.objid = a.attrelid AND d.objsubid = a.attnum)
105
+ OR (d.classid = 'pg_catalog.pg_attrdef'::regclass AND d.objid IN (
106
+ SELECT ad.oid FROM pg_catalog.pg_attrdef ad
107
+ WHERE ad.adrelid = a.attrelid AND ad.adnum = a.attnum)))
108
+ GROUP BY ra.attnum, ra.attname
109
+ ORDER BY ra.attnum) END
78
110
  FROM pg_catalog.pg_attribute a
79
111
  JOIN pg_catalog.pg_type t ON t.oid = a.atttypid
80
112
  JOIN pg_catalog.pg_type bt ON bt.oid = CASE WHEN t.typtype = 'd' THEN t.typbasetype ELSE t.oid END
@@ -343,6 +375,9 @@ class Physical:
343
375
  """Generated columns, which COPY leaves out."""
344
376
  extensions: dict[str, tuple[Extension, ...]]
345
377
  """Each database's installed extensions, in the order they were created."""
378
+ configuration: dict[TableName, str] = field(default_factory=dict[TableName, str])
379
+ """Extensions' configuration tables, each with its ``extcondition``: a ``WHERE``
380
+ clause that keeps out the rows the extension inserts itself, or empty."""
346
381
 
347
382
  def merged(self, other: "Physical") -> "Physical":
348
383
  """This and another database's details together."""
@@ -350,6 +385,7 @@ class Physical:
350
385
  partitioned=self.partitioned | other.partitioned,
351
386
  generated={**self.generated, **other.generated},
352
387
  extensions={**self.extensions, **other.extensions},
388
+ configuration={**self.configuration, **other.configuration},
353
389
  )
354
390
 
355
391
 
@@ -372,12 +408,24 @@ def introspect(
372
408
  columns: defaultdict[int, list[Column]] = defaultdict(list)
373
409
  generated: defaultdict[TableName, set[ColumnName]] = defaultdict(set)
374
410
  cursor.execute(_COLUMNS, [oids])
375
- for relid, name, type_name, not_null, is_generated, base, category in cursor.fetchall():
411
+ for (
412
+ relid,
413
+ name,
414
+ type_name,
415
+ not_null,
416
+ is_generated,
417
+ base,
418
+ category,
419
+ sources,
420
+ ) in cursor.fetchall():
376
421
  column = Column(
377
422
  name=ColumnName(str(name)),
378
423
  type=str(type_name),
379
424
  kind=kind_of(str(base), str(category)),
380
425
  nullable=not not_null,
426
+ generated_from=(
427
+ tuple(ColumnName(n) for n in _strings(sources)) if is_generated else None
428
+ ),
381
429
  )
382
430
  columns[int(str(relid))].append(column)
383
431
  if is_generated:
@@ -421,6 +469,19 @@ def introspect(
421
469
  Extension(name=str(name), version=str(version), schema_=str(schema))
422
470
  for name, version, schema in cursor.fetchall()
423
471
  )
472
+ cursor.execute(_CONFIGURATION)
473
+ configured = [
474
+ (TableName.of(database, str(nsp), str(rel)), str(extension), str(condition))
475
+ for nsp, rel, extension, condition in cursor.fetchall()
476
+ ]
477
+ configuration = {name: condition for name, _, condition in configured}
478
+ made_by = {name: extension for name, extension, _ in configured}
479
+ table_list = [
480
+ table.model_copy(update={"made_by": made_by[table.name]})
481
+ if table.name in made_by
482
+ else table
483
+ for table in table_list
484
+ ]
424
485
  cursor.execute(
425
486
  "SELECT pg_catalog.set_config('search_path', %s, true)",
426
487
  [str(saved[0]) if saved else ""],
@@ -435,6 +496,7 @@ def introspect(
435
496
  partitioned=frozenset(name for name, kind in tables.values() if kind == "p"),
436
497
  generated={name: frozenset(cols) for name, cols in generated.items()},
437
498
  extensions={database: extensions},
499
+ configuration=configuration,
438
500
  )
439
501
  return catalog, physical
440
502
 
@@ -0,0 +1,205 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Profiling for ``datadouble discover``: bounded, read-only queries.
5
+
6
+ Every connection is set read-only, in UTC with ISO dates, with a
7
+ ``statement_timeout``, before the first query. Statistics come from
8
+ ``pg_class``, without reading rows. A sample takes a share of a table's pages
9
+ with ``TABLESAMPLE SYSTEM``, sized from the row estimate (every page of a
10
+ table estimated at 100,000 rows or fewer), and picks rows from them at random
11
+ up to the row limit. Counts and maximums on a time column are asked only for
12
+ columns that lead a valid, non-partial B-tree index. A reference is checked
13
+ only between tables of one database, since a query cannot read across
14
+ databases.
15
+ """
16
+
17
+ import datetime as dt
18
+ from collections.abc import Sequence
19
+
20
+ import psycopg
21
+ from psycopg import errors, sql
22
+
23
+ from datadouble.engine import (
24
+ ProfileTimeoutError,
25
+ SampleRow,
26
+ TableStats,
27
+ utc,
28
+ )
29
+ from datadouble.names import ColumnName, TableName
30
+ from datadouble_postgres.errors import database_error
31
+ from datadouble_postgres.render import Statement, database_of, unqualified
32
+
33
+ _STATS = """
34
+ SELECT n.nspname, c.relname,
35
+ CASE WHEN c.relkind = 'r' THEN
36
+ CASE WHEN c.reltuples < 0 THEN NULL ELSE c.reltuples::bigint END
37
+ ELSE (SELECT CASE WHEN bool_and(k.reltuples < 0) THEN NULL
38
+ ELSE sum(greatest(k.reltuples, 0))::bigint END
39
+ FROM pg_catalog.pg_partition_tree(c.oid) t
40
+ JOIN pg_catalog.pg_class k ON k.oid = t.relid
41
+ WHERE t.isleaf) END,
42
+ CASE WHEN c.relkind = 'r' THEN pg_catalog.pg_total_relation_size(c.oid)
43
+ ELSE (SELECT sum(pg_catalog.pg_total_relation_size(t.relid))::bigint
44
+ FROM pg_catalog.pg_partition_tree(c.oid) t) END
45
+ FROM pg_catalog.pg_class c
46
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
47
+ WHERE c.relkind IN ('r', 'p')
48
+ AND NOT c.relispartition
49
+ AND n.nspname NOT IN ('pg_catalog', 'information_schema')
50
+ AND n.nspname NOT LIKE 'pg\\_toast%'
51
+ AND n.nspname NOT LIKE 'pg\\_temp%'
52
+ ORDER BY 1, 2
53
+ """
54
+
55
+ _INDEXED = """
56
+ SELECT DISTINCT n.nspname, c.relname, a.attname
57
+ FROM pg_catalog.pg_index i
58
+ JOIN pg_catalog.pg_class c ON c.oid = i.indrelid
59
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
60
+ JOIN pg_catalog.pg_class x ON x.oid = i.indexrelid
61
+ JOIN pg_catalog.pg_am m ON m.oid = x.relam
62
+ JOIN pg_catalog.pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = i.indkey[0]
63
+ WHERE i.indkey[0] <> 0 AND m.amname = 'btree' AND i.indpred IS NULL AND i.indisvalid
64
+ AND n.nspname NOT IN ('pg_catalog', 'information_schema')
65
+ ORDER BY 1, 2, 3
66
+ """
67
+
68
+ _READ = 10
69
+ """A reference check reads at most ten times as many child rows as values it wants."""
70
+
71
+ _OVERSAMPLE = 4
72
+ """Pages are sampled for four times the rows wanted, since some pages hold few rows."""
73
+
74
+ _WHOLE = 100_000
75
+ """Tables estimated at this many rows or fewer are sampled from every page: a few pages of
76
+ a small table hold too few rows to say anything."""
77
+
78
+ type Connection = psycopg.Connection[tuple[object, ...]]
79
+
80
+
81
+ def _quoted(name: str) -> str:
82
+ return '"' + name.replace('"', '""') + '"'
83
+
84
+
85
+ class PostgresProfile:
86
+ """Implements :class:`datadouble.engine.Profile` over one connection per database."""
87
+
88
+ def __init__(self, connections: dict[str, Connection]) -> None:
89
+ """Profile through the source's connections, already read-only and time-limited."""
90
+ self.connections = connections
91
+
92
+ def fetch(
93
+ self, database: str, statement: Statement, params: Sequence[object], action: str
94
+ ) -> list[tuple[object, ...]]:
95
+ """Run one query in a database; a cancelled query is a :class:`ProfileTimeoutError`."""
96
+ try:
97
+ with self.connections[database].cursor() as cursor:
98
+ # Without parameters, a literal % in the query is not a placeholder.
99
+ cursor.execute(statement, params or None)
100
+ return cursor.fetchall() if cursor.description else []
101
+ except errors.QueryCanceled:
102
+ message = f"{action} ran past the time limit"
103
+ raise ProfileTimeoutError(message) from None
104
+ except psycopg.Error as error:
105
+ raise database_error(error, action) from None
106
+
107
+ def stats(self) -> tuple[TableStats, ...]:
108
+ """Estimated rows and size, and indexed leading columns, from the catalog."""
109
+ found: list[TableStats] = []
110
+ for database in self.connections:
111
+ indexed: dict[TableName, list[ColumnName]] = {}
112
+ for schema, name, column in self.fetch(
113
+ database, sql.SQL(_INDEXED), (), "reading indexes"
114
+ ):
115
+ table = TableName.of(database, str(schema), str(name))
116
+ indexed.setdefault(table, []).append(ColumnName(str(column)))
117
+ for schema, name, rows, size in self.fetch(
118
+ database, sql.SQL(_STATS), (), "reading table statistics"
119
+ ):
120
+ table = TableName.of(database, str(schema), str(name))
121
+ found.append(
122
+ TableStats(
123
+ table=table,
124
+ rows=None if rows is None else int(str(rows)),
125
+ bytes=None if size is None else int(str(size)),
126
+ indexed=tuple(indexed.get(table, ())),
127
+ )
128
+ )
129
+ return tuple(found)
130
+
131
+ def sample(
132
+ self, table: TableName, columns: tuple[ColumnName, ...], rows: int, estimate: int | None
133
+ ) -> Sequence[SampleRow]:
134
+ """Up to ``rows`` rows, as text, chosen at random from a sample of the table's pages."""
135
+ whole = estimate or 0
136
+ percent = 100.0 if whole <= _WHOLE else min(100.0, 100.0 * _OVERSAMPLE * rows / whole)
137
+ statement = sql.SQL(
138
+ "SELECT {} FROM {} TABLESAMPLE SYSTEM (%s) ORDER BY random() LIMIT %s"
139
+ ).format(
140
+ sql.SQL(", ").join(sql.SQL("{}::text").format(sql.Identifier(c)) for c in columns),
141
+ unqualified(table),
142
+ )
143
+ found = self.fetch(database_of(table), statement, (percent, rows), f"sampling {table}")
144
+ return [tuple(None if v is None else str(v) for v in row) for row in found]
145
+
146
+ def counts_since(
147
+ self, table: TableName, column: ColumnName, cutoffs: tuple[dt.datetime, ...]
148
+ ) -> tuple[int, ...]:
149
+ """Rows at or after each cutoff, counted in one range scan from the earliest."""
150
+ name = sql.Identifier(column)
151
+ counts = sql.SQL(", ").join(
152
+ sql.SQL("count(*) FILTER (WHERE {} >= %s)").format(name) for _ in cutoffs
153
+ )
154
+ statement = sql.SQL("SELECT {} FROM {} WHERE {} >= %s").format(
155
+ counts, unqualified(table), name
156
+ )
157
+ params = (*cutoffs, min(cutoffs))
158
+ found = self.fetch(database_of(table), statement, params, f"counting rows of {table}")
159
+ return tuple(int(str(value)) for value in found[0])
160
+
161
+ def newest(self, table: TableName, column: ColumnName) -> dt.datetime | None:
162
+ """The latest value of ``column``."""
163
+ statement = sql.SQL("SELECT max({0}) FILTER (WHERE isfinite({0})) FROM {1}").format(
164
+ sql.Identifier(column), unqualified(table)
165
+ )
166
+ found = self.fetch(database_of(table), statement, (), f"reading the newest {table} row")
167
+ return utc(found[0][0])
168
+
169
+ def matched(
170
+ self, child: TableName, column: ColumnName, parent: TableName, key: ColumnName, rows: int
171
+ ) -> tuple[int, int] | None:
172
+ """How many of a sample of the child's values the parent's key holds."""
173
+ if database_of(child) != database_of(parent):
174
+ return None
175
+ statement = sql.SQL(
176
+ "SELECT count(*), count(p.{key}) FROM (SELECT DISTINCT v FROM"
177
+ " (SELECT {column} AS v FROM (SELECT {column} FROM {child} LIMIT %s) r"
178
+ " WHERE {column} IS NOT NULL LIMIT %s) s) d"
179
+ " LEFT JOIN {parent} p ON p.{key} = d.v"
180
+ ).format(
181
+ key=sql.Identifier(key),
182
+ column=sql.Identifier(column),
183
+ child=unqualified(child),
184
+ parent=unqualified(parent),
185
+ )
186
+ action = f"checking {child}.{column} against {parent}"
187
+ found = self.fetch(database_of(child), statement, (rows * _READ, rows), action)
188
+ return int(str(found[0][0])), int(str(found[0][1]))
189
+
190
+ def since(self, column: ColumnName, days: int) -> str:
191
+ """``"created_at" >= :as_of - interval '30 days'``."""
192
+ return f"{_quoted(column)} >= :as_of - interval '{days} days'"
193
+
194
+
195
+ def prepare(connections: dict[str, Connection], timeout: int) -> PostgresProfile:
196
+ """Make every connection read-only, with each statement limited to ``timeout`` seconds."""
197
+ profile = PostgresProfile(connections)
198
+ limit = sql.SQL("SET statement_timeout = {}").format(sql.Literal(timeout * 1000))
199
+ for database in connections:
200
+ action = f"preparing {database} for profiling"
201
+ profile.fetch(database, sql.SQL("SET default_transaction_read_only = on"), (), action)
202
+ profile.fetch(database, limit, (), action)
203
+ profile.fetch(database, sql.SQL("SET TimeZone = 'UTC'"), (), action)
204
+ profile.fetch(database, sql.SQL("SET DateStyle = 'ISO, YMD'"), (), action)
205
+ return profile