@crvouga/postgres-mem 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 (109) hide show
  1. package/AGENTS.md +159 -0
  2. package/COMPATIBILITY-AUDIT.md +155 -0
  3. package/COMPATIBILITY.md +87 -0
  4. package/LICENSE +21 -0
  5. package/README.md +325 -0
  6. package/compat/coverage.json +1081 -0
  7. package/compat/divergences.json +191 -0
  8. package/compat/gate-report.json +80 -0
  9. package/compat/requirements.json +1105 -0
  10. package/compat/requirements.raw.html +484 -0
  11. package/compat/scenario-types.ts +98 -0
  12. package/compat/scenarios.ts +98 -0
  13. package/compat/sections/agg.ts +45 -0
  14. package/compat/sections/api.ts +28 -0
  15. package/compat/sections/arr.ts +45 -0
  16. package/compat/sections/cat.ts +47 -0
  17. package/compat/sections/con.ts +32 -0
  18. package/compat/sections/cpy.ts +24 -0
  19. package/compat/sections/cte.ts +29 -0
  20. package/compat/sections/dat.ts +60 -0
  21. package/compat/sections/ddl.ts +55 -0
  22. package/compat/sections/det.ts +20 -0
  23. package/compat/sections/dml.ts +37 -0
  24. package/compat/sections/eco.ts +16 -0
  25. package/compat/sections/err.ts +16 -0
  26. package/compat/sections/exp.ts +53 -0
  27. package/compat/sections/fun.ts +58 -0
  28. package/compat/sections/fzz.ts +36 -0
  29. package/compat/sections/guc.ts +27 -0
  30. package/compat/sections/joi.ts +33 -0
  31. package/compat/sections/jsn.ts +46 -0
  32. package/compat/sections/lim.ts +13 -0
  33. package/compat/sections/par.ts +61 -0
  34. package/compat/sections/pre.ts +26 -0
  35. package/compat/sections/sch.ts +31 -0
  36. package/compat/sections/sel.ts +43 -0
  37. package/compat/sections/seq.ts +31 -0
  38. package/compat/sections/snp.ts +21 -0
  39. package/compat/sections/tok.ts +53 -0
  40. package/compat/sections/trg.ts +57 -0
  41. package/compat/sections/tsr.ts +37 -0
  42. package/compat/sections/txn.ts +39 -0
  43. package/compat/sections/typ.ts +55 -0
  44. package/compat/sections/uni.ts +13 -0
  45. package/compat/sections/win.ts +43 -0
  46. package/compat/smoke-baseline.json +3 -0
  47. package/compat/unsupported-register.json +2526 -0
  48. package/dist/api/bind.d.ts +10 -0
  49. package/dist/api/database.d.ts +69 -0
  50. package/dist/api/statement.d.ts +51 -0
  51. package/dist/ast/nodes.d.ts +810 -0
  52. package/dist/constraints/enforce.d.ts +39 -0
  53. package/dist/errors/error.d.ts +24 -0
  54. package/dist/executor/ddl.d.ts +23 -0
  55. package/dist/executor/dml.d.ts +10 -0
  56. package/dist/executor/execute.d.ts +11 -0
  57. package/dist/executor/relation.d.ts +60 -0
  58. package/dist/executor/select.d.ts +41 -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 +38 -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 +19591 -0
  82. package/dist/index.js.map +7 -0
  83. package/dist/lexer/tokenize.d.ts +8 -0
  84. package/dist/parser/index.d.ts +1 -0
  85. package/dist/parser/parser.d.ts +96 -0
  86. package/dist/runtime/clock.d.ts +14 -0
  87. package/dist/runtime/index.d.ts +3 -0
  88. package/dist/runtime/options.d.ts +25 -0
  89. package/dist/runtime/prng.d.ts +48 -0
  90. package/dist/schema/catalog-tables.d.ts +1 -0
  91. package/dist/schema/catalog.d.ts +12 -0
  92. package/dist/serialization/codec.d.ts +29 -0
  93. package/dist/serialization/index.d.ts +1 -0
  94. package/dist/storage/database-state.d.ts +216 -0
  95. package/dist/transactions/manager.d.ts +25 -0
  96. package/dist/tsearch/stem.d.ts +5 -0
  97. package/dist/tsearch/tsearch.d.ts +59 -0
  98. package/dist/types/cast.d.ts +26 -0
  99. package/dist/types/compare.d.ts +18 -0
  100. package/dist/types/datetime.d.ts +68 -0
  101. package/dist/types/jsonb.d.ts +45 -0
  102. package/dist/types/numeric.d.ts +69 -0
  103. package/dist/types/resolve.d.ts +15 -0
  104. package/dist/types/timezone.d.ts +9 -0
  105. package/dist/types/value.d.ts +99 -0
  106. package/dist/unstable.d.ts +15 -0
  107. package/dist/unstable.js +19153 -0
  108. package/dist/unstable.js.map +7 -0
  109. package/package.json +120 -0
@@ -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,96 @@
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
+ private parseWithableStatement;
24
+ private parseWithClause;
25
+ parseSelectStmt(withClause?: WithClause | null): SelectStmt;
26
+ private parseSelectBody;
27
+ private parseSelectTerm;
28
+ private parseSelectPrimary;
29
+ private parseSelectCore;
30
+ private parseGroupItem;
31
+ private parseSelectTarget;
32
+ private parseOrderByClause;
33
+ private parseOrderByItem;
34
+ private parseLimitOffset;
35
+ private parseFromItem;
36
+ private tryParseJoin;
37
+ private parseFromPrimary;
38
+ private parseWithOrdinality;
39
+ private parseAliasClause;
40
+ private parseInsert;
41
+ private parseReturning;
42
+ private parseUpdateSets;
43
+ private parseSetColumn;
44
+ private parseUpdate;
45
+ private parseDelete;
46
+ private parseCreate;
47
+ private parseIfNotExists;
48
+ private parseIfExists;
49
+ private parseCreateTable;
50
+ private tryParseTableConstraint;
51
+ private skipConstraintTail;
52
+ private parseRefActions;
53
+ private parseRefAction;
54
+ private parseColumnDef;
55
+ private parseIdentityOptions;
56
+ private parseSequenceOptions;
57
+ private parseSignedBigInt;
58
+ private parseCreateIndex;
59
+ private parseCreateView;
60
+ private parseCreateFunction;
61
+ private parseCreateTrigger;
62
+ private parseAlter;
63
+ private parseAlterTableAction;
64
+ private parseDrop;
65
+ private parseTruncate;
66
+ private parseSet;
67
+ private parseExplain;
68
+ private parseCopy;
69
+ parseTypeName(): TypeName;
70
+ parseExpr(): Expr;
71
+ private parseOr;
72
+ private parseAnd;
73
+ private parseNot;
74
+ private parseIs;
75
+ private parseComparison;
76
+ private tryParseAnyAll;
77
+ private parseLikeBetweenIn;
78
+ /** all other binary operators: ||, &, |, #, <<, >>, @>, <@, ->, ->>, etc. */
79
+ private parseGenericOps;
80
+ private parseAdditive;
81
+ private parseMultiplicative;
82
+ private parseExponent;
83
+ private parseUnary;
84
+ private parsePostfix;
85
+ private parsePrimary;
86
+ private parseCase;
87
+ private maybePrecision;
88
+ private parseNestedArrayLiteral;
89
+ private parseFuncCall;
90
+ private parseWindowSpec;
91
+ private parseFrameBound;
92
+ }
93
+ /** Parse SQL text into a list of statements. */
94
+ export declare function parse(sql: string): Statement[];
95
+ /** Parse exactly one statement; throws `misuse`-style errors handled by API layer. */
96
+ export declare function parseSingle(sql: string): Statement;
@@ -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 RandomMode } from "./options.js";
3
+ export { deriveSeed, OsEntropy, Prng } from "./prng.js";
@@ -0,0 +1,25 @@
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
+ /** Options for {@link Database} construction. All fields are optional. */
5
+ export interface DatabaseOptions {
6
+ /**
7
+ * Seed for deterministic `random()` (and any other PRNG-backed builtins).
8
+ * Defaults to {@link DEFAULT_DATABASE_SEED} (`1`). Ignored when {@link random} is `"os"`.
9
+ */
10
+ seed?: number | bigint;
11
+ /**
12
+ * Entropy for `random()` / `gen_random_uuid()`.
13
+ * `"deterministic"` (default) uses {@link seed}. `"os"` uses CSPRNG like PostgreSQL
14
+ * (not rolled back with transactions; not restored from snapshots).
15
+ */
16
+ random?: RandomMode;
17
+ /**
18
+ * Clock for `now()` / `current_timestamp` / etc.
19
+ * Defaults to a fixed instant (`2000-01-01T00:00:00.000Z`).
20
+ * Pass a `Date`, `() => Date`, or `"system"` for wall-clock `now()` like PostgreSQL.
21
+ */
22
+ now?: Date | Clock | "system";
23
+ }
24
+ /** Default {@link DatabaseOptions.seed} when constructing a {@link Database}. */
25
+ 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,29 @@
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 in a snapshot. */
5
+ export interface SnapshotRuntime {
6
+ /** Unsigned 64-bit {@link Prng} state. */
7
+ prngState: bigint;
8
+ /** Clock instant as milliseconds since Unix epoch. */
9
+ nowMs: number;
10
+ }
11
+ /** Result of {@link decodeDatabaseState}. */
12
+ export interface DecodedSnapshot {
13
+ /** Restored catalog and table data. */
14
+ state: DatabaseState;
15
+ runtime: SnapshotRuntime | null;
16
+ }
17
+ /**
18
+ * Encode catalog, rows, and runtime into a postgres-mem `PGMM` snapshot blob
19
+ * (not an on-disk PostgreSQL format).
20
+ *
21
+ * Prefer {@link Database.snapshot} unless you are serializing engine state directly.
22
+ */
23
+ export declare function encodeDatabaseState(state: DatabaseState, runtime: SnapshotRuntime): Uint8Array;
24
+ /**
25
+ * Decode a blob from {@link encodeDatabaseState} / {@link Database.snapshot}.
26
+ *
27
+ * @throws {PostgresError} If the magic, version, or payload is invalid.
28
+ */
29
+ 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,216 @@
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
+ export interface ColumnMeta {
6
+ name: string;
7
+ type: ColumnType;
8
+ notNull: boolean;
9
+ defaultExpr: Expr | null;
10
+ identity: {
11
+ always: boolean;
12
+ sequence: string;
13
+ } | null;
14
+ generated: Expr | null;
15
+ collate: string | null;
16
+ /** resolved domain name when column type came from a domain */
17
+ domain: string | null;
18
+ }
19
+ export type ConstraintMeta = {
20
+ kind: "primary_key";
21
+ name: string;
22
+ columns: string[];
23
+ } | {
24
+ kind: "unique";
25
+ name: string;
26
+ columns: string[];
27
+ nullsNotDistinct: boolean;
28
+ } | {
29
+ kind: "check";
30
+ name: string;
31
+ expr: Expr;
32
+ } | {
33
+ kind: "foreign_key";
34
+ name: string;
35
+ columns: string[];
36
+ refSchema: string;
37
+ refTable: string;
38
+ refColumns: string[];
39
+ onDelete: string | null;
40
+ onUpdate: string | null;
41
+ match: "full" | "simple";
42
+ };
43
+ export interface IndexMeta {
44
+ name: string;
45
+ schema: string;
46
+ table: string;
47
+ unique: boolean;
48
+ /** simple column indexes store names; expression indexes store the AST */
49
+ columns: Array<{
50
+ column: string | null;
51
+ expr: Expr | null;
52
+ dir: "asc" | "desc";
53
+ nulls: "first" | "last";
54
+ }>;
55
+ where: Expr | null;
56
+ nullsNotDistinct: boolean;
57
+ /** true when this index backs a constraint (pkey / unique constraint) */
58
+ isConstraint: boolean;
59
+ }
60
+ export interface TriggerMeta {
61
+ name: string;
62
+ timing: "before" | "after" | "instead_of";
63
+ events: CreateTriggerStmt["events"];
64
+ forEachRow: boolean;
65
+ when: Expr | null;
66
+ funcSchema: string;
67
+ funcName: string;
68
+ funcArgs: string[];
69
+ }
70
+ export declare class TableData {
71
+ name: string;
72
+ schema: string;
73
+ columns: ColumnMeta[];
74
+ rows: Datum[][];
75
+ constraints: ConstraintMeta[];
76
+ triggers: TriggerMeta[];
77
+ temp: boolean;
78
+ /** monotonically increasing oid-like id for catalog output */
79
+ readonly oid: number;
80
+ constructor(schema: string, name: string, columns: ColumnMeta[], oid: number, temp?: boolean);
81
+ columnIndex(name: string): number;
82
+ clone(): TableData;
83
+ }
84
+ export interface ViewData {
85
+ name: string;
86
+ schema: string;
87
+ query: SelectStmt;
88
+ columns: string[] | null;
89
+ materialized: boolean;
90
+ /** materialized contents; null = WITH NO DATA (not populated) */
91
+ matRows: Datum[][] | null;
92
+ matColumns: Array<{
93
+ name: string;
94
+ type: TypeId;
95
+ }> | null;
96
+ temp: boolean;
97
+ oid: number;
98
+ }
99
+ export interface SequenceData {
100
+ name: string;
101
+ schema: string;
102
+ increment: bigint;
103
+ minValue: bigint;
104
+ maxValue: bigint;
105
+ startValue: bigint;
106
+ cache: bigint;
107
+ cycle: boolean;
108
+ lastValue: bigint;
109
+ isCalled: boolean;
110
+ ownedBy: {
111
+ table: string;
112
+ column: string;
113
+ } | null;
114
+ dataType: TypeId;
115
+ temp: boolean;
116
+ oid: number;
117
+ }
118
+ export interface EnumData {
119
+ name: string;
120
+ schema: string;
121
+ labels: string[];
122
+ oid: number;
123
+ }
124
+ export interface DomainData {
125
+ name: string;
126
+ schema: string;
127
+ baseType: ColumnType;
128
+ notNull: boolean;
129
+ defaultExpr: Expr | null;
130
+ checks: Array<{
131
+ name: string;
132
+ expr: Expr;
133
+ }>;
134
+ oid: number;
135
+ }
136
+ export interface FunctionData {
137
+ name: string;
138
+ schema: string;
139
+ argNames: (string | null)[];
140
+ argTypes: TypeId[];
141
+ argDefaults: (Expr | null)[];
142
+ returns: TypeId | null;
143
+ returnsSet: boolean;
144
+ returnsTable: Array<{
145
+ name: string;
146
+ type: TypeId;
147
+ }> | null;
148
+ language: string;
149
+ body: Statement[] | null;
150
+ rawBody: string | null;
151
+ strict: boolean;
152
+ oid: number;
153
+ }
154
+ export declare class SchemaData {
155
+ name: string;
156
+ tables: Map<string, TableData>;
157
+ views: Map<string, ViewData>;
158
+ sequences: Map<string, SequenceData>;
159
+ enums: Map<string, EnumData>;
160
+ domains: Map<string, DomainData>;
161
+ functions: Map<string, FunctionData[]>;
162
+ indexes: Map<string, IndexMeta>;
163
+ oid: number;
164
+ constructor(name: string, oid: number);
165
+ /** all relation names (tables, views, sequences, indexes share pg_class namespace) */
166
+ hasRelation(name: string): boolean;
167
+ clone(): SchemaData;
168
+ }
169
+ export interface PreparedStatement {
170
+ name: string;
171
+ argTypes: TypeId[] | null;
172
+ stmt: Statement;
173
+ }
174
+ export declare class DatabaseState {
175
+ schemas: Map<string, SchemaData>;
176
+ settings: Map<string, string>;
177
+ /** SET LOCAL values, cleared on COMMIT/ROLLBACK */
178
+ localSettings: Map<string, string>;
179
+ prepared: Map<string, PreparedStatement>;
180
+ prng: Prng;
181
+ clock: Clock;
182
+ changes: number;
183
+ private oidCounter;
184
+ inTransaction: boolean;
185
+ /** most recent sequence touched by nextval/setval, for lastval() */
186
+ lastSequence: {
187
+ schema: string;
188
+ name: string;
189
+ } | null;
190
+ constructor(prng: Prng, clock: Clock);
191
+ nextOid(): number;
192
+ getSetting(name: string): string | undefined;
193
+ /** effective search path: existing schemas from search_path setting */
194
+ effectiveSearchPath(): string[];
195
+ currentSchema(): string;
196
+ getSchema(name: string): SchemaData;
197
+ /** Resolve a possibly-qualified relation name to its schema. */
198
+ resolveRelationSchema(parts: string[]): {
199
+ schema: string;
200
+ name: string;
201
+ } | null;
202
+ findTable(parts: string[]): TableData | null;
203
+ requireTable(parts: string[]): TableData;
204
+ findView(parts: string[]): ViewData | null;
205
+ findSequence(parts: string[]): SequenceData | null;
206
+ findEnum(parts: string[]): EnumData | null;
207
+ findDomain(parts: string[]): DomainData | null;
208
+ findFunctions(parts: string[]): FunctionData[];
209
+ findEnumByKey(key: string): EnumData | null;
210
+ /** format_type()-style display name for a type OID (builtin or enum). */
211
+ typeNameForOid(oid: number): string | null;
212
+ /** deep clone for transaction snapshots (datums are immutable; rows copied) */
213
+ clone(): DatabaseState;
214
+ /** copy the contents of `other` into this state (rollback restore) */
215
+ restoreFrom(other: DatabaseState): void;
216
+ }
@@ -0,0 +1,25 @@
1
+ import type { DatabaseState } from "../storage/database-state.js";
2
+ /**
3
+ * Single-session transaction manager: BEGIN clones the whole state (datums are
4
+ * immutable; rows are copied), ROLLBACK restores it. Savepoints stack inner
5
+ * snapshots. The PRNG state participates so `random()` draws rewind on
6
+ * rollback (determinism invariant, mirrors sqlite-mem).
7
+ */
8
+ export declare class TransactionManager {
9
+ private readonly state;
10
+ private base;
11
+ private savepoints;
12
+ constructor(state: DatabaseState);
13
+ get inTransaction(): boolean;
14
+ private takeSnapshot;
15
+ private restore;
16
+ begin(): void;
17
+ commit(): void;
18
+ rollback(): void;
19
+ savepoint(name: string): void;
20
+ releaseSavepoint(name: string): void;
21
+ rollbackToSavepoint(name: string): void;
22
+ private findSavepoint;
23
+ /** abort any open transaction without restoring (used by Database.close) */
24
+ reset(): void;
25
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Porter2 (Snowball English) stemmer — the algorithm behind PostgreSQL's
3
+ * `english` text search dictionary.
4
+ */
5
+ export declare function stemEnglish(input: string): string;
@@ -0,0 +1,59 @@
1
+ export interface Lexeme {
2
+ word: string;
3
+ positions: Array<{
4
+ pos: number;
5
+ weight: string;
6
+ }>;
7
+ }
8
+ /** Build canonical tsvector text: lexemes sorted, with positions. */
9
+ export declare function toTsvector(config: string, text: string): string;
10
+ /** Parse tsvector text (typinput): `'a':1,2 'b':3A b` */
11
+ export declare function parseTsvector(text: string): string;
12
+ /** tsvector || tsvector: shift right-side positions by the left's max position, merge lexemes. */
13
+ export declare function tsvectorConcat(a: string, b: string): string;
14
+ export declare function tsvectorLexemes(vec: string): Lexeme[];
15
+ export type TsQueryNode = {
16
+ kind: "lexeme";
17
+ word: string;
18
+ prefix: boolean;
19
+ weights: string | null;
20
+ } | {
21
+ kind: "and";
22
+ left: TsQueryNode;
23
+ right: TsQueryNode;
24
+ } | {
25
+ kind: "or";
26
+ left: TsQueryNode;
27
+ right: TsQueryNode;
28
+ } | {
29
+ kind: "not";
30
+ operand: TsQueryNode;
31
+ } | {
32
+ kind: "phrase";
33
+ left: TsQueryNode;
34
+ right: TsQueryNode;
35
+ distance: number;
36
+ };
37
+ export declare function toTsquery(config: string, text: string): string;
38
+ export declare function plaintoTsquery(config: string, text: string): string;
39
+ export declare function phrasetoTsquery(config: string, text: string): string;
40
+ export declare function websearchToTsquery(_config: string, _text: string): string;
41
+ export declare function tsqueryText(node: TsQueryNode | null): string;
42
+ export declare function parseTsqueryText(text: string): TsQueryNode | null;
43
+ /** tsquery || tsquery / tsquery && tsquery */
44
+ export declare function tsqueryCombine(op: "and" | "or", a: string, b: string): string;
45
+ /**
46
+ * ts_headline (minimal): wraps query-matching words of the document in
47
+ * StartSel/StopSel. Fragment selection (MaxWords/MinWords windows) is not
48
+ * implemented — short documents match PG output exactly.
49
+ */
50
+ export declare function tsHeadline(config: string, document: string, query: string, options?: string): string;
51
+ /** !! tsquery */
52
+ export declare function tsqueryNegate(a: string): string;
53
+ export declare function tsvectorMatches(vec: string, query: string): boolean;
54
+ export declare const DEFAULT_RANK_WEIGHTS: number[];
55
+ /** calc_rank + normalization flags (RANK_NORM_*). */
56
+ export declare function tsRank(vec: string, query: string, weights?: number[], method?: number): number;
57
+ export declare function tsvectorLength(vec: string): number;
58
+ export declare function tsvectorStrip(vec: string): string;
59
+ export declare function tsvectorSetweight(vec: string, weight: string): string;
@@ -0,0 +1,26 @@
1
+ import { unsupported } from "../errors/error.js";
2
+ import { type Datum, type InputCtx, type OutputCtx, type TypedValue, type TypeId, type TypeMod } from "./value.js";
3
+ export interface CastEnv extends OutputCtx, InputCtx {
4
+ enumLabels(enumType: TypeId): string[] | null;
5
+ }
6
+ export declare const UTC_CAST_ENV: CastEnv;
7
+ export declare function isTextType(t: TypeId): boolean;
8
+ export declare function isNumericType(t: TypeId): boolean;
9
+ export declare function isDatetimeType(t: TypeId): boolean;
10
+ /** implicit-cast reachability (subset of pg_cast castcontext = 'i') */
11
+ export declare function canImplicitCast(from: TypeId, to: TypeId): boolean;
12
+ export declare function canAssignCast(from: TypeId, to: TypeId): boolean;
13
+ export interface CastOptions {
14
+ explicit?: boolean;
15
+ mod?: TypeMod | null;
16
+ /** true for INSERT/UPDATE assignment (allows assignment casts + typmod coercion with truncation errors) */
17
+ assignment?: boolean;
18
+ }
19
+ /** Cast a typed value to `target`. */
20
+ export declare function castTo(env: CastEnv, value: TypedValue, target: TypeId, opts?: CastOptions): TypedValue;
21
+ export declare function numericFamilyCast(from: TypeId, to: TypeId, v: Datum): Datum;
22
+ /** Apply typmod (varchar(n) truncation checks, numeric(p,s), bpchar padding, time precision). */
23
+ export declare function applyTypmod(_env: CastEnv, t: TypeId, v: Datum, opts: CastOptions): Datum;
24
+ /** unify two types for comparison/set operations (simplified union type resolution) */
25
+ export declare function unifyTypes(a: TypeId, b: TypeId): TypeId | null;
26
+ export { unsupported };
@@ -0,0 +1,18 @@
1
+ import { type Datum, type TypeId } from "./value.js";
2
+ /**
3
+ * Total order for non-null datums of the same type. Text uses C-locale
4
+ * (code point) ordering — the engine's pinned collation.
5
+ *
6
+ * Enum ordering needs label positions; callers pass `enumOrder`.
7
+ */
8
+ export interface CompareCtx {
9
+ enumOrder?(enumType: TypeId, label: string): number;
10
+ }
11
+ export declare const DEFAULT_COMPARE_CTX: CompareCtx;
12
+ export declare function datumCompare(t: TypeId, a: Datum, b: Datum, ctx?: CompareCtx): number;
13
+ export declare function datumEquals(t: TypeId, a: Datum, b: Datum, ctx?: CompareCtx): boolean;
14
+ /**
15
+ * Canonical grouping/uniqueness key. Equal values (2.50 = 2.5, +0 = -0)
16
+ * must map to the same key.
17
+ */
18
+ export declare function datumKey(t: TypeId, v: Datum): string;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Internal representations (mirroring PostgreSQL):
3
+ * - date: integer days since 2000-01-01 (PG epoch); ±Infinity as special
4
+ * - time: bigint microseconds since midnight (0 .. 86_400_000_000 inclusive)
5
+ * - timestamp / timestamptz: bigint microseconds since 2000-01-01 00:00:00 (UTC for tz)
6
+ * - interval: { months, days, micros }
7
+ */
8
+ export declare const PG_EPOCH_JDATE = 2451545;
9
+ export declare const UNIX_EPOCH_MICROS_FROM_PG = -946684800000000n;
10
+ export declare const DATE_POS_INF = 2147483647;
11
+ export declare const DATE_NEG_INF = -2147483648;
12
+ export declare const TS_POS_INF = 9223372036854775807n;
13
+ export declare const TS_NEG_INF = -9223372036854775808n;
14
+ export interface Interval {
15
+ readonly kind: "interval";
16
+ readonly months: number;
17
+ readonly days: number;
18
+ readonly micros: bigint;
19
+ }
20
+ export declare function makeInterval(months: number, days: number, micros: bigint): Interval;
21
+ export declare function isInterval(v: unknown): v is Interval;
22
+ export declare const USECS_PER_DAY = 86400000000n;
23
+ export declare const USECS_PER_HOUR = 3600000000n;
24
+ export declare const USECS_PER_MIN = 60000000n;
25
+ export declare const USECS_PER_SEC = 1000000n;
26
+ export declare function civilToDays(y: number, m: number, d: number): number;
27
+ export declare function daysToCivil(days: number): {
28
+ y: number;
29
+ m: number;
30
+ d: number;
31
+ };
32
+ export declare function isLeapYear(y: number): boolean;
33
+ export declare function daysInMonth(y: number, m: number): number;
34
+ export declare function isValidCivil(y: number, m: number, d: number): boolean;
35
+ /** day of week, 0=Sunday (2000-01-01 was a Saturday = 6) */
36
+ export declare function dayOfWeek(days: number): number;
37
+ /** Parse a date string -> days since 2000-01-01. DateStyle ISO, MDY. */
38
+ export declare function parseDate(text: string): number;
39
+ /** Parse time -> micros since midnight. */
40
+ export declare function parseTime(text: string): bigint;
41
+ /** Parse timestamp (no tz interpretation) -> PG micros. */
42
+ export declare function parseTimestamp(text: string): bigint;
43
+ /**
44
+ * Parse timestamptz -> UTC micros. `sessionOffsetSec` applies when the input
45
+ * has no explicit zone (session TimeZone; we default to UTC).
46
+ */
47
+ export declare function parseTimestampTz(text: string, zoneOffsetForNaive: (naiveMicros: bigint) => number): bigint;
48
+ export declare function formatDate(days: number): string;
49
+ export declare function formatTimeOfDay(micros: bigint): string;
50
+ /** floor-divide micros into (days, timeOfDay) */
51
+ export declare function splitTs(micros: bigint): {
52
+ days: number;
53
+ tod: bigint;
54
+ };
55
+ export declare function formatTimestamp(micros: bigint): string;
56
+ /** Format a UTC timestamptz in a fixed zone offset (seconds east of UTC). */
57
+ export declare function formatTimestampTz(micros: bigint, offsetSec: number): string;
58
+ export declare function parseInterval(text: string): Interval;
59
+ /** Render interval in DateStyle 'postgres' (the default). */
60
+ export declare function formatInterval(v: Interval): string;
61
+ export declare function intervalCmp(a: Interval, b: Interval): number;
62
+ export declare function intervalTotalMicros(v: Interval): bigint;
63
+ export declare function intervalAdd(a: Interval, b: Interval): Interval;
64
+ export declare function intervalNeg(a: Interval): Interval;
65
+ export declare function intervalJustifyHours(v: Interval): Interval;
66
+ export declare function intervalJustifyDays(v: Interval): Interval;
67
+ /** date + interval => timestamp micros arithmetic (add months honoring month-end clamping) */
68
+ export declare function timestampAddInterval(ts: bigint, iv: Interval): bigint;