@crvouga/mockingbird-service-postgres 0.1.0

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 (118) hide show
  1. package/AGENTS.md +174 -0
  2. package/COMPATIBILITY-AUDIT.md +156 -0
  3. package/COMPATIBILITY.md +87 -0
  4. package/LICENSE +21 -0
  5. package/README.md +416 -0
  6. package/compat/coverage.json +1081 -0
  7. package/compat/divergences.json +195 -0
  8. package/compat/requirements.json +1105 -0
  9. package/compat/scenario-types.ts +98 -0
  10. package/compat/scenarios.ts +98 -0
  11. package/compat/sections/agg.ts +45 -0
  12. package/compat/sections/api.ts +34 -0
  13. package/compat/sections/arr.ts +45 -0
  14. package/compat/sections/cat.ts +47 -0
  15. package/compat/sections/con.ts +32 -0
  16. package/compat/sections/cpy.ts +24 -0
  17. package/compat/sections/cte.ts +29 -0
  18. package/compat/sections/dat.ts +60 -0
  19. package/compat/sections/ddl.ts +55 -0
  20. package/compat/sections/det.ts +20 -0
  21. package/compat/sections/dml.ts +37 -0
  22. package/compat/sections/eco.ts +16 -0
  23. package/compat/sections/err.ts +16 -0
  24. package/compat/sections/exp.ts +53 -0
  25. package/compat/sections/fun.ts +58 -0
  26. package/compat/sections/fzz.ts +41 -0
  27. package/compat/sections/guc.ts +27 -0
  28. package/compat/sections/joi.ts +33 -0
  29. package/compat/sections/jsn.ts +46 -0
  30. package/compat/sections/lim.ts +13 -0
  31. package/compat/sections/par.ts +54 -0
  32. package/compat/sections/pre.ts +26 -0
  33. package/compat/sections/sch.ts +31 -0
  34. package/compat/sections/sel.ts +43 -0
  35. package/compat/sections/seq.ts +31 -0
  36. package/compat/sections/snp.ts +22 -0
  37. package/compat/sections/tok.ts +53 -0
  38. package/compat/sections/trg.ts +57 -0
  39. package/compat/sections/tsr.ts +37 -0
  40. package/compat/sections/txn.ts +39 -0
  41. package/compat/sections/typ.ts +55 -0
  42. package/compat/sections/uni.ts +13 -0
  43. package/compat/sections/win.ts +43 -0
  44. package/compat/smoke-baseline.json +3 -0
  45. package/compat/unsupported-register.json +2524 -0
  46. package/dist/api/bind.d.ts +11 -0
  47. package/dist/api/database.d.ts +87 -0
  48. package/dist/api/snapshot.d.ts +21 -0
  49. package/dist/api/statement.d.ts +51 -0
  50. package/dist/ast/nodes.d.ts +812 -0
  51. package/dist/constraints/enforce.d.ts +40 -0
  52. package/dist/errors/error.d.ts +24 -0
  53. package/dist/executor/ddl.d.ts +23 -0
  54. package/dist/executor/dml.d.ts +10 -0
  55. package/dist/executor/execute.d.ts +11 -0
  56. package/dist/executor/plpgsql.d.ts +72 -0
  57. package/dist/executor/relation.d.ts +60 -0
  58. package/dist/executor/select.d.ts +45 -0
  59. package/dist/executor/session.d.ts +21 -0
  60. package/dist/executor/triggers-exec.d.ts +1 -0
  61. package/dist/executor/triggers.d.ts +16 -0
  62. package/dist/executor/window.d.ts +13 -0
  63. package/dist/expressions/context.d.ts +23 -0
  64. package/dist/expressions/eval.d.ts +42 -0
  65. package/dist/expressions/operators.d.ts +8 -0
  66. package/dist/expressions/pattern.d.ts +20 -0
  67. package/dist/functions/aggregates.d.ts +17 -0
  68. package/dist/functions/array-fns.d.ts +2 -0
  69. package/dist/functions/datetime-fns.d.ts +26 -0
  70. package/dist/functions/datetime-registry.d.ts +2 -0
  71. package/dist/functions/json-fns.d.ts +7 -0
  72. package/dist/functions/math-fns.d.ts +2 -0
  73. package/dist/functions/misc-fns.d.ts +8 -0
  74. package/dist/functions/scalar.d.ts +10 -0
  75. package/dist/functions/srf.d.ts +12 -0
  76. package/dist/functions/string-fns.d.ts +4 -0
  77. package/dist/functions/tsearch-fns.d.ts +2 -0
  78. package/dist/functions/util.d.ts +14 -0
  79. package/dist/functions/window.d.ts +7 -0
  80. package/dist/index.d.ts +28 -0
  81. package/dist/index.js +23581 -0
  82. package/dist/index.js.map +7 -0
  83. package/dist/indexes/index.d.ts +14 -0
  84. package/dist/indexes/maintain.d.ts +11 -0
  85. package/dist/lexer/tokenize.d.ts +8 -0
  86. package/dist/parser/index.d.ts +1 -0
  87. package/dist/parser/parser.d.ts +98 -0
  88. package/dist/planner/access.d.ts +15 -0
  89. package/dist/runtime/assert.d.ts +5 -0
  90. package/dist/runtime/clock.d.ts +14 -0
  91. package/dist/runtime/index.d.ts +3 -0
  92. package/dist/runtime/options.d.ts +34 -0
  93. package/dist/runtime/prng.d.ts +48 -0
  94. package/dist/schema/catalog-tables.d.ts +1 -0
  95. package/dist/schema/catalog.d.ts +12 -0
  96. package/dist/serialization/codec.d.ts +22 -0
  97. package/dist/serialization/index.d.ts +1 -0
  98. package/dist/serialization/wire.d.ts +63 -0
  99. package/dist/sql/deparse.d.ts +3 -0
  100. package/dist/storage/columnar-slab.d.ts +37 -0
  101. package/dist/storage/database-state.d.ts +253 -0
  102. package/dist/transactions/manager.d.ts +25 -0
  103. package/dist/tsearch/stem.d.ts +5 -0
  104. package/dist/tsearch/tsearch.d.ts +59 -0
  105. package/dist/types/cast.d.ts +26 -0
  106. package/dist/types/compare.d.ts +18 -0
  107. package/dist/types/datetime.d.ts +68 -0
  108. package/dist/types/jsonb.d.ts +47 -0
  109. package/dist/types/jsonpath.d.ts +16 -0
  110. package/dist/types/numeric.d.ts +69 -0
  111. package/dist/types/range.d.ts +17 -0
  112. package/dist/types/resolve.d.ts +15 -0
  113. package/dist/types/timezone.d.ts +9 -0
  114. package/dist/types/value.d.ts +99 -0
  115. package/dist/unstable.d.ts +15 -0
  116. package/dist/unstable.js +21810 -0
  117. package/dist/unstable.js.map +7 -0
  118. package/package.json +131 -0
@@ -0,0 +1,14 @@
1
+ /** Btree / hash index over row indices. Keys are pre-serialized (datumKey tuples). */
2
+ export declare class IndexStore {
3
+ readonly name: string;
4
+ readonly unique: boolean;
5
+ private entries;
6
+ constructor(name: string, unique?: boolean);
7
+ get size(): number;
8
+ checkUnique(key: string, rowIdx?: number): void;
9
+ insert(key: string, rowIdx: number): void;
10
+ remove(key: string, rowIdx: number): void;
11
+ lookup(key: string): readonly number[];
12
+ clear(): void;
13
+ clone(): IndexStore;
14
+ }
@@ -0,0 +1,11 @@
1
+ import { type UniqueSpec } from "../constraints/enforce.js";
2
+ import type { ExecEnv } from "../executor/relation.js";
3
+ import type { TableData } from "../storage/database-state.js";
4
+ import type { Datum } from "../types/value.js";
5
+ import { IndexStore } from "./index.js";
6
+ export declare function invalidateTableIndexes(table: TableData): void;
7
+ export declare function indexStoreFor(env: ExecEnv, table: TableData, spec: UniqueSpec): IndexStore;
8
+ export declare function indexInsertRow(env: ExecEnv, table: TableData, rowIdx: number, row: Datum[]): void;
9
+ export declare function indexRemoveRow(env: ExecEnv, table: TableData, rowIdx: number, row: Datum[]): void;
10
+ export declare function indexUpdateRow(env: ExecEnv, table: TableData, rowIdx: number, oldRow: Datum[], newRow: Datum[]): void;
11
+ export declare function rebuildTableIndexes(env: ExecEnv, table: TableData): void;
@@ -0,0 +1,8 @@
1
+ export type TokenType = "ident" | "quoted_ident" | "string" | "bitstring" | "number" | "param" | "op" | "punct" | "eof";
2
+ export interface Token {
3
+ readonly type: TokenType;
4
+ readonly value: string;
5
+ /** byte offset in the source (for error positions) */
6
+ readonly pos: number;
7
+ }
8
+ export declare function tokenize(sql: string): Token[];
@@ -0,0 +1 @@
1
+ export { parse, parseSingle } from "./parser.js";
@@ -0,0 +1,98 @@
1
+ import type { Expr, SelectStmt, Statement, TypeName, WithClause } from "../ast/nodes.js";
2
+ export declare class Parser {
3
+ private tokens;
4
+ private pos;
5
+ constructor(sql: string);
6
+ private peek;
7
+ private next;
8
+ private atKw;
9
+ private eatKw;
10
+ private expectKw;
11
+ private atPunct;
12
+ private eatPunct;
13
+ private expectPunct;
14
+ private atOp;
15
+ private eatOp;
16
+ private errorAt;
17
+ /** identifier (unquoted non-reserved or quoted) */
18
+ private ident;
19
+ private qualifiedName;
20
+ parseStatements(): Statement[];
21
+ parseStatement(): Statement;
22
+ private skipToStatementEnd;
23
+ /** Consume tokens until the matching `)` after an opening `(` already eaten. */
24
+ private skipBalancedCloseParen;
25
+ private parseWithableStatement;
26
+ private parseWithClause;
27
+ parseSelectStmt(withClause?: WithClause | null): SelectStmt;
28
+ private parseSelectBody;
29
+ private parseSelectTerm;
30
+ private parseSelectPrimary;
31
+ private parseSelectCore;
32
+ private parseGroupItem;
33
+ private parseSelectTarget;
34
+ private parseOrderByClause;
35
+ private parseOrderByItem;
36
+ private parseLimitOffset;
37
+ private parseFromItem;
38
+ private tryParseJoin;
39
+ private parseFromPrimary;
40
+ private parseWithOrdinality;
41
+ private parseAliasClause;
42
+ private parseInsert;
43
+ private parseReturning;
44
+ private parseUpdateSets;
45
+ private parseSetColumn;
46
+ private parseUpdate;
47
+ private parseDelete;
48
+ private parseCreate;
49
+ private parseIfNotExists;
50
+ private parseIfExists;
51
+ private parseCreateTable;
52
+ private tryParseTableConstraint;
53
+ private skipConstraintTail;
54
+ private parseRefActions;
55
+ private parseRefAction;
56
+ private parseColumnDef;
57
+ private parseIdentityOptions;
58
+ private parseSequenceOptions;
59
+ private parseSignedBigInt;
60
+ private parseCreateIndex;
61
+ private parseCreateView;
62
+ private parseCreateFunction;
63
+ private parseCreateTrigger;
64
+ private parseAlter;
65
+ private parseAlterTableAction;
66
+ private parseDrop;
67
+ private parseTruncate;
68
+ private parseSet;
69
+ private parseExplain;
70
+ private parseCopy;
71
+ parseTypeName(): TypeName;
72
+ parseExpr(): Expr;
73
+ private parseOr;
74
+ private parseAnd;
75
+ private parseNot;
76
+ private parseIs;
77
+ private parseComparison;
78
+ private tryParseAnyAll;
79
+ private parseLikeBetweenIn;
80
+ /** all other binary operators: ||, &, |, #, <<, >>, @>, <@, ->, ->>, etc. */
81
+ private parseGenericOps;
82
+ private parseAdditive;
83
+ private parseMultiplicative;
84
+ private parseExponent;
85
+ private parseUnary;
86
+ private parsePostfix;
87
+ private parsePrimary;
88
+ private parseCase;
89
+ private maybePrecision;
90
+ private parseNestedArrayLiteral;
91
+ private parseFuncCall;
92
+ private parseWindowSpec;
93
+ private parseFrameBound;
94
+ }
95
+ /** Parse SQL text into a list of statements. */
96
+ export declare function parse(sql: string): Statement[];
97
+ /** Parse exactly one statement; throws `misuse`-style errors handled by API layer. */
98
+ export declare function parseSingle(sql: string): Statement;
@@ -0,0 +1,15 @@
1
+ import type { Expr, FromItem } from "../ast/nodes.js";
2
+ import { type ExecEnv } from "../executor/relation.js";
3
+ import type { TableData } from "../storage/database-state.js";
4
+ import { type Datum, type TypeId } from "../types/value.js";
5
+ export interface ConstEquality {
6
+ column: string;
7
+ valueExpr: Expr;
8
+ }
9
+ export declare function equalityAgainstConst(expr: Expr): ConstEquality | null;
10
+ export declare function conjunctions(expr: Expr): Expr[];
11
+ /** Single-table PK / unique equality lookup: returns matching rows or null to scan. */
12
+ export declare function tryIndexedTableRows(env: ExecEnv, table: TableData, alias: string, where: Expr): Datum[][] | null;
13
+ export declare function tryIndexedFromItem(env: ExecEnv, item: FromItem, where: Expr | null): Datum[][] | null;
14
+ export declare function joinKeyFromRow(row: Datum[], colIdxs: number[], srcTypes: TypeId[], unifiedTypes: TypeId[], ctx: import("../expressions/context.js").EngineCtx): string | null;
15
+ export declare function rowsMatchEqKeys(ctx: import("../expressions/context.js").EngineCtx, left: Datum[], right: Datum[], leftIdxs: number[], rightIdxs: number[], leftTypes: TypeId[], rightTypes: TypeId[], unifiedTypes: TypeId[]): boolean;
@@ -0,0 +1,5 @@
1
+ /** Internal invariant failure — not a user SQL error. */
2
+ export declare function assert(condition: boolean, message: string): asserts condition;
3
+ export declare function assertDefined<T>(value: T | null | undefined, message: string): T;
4
+ export declare function assertBounds(value: number, min: number, max: number, label: string): void;
5
+ export declare function assertNever(value: never, message?: string): never;
@@ -0,0 +1,14 @@
1
+ /** Fixed reference instant used when callers do not supply a clock (`2000-01-01T00:00:00.000Z`). */
2
+ export declare const DEFAULT_NOW: Date;
3
+ /** Function that returns the current instant for `now()` and related builtins. */
4
+ export type Clock = () => Date;
5
+ /**
6
+ * Clock that always returns a copy of `instant` (default {@link DEFAULT_NOW}).
7
+ *
8
+ * @throws {RangeError} If `instant` is an invalid `Date`.
9
+ */
10
+ export declare function fixedClock(instant?: Date): Clock;
11
+ /** Wall-clock `now()` matching PostgreSQL (`new Date()` each call). */
12
+ export declare function systemClock(): Clock;
13
+ /** Normalize a `Date`, {@link Clock}, `"system"`, or `undefined` into a {@link Clock}. */
14
+ export declare function resolveClock(now?: Date | Clock | "system"): Clock;
@@ -0,0 +1,3 @@
1
+ export { type Clock, DEFAULT_NOW, fixedClock, resolveClock, systemClock } from "./clock.js";
2
+ export { type DatabaseOptions, DEFAULT_DATABASE_SEED, type Int8Mode, type RandomMode } from "./options.js";
3
+ export { deriveSeed, OsEntropy, Prng } from "./prng.js";
@@ -0,0 +1,34 @@
1
+ import type { Clock } from "./clock.js";
2
+ /** Entropy source for `random()` / `gen_random_uuid()`. Default is seeded xorshift64*. */
3
+ export type RandomMode = "deterministic" | "os";
4
+ /** How `int8` columns surface in query row objects. Default `"bigint"`. */
5
+ export type Int8Mode = "bigint" | "number" | "string";
6
+ /** Options for {@link Database} construction. All fields are optional. */
7
+ export interface DatabaseOptions {
8
+ /**
9
+ * Seed for deterministic `random()` (and any other PRNG-backed builtins).
10
+ * Defaults to {@link DEFAULT_DATABASE_SEED} (`1`). Ignored when {@link random} is `"os"`.
11
+ */
12
+ seed?: number | bigint;
13
+ /**
14
+ * Entropy for `random()` / `gen_random_uuid()`.
15
+ * `"deterministic"` (default) uses {@link seed}. `"os"` uses CSPRNG like PostgreSQL
16
+ * (not rolled back with transactions; not restored from snapshots).
17
+ */
18
+ random?: RandomMode;
19
+ /**
20
+ * Clock for `now()` / `current_timestamp` / etc.
21
+ * Defaults to a fixed instant (`2000-01-01T00:00:00.000Z`).
22
+ * Pass a `Date`, `() => Date`, or `"system"` for wall-clock `now()` like PostgreSQL.
23
+ */
24
+ now?: Date | Clock | "system";
25
+ /**
26
+ * How `int8` / `bigint` columns surface in query row objects.
27
+ * Default `"bigint"` matches PostgreSQL's JS-unsafe 64-bit integers.
28
+ * `"number"` uses IEEE number (unsafe beyond `Number.MAX_SAFE_INTEGER`).
29
+ * `"string"` is JSON-safe.
30
+ */
31
+ int8?: Int8Mode;
32
+ }
33
+ /** Default {@link DatabaseOptions.seed} when constructing a {@link Database}. */
34
+ export declare const DEFAULT_DATABASE_SEED = 1;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Deterministic 64-bit PRNG (xorshift64*).
3
+ * Used for PostgreSQL `random()` / `gen_random_uuid()` and any other
4
+ * nondeterministic builtins.
5
+ */
6
+ export declare class Prng {
7
+ private state;
8
+ /**
9
+ * @param seed - Engine seed. `0` is replaced with a non-zero constant.
10
+ */
11
+ constructor(seed?: number | bigint);
12
+ /** Next unsigned 64-bit value. */
13
+ nextU64(): bigint;
14
+ /** Next float in `[0, 1)` from 53 bits of {@link nextU64}. */
15
+ nextFloat(): number;
16
+ /**
17
+ * Next integer in `[min, max]` (inclusive).
18
+ *
19
+ * @throws {RangeError} If `max < min`.
20
+ */
21
+ nextInt(min: number, max: number): number;
22
+ /** Next bigint in `[min, max]` (inclusive). */
23
+ nextBigInt(min: bigint, max: bigint): bigint;
24
+ /** Random UUIDv4 string from PRNG bits. */
25
+ nextUuid4(): string;
26
+ /** Reseed from a float in [-1, 1] (SQL `setseed()`). */
27
+ setSeedFloat(seed: number): void;
28
+ /** Current unsigned 64-bit engine state (for snapshot / transaction rollback). */
29
+ getState(): bigint;
30
+ /** Restore unsigned 64-bit engine state from {@link getState}. */
31
+ setState(state: bigint): void;
32
+ /** Independent copy with the same engine state. */
33
+ clone(): Prng;
34
+ }
35
+ /**
36
+ * CSPRNG-backed entropy for `random()` / `gen_random_uuid()` when
37
+ * {@link DatabaseOptions.random} is `"os"`. `setState` is a no-op so
38
+ * ROLLBACK / snapshot restore do not rewind draws.
39
+ */
40
+ export declare class OsEntropy extends Prng {
41
+ constructor();
42
+ nextU64(): bigint;
43
+ getState(): bigint;
44
+ setState(_state: bigint): void;
45
+ clone(): Prng;
46
+ }
47
+ /** FNV-1a hash of `parts` as a signed 32-bit seed (for tests and custom PRNGs). */
48
+ export declare function deriveSeed(...parts: Array<number | string | bigint>): number;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,12 @@
1
+ import type { Relation } from "../executor/relation.js";
2
+ import type { EngineCtx } from "../expressions/context.js";
3
+ /**
4
+ * Virtual pg_catalog / information_schema relations, materialized on demand.
5
+ * Implemented in catalog-tables.ts; this indirection keeps the executor
6
+ * import graph acyclic.
7
+ */
8
+ export type CatalogBuilder = (ctx: EngineCtx, schema: string, name: string) => Relation | null;
9
+ export declare function setCatalogBuilder(b: CatalogBuilder): void;
10
+ export declare function catalogRelation(ctx: EngineCtx, schema: string, name: string): Relation | null;
11
+ /** Relations resolvable unqualified via the implicit pg_catalog search-path entry. */
12
+ export declare const PG_CATALOG_RELATIONS: ReadonlySet<string>;
@@ -0,0 +1,22 @@
1
+ import type { Clock } from "../runtime/clock.js";
2
+ import type { Prng } from "../runtime/prng.js";
3
+ import { DatabaseState } from "../storage/database-state.js";
4
+ /** PRNG + clock captured alongside catalog/rows. */
5
+ export interface SnapshotRuntime {
6
+ prngState: bigint;
7
+ nowMs: number;
8
+ }
9
+ /** Result of {@link decodeDatabaseState}. */
10
+ export interface DecodedSnapshot {
11
+ state: DatabaseState;
12
+ runtime: SnapshotRuntime | null;
13
+ }
14
+ /**
15
+ * Encode catalog, rows, and runtime into a postgres-mem `PGMM` snapshot blob
16
+ * (not an on-disk PostgreSQL format).
17
+ */
18
+ export declare function encodeDatabaseState(state: DatabaseState, runtime: SnapshotRuntime): Uint8Array;
19
+ /**
20
+ * Decode a blob from {@link encodeDatabaseState} / {@link Database.snapshot}.
21
+ */
22
+ export declare function decodeDatabaseState(snapshot: Uint8Array, prng: Prng, clock: Clock): DecodedSnapshot;
@@ -0,0 +1 @@
1
+ export { type DecodedSnapshot, decodeDatabaseState, encodeDatabaseState, type SnapshotRuntime, } from "./codec.js";
@@ -0,0 +1,63 @@
1
+ export declare function utf8Encode(s: string): Uint8Array;
2
+ export declare function utf8Decode(b: Uint8Array): string;
3
+ export declare function writeVarintU32(w: Writer, value: number): void;
4
+ export declare function readVarintU32(r: Reader): number;
5
+ export declare class Writer {
6
+ private buf;
7
+ private view;
8
+ private len;
9
+ constructor(capacity?: number);
10
+ get position(): number;
11
+ reserve(capacity: number): void;
12
+ private ensure;
13
+ align4(): void;
14
+ u8(value: number): void;
15
+ u32(value: number): void;
16
+ i32(value: number): void;
17
+ u64(value: bigint): void;
18
+ i64(value: bigint): void;
19
+ f64(value: number): void;
20
+ raw(value: Uint8Array): void;
21
+ /** Length-prefixed UTF-8. */
22
+ text(value: string): void;
23
+ /** Write UTF-8 at current position without length prefix (intern blob region). */
24
+ textBytes(value: string): void;
25
+ finish(): Uint8Array;
26
+ fail(): never;
27
+ }
28
+ export declare class Reader {
29
+ private readonly bytes;
30
+ private offset;
31
+ private readonly view;
32
+ constructor(bytes: Uint8Array);
33
+ get position(): number;
34
+ skipAlign4(): void;
35
+ u8(): number;
36
+ u32(): number;
37
+ i32(): number;
38
+ u64(): bigint;
39
+ i64(): bigint;
40
+ f64(): number;
41
+ raw(length: number): Uint8Array;
42
+ text(): string;
43
+ remaining(): number;
44
+ done(): boolean;
45
+ fail(): never;
46
+ }
47
+ export declare function writeBjv(w: Writer, value: unknown, forceIntern: (s: string) => number): void;
48
+ export declare function readBjv(r: Reader, intern: readonly string[]): unknown;
49
+ export declare class InternPool {
50
+ private readonly counts;
51
+ private readonly ids;
52
+ readonly list: string[];
53
+ constructor();
54
+ count(s: string): void;
55
+ /** Assign ids only to strings seen ≥2 times (plus empty string). */
56
+ finalize(): void;
57
+ /** Always intern (schema / catalog strings). */
58
+ forceId(s: string): number;
59
+ id(s: string): number;
60
+ }
61
+ /** Write intern table: count, offsets[], concatenated UTF-8 blob. */
62
+ export declare function writeInternTable(w: Writer, strings: readonly string[]): void;
63
+ export declare function readInternTable(r: Reader): string[];
@@ -0,0 +1,3 @@
1
+ import type { SelectStmt } from "../ast/nodes.js";
2
+ /** Minimal SELECT deparsing for pg_get_viewdef / information_schema. */
3
+ export declare function deparseSelect(stmt: SelectStmt): string;
@@ -0,0 +1,37 @@
1
+ import type { Datum } from "../types/value.js";
2
+ /** Column pack tags (PGMM v3). */
3
+ export declare const PACK_NULL = 0;
4
+ export declare const PACK_BOOL = 1;
5
+ export declare const PACK_FLOAT = 2;
6
+ export declare const PACK_INT = 3;
7
+ export declare const PACK_TEXT_INTERN = 4;
8
+ export declare const PACK_TEXT_INLINE = 5;
9
+ export declare const PACK_BLOB = 6;
10
+ export declare const PACK_TAGGED = 7;
11
+ export interface SlabColumn {
12
+ pack: number;
13
+ nullBitmap: Uint8Array | null;
14
+ /** Prefix sum of non-null rows for O(1) null-index lookup. */
15
+ nonNullPrefix?: Uint32Array;
16
+ /** Typed payload or inline blob region inside `buffer`. */
17
+ payload: Uint8Array;
18
+ /** For PACK_TEXT_INLINE: u32 offsets into payload per row. */
19
+ inlineOffsets?: Uint32Array;
20
+ /** For PACK_TAGGED: decoded values per non-null row in order. */
21
+ tagged?: Datum[];
22
+ /** For PACK_BLOB: one entry per non-null row (zero-copy views). */
23
+ blobChunks?: Uint8Array[];
24
+ }
25
+ /** Frozen columnar row storage; zero-copy views into snapshot buffer. */
26
+ export declare class ColumnarSlab {
27
+ readonly buffer: Uint8Array;
28
+ readonly rowCount: number;
29
+ readonly columns: SlabColumn[];
30
+ private readonly intern;
31
+ constructor(buffer: Uint8Array, rowCount: number, columns: SlabColumn[], intern: readonly string[]);
32
+ cell(rowIndex: number, col: number): Datum;
33
+ rowAt(rowIndex: number): Datum[];
34
+ scan(): Generator<Datum[]>;
35
+ materialize(): Datum[][];
36
+ }
37
+ export declare function packKindOf(value: Datum): number;
@@ -0,0 +1,253 @@
1
+ import type { CreateTriggerStmt, Expr, SelectStmt, Statement } from "../ast/nodes.js";
2
+ import type { Clock } from "../runtime/clock.js";
3
+ import type { Prng } from "../runtime/prng.js";
4
+ import { type ColumnType, type Datum, type TypeId } from "../types/value.js";
5
+ import type { ColumnarSlab } from "./columnar-slab.js";
6
+ export interface ColumnMeta {
7
+ name: string;
8
+ type: ColumnType;
9
+ notNull: boolean;
10
+ defaultExpr: Expr | null;
11
+ identity: {
12
+ always: boolean;
13
+ sequence: string;
14
+ } | null;
15
+ generated: Expr | null;
16
+ collate: string | null;
17
+ /** resolved domain name when column type came from a domain */
18
+ domain: string | null;
19
+ }
20
+ export type ConstraintMeta = {
21
+ kind: "primary_key";
22
+ name: string;
23
+ columns: string[];
24
+ } | {
25
+ kind: "unique";
26
+ name: string;
27
+ columns: string[];
28
+ nullsNotDistinct: boolean;
29
+ } | {
30
+ kind: "check";
31
+ name: string;
32
+ expr: Expr;
33
+ } | {
34
+ kind: "foreign_key";
35
+ name: string;
36
+ columns: string[];
37
+ refSchema: string;
38
+ refTable: string;
39
+ refColumns: string[];
40
+ onDelete: string | null;
41
+ onUpdate: string | null;
42
+ match: "full" | "simple";
43
+ };
44
+ export interface IndexMeta {
45
+ name: string;
46
+ schema: string;
47
+ table: string;
48
+ unique: boolean;
49
+ /** simple column indexes store names; expression indexes store the AST */
50
+ columns: Array<{
51
+ column: string | null;
52
+ expr: Expr | null;
53
+ dir: "asc" | "desc";
54
+ nulls: "first" | "last";
55
+ }>;
56
+ where: Expr | null;
57
+ nullsNotDistinct: boolean;
58
+ /** true when this index backs a constraint (pkey / unique constraint) */
59
+ isConstraint: boolean;
60
+ }
61
+ export interface TriggerMeta {
62
+ name: string;
63
+ timing: "before" | "after" | "instead_of";
64
+ events: CreateTriggerStmt["events"];
65
+ forEachRow: boolean;
66
+ when: Expr | null;
67
+ funcSchema: string;
68
+ funcName: string;
69
+ funcArgs: string[];
70
+ }
71
+ export declare class TableData {
72
+ name: string;
73
+ schema: string;
74
+ columns: ColumnMeta[];
75
+ rows: Datum[][];
76
+ /** Frozen columnar storage after snapshot hydrate; `rows` stays empty until materialized. */
77
+ slab: ColumnarSlab | null;
78
+ constraints: ConstraintMeta[];
79
+ triggers: TriggerMeta[];
80
+ temp: boolean;
81
+ /** monotonically increasing oid-like id for catalog output */
82
+ readonly oid: number;
83
+ /** >0 while shared with a clone or transaction snapshot. */
84
+ shareCount: number;
85
+ /** Derived unique/btree index maps; null until built or invalidated. */
86
+ indexStores: Map<string, import("../indexes/index.js").IndexStore> | null;
87
+ constructor(schema: string, name: string, columns: ColumnMeta[], oid: number, temp?: boolean);
88
+ rowCount(): number;
89
+ rowAt(index: number): Datum[];
90
+ /** All rows for scans; materializes slab once into `rows` when needed. */
91
+ allRows(): Datum[][];
92
+ attachSlab(slab: ColumnarSlab): void;
93
+ materializeSlab(): void;
94
+ /** Writable row storage; materializes slab if needed. */
95
+ mutableRows(): Datum[][];
96
+ get frozen(): boolean;
97
+ freeze(): void;
98
+ thaw(): void;
99
+ columnIndex(name: string): number;
100
+ clone(): TableData;
101
+ /** Independent writable copy (row tuples copied so ALTER COLUMN is isolated). */
102
+ cloneForWrite(): TableData;
103
+ }
104
+ export interface ViewData {
105
+ name: string;
106
+ schema: string;
107
+ query: SelectStmt;
108
+ columns: string[] | null;
109
+ materialized: boolean;
110
+ /** materialized contents; null = WITH NO DATA (not populated) */
111
+ matRows: Datum[][] | null;
112
+ matColumns: Array<{
113
+ name: string;
114
+ type: TypeId;
115
+ }> | null;
116
+ temp: boolean;
117
+ oid: number;
118
+ shareCount?: number;
119
+ }
120
+ export interface SequenceData {
121
+ name: string;
122
+ schema: string;
123
+ increment: bigint;
124
+ minValue: bigint;
125
+ maxValue: bigint;
126
+ startValue: bigint;
127
+ cache: bigint;
128
+ cycle: boolean;
129
+ lastValue: bigint;
130
+ isCalled: boolean;
131
+ ownedBy: {
132
+ table: string;
133
+ column: string;
134
+ } | null;
135
+ dataType: TypeId;
136
+ temp: boolean;
137
+ oid: number;
138
+ shareCount?: number;
139
+ }
140
+ export interface EnumData {
141
+ name: string;
142
+ schema: string;
143
+ labels: string[];
144
+ oid: number;
145
+ shareCount?: number;
146
+ }
147
+ export interface DomainData {
148
+ name: string;
149
+ schema: string;
150
+ baseType: ColumnType;
151
+ notNull: boolean;
152
+ defaultExpr: Expr | null;
153
+ checks: Array<{
154
+ name: string;
155
+ expr: Expr;
156
+ }>;
157
+ oid: number;
158
+ shareCount?: number;
159
+ }
160
+ export interface FunctionData {
161
+ name: string;
162
+ schema: string;
163
+ argNames: (string | null)[];
164
+ argTypes: TypeId[];
165
+ argDefaults: (Expr | null)[];
166
+ returns: TypeId | null;
167
+ returnsSet: boolean;
168
+ returnsTable: Array<{
169
+ name: string;
170
+ type: TypeId;
171
+ }> | null;
172
+ language: string;
173
+ body: Statement[] | null;
174
+ rawBody: string | null;
175
+ strict: boolean;
176
+ oid: number;
177
+ jsImpl?: (...args: Array<null | boolean | number | bigint | string | Uint8Array>) => null | boolean | number | bigint | string | Uint8Array;
178
+ }
179
+ export declare class SchemaData {
180
+ name: string;
181
+ tables: Map<string, TableData>;
182
+ views: Map<string, ViewData>;
183
+ sequences: Map<string, SequenceData>;
184
+ enums: Map<string, EnumData>;
185
+ domains: Map<string, DomainData>;
186
+ functions: Map<string, FunctionData[]>;
187
+ indexes: Map<string, IndexMeta>;
188
+ oid: number;
189
+ constructor(name: string, oid: number);
190
+ /** all relation names (tables, views, sequences, indexes share pg_class namespace) */
191
+ hasRelation(name: string): boolean;
192
+ clone(): SchemaData;
193
+ /** Share table/sequence objects; copy maps so CREATE/DROP is isolated. */
194
+ cloneShallow(): SchemaData;
195
+ }
196
+ export interface PreparedStatement {
197
+ name: string;
198
+ argTypes: TypeId[] | null;
199
+ stmt: Statement;
200
+ }
201
+ export declare class DatabaseState {
202
+ schemas: Map<string, SchemaData>;
203
+ settings: Map<string, string>;
204
+ /** SET LOCAL values, cleared on COMMIT/ROLLBACK */
205
+ localSettings: Map<string, string>;
206
+ prepared: Map<string, PreparedStatement>;
207
+ prng: Prng;
208
+ clock: Clock;
209
+ changes: number;
210
+ private oidCounter;
211
+ inTransaction: boolean;
212
+ /** most recent sequence touched by nextval/setval, for lastval() */
213
+ lastSequence: {
214
+ schema: string;
215
+ name: string;
216
+ } | null;
217
+ /** Session currval per sequence; absent entry means currval is undefined. */
218
+ sequenceCurrval: Map<string, bigint>;
219
+ constructor(prng: Prng, clock: Clock);
220
+ nextOid(): number;
221
+ getSetting(name: string): string | undefined;
222
+ /** effective search path: existing schemas from search_path setting */
223
+ effectiveSearchPath(): string[];
224
+ currentSchema(): string;
225
+ getSchema(name: string): SchemaData;
226
+ /** Resolve a possibly-qualified relation name to its schema. */
227
+ resolveRelationSchema(parts: string[]): {
228
+ schema: string;
229
+ name: string;
230
+ } | null;
231
+ findTable(parts: string[]): TableData | null;
232
+ requireTable(parts: string[]): TableData;
233
+ findView(parts: string[]): ViewData | null;
234
+ findSequence(parts: string[]): SequenceData | null;
235
+ findEnum(parts: string[]): EnumData | null;
236
+ findDomain(parts: string[]): DomainData | null;
237
+ findFunctions(parts: string[]): FunctionData[];
238
+ findEnumByKey(key: string): EnumData | null;
239
+ /** format_type()-style display name for a type OID (builtin or enum). */
240
+ typeNameForOid(oid: number): string | null;
241
+ /** deep clone (datums are immutable; rows copied) */
242
+ clone(): DatabaseState;
243
+ /** Share frozen catalog objects; copy maps so CREATE/DROP is isolated. */
244
+ cloneShallow(): DatabaseState;
245
+ freezeShared(): void;
246
+ thawShared(): void;
247
+ ensureWritableTable(table: TableData): TableData;
248
+ ensureWritableSequence(seq: SequenceData): SequenceData;
249
+ ensureWritableView(view: ViewData): ViewData;
250
+ ensureWritableEnum(en: EnumData): EnumData;
251
+ /** copy the contents of `other` into this state (rollback restore) */
252
+ restoreFrom(other: DatabaseState): void;
253
+ }