@typesql/pg 0.0.3 → 0.0.4

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 (46) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +23 -2
  3. package/dist/bin.d.ts +3 -0
  4. package/dist/bin.d.ts.map +1 -0
  5. package/dist/bin.js +5 -0
  6. package/dist/bin.js.map +1 -0
  7. package/dist/client.d.ts +5 -2
  8. package/dist/client.d.ts.map +1 -1
  9. package/dist/client.js +10 -3
  10. package/dist/client.js.map +1 -1
  11. package/dist/index.d.ts +8 -2
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +2 -6
  14. package/dist/index.js.map +1 -1
  15. package/dist/introspect/cli.d.ts +24 -0
  16. package/dist/introspect/cli.d.ts.map +1 -0
  17. package/dist/introspect/cli.js +121 -0
  18. package/dist/introspect/cli.js.map +1 -0
  19. package/dist/introspect/emit.d.ts +30 -0
  20. package/dist/introspect/emit.d.ts.map +1 -0
  21. package/dist/introspect/emit.js +144 -0
  22. package/dist/introspect/emit.js.map +1 -0
  23. package/dist/introspect/index.d.ts +5 -0
  24. package/dist/introspect/index.d.ts.map +1 -0
  25. package/dist/introspect/index.js +5 -0
  26. package/dist/introspect/index.js.map +1 -0
  27. package/dist/introspect/introspect.d.ts +67 -0
  28. package/dist/introspect/introspect.d.ts.map +1 -0
  29. package/dist/introspect/introspect.js +109 -0
  30. package/dist/introspect/introspect.js.map +1 -0
  31. package/dist/introspect/nullability.d.ts +60 -0
  32. package/dist/introspect/nullability.d.ts.map +1 -0
  33. package/dist/introspect/nullability.js +354 -0
  34. package/dist/introspect/nullability.js.map +1 -0
  35. package/dist/type-map.d.ts +42 -14
  36. package/dist/type-map.d.ts.map +1 -1
  37. package/package.json +10 -3
  38. package/src/bin.ts +5 -0
  39. package/src/client.ts +10 -4
  40. package/src/index.ts +7 -4
  41. package/src/introspect/cli.ts +138 -0
  42. package/src/introspect/emit.ts +168 -0
  43. package/src/introspect/index.ts +12 -0
  44. package/src/introspect/introspect.ts +221 -0
  45. package/src/introspect/nullability.ts +356 -0
  46. package/src/type-map.ts +42 -14
@@ -0,0 +1,221 @@
1
+ import type { PgQueryable } from "../client.js";
2
+ import { ViewNullability, type NullabilityOptions } from "./nullability.js";
3
+
4
+ export type RelationKind = "table" | "partitioned table" | "view" | "materialized view" | "foreign table";
5
+
6
+ export interface IntrospectedColumn {
7
+ readonly name: string;
8
+ /**
9
+ * Canonical Postgres type name as typesql spells it: `int4`, `timestamptz`, `varchar`, an enum
10
+ * name, `${T}[]` for arrays. Domains are replaced by their base type; `citext` is `text`.
11
+ */
12
+ readonly type: string;
13
+ /** The column's type as Postgres prints it (`character varying(40)`, a domain name, ...). */
14
+ readonly declaredType: string;
15
+ /** The domain the column is declared with, if any (`public.positive`). */
16
+ readonly domain: string | null;
17
+ readonly nullable: boolean;
18
+ /** Optional on INSERT: a DEFAULT, serial, identity or generated column. Always false for views. */
19
+ readonly hasDefault: boolean;
20
+ /** `GENERATED ALWAYS AS IDENTITY` / `GENERATED BY DEFAULT AS IDENTITY`. */
21
+ readonly identity: "always" | "by default" | null;
22
+ /** The expression of a `GENERATED ALWAYS AS (…) STORED` column. */
23
+ readonly generated: string | null;
24
+ /** The DEFAULT expression. */
25
+ readonly default: string | null;
26
+ readonly comment: string | null;
27
+ }
28
+
29
+ export interface IntrospectedRelation {
30
+ readonly schema: string;
31
+ readonly name: string;
32
+ readonly kind: RelationKind;
33
+ readonly comment: string | null;
34
+ readonly columns: readonly IntrospectedColumn[];
35
+ }
36
+
37
+ export interface IntrospectedEnum {
38
+ readonly schema: string;
39
+ readonly name: string;
40
+ /** Labels in sort order. */
41
+ readonly values: readonly string[];
42
+ }
43
+
44
+ export interface IntrospectedDatabase {
45
+ /** `server_version`, e.g. `17.2`. */
46
+ readonly version: string;
47
+ /** Schemas that were read, in order. */
48
+ readonly schemas: readonly string[];
49
+ readonly relations: readonly IntrospectedRelation[];
50
+ /** Enums of the read schemas and enums their columns use. */
51
+ readonly enums: readonly IntrospectedEnum[];
52
+ }
53
+
54
+ export interface IntrospectOptions {
55
+ /** Schemas to read. Default: every schema except `pg_catalog`, `information_schema` and `pg_*`. */
56
+ readonly schemas?: readonly string[];
57
+ /**
58
+ * Relations to leave out: names (`kysely_migration`) or `schema.name`, with `*` matching any
59
+ * run of characters (`kysely_migration*`, `audit.*`).
60
+ */
61
+ readonly exclude?: readonly string[];
62
+ /**
63
+ * View columns to treat as NOT NULL when the analysis cannot prove it, called with the view's
64
+ * name and the column's name.
65
+ */
66
+ readonly viewNotNull?: NullabilityOptions["notNull"];
67
+ }
68
+
69
+ const globToRegExp = (glob: string): RegExp =>
70
+ new RegExp(`^${glob.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`);
71
+
72
+ const KINDS: Readonly<Record<string, RelationKind>> = {
73
+ r: "table",
74
+ p: "partitioned table",
75
+ v: "view",
76
+ m: "materialized view",
77
+ f: "foreign table",
78
+ };
79
+
80
+ /** Postgres type names typesql spells differently. */
81
+ const TYPE_ALIASES: Readonly<Record<string, string>> = { citext: "text" };
82
+
83
+ interface TypeRow {
84
+ readonly oid: string;
85
+ readonly name: string;
86
+ readonly schema: string;
87
+ readonly typtype: string;
88
+ readonly basetype: string;
89
+ readonly elem: string;
90
+ readonly array: string;
91
+ readonly notnull: boolean;
92
+ }
93
+
94
+ interface ResolvedType {
95
+ readonly type: string;
96
+ readonly notnull: boolean;
97
+ readonly enumOid: string | null;
98
+ readonly domain: string | null;
99
+ }
100
+
101
+ function resolver(types: ReadonlyMap<string, TypeRow>) {
102
+ const resolve = (oid: string): ResolvedType => {
103
+ const t = types.get(oid);
104
+ if (!t) return { type: "unknown", notnull: false, enumOid: null, domain: null };
105
+ if (t.typtype === "d") {
106
+ const base = resolve(t.basetype);
107
+ return { ...base, notnull: base.notnull || t.notnull, domain: `${t.schema}.${t.name}` };
108
+ }
109
+ const elem = t.elem !== "0" ? types.get(t.elem) : undefined;
110
+ if (elem && elem.array === t.oid) {
111
+ const inner = resolve(elem.oid);
112
+ return { type: inner.type.endsWith("[]") ? inner.type : `${inner.type}[]`, notnull: false, enumOid: inner.enumOid, domain: null };
113
+ }
114
+ return { type: TYPE_ALIASES[t.name] ?? t.name, notnull: false, enumOid: t.typtype === "e" ? t.oid : null, domain: null };
115
+ };
116
+ return resolve;
117
+ }
118
+
119
+ /** Default schema filter: everything but the system schemas. */
120
+ const USER_SCHEMAS = `n.nspname NOT IN ('pg_catalog', 'information_schema') AND n.nspname NOT LIKE 'pg\\_%'`;
121
+
122
+ /**
123
+ * Read tables, views, materialized views, foreign tables and enums of a live database through
124
+ * any node-postgres-style client (`Client`, `Pool`, `PoolClient`).
125
+ */
126
+ export async function introspect(client: PgQueryable, options: IntrospectOptions = {}): Promise<IntrospectedDatabase> {
127
+ const q = async <R>(text: string, values?: unknown[]): Promise<R[]> => (await client.query(text, values)).rows as R[];
128
+
129
+ const [{ version }] = (await q<{ version: string }>(`SELECT current_setting('server_version') AS version`)) as [{ version: string }];
130
+ const schemaRows = options.schemas
131
+ ? await q<{ name: string }>(
132
+ `SELECT n.nspname AS name FROM unnest($1::text[]) WITH ORDINALITY AS s(name, i)
133
+ JOIN pg_namespace n ON n.nspname = s.name ORDER BY s.i`,
134
+ [[...options.schemas]],
135
+ )
136
+ : await q<{ name: string }>(
137
+ `SELECT n.nspname AS name FROM pg_namespace n WHERE ${USER_SCHEMAS}
138
+ ORDER BY n.nspname <> 'public', n.nspname`,
139
+ );
140
+ const schemas = schemaRows.map((r) => r.name);
141
+ const missing = (options.schemas ?? []).filter((s) => !schemas.includes(s));
142
+ if (missing.length > 0) throw new Error(`schema ${missing.map((s) => JSON.stringify(s)).join(", ")} does not exist`);
143
+
144
+ const types = new Map(
145
+ (await q<TypeRow>(
146
+ `SELECT t.oid::int8::text AS oid, t.typname AS name, n.nspname AS schema, t.typtype,
147
+ t.typbasetype::int8::text AS basetype, t.typelem::int8::text AS elem,
148
+ t.typarray::int8::text AS array, t.typnotnull AS notnull
149
+ FROM pg_type t JOIN pg_namespace n ON n.oid = t.typnamespace`,
150
+ )).map((t) => [t.oid, t]),
151
+ );
152
+ const resolve = resolver(types);
153
+
154
+ const excluded = (options.exclude ?? []).map(globToRegExp);
155
+ const relRows = (await q<{ oid: string; schema: string; name: string; relkind: string; comment: string | null }>(
156
+ `SELECT c.oid::int8::text AS oid, n.nspname AS schema, c.relname AS name, c.relkind,
157
+ obj_description(c.oid, 'pg_class') AS comment
158
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
159
+ WHERE c.relkind IN ('r', 'p', 'v', 'm', 'f') AND n.nspname = ANY($1::text[])
160
+ ORDER BY array_position($1::text[], n.nspname::text), c.relname`,
161
+ [schemas],
162
+ )).filter((r) => !excluded.some((re) => re.test(r.name) || re.test(`${r.schema}.${r.name}`)));
163
+ const colRows = await q<{
164
+ relid: string; name: string; typid: string; declared: string; notnull: boolean;
165
+ identity: string; generated: string; default: string | null; comment: string | null;
166
+ }>(
167
+ `SELECT a.attrelid::int8::text AS relid, a.attname AS name, a.atttypid::int8::text AS typid,
168
+ format_type(a.atttypid, a.atttypmod) AS declared, a.attnotnull AS notnull,
169
+ a.attidentity AS identity, a.attgenerated AS generated,
170
+ pg_get_expr(d.adbin, d.adrelid) AS default, col_description(a.attrelid, a.attnum) AS comment
171
+ FROM pg_attribute a
172
+ LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum
173
+ WHERE a.attrelid = ANY($1::oid[]) AND a.attnum > 0 AND NOT a.attisdropped
174
+ ORDER BY a.attrelid, a.attnum`,
175
+ [relRows.map((r) => r.oid)],
176
+ );
177
+ const colsByRel = new Map<string, typeof colRows>();
178
+ for (const c of colRows) colsByRel.set(c.relid, [...(colsByRel.get(c.relid) ?? []), c]);
179
+
180
+ const views = new ViewNullability((text, values) => client.query(text, values), {
181
+ ...(options.viewNotNull && { notNull: options.viewNotNull }),
182
+ });
183
+ const usedEnums = new Set<string>();
184
+ const relations: IntrospectedRelation[] = [];
185
+ for (const rel of relRows) {
186
+ const kind = KINDS[rel.relkind]!;
187
+ const isView = kind === "view" || kind === "materialized view";
188
+ const viewNotNull = isView ? await views.notNull(rel.oid) : [];
189
+ const columns = (colsByRel.get(rel.oid) ?? []).map((c, i): IntrospectedColumn => {
190
+ const t = resolve(c.typid);
191
+ if (t.enumOid) usedEnums.add(t.enumOid);
192
+ const generated = c.generated !== "" ? c.default : null;
193
+ const identity = c.identity === "a" ? "always" : c.identity === "d" ? "by default" : null;
194
+ return {
195
+ name: c.name,
196
+ type: t.type,
197
+ declaredType: c.declared,
198
+ domain: t.domain,
199
+ nullable: isView ? !viewNotNull[i] : !(c.notnull || t.notnull),
200
+ hasDefault: !isView && (c.default !== null || identity !== null || generated !== null),
201
+ identity,
202
+ generated,
203
+ default: generated === null ? c.default : null,
204
+ comment: c.comment,
205
+ };
206
+ });
207
+ relations.push({ schema: rel.schema, name: rel.name, kind, comment: rel.comment, columns });
208
+ }
209
+
210
+ const enumRows = await q<{ oid: string; schema: string; name: string; values: string[] }>(
211
+ `SELECT t.oid::int8::text AS oid, n.nspname AS schema, t.typname AS name,
212
+ array_agg(e.enumlabel::text ORDER BY e.enumsortorder) AS values
213
+ FROM pg_type t JOIN pg_namespace n ON n.oid = t.typnamespace JOIN pg_enum e ON e.enumtypid = t.oid
214
+ WHERE n.nspname = ANY($1::text[]) OR t.oid = ANY($2::oid[])
215
+ GROUP BY t.oid, n.nspname, t.typname
216
+ ORDER BY t.typname, n.nspname`,
217
+ [schemas, [...usedEnums]],
218
+ );
219
+ const enums = enumRows.map(({ schema, name, values }) => ({ schema, name, values }));
220
+ return { version, schemas, relations, enums };
221
+ }
@@ -0,0 +1,356 @@
1
+ /**
2
+ * Nullability of view columns, derived from the view's query tree.
3
+ *
4
+ * Postgres records no NOT NULL information for view (or materialized view) columns. Its rewrite
5
+ * rule (`pg_rewrite.ev_action`, the `_RETURN` rule) holds the parsed query, though, and from
6
+ * PostgreSQL 16 every column reference in it carries `varnullingrels`, the outer joins that can
7
+ * null it. A view column is NOT NULL here only when its expression provably cannot be NULL: a
8
+ * NOT NULL table column that no outer join nulls, a non-NULL constant, a cast or a strict
9
+ * operator over such values, a CASE whose every branch is NOT NULL, `count(*)`, ... Anything
10
+ * else (function calls outside a short list, scalar subqueries, set-returning function columns)
11
+ * is nullable. On PostgreSQL 15 and older every column reference counts as nullable.
12
+ *
13
+ * This module has no imports so that scripts/pg-catalog-from-pg.mjs can load it with Node's
14
+ * type stripping.
15
+ */
16
+
17
+ /** Runs a query: node-postgres' `client.query(text, values)` fits. */
18
+ export type QueryFn = (text: string, values?: unknown[]) => Promise<{ readonly rows: readonly any[] }>;
19
+
20
+ export interface NullabilityOptions {
21
+ /**
22
+ * Columns known never to be NULL that the analysis cannot prove (typically columns of a
23
+ * set-returning function). Called with the view's name and the column's name.
24
+ */
25
+ readonly notNull?: (view: string, column: string) => boolean;
26
+ }
27
+
28
+ /** A node of a parsed `pg_node_tree`: `{ _: "VAR", varno: "1", … }`. */
29
+ export interface Node {
30
+ readonly _: string;
31
+ readonly [field: string]: NodeValue;
32
+ }
33
+ export type NodeValue = Node | readonly NodeValue[] | string | null;
34
+
35
+ // ───────────────────────────── pg_node_tree reader ─────────────────────────────
36
+
37
+ type Token = string | { readonly str: string };
38
+
39
+ /** Tokens of the text form of a node tree (`outfuncs.c`). `[ … ]` datum bytes are skipped. */
40
+ function tokenize(s: string): Token[] {
41
+ const out: Token[] = [];
42
+ let i = 0;
43
+ while (i < s.length) {
44
+ const c = s[i]!;
45
+ if (c === " " || c === "\n" || c === "\t") { i++; continue; }
46
+ if (c === "(" || c === ")" || c === "{" || c === "}") { out.push(c); i++; continue; }
47
+ if (c === "[") { i = s.indexOf("]", i) + 1; continue; }
48
+ if (c === '"') {
49
+ let v = "";
50
+ i++;
51
+ while (i < s.length && s[i] !== '"') { if (s[i] === "\\") i++; v += s[i++]; }
52
+ i++;
53
+ out.push({ str: v });
54
+ continue;
55
+ }
56
+ let v = "";
57
+ while (i < s.length && !" \n\t(){}".includes(s[i]!)) { if (s[i] === "\\") i++; v += s[i++]; }
58
+ out.push(v);
59
+ }
60
+ return out;
61
+ }
62
+
63
+ /** Parse a node tree into plain values: nodes as objects, lists as arrays, `<>` as null. */
64
+ export function parseNodeTree(text: string): NodeValue {
65
+ const toks = tokenize(text);
66
+ let p = 0;
67
+ const isLabel = (t: Token | undefined): boolean => typeof t === "string" && t.startsWith(":");
68
+ const value = (): NodeValue => {
69
+ const t = toks[p++];
70
+ if (t === "{") {
71
+ const node: Record<string, NodeValue> = { _: toks[p++] as string };
72
+ while (p < toks.length && toks[p] !== "}") {
73
+ const label = toks[p++];
74
+ if (!isLabel(label)) continue; // a datum's length before its skipped bytes
75
+ if (toks[p] === "}" || isLabel(toks[p])) { node[(label as string).slice(1)] = null; continue; }
76
+ node[(label as string).slice(1)] = value();
77
+ }
78
+ p++;
79
+ return node as Node;
80
+ }
81
+ if (t === "(") {
82
+ const list: NodeValue[] = [];
83
+ while (p < toks.length && toks[p] !== ")") list.push(value());
84
+ p++;
85
+ return list;
86
+ }
87
+ if (t === undefined || t === "<>") return null;
88
+ return typeof t === "object" ? t.str : t;
89
+ };
90
+ return value();
91
+ }
92
+
93
+ const list = (x: NodeValue | undefined): readonly NodeValue[] => (Array.isArray(x) ? x : []);
94
+ const node = (x: NodeValue | undefined): Node | null => (x !== null && typeof x === "object" && !Array.isArray(x) ? (x as Node) : null);
95
+ const str = (x: NodeValue | undefined): string | null => (typeof x === "string" ? x : null);
96
+
97
+ // ───────────────────────────── function knowledge ─────────────────────────────
98
+
99
+ /** `pg_catalog` functions that return a non-NULL value for non-NULL arguments. */
100
+ const NON_NULL_FUNCTIONS = new Set([
101
+ "current_database", "current_user", "session_user", "current_schema", "pg_get_userbyid", "pg_my_temp_schema",
102
+ "nameconcatoid", "pg_has_role", "has_table_privilege", "has_column_privilege", "has_any_column_privilege",
103
+ "has_function_privilege", "has_schema_privilege", "has_sequence_privilege", "has_type_privilege",
104
+ "pg_relation_is_updatable", "pg_column_is_updatable", "pg_is_other_temp_schema",
105
+ "now", "statement_timestamp", "transaction_timestamp", "clock_timestamp",
106
+ "lower", "upper", "length", "char_length", "octet_length", "concat", "concat_ws", "md5", "btrim", "ltrim", "rtrim",
107
+ "abs", "round", "trunc", "floor", "ceil", "ceiling", "date_trunc", "age",
108
+ ]);
109
+
110
+ /** `pg_stat_get_*` accessors returning a number report 0 when no statistics exist, except these. */
111
+ const NULLABLE_STAT_FUNCTIONS = new Set([
112
+ "pg_stat_get_db_checksum_failures", "pg_stat_get_backend_pid", "pg_stat_get_backend_dbid", "pg_stat_get_backend_userid",
113
+ ]);
114
+ const isNonNullStatFunction = (name: string, ret: string): boolean =>
115
+ name.startsWith("pg_stat_get_") && (ret === "int8" || ret === "int4" || ret === "float8") && !NULLABLE_STAT_FUNCTIONS.has(name);
116
+
117
+ /** Aggregates that never return NULL. */
118
+ const NON_NULL_AGGREGATES = new Set(["count"]);
119
+ /** Window functions that never return NULL. */
120
+ const NON_NULL_WINDOW_FUNCTIONS = new Set(["count", "row_number", "rank", "dense_rank", "percent_rank", "cume_dist"]);
121
+
122
+ /**
123
+ * Set-returning functions in FROM and their output columns (1-based) that are never NULL. A
124
+ * strict set-returning function returns no rows for NULL arguments, so the arguments do not
125
+ * matter. `jsonb_each` values are `jsonb` (a JSON null is `'null'::jsonb`, not SQL NULL);
126
+ * the `_text` variants turn a JSON null into SQL NULL.
127
+ */
128
+ const NON_NULL_SRF_COLUMNS: Readonly<Record<string, readonly number[]>> = {
129
+ generate_series: [1], generate_subscripts: [1],
130
+ jsonb_each: [1, 2], json_each: [1, 2], jsonb_each_text: [1], json_each_text: [1],
131
+ jsonb_object_keys: [1], json_object_keys: [1], jsonb_array_elements: [1], json_array_elements: [1],
132
+ regexp_matches: [1], regexp_split_to_table: [1],
133
+ };
134
+
135
+ /**
136
+ * `pg_catalog` operators that can return NULL for non-NULL operands: JSON field and path access
137
+ * (a missing key) and jsonpath matches (an unknown result). Other built-in operators are strict
138
+ * and return a value for non-NULL operands; operators outside `pg_catalog` count as nullable.
139
+ */
140
+ const NULLABLE_OPERATORS = new Set(["->", "->>", "#>", "#>>", "@@", "@?"]);
141
+
142
+ interface Proc { readonly name: string; readonly ret: string; readonly system: boolean }
143
+ interface Att { readonly attnum: number; readonly notnull: boolean; readonly relkind: string }
144
+
145
+ // ───────────────────────────── analysis ─────────────────────────────
146
+
147
+ /** Per-column NOT NULL of views and materialized views; caches what it reads. */
148
+ export class ViewNullability {
149
+ private readonly query: QueryFn;
150
+ private readonly options: NullabilityOptions;
151
+ private readonly views = new Map<string, Promise<boolean[]>>();
152
+ private readonly atts = new Map<string, Promise<Att[]>>();
153
+ private procs: Promise<Map<string, Proc>> | null = null;
154
+ private operators: Promise<Map<string, Proc>> | null = null;
155
+
156
+ constructor(query: QueryFn, options: NullabilityOptions = {}) {
157
+ this.query = query;
158
+ this.options = options;
159
+ }
160
+
161
+ /** NOT NULL flags of the view's columns, in column order. `relid` is the view's `pg_class.oid`. */
162
+ notNull(relid: string | number): Promise<boolean[]> {
163
+ const key = String(relid);
164
+ let cached = this.views.get(key);
165
+ if (!cached) {
166
+ cached = this.analyze(key);
167
+ this.views.set(key, cached);
168
+ }
169
+ return cached;
170
+ }
171
+
172
+ private async analyze(relid: string): Promise<boolean[]> {
173
+ const { rows } = await this.query(
174
+ `SELECT r.ev_action, c.relname FROM pg_rewrite r JOIN pg_class c ON c.oid = r.ev_class
175
+ WHERE r.ev_class = $1 AND r.rulename = '_RETURN'`,
176
+ [relid],
177
+ );
178
+ const row = rows[0] as { ev_action: string; relname: string } | undefined;
179
+ if (!row) return [];
180
+ const query = node(list(parseNodeTree(row.ev_action))[0]);
181
+ if (!query) return [];
182
+ const out: boolean[] = [];
183
+ for (const te of list(query["targetList"])) {
184
+ const entry = node(te);
185
+ if (!entry || entry["resjunk"] === "true") continue;
186
+ const name = str(entry["resname"]) ?? "";
187
+ out.push((await this.expr(entry["expr"], query)) || (this.options.notNull?.(row.relname, name) ?? false));
188
+ }
189
+ return out;
190
+ }
191
+
192
+ private loadProcs(): Promise<Map<string, Proc>> {
193
+ this.procs ??= this.query(
194
+ `SELECT p.oid::int8::text AS oid, p.proname AS name, t.typname AS ret, p.pronamespace = 'pg_catalog'::regnamespace AS system
195
+ FROM pg_proc p JOIN pg_type t ON t.oid = p.prorettype`,
196
+ ).then(({ rows }) => new Map((rows as (Proc & { oid: string })[]).map((r) => [r.oid, r])));
197
+ return this.procs;
198
+ }
199
+
200
+ private loadOperators(): Promise<Map<string, Proc>> {
201
+ this.operators ??= this.query(
202
+ `SELECT o.oid::int8::text AS oid, o.oprname AS name, '' AS ret, o.oprnamespace = 'pg_catalog'::regnamespace AS system
203
+ FROM pg_operator o`,
204
+ ).then(({ rows }) => new Map((rows as (Proc & { oid: string })[]).map((r) => [r.oid, r])));
205
+ return this.operators;
206
+ }
207
+
208
+ /** A built-in operator that returns a value for non-NULL operands. */
209
+ private async strictOperator(e: Node): Promise<boolean> {
210
+ const op = (await this.loadOperators()).get(str(e["opno"]) ?? "");
211
+ return op?.system === true && !NULLABLE_OPERATORS.has(op.name);
212
+ }
213
+
214
+ private columns(relid: string): Promise<Att[]> {
215
+ let cached = this.atts.get(relid);
216
+ if (!cached) {
217
+ cached = this.query(
218
+ // NOT NULL: the column's constraint, or a NOT NULL domain anywhere in its domain chain.
219
+ `SELECT a.attnum, c.relkind,
220
+ a.attnotnull OR coalesce((
221
+ WITH RECURSIVE chain(oid, nn) AS (
222
+ SELECT t.oid, t.typnotnull FROM pg_type t WHERE t.oid = a.atttypid AND t.typtype = 'd'
223
+ UNION ALL
224
+ SELECT b.oid, b.typnotnull FROM chain JOIN pg_type d ON d.oid = chain.oid
225
+ JOIN pg_type b ON b.oid = d.typbasetype AND b.typtype = 'd')
226
+ SELECT bool_or(nn) FROM chain), false) AS notnull
227
+ FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid
228
+ WHERE a.attrelid = $1 AND a.attnum > 0 AND NOT a.attisdropped`,
229
+ [relid],
230
+ ).then(({ rows }) => rows as Att[]);
231
+ this.atts.set(relid, cached);
232
+ }
233
+ return cached;
234
+ }
235
+
236
+ /** Is output column `attno` (1-based) of a (sub)query NOT NULL? */
237
+ private async queryColumn(query: Node, attno: number): Promise<boolean> {
238
+ if (query["setOperations"]) {
239
+ // UNION / INTERSECT / EXCEPT: every arm (a subquery in the range table) must be NOT NULL.
240
+ for (const r of list(query["rtable"])) {
241
+ const rte = node(r);
242
+ const sub = node(rte?.["subquery"]);
243
+ if (rte?.["rtekind"] === "1" && sub && !(await this.queryColumn(sub, attno))) return false;
244
+ }
245
+ return true;
246
+ }
247
+ const entries = list(query["targetList"]).map(node).filter((t): t is Node => t !== null && t["resjunk"] !== "true");
248
+ const te = entries[attno - 1];
249
+ return te ? this.expr(te["expr"], query) : false;
250
+ }
251
+
252
+ private async variable(v: Node, query: Node): Promise<boolean> {
253
+ // No varnullingrels (PostgreSQL ≤ 15): outer joins are not visible, so nothing is proven.
254
+ if (!("varnullingrels" in v) || v["varlevelsup"] !== "0") return false;
255
+ if (list(v["varnullingrels"]).length > 1) return false; // `(b 3)`: an outer join can null it
256
+ // ROLLUP / CUBE / GROUPING SETS null the grouped columns (PostgreSQL ≤ 17 does not mark them).
257
+ if (list(query["groupingSets"]).length > 0) return false;
258
+ const rte = node(list(query["rtable"])[Number(v["varno"]) - 1]);
259
+ const attno = Number(v["varattno"]);
260
+ if (!rte || !(attno > 0)) return false;
261
+ switch (rte["rtekind"]) {
262
+ case "0": { // relation
263
+ const relid = str(rte["relid"])!;
264
+ const att = (await this.columns(relid)).find((a) => a.attnum === attno);
265
+ if (!att) return false;
266
+ if (att.relkind === "v" || att.relkind === "m") return (await this.notNull(relid))[attno - 1] ?? false;
267
+ return att.notnull;
268
+ }
269
+ case "1": { // subquery
270
+ const sub = node(rte["subquery"]);
271
+ return sub ? this.queryColumn(sub, attno) : false;
272
+ }
273
+ case "2": // join alias variable
274
+ return this.expr(list(rte["joinaliasvars"])[attno - 1] ?? null, query);
275
+ case "3": // function in FROM
276
+ return this.functionColumn(rte, attno);
277
+ case "9": // PostgreSQL 18 GROUP BY expressions
278
+ return this.expr(list(rte["groupexprs"])[attno - 1] ?? null, query);
279
+ default:
280
+ return false;
281
+ }
282
+ }
283
+
284
+ /** Column `attno` of a single set-returning function in FROM (`WITH ORDINALITY` adds a NOT NULL counter). */
285
+ private async functionColumn(rte: Node, attno: number): Promise<boolean> {
286
+ const functions = list(rte["functions"]);
287
+ const only = node(functions[0]);
288
+ if (functions.length !== 1 || !only) return false;
289
+ const count = Number(str(only["funccolcount"]));
290
+ if (rte["funcordinality"] === "true" && attno === count + 1) return true;
291
+ const call = node(only["funcexpr"]);
292
+ if (call?._ !== "FUNCEXPR") return false;
293
+ const proc = (await this.loadProcs()).get(str(call["funcid"]) ?? "");
294
+ return proc?.system === true && (NON_NULL_SRF_COLUMNS[proc.name]?.includes(attno) ?? false);
295
+ }
296
+
297
+ private async all(args: NodeValue | undefined, query: Node): Promise<boolean> {
298
+ for (const a of list(args)) if (!(await this.expr(a, query))) return false;
299
+ return true;
300
+ }
301
+
302
+ private async expr(value: NodeValue | undefined, query: Node): Promise<boolean> {
303
+ const e = node(value);
304
+ if (!e) return false;
305
+ switch (e._) {
306
+ case "VAR":
307
+ return this.variable(e, query);
308
+ case "CONST":
309
+ return e["constisnull"] === "false";
310
+ case "RELABELTYPE": case "COERCEVIAIO": case "COERCETODOMAIN": case "ARRAYCOERCEEXPR": case "COLLATEEXPR":
311
+ return this.expr(e["arg"], query);
312
+ case "FUNCEXPR": {
313
+ if (e["funcretset"] !== "false") return false;
314
+ const proc = (await this.loadProcs()).get(str(e["funcid"]) ?? "");
315
+ // format_type(type, typmod) is not strict: a NULL typmod still gives a name.
316
+ if (proc?.system && proc.name === "format_type") return this.expr(list(e["args"])[0] ?? null, query);
317
+ // Explicit and implicit casts (funcformat 1, 2) keep a non-NULL input non-NULL.
318
+ const castLike = e["funcformat"] === "1" || e["funcformat"] === "2";
319
+ const known = proc?.system === true && (NON_NULL_FUNCTIONS.has(proc.name) || isNonNullStatFunction(proc.name, proc.ret));
320
+ return (castLike || known) && this.all(e["args"], query);
321
+ }
322
+ case "BOOLEXPR":
323
+ return this.all(e["args"], query);
324
+ case "OPEXPR":
325
+ return (await this.strictOperator(e)) && this.all(e["args"], query);
326
+ case "SCALARARRAYOPEXPR": {
327
+ // `x = ANY (arr)` is NULL when there is no match and `arr` holds a NULL: only an
328
+ // `ARRAY[…]` of NOT NULL elements is safe.
329
+ const [left, right] = list(e["args"]);
330
+ const array = node(right);
331
+ return (await this.strictOperator(e)) && array?._ === "ARRAYEXPR"
332
+ && (await this.expr(left ?? null, query)) && this.all(array["elements"], query);
333
+ }
334
+ case "DISTINCTEXPR": case "NULLTEST": case "BOOLEANTEST": case "ARRAYEXPR": case "ROW":
335
+ return true;
336
+ case "COALESCEEXPR": case "MINMAXEXPR":
337
+ for (const a of list(e["args"])) if (await this.expr(a, query)) return true;
338
+ return false;
339
+ case "CASEEXPR":
340
+ for (const w of list(e["args"])) if (!(await this.expr(node(w)?.["result"], query))) return false;
341
+ return this.expr(e["defresult"], query);
342
+ case "SUBLINK": // EXISTS (0) and ARRAY (6) sublinks are never NULL
343
+ return e["subLinkType"] === "0" || e["subLinkType"] === "6";
344
+ case "AGGREF": {
345
+ const proc = (await this.loadProcs()).get(str(e["aggfnoid"]) ?? "");
346
+ return proc?.system === true && NON_NULL_AGGREGATES.has(proc.name);
347
+ }
348
+ case "WINDOWFUNC": {
349
+ const proc = (await this.loadProcs()).get(str(e["winfnoid"]) ?? "");
350
+ return proc?.system === true && NON_NULL_WINDOW_FUNCTIONS.has(proc.name);
351
+ }
352
+ default:
353
+ return false;
354
+ }
355
+ }
356
+ }
package/src/type-map.ts CHANGED
@@ -1,22 +1,15 @@
1
- import type { DefaultTypeMap } from "@typesql/core";
1
+ import type { DefaultParamTypeMap, DefaultTypeMap } from "@typesql/core";
2
2
 
3
3
  /**
4
4
  * The object node-postgres returns for an `interval` column (package `postgres-interval` 1.x,
5
5
  * wired up by `pg-types`). Fields are only present when non-zero; `toPostgres()` renders the
6
6
  * value back to Postgres syntax and `toISO()`/`toISOString()` produce an ISO 8601 duration.
7
+ *
8
+ * Written inline in `PgTypeMap` (this alias only reads it back), so row types stay plain
9
+ * object types: declaration emit in a package without a direct `@typesql/pg` dependency does
10
+ * not need to name `PgInterval` (TS2883).
7
11
  */
8
- export interface PgInterval {
9
- years?: number;
10
- months?: number;
11
- days?: number;
12
- hours?: number;
13
- minutes?: number;
14
- seconds?: number;
15
- milliseconds?: number;
16
- toPostgres(): string;
17
- toISO(): string;
18
- toISOString(): string;
19
- }
12
+ export type PgInterval = PgTypeMap["interval"];
20
13
 
21
14
  /**
22
15
  * Canonical Postgres type name → TS type as `pg` 8.x returns it with its default type
@@ -52,12 +45,47 @@ export interface PgInterval {
52
45
  * line[], lseg[], box[], path[], polygon[], int4range[], int8range[], tsrange[],
53
46
  * tstzrange[], daterange[], macaddr8[], regclass[]/regtype[]/regproc[], record[].
54
47
  * Register your own parser (`pg.types.setTypeParser`) or cast in SQL if you depend on these.
48
+ * The two that `PgCatalog` columns use are declared here as the text pg returns: `aclitem[]`
49
+ * (`relacl`, `datacl`, ...) and `"char"[]` (`proargmodes`).
55
50
  */
56
51
  export interface PgTypeMap extends Omit<DefaultTypeMap, "bytea" | "interval" | "record" | "void"> {
52
+ /** What parameters accept on top of the row types. */
53
+ $params: PgParamTypeMap;
57
54
  bytea: Buffer;
58
- interval: PgInterval;
55
+ interval: {
56
+ years?: number;
57
+ months?: number;
58
+ days?: number;
59
+ hours?: number;
60
+ minutes?: number;
61
+ seconds?: number;
62
+ milliseconds?: number;
63
+ toPostgres(): string;
64
+ toISO(): string;
65
+ toISOString(): string;
66
+ };
59
67
  /** Anonymous `ROW(...)` results have no parser: raw text such as `"(1,foo)"`. */
60
68
  record: string;
61
69
  /** `void`-returning functions (`pg_sleep`) yield an empty string. */
62
70
  void: string;
71
+ /** No array parser: the raw `{...}` text, e.g. `"{postgres=arwdDxtm/postgres}"`. */
72
+ "aclitem[]": string;
73
+ /** No array parser for `"char"[]`: the raw `{...}` text, e.g. `"{i,o}"`. */
74
+ "char[]": string;
63
75
  }
76
+
77
+ /**
78
+ * TS types `pg` parameters accept on top of the row type (`PgTypeMap["$params"]`). Verified
79
+ * against `pg/lib/utils.js` (`prepareValue`, 8.x): a `Date` is sent as a timestamp with the
80
+ * local offset, `Buffer`/typed arrays as bytea, a `bigint` or number with `toString()`, and
81
+ * objects with `toPostgres()` (such as `PgInterval`) through it; Postgres parses the text.
82
+ *
83
+ * int8, numeric, money number | bigint | string
84
+ * date, timestamp, timestamptz Date | string
85
+ * interval string, besides the `PgInterval` row type
86
+ * bytea Uint8Array, besides `Buffer`
87
+ *
88
+ * Plain objects are `JSON.stringify`d and arrays become Postgres array literals, so neither is
89
+ * listed for other types.
90
+ */
91
+ export interface PgParamTypeMap extends DefaultParamTypeMap {}