datadouble-postgres 0.0.3__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.
- datadouble_postgres/__init__.py +192 -0
- datadouble_postgres/cluster.py +229 -0
- datadouble_postgres/errors.py +107 -0
- datadouble_postgres/introspect.py +542 -0
- datadouble_postgres/py.typed +0 -0
- datadouble_postgres/render.py +212 -0
- datadouble_postgres/source.py +380 -0
- datadouble_postgres/working.py +1003 -0
- datadouble_postgres-0.0.3.dist-info/METADATA +249 -0
- datadouble_postgres-0.0.3.dist-info/RECORD +13 -0
- datadouble_postgres-0.0.3.dist-info/WHEEL +4 -0
- datadouble_postgres-0.0.3.dist-info/entry_points.txt +2 -0
- datadouble_postgres-0.0.3.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,542 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""Reading a PostgreSQL catalog into Datadouble's engine-neutral model.
|
|
5
|
+
|
|
6
|
+
Each database is read on its own connection, and its tables are named
|
|
7
|
+
``database.schema.table``. Tables are ordinary and partitioned tables outside the system schemas;
|
|
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.
|
|
12
|
+
|
|
13
|
+
Every extension except ``plpgsql``, which every database has, is a
|
|
14
|
+
requirement at the version the source runs.
|
|
15
|
+
|
|
16
|
+
Objects are the functions and procedures, views and materialized views,
|
|
17
|
+
triggers, user-defined types (enums, domains, composite and range types) and
|
|
18
|
+
sequences outside the system schemas that no extension owns. Their
|
|
19
|
+
definitions come from ``pg_get_functiondef``, ``pg_get_viewdef`` and
|
|
20
|
+
``pg_get_triggerdef``, and from the catalog for types and sequences. Their
|
|
21
|
+
dependencies come from ``pg_depend``, which is exact for views, triggers,
|
|
22
|
+
types, sequences and routines with SQL-standard bodies; other routine bodies
|
|
23
|
+
(PL/pgSQL and the like) are parsed for names, and those edges are marked
|
|
24
|
+
inferred. A table needs the types of its columns (or a typed table's type),
|
|
25
|
+
the sequences and functions its defaults, check constraints and indexes
|
|
26
|
+
use, the functions and tables its row-level security policies use, and an
|
|
27
|
+
inheriting table its parent, from ``pg_depend`` too.
|
|
28
|
+
Objects are named ``database.schema.object`` like tables, and a
|
|
29
|
+
trigger ``database.schema.table.trigger``'s last part is ``table.trigger``,
|
|
30
|
+
since trigger names are only unique per table. Each database is read on its
|
|
31
|
+
own, so no edge crosses databases.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
from collections import defaultdict
|
|
35
|
+
from dataclasses import dataclass
|
|
36
|
+
|
|
37
|
+
import psycopg
|
|
38
|
+
from pydantic import BaseModel, ConfigDict
|
|
39
|
+
|
|
40
|
+
from datadouble.catalog import (
|
|
41
|
+
Catalog,
|
|
42
|
+
Column,
|
|
43
|
+
ColumnKind,
|
|
44
|
+
Dependency,
|
|
45
|
+
ForeignKey,
|
|
46
|
+
ObjectKind,
|
|
47
|
+
ObjectRef,
|
|
48
|
+
Requirement,
|
|
49
|
+
RequirementKind,
|
|
50
|
+
SourceObject,
|
|
51
|
+
Table,
|
|
52
|
+
definition_fingerprint,
|
|
53
|
+
)
|
|
54
|
+
from datadouble.names import ColumnName, EngineName, TableName
|
|
55
|
+
from datadouble.objects import Candidates, Dialect, infer_dependencies, merge
|
|
56
|
+
|
|
57
|
+
ENGINE = EngineName("postgres")
|
|
58
|
+
|
|
59
|
+
_TABLES = """
|
|
60
|
+
SELECT c.oid, n.nspname, c.relname, c.relkind
|
|
61
|
+
FROM pg_catalog.pg_class c
|
|
62
|
+
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
|
|
63
|
+
WHERE c.relkind IN ('r', 'p')
|
|
64
|
+
AND NOT c.relispartition
|
|
65
|
+
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
|
|
66
|
+
AND n.nspname NOT LIKE 'pg\\_toast%'
|
|
67
|
+
AND n.nspname NOT LIKE 'pg\\_temp%'
|
|
68
|
+
AND NOT EXISTS (
|
|
69
|
+
SELECT 1 FROM pg_catalog.pg_depend d
|
|
70
|
+
WHERE d.classid = 'pg_catalog.pg_class'::regclass AND d.objid = c.oid AND d.deptype = 'e'
|
|
71
|
+
)
|
|
72
|
+
ORDER BY n.nspname, c.relname
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
_COLUMNS = """
|
|
76
|
+
SELECT a.attrelid, a.attname, pg_catalog.format_type(a.atttypid, a.atttypmod),
|
|
77
|
+
a.attnotnull, a.attgenerated <> '', bt.typname, bt.typcategory
|
|
78
|
+
FROM pg_catalog.pg_attribute a
|
|
79
|
+
JOIN pg_catalog.pg_type t ON t.oid = a.atttypid
|
|
80
|
+
JOIN pg_catalog.pg_type bt ON bt.oid = CASE WHEN t.typtype = 'd' THEN t.typbasetype ELSE t.oid END
|
|
81
|
+
WHERE a.attrelid = ANY(%s) AND a.attnum > 0 AND NOT a.attisdropped
|
|
82
|
+
ORDER BY a.attrelid, a.attnum
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
_KEYS = """
|
|
86
|
+
SELECT con.conrelid, con.contype, con.conname, tn.nspname, tc.relname,
|
|
87
|
+
array_agg(a.attname ORDER BY k.ord), array_agg(fa.attname ORDER BY k.ord)
|
|
88
|
+
FROM pg_catalog.pg_constraint con
|
|
89
|
+
LEFT JOIN pg_catalog.pg_class tc
|
|
90
|
+
ON tc.oid = coalesce(pg_catalog.pg_partition_root(con.confrelid)::oid, con.confrelid)
|
|
91
|
+
LEFT JOIN pg_catalog.pg_namespace tn ON tn.oid = tc.relnamespace
|
|
92
|
+
CROSS JOIN LATERAL unnest(con.conkey, coalesce(con.confkey, con.conkey))
|
|
93
|
+
WITH ORDINALITY AS k(attnum, fattnum, ord)
|
|
94
|
+
JOIN pg_catalog.pg_attribute a ON a.attrelid = con.conrelid AND a.attnum = k.attnum
|
|
95
|
+
LEFT JOIN pg_catalog.pg_attribute fa ON fa.attrelid = con.confrelid AND fa.attnum = k.fattnum
|
|
96
|
+
WHERE con.conrelid = ANY(%s) AND con.contype IN ('p', 'f') AND con.conparentid = 0
|
|
97
|
+
GROUP BY con.conrelid, con.contype, con.conname, tn.nspname, tc.relname
|
|
98
|
+
ORDER BY con.conrelid, con.conname
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
_EXTENSIONS = """
|
|
102
|
+
SELECT e.extname, e.extversion, n.nspname
|
|
103
|
+
FROM pg_catalog.pg_extension e
|
|
104
|
+
JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace
|
|
105
|
+
WHERE e.extname <> 'plpgsql'
|
|
106
|
+
ORDER BY e.oid
|
|
107
|
+
"""
|
|
108
|
+
|
|
109
|
+
_ROUTINES = """
|
|
110
|
+
SELECT 'pg_catalog.pg_proc'::regclass::oid, p.oid, n.nspname, p.proname, p.prokind,
|
|
111
|
+
'(' || pg_catalog.pg_get_function_identity_arguments(p.oid) || ')',
|
|
112
|
+
pg_catalog.pg_get_functiondef(p.oid),
|
|
113
|
+
CASE WHEN l.lanname IN ('c', 'internal') THEN '' ELSE p.prosrc END, l.lanname
|
|
114
|
+
FROM pg_catalog.pg_proc p
|
|
115
|
+
JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
|
|
116
|
+
JOIN pg_catalog.pg_language l ON l.oid = p.prolang
|
|
117
|
+
WHERE p.prokind IN ('f', 'p')
|
|
118
|
+
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
|
|
119
|
+
AND n.nspname NOT LIKE 'pg\\_toast%'
|
|
120
|
+
AND n.nspname NOT LIKE 'pg\\_temp%'
|
|
121
|
+
AND NOT EXISTS (
|
|
122
|
+
SELECT 1 FROM pg_catalog.pg_depend e
|
|
123
|
+
WHERE e.classid = 'pg_catalog.pg_proc'::regclass AND e.objid = p.oid AND e.deptype = 'e'
|
|
124
|
+
)
|
|
125
|
+
"""
|
|
126
|
+
|
|
127
|
+
_RELATIONS = """
|
|
128
|
+
SELECT 'pg_catalog.pg_class'::regclass::oid, c.oid, n.nspname, c.relname, c.relkind, NULL,
|
|
129
|
+
CASE c.relkind
|
|
130
|
+
WHEN 'S' THEN (
|
|
131
|
+
SELECT 'sequence ' || pg_catalog.format_type(s.seqtypid, NULL)
|
|
132
|
+
|| ' increment ' || s.seqincrement || ' minvalue ' || s.seqmin
|
|
133
|
+
|| ' maxvalue ' || s.seqmax || ' start ' || s.seqstart
|
|
134
|
+
|| ' cache ' || s.seqcache || CASE WHEN s.seqcycle THEN ' cycle' ELSE '' END
|
|
135
|
+
FROM pg_catalog.pg_sequence s WHERE s.seqrelid = c.oid)
|
|
136
|
+
ELSE pg_catalog.pg_get_viewdef(c.oid)
|
|
137
|
+
END,
|
|
138
|
+
'', ''
|
|
139
|
+
FROM pg_catalog.pg_class c
|
|
140
|
+
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
|
|
141
|
+
WHERE c.relkind IN ('v', 'm', 'S')
|
|
142
|
+
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
|
|
143
|
+
AND n.nspname NOT LIKE 'pg\\_toast%'
|
|
144
|
+
AND n.nspname NOT LIKE 'pg\\_temp%'
|
|
145
|
+
AND NOT EXISTS (
|
|
146
|
+
SELECT 1 FROM pg_catalog.pg_depend e
|
|
147
|
+
WHERE e.classid = 'pg_catalog.pg_class'::regclass AND e.objid = c.oid AND e.deptype = 'e'
|
|
148
|
+
)
|
|
149
|
+
AND NOT EXISTS (
|
|
150
|
+
SELECT 1 FROM pg_catalog.pg_depend i
|
|
151
|
+
WHERE i.classid = 'pg_catalog.pg_class'::regclass AND i.objid = c.oid AND i.deptype = 'i'
|
|
152
|
+
)
|
|
153
|
+
"""
|
|
154
|
+
|
|
155
|
+
_TRIGGERS = """
|
|
156
|
+
SELECT 'pg_catalog.pg_trigger'::regclass::oid, t.oid, n.nspname,
|
|
157
|
+
c.relname || '.' || t.tgname, 'T', NULL, pg_catalog.pg_get_triggerdef(t.oid), '', ''
|
|
158
|
+
FROM pg_catalog.pg_trigger t
|
|
159
|
+
JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid
|
|
160
|
+
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
|
|
161
|
+
WHERE NOT t.tgisinternal AND (NOT c.relispartition OR t.tgparentid = 0)
|
|
162
|
+
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
|
|
163
|
+
AND n.nspname NOT LIKE 'pg\\_toast%'
|
|
164
|
+
AND n.nspname NOT LIKE 'pg\\_temp%'
|
|
165
|
+
"""
|
|
166
|
+
|
|
167
|
+
_TYPES = """
|
|
168
|
+
SELECT 'pg_catalog.pg_type'::regclass::oid, t.oid, n.nspname, t.typname, 't', NULL,
|
|
169
|
+
CASE t.typtype
|
|
170
|
+
WHEN 'e' THEN 'enum ' || (
|
|
171
|
+
SELECT pg_catalog.string_agg(pg_catalog.quote_literal(e.enumlabel), ', '
|
|
172
|
+
ORDER BY e.enumsortorder)
|
|
173
|
+
FROM pg_catalog.pg_enum e WHERE e.enumtypid = t.oid)
|
|
174
|
+
WHEN 'd' THEN 'domain ' || pg_catalog.format_type(t.typbasetype, t.typtypmod)
|
|
175
|
+
|| coalesce(' default ' || t.typdefault, '')
|
|
176
|
+
|| CASE WHEN t.typnotnull THEN ' not null' ELSE '' END
|
|
177
|
+
|| coalesce((
|
|
178
|
+
SELECT ' ' || pg_catalog.string_agg(pg_catalog.pg_get_constraintdef(k.oid), ' '
|
|
179
|
+
ORDER BY k.conname)
|
|
180
|
+
FROM pg_catalog.pg_constraint k WHERE k.contypid = t.oid), '')
|
|
181
|
+
WHEN 'c' THEN 'composite ' || (
|
|
182
|
+
SELECT pg_catalog.string_agg(
|
|
183
|
+
pg_catalog.quote_ident(a.attname) || ' '
|
|
184
|
+
|| pg_catalog.format_type(a.atttypid, a.atttypmod), ', ' ORDER BY a.attnum)
|
|
185
|
+
FROM pg_catalog.pg_attribute a
|
|
186
|
+
WHERE a.attrelid = t.typrelid AND a.attnum > 0 AND NOT a.attisdropped)
|
|
187
|
+
ELSE 'range ' || (
|
|
188
|
+
SELECT pg_catalog.format_type(r.rngsubtype, NULL)
|
|
189
|
+
FROM pg_catalog.pg_range r WHERE r.rngtypid = t.oid)
|
|
190
|
+
END,
|
|
191
|
+
'', ''
|
|
192
|
+
FROM pg_catalog.pg_type t
|
|
193
|
+
JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
|
|
194
|
+
WHERE (t.typtype IN ('e', 'd', 'r')
|
|
195
|
+
OR (t.typtype = 'c' AND (
|
|
196
|
+
SELECT c.relkind FROM pg_catalog.pg_class c WHERE c.oid = t.typrelid) = 'c'))
|
|
197
|
+
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
|
|
198
|
+
AND n.nspname NOT LIKE 'pg\\_toast%'
|
|
199
|
+
AND n.nspname NOT LIKE 'pg\\_temp%'
|
|
200
|
+
AND NOT EXISTS (
|
|
201
|
+
SELECT 1 FROM pg_catalog.pg_depend e
|
|
202
|
+
WHERE e.classid = 'pg_catalog.pg_type'::regclass AND e.objid = t.oid AND e.deptype = 'e'
|
|
203
|
+
)
|
|
204
|
+
"""
|
|
205
|
+
|
|
206
|
+
_CATALOG_OIDS = "SELECT 'pg_catalog.pg_class'::regclass::oid, 'pg_catalog.pg_type'::regclass::oid"
|
|
207
|
+
|
|
208
|
+
_PARTITIONS = """
|
|
209
|
+
SELECT c.oid, pg_catalog.pg_partition_root(c.oid)::oid
|
|
210
|
+
FROM pg_catalog.pg_class c
|
|
211
|
+
WHERE c.relispartition
|
|
212
|
+
"""
|
|
213
|
+
"""Each partition and its partitioned root, which stands for it."""
|
|
214
|
+
|
|
215
|
+
_TYPE_ALIASES = """
|
|
216
|
+
SELECT t.oid, t.typrelid, t.typelem, t.typcategory = 'A'
|
|
217
|
+
FROM pg_catalog.pg_type t
|
|
218
|
+
WHERE t.typrelid <> 0 OR t.typcategory = 'A'
|
|
219
|
+
ORDER BY t.typcategory = 'A', t.oid
|
|
220
|
+
"""
|
|
221
|
+
"""Row types stand for their relation, and array types for their element; row types
|
|
222
|
+
come first, so an array of a row type finds the relation."""
|
|
223
|
+
|
|
224
|
+
_DEPENDS = """
|
|
225
|
+
SELECT DISTINCT
|
|
226
|
+
CASE WHEN d.classid = 'pg_catalog.pg_rewrite'::regclass
|
|
227
|
+
THEN 'pg_catalog.pg_class'::regclass ELSE d.classid END::oid,
|
|
228
|
+
CASE WHEN d.classid = 'pg_catalog.pg_rewrite'::regclass THEN r.ev_class ELSE d.objid END,
|
|
229
|
+
d.refclassid::oid, d.refobjid
|
|
230
|
+
FROM pg_catalog.pg_depend d
|
|
231
|
+
LEFT JOIN pg_catalog.pg_rewrite r
|
|
232
|
+
ON d.classid = 'pg_catalog.pg_rewrite'::regclass AND r.oid = d.objid
|
|
233
|
+
WHERE d.deptype IN ('n', 'a')
|
|
234
|
+
AND d.classid IN ('pg_catalog.pg_proc'::regclass, 'pg_catalog.pg_class'::regclass,
|
|
235
|
+
'pg_catalog.pg_trigger'::regclass, 'pg_catalog.pg_type'::regclass,
|
|
236
|
+
'pg_catalog.pg_rewrite'::regclass)
|
|
237
|
+
AND d.refclassid IN ('pg_catalog.pg_proc'::regclass, 'pg_catalog.pg_class'::regclass,
|
|
238
|
+
'pg_catalog.pg_type'::regclass)
|
|
239
|
+
"""
|
|
240
|
+
"""Every normal and automatic dependency, a view's rule standing for the view."""
|
|
241
|
+
|
|
242
|
+
_TABLE_DEPENDS = """
|
|
243
|
+
SELECT DISTINCT n.relid, d.refclassid::oid, d.refobjid
|
|
244
|
+
FROM pg_catalog.pg_depend d
|
|
245
|
+
CROSS JOIN LATERAL (
|
|
246
|
+
SELECT CASE d.classid
|
|
247
|
+
WHEN 'pg_catalog.pg_class'::regclass THEN CASE
|
|
248
|
+
WHEN d.objsubid > 0 THEN d.objid
|
|
249
|
+
-- An index's expressions and predicate count as its table's; a typed
|
|
250
|
+
-- table needs its type, and an inheriting table its parent.
|
|
251
|
+
ELSE coalesce(
|
|
252
|
+
(SELECT i.indrelid FROM pg_catalog.pg_index i WHERE i.indexrelid = d.objid),
|
|
253
|
+
(SELECT c.oid FROM pg_catalog.pg_class c
|
|
254
|
+
WHERE c.oid = d.objid AND c.relkind IN ('r', 'p')))
|
|
255
|
+
END
|
|
256
|
+
WHEN 'pg_catalog.pg_policy'::regclass THEN (
|
|
257
|
+
SELECT p.polrelid FROM pg_catalog.pg_policy p WHERE p.oid = d.objid)
|
|
258
|
+
WHEN 'pg_catalog.pg_attrdef'::regclass THEN (
|
|
259
|
+
SELECT a.adrelid FROM pg_catalog.pg_attrdef a WHERE a.oid = d.objid)
|
|
260
|
+
WHEN 'pg_catalog.pg_constraint'::regclass THEN (
|
|
261
|
+
SELECT k.conrelid FROM pg_catalog.pg_constraint k
|
|
262
|
+
WHERE k.oid = d.objid AND k.contype = 'c')
|
|
263
|
+
END AS relid
|
|
264
|
+
) n
|
|
265
|
+
WHERE d.deptype = 'n' AND n.relid IS NOT NULL
|
|
266
|
+
AND d.classid IN ('pg_catalog.pg_class'::regclass, 'pg_catalog.pg_attrdef'::regclass,
|
|
267
|
+
'pg_catalog.pg_constraint'::regclass, 'pg_catalog.pg_policy'::regclass)
|
|
268
|
+
AND d.refclassid IN ('pg_catalog.pg_proc'::regclass, 'pg_catalog.pg_class'::regclass,
|
|
269
|
+
'pg_catalog.pg_type'::regclass)
|
|
270
|
+
"""
|
|
271
|
+
"""What tables need: a column's type, a typed table's type, an inheriting
|
|
272
|
+
table's parent, the sequences and functions its default uses, the functions
|
|
273
|
+
its check constraints, index expressions and predicates call, and the
|
|
274
|
+
functions and tables its row-level security policies use."""
|
|
275
|
+
|
|
276
|
+
_OBJECT_KINDS = {
|
|
277
|
+
"f": ObjectKind.FUNCTION,
|
|
278
|
+
"p": ObjectKind.PROCEDURE,
|
|
279
|
+
"v": ObjectKind.VIEW,
|
|
280
|
+
"m": ObjectKind.MATERIALIZED_VIEW,
|
|
281
|
+
"S": ObjectKind.SEQUENCE,
|
|
282
|
+
"T": ObjectKind.TRIGGER,
|
|
283
|
+
"t": ObjectKind.TYPE,
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
_DIALECT = Dialect(quotes='"', dollar_quotes=True)
|
|
287
|
+
_PYTHON = Dialect(quotes='"', dollar_quotes=True, hash_comments=True)
|
|
288
|
+
"""PL/Python bodies, whose comments start with ``#``."""
|
|
289
|
+
|
|
290
|
+
_KINDS = {
|
|
291
|
+
"int2": ColumnKind.INTEGER,
|
|
292
|
+
"int4": ColumnKind.INTEGER,
|
|
293
|
+
"int8": ColumnKind.INTEGER,
|
|
294
|
+
"numeric": ColumnKind.DECIMAL,
|
|
295
|
+
"float4": ColumnKind.FLOAT,
|
|
296
|
+
"float8": ColumnKind.FLOAT,
|
|
297
|
+
"bool": ColumnKind.BOOLEAN,
|
|
298
|
+
"date": ColumnKind.DATE,
|
|
299
|
+
"timestamp": ColumnKind.TIMESTAMP,
|
|
300
|
+
"timestamptz": ColumnKind.TIMESTAMP,
|
|
301
|
+
"time": ColumnKind.TIME,
|
|
302
|
+
"timetz": ColumnKind.TIME,
|
|
303
|
+
"bytea": ColumnKind.BINARY,
|
|
304
|
+
"json": ColumnKind.JSON,
|
|
305
|
+
"jsonb": ColumnKind.JSON,
|
|
306
|
+
"uuid": ColumnKind.UUID,
|
|
307
|
+
"text": ColumnKind.TEXT,
|
|
308
|
+
"varchar": ColumnKind.TEXT,
|
|
309
|
+
"bpchar": ColumnKind.TEXT,
|
|
310
|
+
"name": ColumnKind.TEXT,
|
|
311
|
+
"citext": ColumnKind.TEXT,
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def kind_of(base_type: str, category: str) -> ColumnKind:
|
|
316
|
+
"""The engine-neutral kind of a base type."""
|
|
317
|
+
if category == "A":
|
|
318
|
+
return ColumnKind.ARRAY
|
|
319
|
+
return _KINDS.get(base_type, ColumnKind.OTHER)
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
class Extension(BaseModel):
|
|
323
|
+
"""An installed extension: its version and the schema its objects are in."""
|
|
324
|
+
|
|
325
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
326
|
+
|
|
327
|
+
name: str
|
|
328
|
+
version: str
|
|
329
|
+
schema_: str
|
|
330
|
+
|
|
331
|
+
def requirement(self) -> Requirement:
|
|
332
|
+
"""The extension as a requirement of the source."""
|
|
333
|
+
return Requirement(kind=RequirementKind.EXTENSION, name=self.name, version=self.version)
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
@dataclass(frozen=True, slots=True)
|
|
337
|
+
class Physical:
|
|
338
|
+
"""What the adapter needs beyond the engine-neutral catalog."""
|
|
339
|
+
|
|
340
|
+
partitioned: frozenset[TableName]
|
|
341
|
+
"""Partitioned tables, read without ``ONLY`` so their partitions are included."""
|
|
342
|
+
generated: dict[TableName, frozenset[ColumnName]]
|
|
343
|
+
"""Generated columns, which COPY leaves out."""
|
|
344
|
+
extensions: dict[str, tuple[Extension, ...]]
|
|
345
|
+
"""Each database's installed extensions, in the order they were created."""
|
|
346
|
+
|
|
347
|
+
def merged(self, other: "Physical") -> "Physical":
|
|
348
|
+
"""This and another database's details together."""
|
|
349
|
+
return Physical(
|
|
350
|
+
partitioned=self.partitioned | other.partitioned,
|
|
351
|
+
generated={**self.generated, **other.generated},
|
|
352
|
+
extensions={**self.extensions, **other.extensions},
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def introspect(
|
|
357
|
+
connection: psycopg.Connection[tuple[object, ...]], database: str
|
|
358
|
+
) -> tuple[Catalog, Physical]:
|
|
359
|
+
"""Read one database's catalog in one transaction with an empty search path."""
|
|
360
|
+
with connection.transaction(), connection.cursor() as cursor:
|
|
361
|
+
# An empty search path makes format_type qualify user-defined types. It
|
|
362
|
+
# is put back afterwards, since this may run inside the snapshot's
|
|
363
|
+
# transaction, where spec SQL relies on the usual search path.
|
|
364
|
+
saved = cursor.execute("SELECT pg_catalog.current_setting('search_path')").fetchone()
|
|
365
|
+
cursor.execute("SELECT pg_catalog.set_config('search_path', '', true)")
|
|
366
|
+
cursor.execute(_TABLES)
|
|
367
|
+
tables = {
|
|
368
|
+
int(str(oid)): (TableName.of(database, str(nsp), str(rel)), str(kind))
|
|
369
|
+
for oid, nsp, rel, kind in cursor.fetchall()
|
|
370
|
+
}
|
|
371
|
+
oids = list(tables)
|
|
372
|
+
columns: defaultdict[int, list[Column]] = defaultdict(list)
|
|
373
|
+
generated: defaultdict[TableName, set[ColumnName]] = defaultdict(set)
|
|
374
|
+
cursor.execute(_COLUMNS, [oids])
|
|
375
|
+
for relid, name, type_name, not_null, is_generated, base, category in cursor.fetchall():
|
|
376
|
+
column = Column(
|
|
377
|
+
name=ColumnName(str(name)),
|
|
378
|
+
type=str(type_name),
|
|
379
|
+
kind=kind_of(str(base), str(category)),
|
|
380
|
+
nullable=not not_null,
|
|
381
|
+
)
|
|
382
|
+
columns[int(str(relid))].append(column)
|
|
383
|
+
if is_generated:
|
|
384
|
+
generated[tables[int(str(relid))][0]].add(column.name)
|
|
385
|
+
primary: dict[int, tuple[ColumnName, ...]] = {}
|
|
386
|
+
foreign: defaultdict[int, list[ForeignKey]] = defaultdict(list)
|
|
387
|
+
cursor.execute(_KEYS, [oids])
|
|
388
|
+
# A reference to a table outside the catalog (one an extension owns,
|
|
389
|
+
# say) keeps its real target, so the planner asks for a fallback.
|
|
390
|
+
for relid, contype, name, namespace, target, names, target_names in cursor.fetchall():
|
|
391
|
+
own = tuple(ColumnName(str(n)) for n in _strings(names))
|
|
392
|
+
if contype == "p":
|
|
393
|
+
primary[int(str(relid))] = own
|
|
394
|
+
else:
|
|
395
|
+
foreign[int(str(relid))].append(
|
|
396
|
+
ForeignKey(
|
|
397
|
+
name=str(name),
|
|
398
|
+
columns=own,
|
|
399
|
+
target=TableName.of(database, str(namespace), str(target)),
|
|
400
|
+
target_columns=tuple(ColumnName(str(n)) for n in _strings(target_names)),
|
|
401
|
+
)
|
|
402
|
+
)
|
|
403
|
+
table_list = [
|
|
404
|
+
Table(
|
|
405
|
+
name=name,
|
|
406
|
+
columns=tuple(columns[oid]),
|
|
407
|
+
primary_key=primary.get(oid, ()),
|
|
408
|
+
foreign_keys=tuple(foreign[oid]),
|
|
409
|
+
)
|
|
410
|
+
for oid, (name, _) in tables.items()
|
|
411
|
+
]
|
|
412
|
+
objects, needs = _objects(
|
|
413
|
+
cursor, database, {oid: name for oid, (name, _) in tables.items()}, table_list
|
|
414
|
+
)
|
|
415
|
+
table_list = [
|
|
416
|
+
table.model_copy(update={"depends_on": tuple(dict.fromkeys(needs[table.name]))})
|
|
417
|
+
for table in table_list
|
|
418
|
+
]
|
|
419
|
+
cursor.execute(_EXTENSIONS)
|
|
420
|
+
extensions = tuple(
|
|
421
|
+
Extension(name=str(name), version=str(version), schema_=str(schema))
|
|
422
|
+
for name, version, schema in cursor.fetchall()
|
|
423
|
+
)
|
|
424
|
+
cursor.execute(
|
|
425
|
+
"SELECT pg_catalog.set_config('search_path', %s, true)",
|
|
426
|
+
[str(saved[0]) if saved else ""],
|
|
427
|
+
)
|
|
428
|
+
catalog = Catalog(
|
|
429
|
+
engine=ENGINE,
|
|
430
|
+
tables=tuple(table_list),
|
|
431
|
+
requirements=tuple(extension.requirement() for extension in extensions),
|
|
432
|
+
objects=objects,
|
|
433
|
+
)
|
|
434
|
+
physical = Physical(
|
|
435
|
+
partitioned=frozenset(name for name, kind in tables.values() if kind == "p"),
|
|
436
|
+
generated={name: frozenset(cols) for name, cols in generated.items()},
|
|
437
|
+
extensions={database: extensions},
|
|
438
|
+
)
|
|
439
|
+
return catalog, physical
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
type _Node = TableName | ObjectRef
|
|
443
|
+
type _Key = tuple[int, int]
|
|
444
|
+
"""A catalog row: the OID of the system catalog it is in, and its own OID."""
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _objects(
|
|
448
|
+
cursor: psycopg.Cursor[tuple[object, ...]],
|
|
449
|
+
database: str,
|
|
450
|
+
tables: dict[int, TableName],
|
|
451
|
+
table_list: list[Table],
|
|
452
|
+
) -> tuple[tuple[SourceObject, ...], defaultdict[TableName, list[Dependency]]]:
|
|
453
|
+
"""The source's objects, with their exact and inferred dependencies, and what tables need."""
|
|
454
|
+
found = cursor.execute(_CATALOG_OIDS).fetchone() or (0, 0)
|
|
455
|
+
pg_class, pg_type = int(str(found[0])), int(str(found[1]))
|
|
456
|
+
nodes: dict[_Key, _Node] = {(pg_class, oid): name for oid, name in tables.items()}
|
|
457
|
+
cursor.execute(_PARTITIONS)
|
|
458
|
+
roots = {int(str(oid)): int(str(root)) for oid, root in cursor.fetchall()}
|
|
459
|
+
nodes |= {(pg_class, oid): tables[root] for oid, root in roots.items() if root in tables}
|
|
460
|
+
definitions: dict[ObjectRef, tuple[str, str, str]] = {}
|
|
461
|
+
for query in (_ROUTINES, _RELATIONS, _TRIGGERS, _TYPES):
|
|
462
|
+
cursor.execute(query)
|
|
463
|
+
for catalog, oid, namespace, name, kind, signature, *text in cursor.fetchall():
|
|
464
|
+
ref = ObjectRef(
|
|
465
|
+
kind=_OBJECT_KINDS[str(kind)],
|
|
466
|
+
namespace=(database, str(namespace)),
|
|
467
|
+
name=str(name),
|
|
468
|
+
signature=None if signature is None else str(signature),
|
|
469
|
+
)
|
|
470
|
+
nodes[(int(str(catalog)), int(str(oid)))] = ref
|
|
471
|
+
definition, body, language = (str(part or "") for part in text)
|
|
472
|
+
definitions[ref] = (definition, body, language)
|
|
473
|
+
_aliases(cursor, nodes, pg_class, pg_type)
|
|
474
|
+
exact: defaultdict[ObjectRef, list[Dependency]] = defaultdict(list)
|
|
475
|
+
cursor.execute(_DEPENDS)
|
|
476
|
+
for classid, objid, refclassid, refobjid in cursor.fetchall():
|
|
477
|
+
owner = nodes.get((int(str(classid)), int(str(objid))))
|
|
478
|
+
target = nodes.get((int(str(refclassid)), int(str(refobjid))))
|
|
479
|
+
if isinstance(owner, ObjectRef) and target is not None and target != owner:
|
|
480
|
+
edge = (
|
|
481
|
+
Dependency(table=target)
|
|
482
|
+
if isinstance(target, TableName)
|
|
483
|
+
else Dependency(object=target)
|
|
484
|
+
)
|
|
485
|
+
exact[owner].append(edge)
|
|
486
|
+
needs: defaultdict[TableName, list[Dependency]] = defaultdict(list)
|
|
487
|
+
cursor.execute(_TABLE_DEPENDS)
|
|
488
|
+
for relid, refclassid, refobjid in cursor.fetchall():
|
|
489
|
+
owner = nodes.get((pg_class, int(str(relid))))
|
|
490
|
+
target = nodes.get((int(str(refclassid)), int(str(refobjid))))
|
|
491
|
+
if isinstance(owner, TableName) and isinstance(target, ObjectRef):
|
|
492
|
+
needs[owner].append(Dependency(object=target))
|
|
493
|
+
elif isinstance(owner, TableName) and isinstance(target, TableName) and target != owner:
|
|
494
|
+
needs[owner].append(Dependency(table=target))
|
|
495
|
+
plain = [SourceObject(ref=ref, fingerprint="") for ref in definitions]
|
|
496
|
+
candidates = Candidates.of(table_list, plain)
|
|
497
|
+
objects = tuple(
|
|
498
|
+
SourceObject(
|
|
499
|
+
ref=ref,
|
|
500
|
+
fingerprint=definition_fingerprint(definition),
|
|
501
|
+
depends_on=merge(
|
|
502
|
+
exact[ref],
|
|
503
|
+
infer_dependencies(
|
|
504
|
+
body,
|
|
505
|
+
ref,
|
|
506
|
+
candidates,
|
|
507
|
+
_PYTHON if language.startswith("plpython") else _DIALECT,
|
|
508
|
+
),
|
|
509
|
+
),
|
|
510
|
+
)
|
|
511
|
+
for ref, (definition, body, language) in definitions.items()
|
|
512
|
+
)
|
|
513
|
+
return objects, needs
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def _aliases(
|
|
517
|
+
cursor: psycopg.Cursor[tuple[object, ...]],
|
|
518
|
+
nodes: dict[_Key, _Node],
|
|
519
|
+
pg_class: int,
|
|
520
|
+
pg_type: int,
|
|
521
|
+
) -> None:
|
|
522
|
+
"""Map row types to their relations, arrays to their elements, composites' rows to the type.
|
|
523
|
+
|
|
524
|
+
A standalone composite type's dependencies are recorded on its ``pg_class``
|
|
525
|
+
row, which then stands for the type.
|
|
526
|
+
"""
|
|
527
|
+
cursor.execute(_TYPE_ALIASES)
|
|
528
|
+
for oid, relid, element, is_array in cursor.fetchall():
|
|
529
|
+
own, relation = (pg_type, int(str(oid))), (pg_class, int(str(relid)))
|
|
530
|
+
if is_array:
|
|
531
|
+
element_node = nodes.get((pg_type, int(str(element))))
|
|
532
|
+
if element_node is not None:
|
|
533
|
+
nodes.setdefault(own, element_node)
|
|
534
|
+
elif own in nodes:
|
|
535
|
+
nodes[relation] = nodes[own]
|
|
536
|
+
elif relation in nodes:
|
|
537
|
+
nodes[own] = nodes[relation]
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def _strings(value: object) -> list[str]:
|
|
541
|
+
items: list[object] = list(value) if isinstance(value, list) else [] # pyright: ignore[reportUnknownArgumentType] - psycopg returns arrays as untyped lists
|
|
542
|
+
return [str(item) for item in items]
|
|
File without changes
|