@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,39 @@
1
+ import type { ExecEnv } from "../executor/relation.js";
2
+ import type { IndexMeta, TableData } from "../storage/database-state.js";
3
+ import { type Datum } from "../types/value.js";
4
+ /** NOT NULL column constraints (23502). */
5
+ export declare function checkNotNull(env: ExecEnv, table: TableData, row: Datum[]): void;
6
+ /** CHECK constraints (23514); NULL results pass. */
7
+ export declare function checkChecks(env: ExecEnv, table: TableData, row: Datum[]): void;
8
+ interface UniqueSpec {
9
+ name: string;
10
+ /** column indexes for plain column keys; -1 with expr set for expression keys */
11
+ keys: Array<{
12
+ colIdx: number;
13
+ expr: import("../ast/nodes.js").Expr | null;
14
+ }>;
15
+ columnNames: string[];
16
+ nullsNotDistinct: boolean;
17
+ where: import("../ast/nodes.js").Expr | null;
18
+ isPrimary: boolean;
19
+ }
20
+ export declare function uniqueSpecsFor(env: ExecEnv, table: TableData): UniqueSpec[];
21
+ /**
22
+ * Unique / primary key enforcement (23505). `selfIdx` is the row's own index
23
+ * in table.rows (already inserted / updated in place).
24
+ */
25
+ export declare function checkUnique(env: ExecEnv, table: TableData, row: Datum[], selfIdx: number): void;
26
+ /** does `row` conflict with an existing row under `spec`? returns the row index */
27
+ export declare function findConflict(env: ExecEnv, table: TableData, spec: UniqueSpec, row: Datum[]): number | null;
28
+ export type { IndexMeta, UniqueSpec };
29
+ /** referencing-side FK enforcement: every non-null key must exist in the referenced table (23503) */
30
+ export declare function checkForeignKeys(env: ExecEnv, table: TableData, row: Datum[]): void;
31
+ export interface ReferencingConstraint {
32
+ table: TableData;
33
+ constraint: Extract<import("../storage/database-state.js").ConstraintMeta, {
34
+ kind: "foreign_key";
35
+ }>;
36
+ }
37
+ /** all FK constraints in the database that reference `table` */
38
+ export declare function referencingConstraints(env: ExecEnv, table: TableData): ReferencingConstraint[];
39
+ export declare function fullRowCheck(env: ExecEnv, table: TableData, row: Datum[], selfIdx: number): void;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * PostgresError mirrors the shape a real PostgreSQL server reports:
3
+ * a human message plus a five-character SQLSTATE code.
4
+ *
5
+ * `category` is a stable, coarse-grained enum for consumers that do not want
6
+ * to switch on raw SQLSTATE codes. New categories may appear in minor
7
+ * releases — always include a default case.
8
+ */
9
+ export type ErrorCategory = "syntax" | "undefined_table" | "undefined_column" | "undefined_function" | "undefined_object" | "duplicate_object" | "duplicate_table" | "duplicate_column" | "constraint_not_null" | "constraint_unique" | "constraint_check" | "constraint_foreign_key" | "constraint_exclusion" | "restrict_violation" | "invalid_text_representation" | "numeric_value_out_of_range" | "division_by_zero" | "datatype_mismatch" | "cannot_coerce" | "invalid_parameter_value" | "invalid_datetime" | "ambiguous_column" | "ambiguous_function" | "grouping_error" | "windowing_error" | "invalid_column_reference" | "wrong_object_type" | "dependent_objects" | "transaction_state" | "misuse" | "unsupported" | "internal" | "data_exception" | "program_limit_exceeded" | "invalid_cursor" | "snapshot_format" | "snapshot_version" | "string_data_right_truncation" | "invalid_regular_expression" | "case_not_found" | "cardinality_violation" | "undefined_parameter" | "not_null_violation" | "check_violation" | "array_subscript_error" | "array_element_error" | "invalid_escape_sequence" | "feature_not_supported" | "null_value_not_allowed" | "invalid_argument_for_power_function" | "invalid_argument_for_log" | "invalid_argument_for_width_bucket_function" | "sequence_generator_limit_exceeded" | "object_not_in_prerequisite_state" | "substring_error" | "invalid_table_definition" | "duplicate_schema" | "duplicate_function" | "generated_always" | "invalid_row_count" | "duplicate_prepared_statement" | "undefined_prepared_statement" | "invalid_savepoint_specification" | "raise_exception" | "invalid_function_definition";
10
+ export declare class PostgresError extends Error {
11
+ readonly category: ErrorCategory;
12
+ /** Five-character SQLSTATE, e.g. "42P01". Always set. */
13
+ readonly sqlState: string;
14
+ /** Alias of sqlState (node-postgres `err.code` convention). */
15
+ readonly code: string;
16
+ constructor(category: ErrorCategory, message: string, sqlState?: string);
17
+ }
18
+ export declare function pgError(category: ErrorCategory, message: string, sqlState?: string): PostgresError;
19
+ /**
20
+ * SQL the oracle accepts but this engine has not implemented must fail loud,
21
+ * never silently misbehave. The compat gate keys off this.
22
+ */
23
+ export declare function unsupported(what: string): PostgresError;
24
+ export declare function isPostgresError(err: unknown): err is PostgresError;
@@ -0,0 +1,23 @@
1
+ import type { AlterEnumStmt, AlterIndexStmt, AlterSchemaStmt, AlterSequenceStmt, AlterTableStmt, AlterViewStmt, CreateDomainStmt, CreateEnumStmt, CreateFunctionStmt, CreateIndexStmt, CreateSchemaStmt, CreateSequenceStmt, CreateTableAsStmt, CreateTableStmt, CreateTriggerStmt, CreateViewStmt, DropStmt, RefreshMaterializedViewStmt, SequenceOptions, TruncateStmt } from "../ast/nodes.js";
2
+ import { SchemaData, type SequenceData } from "../storage/database-state.js";
3
+ import { type ExecEnv, type ExecResult } from "./relation.js";
4
+ export declare function buildSequence(env: ExecEnv, schema: SchemaData, name: string, options: SequenceOptions, temp: boolean): SequenceData;
5
+ export declare function executeCreateSequence(env: ExecEnv, stmt: CreateSequenceStmt): ExecResult;
6
+ export declare function executeAlterSequence(env: ExecEnv, stmt: AlterSequenceStmt): ExecResult;
7
+ export declare function executeCreateTable(env: ExecEnv, stmt: CreateTableStmt): ExecResult;
8
+ export declare function executeCreateTableAs(env: ExecEnv, stmt: CreateTableAsStmt): ExecResult;
9
+ export declare function executeCreateIndex(env: ExecEnv, stmt: CreateIndexStmt): ExecResult;
10
+ export declare function executeCreateView(env: ExecEnv, stmt: CreateViewStmt): ExecResult;
11
+ export declare function executeRefreshMatView(env: ExecEnv, stmt: RefreshMaterializedViewStmt): ExecResult;
12
+ export declare function executeCreateSchema(env: ExecEnv, stmt: CreateSchemaStmt): ExecResult;
13
+ export declare function executeCreateEnum(env: ExecEnv, stmt: CreateEnumStmt): ExecResult;
14
+ export declare function executeAlterEnum(env: ExecEnv, stmt: AlterEnumStmt): ExecResult;
15
+ export declare function executeCreateDomain(env: ExecEnv, stmt: CreateDomainStmt): ExecResult;
16
+ export declare function executeCreateFunction(env: ExecEnv, stmt: CreateFunctionStmt): ExecResult;
17
+ export declare function executeCreateTrigger(env: ExecEnv, stmt: CreateTriggerStmt): ExecResult;
18
+ export declare function executeAlterTable(env: ExecEnv, stmt: AlterTableStmt): ExecResult;
19
+ export declare function executeAlterView(env: ExecEnv, stmt: AlterViewStmt): ExecResult;
20
+ export declare function executeAlterIndex(env: ExecEnv, stmt: AlterIndexStmt): ExecResult;
21
+ export declare function executeAlterSchema(env: ExecEnv, stmt: AlterSchemaStmt): ExecResult;
22
+ export declare function executeDrop(env: ExecEnv, stmt: DropStmt): ExecResult;
23
+ export declare function executeTruncate(env: ExecEnv, stmt: TruncateStmt): ExecResult;
@@ -0,0 +1,10 @@
1
+ import type { DeleteStmt, InsertStmt, SelectStmt, UpdateStmt } from "../ast/nodes.js";
2
+ import type { TableData } from "../storage/database-state.js";
3
+ import { type Datum } from "../types/value.js";
4
+ import { type ExecEnv, type ExecResult, type Relation } from "./relation.js";
5
+ export declare function executeInsert(env0: ExecEnv, stmt: InsertStmt): ExecResult;
6
+ export declare function executeUpdate(env0: ExecEnv, stmt: UpdateStmt): ExecResult;
7
+ export declare function executeDelete(env0: ExecEnv, stmt: DeleteStmt): ExecResult;
8
+ export declare function handleReferencedDelete(env: ExecEnv, table: TableData, row: Datum[], depth: number): void;
9
+ export declare function handleReferencedUpdate(env: ExecEnv, table: TableData, oldRows: Datum[][], newRows: Datum[][]): void;
10
+ export type { Relation, SelectStmt };
@@ -0,0 +1,11 @@
1
+ import type { Statement } from "../ast/nodes.js";
2
+ import "../schema/catalog-tables.js";
3
+ import "./triggers-exec.js";
4
+ import type { DatabaseState } from "../storage/database-state.js";
5
+ import type { TypedValue } from "../types/value.js";
6
+ import { type ExecEnv, type ExecResult } from "./relation.js";
7
+ /** Execute one parsed statement against `state`. */
8
+ export declare function executeStatement(env: ExecEnv, stmt: Statement): ExecResult;
9
+ /** Fresh execution environment for one top-level statement. */
10
+ export declare function makeEnv(state: DatabaseState, params?: TypedValue[] | null): ExecEnv;
11
+ export type { ExecEnv, ExecResult };
@@ -0,0 +1,60 @@
1
+ import type { EngineCtx } from "../expressions/context.js";
2
+ import type { Datum, TypedValue, TypeId } from "../types/value.js";
3
+ /** A column of an intermediate or final result relation. */
4
+ export interface RelColumn {
5
+ name: string;
6
+ type: TypeId;
7
+ /** range-variable (table alias) the column belongs to; null for computed columns */
8
+ table: string | null;
9
+ /** hidden columns (e.g. ORDER BY helpers) are excluded from final output */
10
+ hidden?: boolean;
11
+ }
12
+ export interface Relation {
13
+ columns: RelColumn[];
14
+ rows: Datum[][];
15
+ }
16
+ export declare function emptyRelation(): Relation;
17
+ /**
18
+ * Row-level name resolution scope. Chains to an outer scope for correlated
19
+ * subqueries and LATERAL.
20
+ */
21
+ export declare class RowScope {
22
+ readonly columns: RelColumn[];
23
+ row: Datum[];
24
+ readonly parent: RowScope | null;
25
+ /** range variables visible as whole-row references */
26
+ readonly rangeVars: Set<string>;
27
+ constructor(columns: RelColumn[], row: Datum[], parent?: RowScope | null,
28
+ /** range variables visible as whole-row references */
29
+ rangeVars?: Set<string>);
30
+ /** Resolve a (possibly qualified) column reference. undefined = not found. */
31
+ lookup(parts: string[]): TypedValue | undefined;
32
+ /** Build a record value from all columns belonging to a range variable. */
33
+ wholeRow(rangeVar: string): TypedValue | undefined;
34
+ hasRangeVar(name: string): boolean;
35
+ }
36
+ /** Environment threaded through statement execution. */
37
+ export interface ExecEnv {
38
+ ctx: EngineCtx;
39
+ params: TypedValue[] | null;
40
+ /** CTE results by name (WITH clause); shadowed inner-to-outer */
41
+ ctes: Map<string, Relation>;
42
+ outer: RowScope | null;
43
+ }
44
+ export declare function childEnv(env: ExecEnv, outer: RowScope | null): ExecEnv;
45
+ export declare function withCtes(env: ExecEnv, ctes: Map<string, Relation>): ExecEnv;
46
+ /** Final result surfaced by the API layer. */
47
+ export interface ExecResult {
48
+ columns: Array<{
49
+ name: string;
50
+ type: TypeId;
51
+ }>;
52
+ rows: Datum[][];
53
+ command: string;
54
+ rowCount: number;
55
+ }
56
+ export declare function relationResult(rel: Relation, command: string): ExecResult;
57
+ export declare function commandResult(command: string, rowCount: number): ExecResult;
58
+ /** column name PG infers for an expression without an alias */
59
+ export declare function inferColumnName(e: import("../ast/nodes.js").Expr): string;
60
+ export type { EngineCtx };
@@ -0,0 +1,41 @@
1
+ import type { Expr, FromItem, FuncCall, OrderByItem, SelectBody, SelectCore, SelectStmt, Statement, WithClause } from "../ast/nodes.js";
2
+ import type { EvalScope } from "../expressions/eval.js";
3
+ import type { FunctionData } from "../storage/database-state.js";
4
+ import { type TypedValue } from "../types/value.js";
5
+ import { type ExecEnv, type ExecResult, type Relation, RowScope } from "./relation.js";
6
+ export type StatementRunner = (env: ExecEnv, stmt: Statement) => ExecResult;
7
+ export declare function setStatementRunner(r: StatementRunner): void;
8
+ export declare function runStatement(env: ExecEnv, stmt: Statement): ExecResult;
9
+ export declare function exprEq(a: unknown, b: unknown): boolean;
10
+ export interface ScopeExtras {
11
+ aggMap?: Map<FuncCall, TypedValue> | null;
12
+ windowAt?: (call: FuncCall) => TypedValue | undefined;
13
+ exprOverride?: (e: Expr) => TypedValue | undefined;
14
+ groupingValue?: (e: Expr) => TypedValue | undefined;
15
+ /** grouped context: bare column refs that survive overrides are errors */
16
+ strictGrouping?: boolean;
17
+ }
18
+ export declare function makeEvalScope(env: ExecEnv, scope: RowScope | null, extras?: ScopeExtras): EvalScope;
19
+ export declare function evalScalar(env: ExecEnv, scope: RowScope | null, e: Expr, extras?: ScopeExtras): TypedValue;
20
+ /** SQL three-valued predicate: null → false */
21
+ export declare function evalPredicate(env: ExecEnv, scope: RowScope | null, e: Expr, extras?: ScopeExtras): boolean;
22
+ export declare function resolveUserFunction(env: ExecEnv, name: string[], argCount: number): FunctionData | null;
23
+ export declare function callSqlFunctionScalar(env: ExecEnv, fn: FunctionData, args: TypedValue[]): TypedValue;
24
+ export declare function callSqlFunctionSet(env: ExecEnv, fn: FunctionData, args: TypedValue[]): Relation;
25
+ export declare function applyWith(env: ExecEnv, w: WithClause | null): ExecEnv;
26
+ interface Source {
27
+ rel: Relation;
28
+ rangeVars: Set<string>;
29
+ }
30
+ export declare function buildFrom(env: ExecEnv, items: FromItem[]): Source;
31
+ export interface SortSpec {
32
+ colIdx: number;
33
+ dir: "asc" | "desc";
34
+ nullsFirst: boolean;
35
+ }
36
+ export declare function sortRows(env: ExecEnv, rel: Relation, specs: SortSpec[]): void;
37
+ export declare function executeBody(env: ExecEnv, body: SelectBody): Relation;
38
+ export declare function executeCore(env0: ExecEnv, core: SelectCore, orderBy: OrderByItem[]): Relation;
39
+ export declare function executeSelectStmt(env0: ExecEnv, stmt: SelectStmt): Relation;
40
+ export declare function selectResult(env: ExecEnv, stmt: SelectStmt): ExecResult;
41
+ export {};
@@ -0,0 +1,21 @@
1
+ import type { CopyStmt, DeallocateStmt, ExecuteStmt, ExplainStmt, PrepareStmt, ResetStmt, SetStmt, ShowStmt, TransactionStmt } from "../ast/nodes.js";
2
+ import { DatabaseState } from "../storage/database-state.js";
3
+ import { TransactionManager } from "../transactions/manager.js";
4
+ import { type ExecEnv, type ExecResult } from "./relation.js";
5
+ import { executeSelectStmt } from "./select.js";
6
+ export declare function txManagerFor(state: DatabaseState): TransactionManager;
7
+ export declare function executeTransaction(env: ExecEnv, stmt: TransactionStmt): ExecResult;
8
+ export declare function executeSet(env: ExecEnv, stmt: SetStmt): ExecResult;
9
+ export declare function executeShow(env: ExecEnv, stmt: ShowStmt): ExecResult;
10
+ export declare function executeReset(env: ExecEnv, stmt: ResetStmt): ExecResult;
11
+ export declare function executePrepare(env: ExecEnv, stmt: PrepareStmt): ExecResult;
12
+ export declare function executeExecute(env: ExecEnv, stmt: ExecuteStmt): ExecResult;
13
+ export declare function executeDeallocate(env: ExecEnv, stmt: DeallocateStmt): ExecResult;
14
+ export declare function executeExplain(env: ExecEnv, stmt: ExplainStmt): ExecResult;
15
+ export declare function executeCopy(env: ExecEnv, stmt: CopyStmt): ExecResult;
16
+ /**
17
+ * Execute COPY ... FROM STDIN with api-provided text/csv data by synthesizing
18
+ * an INSERT (reuses defaults, identity, constraints, FK actions, triggers).
19
+ */
20
+ export declare function executeCopyFromData(env: ExecEnv, stmt: CopyStmt, data: string): ExecResult;
21
+ export { executeSelectStmt };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,16 @@
1
+ import type { TableData, TriggerMeta } from "../storage/database-state.js";
2
+ import type { Datum } from "../types/value.js";
3
+ import type { ExecEnv } from "./relation.js";
4
+ export type TriggerEvent = "insert" | "update" | "delete";
5
+ export interface TriggerFireResult {
6
+ /** null = row operation skipped (BEFORE trigger returned NULL) */
7
+ row: Datum[] | null;
8
+ }
9
+ /**
10
+ * Fire row-level triggers for one row. Trigger function bodies execute via
11
+ * the plpgsql-lite interpreter in triggers-exec.ts (registered lazily).
12
+ */
13
+ export type TriggerExecutor = (env: ExecEnv, table: TableData, trigger: TriggerMeta, event: TriggerEvent, oldRow: Datum[] | null, newRow: Datum[] | null) => Datum[] | null;
14
+ export declare function setTriggerExecutor(e: TriggerExecutor): void;
15
+ export declare function fireRowTriggers(env: ExecEnv, table: TableData, timing: "before" | "after" | "instead_of", event: TriggerEvent, oldRow: Datum[] | null, newRow: Datum[] | null): TriggerFireResult;
16
+ export declare function hasRowTriggers(table: TableData, timing: "before" | "after" | "instead_of", event: TriggerEvent): boolean;
@@ -0,0 +1,13 @@
1
+ import type { Expr, FuncCall, WindowSpec } from "../ast/nodes.js";
2
+ import type { EngineCtx } from "../expressions/context.js";
3
+ import { type TypedValue } from "../types/value.js";
4
+ /** Evaluator callback: evaluate `e` in the context of source row `rowIdx`. */
5
+ export type RowEval = (rowIdx: number, e: Expr) => TypedValue;
6
+ /**
7
+ * Compute all window function results for one SELECT.
8
+ * Returns per-call arrays indexed by source row.
9
+ */
10
+ export declare function computeWindowValues(ctx: EngineCtx, calls: FuncCall[], rowCount: number, evalAt: RowEval, namedWindows: ReadonlyArray<{
11
+ name: string;
12
+ spec: WindowSpec;
13
+ }>): Map<FuncCall, TypedValue[]>;
@@ -0,0 +1,23 @@
1
+ import type { DatabaseState } from "../storage/database-state.js";
2
+ import type { CastEnv } from "../types/cast.js";
3
+ import type { CompareCtx } from "../types/compare.js";
4
+ import { type TypeId } from "../types/value.js";
5
+ /**
6
+ * Engine-wide evaluation context: database state plus per-statement clock
7
+ * captures. One instance is created per top-level statement execution.
8
+ */
9
+ export declare class EngineCtx implements CastEnv, CompareCtx {
10
+ readonly state: DatabaseState;
11
+ /** transaction timestamp (now(), current_timestamp) — UTC micros since PG epoch */
12
+ readonly txNow: bigint;
13
+ /** statement timestamp */
14
+ readonly stmtNow: bigint;
15
+ constructor(state: DatabaseState, txNow?: bigint);
16
+ timezone(): string;
17
+ zoneOffsetAt(utcMicros: bigint): number;
18
+ zoneOffsetForNaive(naiveMicros: bigint): number;
19
+ enumLabels(enumType: TypeId): string[] | null;
20
+ enumHasLabel(enumType: TypeId, label: string): boolean;
21
+ enumOrder(enumType: TypeId, label: string): number;
22
+ requireEnum(enumType: TypeId): string[];
23
+ }
@@ -0,0 +1,38 @@
1
+ import type { Expr, FuncCall, SelectStmt } from "../ast/nodes.js";
2
+ import { type Datum, type TypedValue, type TypeId } from "../types/value.js";
3
+ import type { EngineCtx } from "./context.js";
4
+ /**
5
+ * Environment the executor provides for expression evaluation: column
6
+ * resolution, parameter binding, subquery execution, aggregate / window
7
+ * result lookup, and user-defined function invocation.
8
+ */
9
+ export interface EvalScope {
10
+ lookupColumn(parts: string[]): TypedValue | undefined;
11
+ /**
12
+ * Whole-expression interception (GROUP BY expression matching). Checked
13
+ * before normal evaluation of every node.
14
+ */
15
+ exprOverride?(node: Expr): TypedValue | undefined;
16
+ param?(index: number): TypedValue;
17
+ execScalarSubquery?(q: SelectStmt): TypedValue;
18
+ execExistsSubquery?(q: SelectStmt): boolean;
19
+ /** rows with a single projected column for IN / ANY / ALL / ARRAY(...) */
20
+ execColumnSubquery?(q: SelectStmt): {
21
+ type: TypeId;
22
+ values: Datum[];
23
+ };
24
+ /** precomputed aggregate results (keyed by AST node identity) */
25
+ aggValue?(node: FuncCall): TypedValue | undefined;
26
+ /** precomputed window function results */
27
+ windowValue?(node: FuncCall): TypedValue | undefined;
28
+ groupingValue?(node: Expr): TypedValue | undefined;
29
+ callUserFunction?(name: string[], args: TypedValue[], node: FuncCall): TypedValue | undefined;
30
+ /** sequence functions et al need state mutation; provided by executor */
31
+ callStatefulFunction?(name: string, args: TypedValue[]): TypedValue | undefined;
32
+ }
33
+ export declare function evalExpr(ctx: EngineCtx, scope: EvalScope, e: Expr): TypedValue;
34
+ export declare function numberLitValue(raw: string): TypedValue;
35
+ export declare function toBool(ctx: EngineCtx, v: TypedValue): boolean | null;
36
+ /** Domain NOT NULL + CHECK constraints, with VALUE bound to the cast result. */
37
+ export declare function applyDomainChecks(ctx: EngineCtx, domainKey: string, value: TypedValue): void;
38
+ export declare function anyAllCompare(ctx: EngineCtx, op: string, left: TypedValue, rights: TypedValue[], kind: "any" | "all"): TypedValue;
@@ -0,0 +1,8 @@
1
+ import { isNumeric, makeNumeric, numericSqrt, parseNumeric } from "../types/numeric.js";
2
+ import { float8Text, type TypedValue } from "../types/value.js";
3
+ import type { EngineCtx } from "./context.js";
4
+ export declare function evalBinary(ctx: EngineCtx, op: string, l0: TypedValue, r0: TypedValue): TypedValue;
5
+ /** jsonb - text / jsonb - int / jsonb - text[] */
6
+ export declare function evalJsonbDelete(_ctx: EngineCtx, l: TypedValue, r: TypedValue): TypedValue;
7
+ export declare function evalUnary(ctx: EngineCtx, op: string, operand: TypedValue): TypedValue;
8
+ export { float8Text, isNumeric, makeNumeric, numericSqrt, parseNumeric };
@@ -0,0 +1,20 @@
1
+ /** LIKE pattern → anchored RegExp source. */
2
+ export declare function likeToRegex(pattern: string, escape: string | null): string;
3
+ export declare function likeMatch(text: string, pattern: string, escape: string | null, caseInsensitive: boolean): boolean;
4
+ /** SIMILAR TO pattern → anchored RegExp source (SQL regex dialect). */
5
+ export declare function similarToRegex(pattern: string, escape: string | null): string;
6
+ export declare function similarToMatch(text: string, pattern: string, escape: string | null): boolean;
7
+ /**
8
+ * Translate a POSIX ARE (PG regex flavor) to a JS RegExp source.
9
+ * Covers the common surface: classes, quantifiers, anchors, \m/\M/\y word
10
+ * boundaries, [[:class:]] names. Exotic ARE features (\A directors, back
11
+ * refs into lookahead) are passed through and may diverge (documented).
12
+ */
13
+ export declare function pgRegexToJs(pattern: string): string;
14
+ export declare function pgRegex(pattern: string, flags: string): RegExp;
15
+ export declare function regexMatch(text: string, pattern: string, caseInsensitive: boolean): boolean;
16
+ /**
17
+ * Translate PG regex option letters to JS RegExp flags. PG default is
18
+ * newline-insensitive (JS `s`); `n`/`m` switch to newline-sensitive (`m`).
19
+ */
20
+ export declare function regexFlags(pgFlags: string, dropGlobal?: boolean): string;
@@ -0,0 +1,17 @@
1
+ import type { EngineCtx } from "../expressions/context.js";
2
+ import { type TypedValue, type TypeId } from "../types/value.js";
3
+ /** Incremental accumulator; the executor feeds rows and reads the result. */
4
+ export interface AggregateAcc {
5
+ step(args: TypedValue[]): void;
6
+ result(): TypedValue;
7
+ }
8
+ export type AggregateFactory = (ctx: EngineCtx, argTypes: TypeId[]) => AggregateAcc;
9
+ export declare function getAggregateFactories(): Map<string, AggregateFactory>;
10
+ export declare function isAggregateName(name: string): boolean;
11
+ export declare function createAggregate(ctx: EngineCtx, name: string, argTypes: TypeId[]): AggregateAcc;
12
+ /** true for aggregates whose arguments come from WITHIN GROUP (ORDER BY ...) */
13
+ export declare function isOrderedSetAggregate(name: string): boolean;
14
+ /** unify agg arg type across rows (executor helper) */
15
+ export declare function unifyAggType(a: TypeId, b: TypeId): TypeId;
16
+ /** result type helpers used by planner-ish code paths */
17
+ export declare function aggregateResultHint(name: string, argT: TypeId): TypeId;
@@ -0,0 +1,2 @@
1
+ import { type ScalarFn } from "./util.js";
2
+ export declare function getArrayFunctions(): Map<string, ScalarFn>;
@@ -0,0 +1,26 @@
1
+ import type { EngineCtx } from "../expressions/context.js";
2
+ import { type Interval } from "../types/datetime.js";
3
+ import { type Numeric } from "../types/numeric.js";
4
+ import { type TypedValue } from "../types/value.js";
5
+ /**
6
+ * EXTRACT / date_part. `asNumeric=true` → numeric result (EXTRACT, PG 14+);
7
+ * false → float8 (date_part).
8
+ */
9
+ export declare function extractDatePart(ctx: EngineCtx, field0: string, src0: TypedValue, asNumeric: boolean): TypedValue;
10
+ /** ISO 8601 week + iso year for a day number. */
11
+ export declare function isoWeek(days: number): {
12
+ week: number;
13
+ year: number;
14
+ };
15
+ export declare function dateTruncDays(field: string, days: number): number;
16
+ export declare function dateTruncMicros(field: string, micros: bigint): bigint;
17
+ export declare function dateTruncInterval(field: string, v: Interval): Interval;
18
+ export declare function makeDateDatum(y: number, m: number, d: number): number;
19
+ export declare function makeTimeDatum(h: number, min: number, sec: number): bigint;
20
+ export declare function justifyHours(v: Interval): Interval;
21
+ export declare function justifyDays(v: Interval): Interval;
22
+ export declare function justifyInterval(v: Interval): Interval;
23
+ /** age(a, b): symbolic year/month/day difference like PG timestamp_age */
24
+ export declare function timestampAge(a: bigint, b: bigint): Interval;
25
+ export declare function numericSecondsToMicros(n: Numeric): bigint;
26
+ export declare function parseNumericArg(text: string): Numeric;
@@ -0,0 +1,2 @@
1
+ import { type ScalarFn } from "./util.js";
2
+ export declare function getDatetimeFunctions(): Map<string, ScalarFn>;
@@ -0,0 +1,7 @@
1
+ import type { EngineCtx } from "../expressions/context.js";
2
+ import { type JsonbValue } from "../types/jsonb.js";
3
+ import { type Datum, type TypeId } from "../types/value.js";
4
+ import { type ScalarFn } from "./util.js";
5
+ /** Convert an engine Datum to a JsonbValue tree (to_jsonb / jsonb_build_*). */
6
+ export declare function datumToJsonb(ctx: EngineCtx, t: TypeId, v: Datum): JsonbValue;
7
+ export declare function getJsonFunctions(): Map<string, ScalarFn>;
@@ -0,0 +1,2 @@
1
+ import { type ScalarFn } from "./util.js";
2
+ export declare function getMathFunctions(): Map<string, ScalarFn>;
@@ -0,0 +1,8 @@
1
+ import type { EngineCtx } from "../expressions/context.js";
2
+ import type { SequenceData } from "../storage/database-state.js";
3
+ import { type ScalarFn } from "./util.js";
4
+ export declare const PG_VERSION_TEXT = "PostgreSQL 18.3 (postgres-mem) on TypeScript, in-memory engine";
5
+ export declare const PG_SERVER_VERSION = "18.3";
6
+ export declare const PG_SERVER_VERSION_NUM = "180003";
7
+ export declare function sequenceNextval(ctx: EngineCtx, seq: SequenceData): bigint;
8
+ export declare function getMiscFunctions(): Map<string, ScalarFn>;
@@ -0,0 +1,10 @@
1
+ import type { EngineCtx } from "../expressions/context.js";
2
+ import type { TypedValue } from "../types/value.js";
3
+ import type { ScalarFn } from "./util.js";
4
+ /**
5
+ * All engine scalar builtins keyed by lowercase name. Built lazily once;
6
+ * the inventory gate walks this map against the oracle's pg_proc.
7
+ */
8
+ export declare function getScalarFunctions(): Map<string, ScalarFn>;
9
+ export declare function hasScalarFunction(name: string): boolean;
10
+ export declare function callScalarFunction(ctx: EngineCtx, name: string, args: TypedValue[]): TypedValue;
@@ -0,0 +1,12 @@
1
+ import type { EngineCtx } from "../expressions/context.js";
2
+ import { type Datum, type TypedValue, type TypeId } from "../types/value.js";
3
+ export interface SrfResult {
4
+ columns: Array<{
5
+ name: string;
6
+ type: TypeId;
7
+ }>;
8
+ rows: Datum[][];
9
+ }
10
+ export type SrfFn = (ctx: EngineCtx, args: TypedValue[], alias: string) => SrfResult;
11
+ export declare function getSrfFunctions(): Map<string, SrfFn>;
12
+ export declare function isSrfName(name: string): boolean;
@@ -0,0 +1,4 @@
1
+ import { type ScalarFn } from "./util.js";
2
+ /** PG substr semantics: 1-based, negative start shifts window. */
3
+ export declare function substrImpl(s: string, start: number, len?: number): string;
4
+ export declare function getStringFunctions(): Map<string, ScalarFn>;
@@ -0,0 +1,2 @@
1
+ import { type ScalarFn } from "./util.js";
2
+ export declare function getTsearchFunctions(): Map<string, ScalarFn>;
@@ -0,0 +1,14 @@
1
+ import type { EngineCtx } from "../expressions/context.js";
2
+ import { type Numeric } from "../types/numeric.js";
3
+ import { type Datum, type TypedValue, type TypeId } from "../types/value.js";
4
+ export type ScalarFn = (ctx: EngineCtx, args: TypedValue[]) => TypedValue;
5
+ /** Wrap a function so any NULL argument short-circuits to a NULL result. */
6
+ export declare function strict(resultType: TypeId, fn: ScalarFn): ScalarFn;
7
+ export declare function argText(ctx: EngineCtx, v: TypedValue): string;
8
+ export declare function argInt(ctx: EngineCtx, v: TypedValue): number;
9
+ export declare function argBigInt(ctx: EngineCtx, v: TypedValue): bigint;
10
+ export declare function argFloat(ctx: EngineCtx, v: TypedValue): number;
11
+ export declare function argNumeric(ctx: EngineCtx, v: TypedValue): Numeric;
12
+ export declare function argBool(ctx: EngineCtx, v: TypedValue): boolean;
13
+ export declare function numericAsNumber(v: Datum): number;
14
+ export declare function arityError(name: string, args: TypedValue[]): never;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Window function surface. The executor's window module implements the
3
+ * evaluation; this registry only classifies names so the parser/executor can
4
+ * route OVER() calls, and the inventory gate can enumerate them.
5
+ */
6
+ export declare const WINDOW_FUNCTION_NAMES: Set<string>;
7
+ export declare function isWindowFunctionName(name: string): boolean;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * Pure TypeScript in-memory PostgreSQL. Import {@link Database} to get started.
4
+ *
5
+ * Deterministic by default (`random()` seed `1`, `now()` = `2000-01-01T00:00:00.000Z`).
6
+ * Pass `{ random: "os" }` / `{ now: "system" }` for PostgreSQL-like entropy and wall clock.
7
+ * Zero WASM, native bindings, or filesystem.
8
+ *
9
+ * Advanced / internal helpers live under `@crvouga/postgres-mem/unstable` and are
10
+ * exempt from semver.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * import { Database } from "@crvouga/postgres-mem";
15
+ *
16
+ * const db = new Database();
17
+ * db.exec("CREATE TABLE t (id serial PRIMARY KEY, name text)");
18
+ * db.prepare("INSERT INTO t (name) VALUES ($1)").run("Ada");
19
+ * const rows = db.query<{ id: number; name: string }>("SELECT * FROM t");
20
+ * ```
21
+ *
22
+ * @module
23
+ */
24
+ import "./serialization/codec.js";
25
+ export type { BindValue, JsValue, QueryRow } from "./api/bind.js";
26
+ export { Database, type DatabaseOptions } from "./api/database.js";
27
+ export { type ResultSet, type RunResult, Statement } from "./api/statement.js";
28
+ export { type ErrorCategory, PostgresError } from "./errors/error.js";