@supabase/lite 0.2.1-next.1 → 0.2.1-next.2

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.
@@ -1,182 +1,6 @@
1
- import { d as deparsePostgresDdl, A as AnyAST, V as VarsContext, I as IntrospectResult$1, T as TransactionOptions$1, a as IConnectionConfig$1, C as Connection$1 } from '../Connection-rAPmec1m.js';
2
- import { ConnectionMigrator, MaybePromise, SchemaDiffResult, PlanStep, PlanResult, IConnectionConfig, Connection, Dialect, IntrospectResult, TransactionOptions } from '@supabase/lite';
3
- import { KyselyPlugin } from 'kysely';
4
- import 'libpg-query';
5
- import 'pgsql-deparser';
1
+ import { I as IConnectionConfig, C as Connection } from '../Connection-CSVCuMv-.js';
2
+ import 'kysely';
6
3
 
7
- type SqliteMigratorOptions = {
8
- onTranslation?: (result: SqlitePostgresTranslationResult) => MaybePromise<void>;
9
- };
10
- declare class SqliteMigrator implements ConnectionMigrator {
11
- private readonly conn;
12
- private readonly desiredSchema;
13
- private readonly options;
14
- private readonly differ;
15
- private readonly planner;
16
- translationResult?: SqlitePostgresTranslationResult;
17
- constructor(conn: SqliteConnection, desiredSchema: string, options?: SqliteMigratorOptions);
18
- getDesiredSchema(): Promise<string>;
19
- diff(): Promise<SchemaDiffResult>;
20
- safeSortPlanSteps(steps: PlanStep[]): PlanStep[];
21
- migratePlan(planResult: PlanResult, opts?: {
22
- force?: boolean;
23
- }): Promise<void>;
24
- migrate(opts?: {
25
- force?: boolean;
26
- }): Promise<SchemaDiffResult>;
27
- }
4
+ declare function createConnection<E extends IConnectionConfig = IConnectionConfig>(_config?: E): Promise<Connection>;
28
5
 
29
- interface ISqliteConnectionConfig extends IConnectionConfig {
30
- /**
31
- * The origin dialect for schema declarations. If "postgres",
32
- * the schema declarations will be translated to SQLite syntax.
33
- * If "sqlite", the schema declarations will be left as is.
34
- * @default "postgres"
35
- */
36
- ddlDialect?: "postgres" | "sqlite";
37
- /**
38
- * The origin dialect for query execution. If "sqlite", the queries will be executed as is.
39
- * Currently only "sqlite" is supported.
40
- * @default "sqlite"
41
- */
42
- queryDialect?: "sqlite";
43
- /**
44
- * Max bound parameters per statement. Enforced across all SQLite drivers
45
- * for portability: drivers and hosts vary in how many parameters they
46
- * accept (e.g. Cloudflare D1, sqlite-wasm), so we cap conservatively.
47
- * Statements exceeding this throw before execution.
48
- * @default 100
49
- */
50
- maxBoundParameters?: number;
51
- /**
52
- * Translation options for SQLite databases
53
- */
54
- translation?: {
55
- /**
56
- * The approach to take when translating PostgreSQL schema declarations to SQLite syntax.
57
- * Only applies if `ddl` is "postgres".
58
- */
59
- schemas?: {
60
- /**
61
- * The approach to take when translating PostgreSQL schema declarations to SQLite syntax.
62
- * If "quote" -> `public`.`table` -> `"public.table"`
63
- * If "snake_case" -> `public`.`table` -> `public__table`
64
- * @default "quote"
65
- */
66
- approach?: "quote" | "snake_case";
67
- /**
68
- * Whether to append the default schema to the table name when a table does not have a schema
69
- * @default false
70
- */
71
- appendDefaultSchema?: boolean;
72
- /**
73
- * The default schema to use when a table does not have a schema
74
- * @default "public"
75
- */
76
- defaultSchema?: string | false;
77
- };
78
- /**
79
- * Deparse details the connection must be aware of
80
- */
81
- deparse?: SqlitePostgresDeparseInfo;
82
- };
83
- }
84
- type DeparsePostgresDdlResult = Awaited<ReturnType<typeof deparsePostgresDdl>>;
85
- type SqlitePostgresDeparseInfo = Pick<DeparsePostgresDdlResult, "enums" | "rls" | "schema" | "vars"> & Partial<Pick<DeparsePostgresDdlResult, "tableConstraints" | "comments">>;
86
- type SqlitePostgresTranslationResult = Pick<DeparsePostgresDdlResult, "ddl"> & Partial<DeparsePostgresDdlResult>;
87
- declare abstract class SqliteConnection<Driver = unknown, DB = any, Config extends ISqliteConnectionConfig = ISqliteConnectionConfig> extends Connection<Driver, DB, Config> {
88
- dialect: Dialect;
89
- deserializeRow(row: Record<string, unknown>): Record<string, unknown>;
90
- constructor(config?: Config);
91
- static parseDeparseInfo(details: any): {
92
- rls?: undefined;
93
- vars?: undefined;
94
- } | {
95
- rls: {
96
- tables: any;
97
- policies: any;
98
- };
99
- vars: any;
100
- };
101
- updateDeparseInfo(details: NonNullable<ISqliteConnectionConfig["translation"]>["deparse"]): void;
102
- protected withSqlitePlugins(add_plugins?: KyselyPlugin[]): KyselyPlugin[];
103
- translateDdl(ddl: string): Promise<SqlitePostgresTranslationResult>;
104
- introspect(options?: {
105
- useCache?: boolean;
106
- postprocess?: boolean;
107
- }): Promise<IntrospectResult>;
108
- transaction(statements: string[], opts?: TransactionOptions): Promise<void>;
109
- close(): Promise<void>;
110
- /**
111
- * When ddlDialect === "postgres", enrich the PRAGMA-derived IntrospectResult
112
- * with metadata recovered from the parsed Postgres DDL: real FK constraint
113
- * names, table-level UNIQUE/CHECK constraints, column pg_type / is_generated,
114
- * and comments.
115
- */
116
- private mergeDeparseMetadata;
117
- private markForeignKeyVisibility;
118
- /**
119
- * Create a migrator for the given schema.
120
- * @param desiredSchema The desired schema to migrate to. Input DDL is expected to be `config.ddlDialect`.
121
- * @returns A migrator instance.
122
- */
123
- createMigrator(desiredSchema: string): SqliteMigrator;
124
- get maxBoundParameters(): number;
125
- /**
126
- * Throws if the compiled statement has more bound parameters than
127
- * `maxBoundParameters`. Drivers call this from their query executor so
128
- * the same limit is enforced regardless of host capability.
129
- */
130
- assertParamLimit(parameters: readonly unknown[] | undefined): void;
131
- /**
132
- * Asserts the parameter limit and normalizes bind values. Drivers call
133
- * this once per statement; same limit and same value coercion everywhere.
134
- */
135
- prepareBindParams(parameters: readonly unknown[] | undefined): unknown[];
136
- /**
137
- * Coerces JS values to types every SQLite driver accepts. Drivers vary:
138
- * `bun:sqlite` silently coerces booleans, `node:sqlite` throws. Normalize
139
- * centrally so the executor boundary behaves identically everywhere.
140
- *
141
- * - `undefined` is dropped (matches prior DO behaviour and Kysely slots
142
- * that never bound a value).
143
- * - `boolean` → `0` / `1`.
144
- * - pass-through: `null`, `number`, `bigint`, `string`, `Uint8Array`,
145
- * `ArrayBuffer`, `Date` (drivers handle these, or upstream field
146
- * serializers have already converted).
147
- * - unknown types throw with the offending index so divergence surfaces
148
- * loudly instead of as a driver-specific bind error.
149
- */
150
- normalizeBindParams(parameters: readonly unknown[] | undefined): unknown[];
151
- normalizeDbError(e: unknown): unknown;
152
- onPostgrestAST(ast: AnyAST, vars?: VarsContext): Promise<AnyAST>;
153
- private applyRls;
154
- }
155
-
156
- interface ICloudConnectionConfig extends ISqliteConnectionConfig {
157
- projectRef: string;
158
- token: string;
159
- host: string;
160
- }
161
- declare class CloudConnection<DB = any> extends SqliteConnection<never, DB> {
162
- readonly config: ICloudConnectionConfig;
163
- dialect: "sqlite";
164
- driver: never;
165
- kysely: never;
166
- constructor(config: ICloudConnectionConfig);
167
- private fetch;
168
- introspect(options?: {
169
- useCache?: boolean;
170
- postprocess?: boolean;
171
- }): Promise<IntrospectResult$1>;
172
- transaction(statements: string[], opts?: TransactionOptions$1): Promise<void>;
173
- exec<T = {
174
- rows: unknown[];
175
- } | void>(statement: string, ...parameters: readonly unknown[]): Promise<T>;
176
- close(): Promise<void>;
177
- }
178
- declare function cloud<DB = any>(config: ICloudConnectionConfig): CloudConnection<DB>;
179
-
180
- declare function createConnection(_config?: IConnectionConfig$1): Promise<Connection$1>;
181
-
182
- export { CloudConnection, Connection$1 as Connection, type ICloudConnectionConfig, IConnectionConfig$1 as IConnectionConfig, type ISqliteConnectionConfig, SqliteConnection, type SqlitePostgresTranslationResult, cloud, createConnection };
6
+ export { Connection, IConnectionConfig, createConnection };
@@ -1,4 +1,4 @@
1
- import {Deparser,QuoteUtils}from'pgsql-deparser';import {DeparserContext}from'pgsql-deparser/visitors/base.js';import {SqlFormatter}from'pgsql-deparser/utils/sql-formatter.js';import {Connection,RelationNotFoundError,invariant,DataLossError,PlanStepType}from'@supabase/lite';import {OperationNodeTransformer,SchemableIdentifierNode,JoinNode,TableNode,AliasNode,ListNode,UsingNode}from'kysely';try {
1
+ try {
2
2
  /**
3
3
  * Adding this to avoid warnings from node:sqlite being experimental
4
4
  */
@@ -9,207 +9,4 @@ import {Deparser,QuoteUtils}from'pgsql-deparser';import {DeparserContext}from'pg
9
9
  };
10
10
  } catch {}
11
11
 
12
- var un=Object.defineProperty;var g=(i,e)=>()=>(i&&(e=i(i=0)),e);var pn=(i,e)=>{for(var t in e)un(i,t,{get:e[t],enumerable:true});};var yt=g(()=>{});var St=g(()=>{});function fn(i){return Object.prototype.toString.call(i)==="[object Object]"}function mn(i){return i!==null&&typeof i=="object"}function H(i,e,t=void 0){let n=typeof e=="string"?e.split(/[.[\]"]+/).filter(r=>r):e;if(n.length===0)return i;try{let[r,...s]=n;return !r||!(r in i)?t:H(i[r],s,t)}catch{if(typeof t<"u")return t;throw new Error(`Invalid path: ${n.join(".")}`)}}function Fe(i,...e){for(let t of e)for(let[n,r]of Object.entries(t))r!==void 0&&(!fn(r)&&!Array.isArray(r)||Array.isArray(r)&&!Array.isArray(i[n])?i[n]=r:mn(i[n])?Fe(i[n],r):i[n]=r);return i}var ye=g(()=>{});var Et=g(()=>{});function bt(i,e){if(!i)throw new Error(e)}var Tt=g(()=>{});function qe(i){return (i??"").trim().toLowerCase()}function Ue(i){return (i??"").replace(/\s+/g," ").replace(/"/g,"").trim().toLowerCase()}function je(i){if(i==null)return null;let e=i.trim();for(;e.startsWith("(")&&e.endsWith(")");)e=e.slice(1,-1).trim();return (e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))&&(e=e.slice(1,-1)),e}var Be=g(()=>{});function h(i,e='"'){return `${e}${i}${e}`}function wt(i,e,t){if(e instanceof RegExp)return e.test(i);if(typeof e=="string")switch(!t&&e.startsWith("/")&&(t="regex"),t){case "regex":return new RegExp(e).test(i);case "sql":return new RegExp(e.replace("%",".*").replace("_",".")).test(i);case "wildcard":return new RegExp(e.replace("*",".*")).test(i);default:return i.includes(e)}return false}var Se=g(()=>{});var Ct=g(()=>{});var xt=g(()=>{});var Me=g(()=>{yt();St();ye();Et();Tt();Be();Se();Ct();xt();});var D,be=g(()=>{D=class i{constructor(e){this.data=e;}appliesTo(e){return this.data.command==="ALL"||this.data.command===e}appliesToRole(e){return this.data.roles.length===0||this.data.roles.includes(e)}toJSON(){return this.data}static fromJSON(e){return new i(e)}};});var V,Ke=g(()=>{Be();V=class{makeIndexKey(e){return `${e.table}:${e.name}:${e.unique}:${e.columns.join(",")}`}makeForeignKeyKey(e){return `${e.table}:${e.column}:${e.ref_table}:${e.ref_column}`}diff(e,t){let n=[],r=[],s=[],o=[],a=new Set(e.tables.map(m=>m.name)),l=new Set(t.tables.map(m=>m.name));for(let m of t.tables)a.has(m.name)||n.push({type:"added",name:m.name,sql:m.sql});for(let m of e.tables)l.has(m.name)||n.push({type:"removed",name:m.name});for(let m of e.tables){let T=t.tables.find(N=>N.name===m.name);if(!T)continue;let f=Ue(m.sql),C=Ue(T.sql);f!==C&&n.push({type:"modified",name:m.name,sql:T.sql});}let u=e.tables.filter(m=>l.has(m.name));for(let m of u){let T=e.columns.filter(w=>w.table===m.name),f=t.columns.filter(w=>w.table===m.name),C=new Map(T.map(w=>[w.name,w])),N=new Map(f.map(w=>[w.name,w]));for(let[w,k]of N)C.has(w)||r.push({type:"added",table:m.name,name:w,column:k});for(let[w]of C)N.has(w)||r.push({type:"removed",table:m.name,name:w});for(let[w,k]of C){let I=N.get(w);if(!I)continue;let P={};qe(k.type)!==qe(I.type)&&(P.type={from:k.type,to:I.type}),k.nullable!==I.nullable&&(P.nullable={from:k.nullable,to:I.nullable}),je(k.default_value)!==je(I.default_value)&&(P.default_value={from:k.default_value,to:I.default_value}),Object.keys(P).length>0&&r.push({type:"modified",table:m.name,name:w,changes:P});}}let p=new Map(e.indexes.map(m=>[this.makeIndexKey(m),m])),c=new Map(t.indexes.map(m=>[this.makeIndexKey(m),m]));for(let[m,T]of c)p.has(m)||s.push({type:"added",...T});for(let[m,T]of p)c.has(m)||s.push({type:"removed",...T});let d=new Map(e.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m])),E=new Map(t.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m]));for(let[m,T]of E)d.has(m)||o.push({type:"added",...T});for(let[m,T]of d)E.has(m)||o.push({type:"removed",...T});let y=n.length>0||r.length>0||s.length>0||o.length>0;return {tables:n,columns:r,indexes:s,foreign_keys:o,has_changes:y}}};});var Ve=g(()=>{});var Cn,G,Ge=g(()=>{Ve();Se();Cn=["CURRENT_TIMESTAMP","CURRENT_TIME","CURRENT_DATE"],G=class{plan(e,t,n,r){if(!e.has_changes)return {steps:[],warnings:[],unsafe:false};let s=[],o=[];s.push({sql:"PRAGMA foreign_keys=OFF;",description:"Disable foreign key checks",type:"disable_foreign_keys"}),s.push({sql:"BEGIN;",description:"Begin transaction",type:"begin_transaction"});for(let c of e.tables.filter(d=>d.type==="added")){s.push({sql:`${c.sql};`,description:`CREATE TABLE ${h(c.name)}`,type:"create_table"});let d=n.indexes.filter(E=>E.table===c.name);for(let E of d){let y=E.unique?"UNIQUE ":"",m=E.columns.map(T=>h(T)).join(", ");s.push({sql:`CREATE ${y}INDEX ${h(E.name)} ON ${h(c.name)} (${m});`,description:`Create index ${h(E.name)} on ${h(c.name)}`,type:"add_index"});}}let a=new Set(t.tables.map(c=>c.name)),l=new Set(n.tables.map(c=>c.name)),u=new Set(e.tables.filter(c=>c.type==="modified").map(c=>c.name)),p=[...a].filter(c=>l.has(c));for(let c of p){if(!(u.has(c)||e.columns.some(m=>m.table===c)||e.indexes.some(m=>m.table===c)||e.foreign_keys.some(m=>m.table===c)))continue;let{canAlter:E,addedCols:y}=this.canSimpleAlter(c,e,n);if(E){for(let f of y)s.push({sql:`ALTER TABLE ${h(c)} ADD COLUMN ${this.columnDef(f)};`,description:`Add column ${h(f.name)} to ${h(c)}`,type:"add_column"});let m=e.indexes.filter(f=>f.table===c&&f.type==="added"),T=e.indexes.filter(f=>f.table===c&&f.type==="removed");for(let f of T)s.push({sql:`DROP INDEX IF EXISTS ${h(f.name)};`,description:`Drop index ${h(f.name)}`,type:"drop_index"});for(let f of m){let C=f.unique?"UNIQUE ":"",N=f.columns.map(w=>h(w)).join(", ");s.push({sql:`CREATE ${C}INDEX ${h(f.name)} ON ${h(c)} (${N});`,description:`Create index ${h(f.name)} on ${h(c)}`,type:"add_index"});}}else {let m=this.rebuildTable(c,t,n,e);s.push(...m.steps),o.push(...m.warnings);}}for(let c of e.tables.filter(d=>d.type==="removed"))s.push({sql:`DROP TABLE ${h(c.name)};`,description:`Drop table ${h(c.name)}`,type:"drop_table"}),o.push({table:c.name,reason:"table will be dropped"});return s.push({sql:"COMMIT;",description:"Commit transaction",type:"commit_transaction"}),s.push({sql:"PRAGMA foreign_keys=ON;",description:"Re-enable foreign key checks",type:"enable_foreign_keys"}),{steps:s,warnings:o,unsafe:o.length>0}}rebuildTable(e,t,n,r){let s=[],o=[],a=n.tables.find(f=>f.name===e);if(!a)return {steps:s,warnings:o};let l=`_${e}_migrate_new`,u=a.sql.replace(new RegExp(`(CREATE\\s+TABLE\\s+)(?:"${e}"|${e})`,"i"),`$1${h(l)}`);s.push({sql:`${u};`,description:`Create temporary table ${h(l)}`,type:"create_table"});let p=t.columns.filter(f=>f.table===e).map(f=>f.name),c=n.columns.filter(f=>f.table===e).map(f=>f.name),d=p.filter(f=>c.includes(f));if(d.length>0){let f=d.map(C=>h(C)).join(", ");s.push({sql:`INSERT INTO ${h(l)} (${f})
13
- SELECT ${f}
14
- FROM ${h(e)};`,description:`Copy data from ${h(e)} to ${h(l)}`,type:"copy_data"});}s.push({sql:`DROP TABLE ${h(e)};`,description:`Drop old table ${h(e)}`,type:"drop_table"}),s.push({sql:`ALTER TABLE ${h(l)} RENAME TO ${h(e)};`,description:`Rename ${h(l)} to ${h(e)}`,type:"rename_table"});let E=n.indexes.filter(f=>f.table===e);for(let f of E){let C=f.unique?"UNIQUE ":"",N=f.columns.map(w=>h(w)).join(", ");s.push({sql:`CREATE ${C}INDEX ${h(f.name)} ON ${h(e)} (${N});`,description:`Recreate index ${h(f.name)} on ${h(e)}`,type:"add_index"});}let y=n.triggers?.filter(f=>f.table===e)??[];for(let f of y)s.push({sql:`${f.sql};`,description:`Recreate trigger ${h(f.name)} on ${h(e)}`,type:"create_trigger"});let m=r.columns.filter(f=>f.table===e&&f.type==="removed");for(let f of m)o.push({table:e,reason:`column "${f.name}" will be dropped`});let T=r.columns.filter(f=>f.table===e&&f.type==="modified");for(let f of T)f.changes?.type&&o.push({table:e,reason:`column "${f.name}" type changes from ${f.changes.type.from} to ${f.changes.type.to}`}),f.changes?.nullable&&!f.changes.nullable.to&&o.push({table:e,reason:`column "${f.name}" becomes NOT NULL`});return {steps:s,warnings:o}}canSimpleAlter(e,t,n){let r=t.columns.filter(c=>c.table===e),s=r.filter(c=>c.type==="added"),o=r.filter(c=>c.type==="removed"),a=r.filter(c=>c.type==="modified"),l=t.foreign_keys.some(c=>c.table===e);if(o.length>0||a.length>0||l)return {canAlter:false,addedCols:s};let u=n.tables.find(c=>c.name===e);return u&&/\bCHECK\s*\(/i.test(u.sql)?{canAlter:false,addedCols:s}:{canAlter:s.every(c=>{let d=c.column;return this.hasNonConstantDefault(d.default_value)?false:d.nullable||d.default_value!=null})&&s.length>0,addedCols:s}}hasNonConstantDefault(e){if(e==null)return false;let t=e.trim().toUpperCase();return Cn.includes(t)}columnDef(e){let t=e.column,n=`${h(t.name)} ${t.type||"TEXT"}`;return t.nullable||(n+=" NOT NULL"),t.default_value!=null&&(n+=` DEFAULT ${t.default_value}`),n}};});async function Q(i){let{parse:e}=await import('pgsql-parser');return e(i)}var Pt=g(()=>{});function ee(i){if("String"in i)return i.String.sval}function F(i){return i.map(ee).filter(e=>e!=null)}function q(i){return i==null?[]:i.List!==void 0?i.List.items||[]:Array.isArray(i)?i:[i]}function Ne(i){return QuoteUtils.quoteIdentifier(i)}function J(i){return Object.keys(i)[0]}function $t(i){if("A_Const"in i){if(i.A_Const.ival)return i.A_Const.ival.ival;if(i.A_Const.fval)return i.A_Const.fval.fval;if(i.A_Const.sval)return i.A_Const.sval.sval;if(i.A_Const.boolval)return i.A_Const.boolval.boolval;if(i.A_Const.isnull)return null}}var U=g(()=>{});function qt(i){let e=i.toLowerCase().trim();if(e.startsWith("_")||e.endsWith("[]"))return "TEXT";let t=Ln[e];if(!t)throw new j(`Unsupported PostgreSQL type: "${i}"`);return t}function Re(i){let e=i.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(e)}function Ae(i){let e=i.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(e)}function ke(i){let e=i.toLowerCase();return ["numeric","decimal"].includes(e)}var j,S,Ln,Ft,Dn,Ie,Y=g(()=>{U();j=class extends Error{},S=class extends j{constructor(t,n){super(n??`Unsupported node type: ${J(t)}`);this.node=t;}},Ln={int2:"INTEGER",smallint:"INTEGER",int4:"INTEGER",integer:"INTEGER",int:"INTEGER",int8:"INTEGER",bigint:"INTEGER",serial:"INTEGER",serial4:"INTEGER",bigserial:"INTEGER",serial8:"INTEGER",smallserial:"INTEGER",serial2:"INTEGER",float4:"REAL",real:"REAL",float8:"REAL","double precision":"REAL",numeric:"REAL",decimal:"REAL",text:"TEXT",varchar:"TEXT","character varying":"TEXT",char:"TEXT",character:"TEXT",bpchar:"TEXT",name:"TEXT",bytea:"BLOB",bool:"INTEGER",boolean:"INTEGER",date:"TEXT",time:"TEXT","time without time zone":"TEXT",timetz:"TEXT","time with time zone":"TEXT",timestamp:"TEXT","timestamp without time zone":"TEXT",timestamptz:"TEXT","timestamp with time zone":"TEXT",interval:"TEXT",json:"TEXT",jsonb:"TEXT",uuid:"TEXT",inet:"TEXT"},Ft=["<",">","<=",">=","=","<>","!=","+","-","*","/","%","&","|","<<",">>","||","BETWEEN","NOT BETWEEN","IN","NOT IN","LIKE","NOT LIKE","IS NULL","IS NOT NULL","IS TRUE","IS NOT TRUE","IS FALSE","IS NOT FALSE","IS UNKNOWN","IS NOT UNKNOWN","AND","OR","NOT","->>"];Dn={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"error"},AlterSeqStmt:{react:"error"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{react:"ignore"},PartitionElem:{react:"error"},PartitionCmd:{react:"error"},VariableSetStmt:{react:"ignore"},CompositeTypeStmt:{react:"error"},AlterEnumStmt:{react:"error"},AlterObjectSchemaStmt:{react:"error"},AlterOwnerStmt:{react:"error"},AlterTypeStmt:{react:"error"},AlterFunctionStmt:{react:"error"},AlterDefaultPrivilegesStmt:{react:"error"},GrantStmt:{react:"error"},GrantRoleStmt:{react:"error"},CopyStmt:{react:"error"},CreateCastStmt:{react:"error"},AlterOpFamilyStmt:{react:"error"},AlterOperatorStmt:{react:"error"},TruncateStmt:{react:"error"},A_Indirection:{react:"error"},XmlExpr:{react:"error"},XmlSerialize:{react:"error"},RangeTableSample:{react:"error"},GroupingSet:{react:"error"}},Ie=new Map(Object.entries(Dn));});var Oe,Ut=g(()=>{Y();U();Oe=class{constructor(e){this.ast=e;this.result=[...this.walk(this.ast,[],{trackPaths:["returningList"]})];}result=[];*walk(e=this.ast,t=[],n={}){if(!e||typeof e!="object")return;let{trackPaths:r=[]}=n;if(Array.isArray(e)){for(let o=0;o<e.length;o++)yield*this.walk(e[o],t,n);return}let s=Object.keys(e);if(s.length===1&&s[0][0]>="A"&&s[0][0]<="Z"){let o=s[0];yield {node:e,path:t},yield*this.walk(e[o],[...t,o],n);}else for(let[o,a]of Object.entries(e))if(a&&typeof a=="object"){let l=r.includes(o)?[...t,o]:t;yield*this.walk(a,l,n);}}containsUnsupportedNode(){for(let{node:e}of this.result){let t=J(e),n=Ie.get(t);if(n&&n.react==="error")return true}}hasFuncCall(){for(let{node:e}of this.result)if("FuncCall"in e)return true;return false}getFuncCalls(){return Array.from(this.result).map(({node:e})=>e).filter(e=>"FuncCall"in e).map(e=>e.FuncCall)}getFuncCallNames(){return this.getFuncCalls().flatMap(e=>e.funcname?.map(t=>t.String?.sval||t.String?.str))}hasSqlValueFunction(){for(let{node:e}of this.result)if("SQLValueFunction"in e)return true;return false}getSqlValueFunctions(){return Array.from(this.result).map(({node:e})=>e).filter(e=>"SQLValueFunction"in e).map(e=>e.SQLValueFunction)}getSqlValueFunctionNames(){return this.getSqlValueFunctions().map(e=>e.op)}hasUnsafeStar(){let e=this.result.filter(({node:t})=>"A_Star"in t);if(e.length===0)return false;for(let{path:t}of e)if(!t.includes("SelectStmt")&&!t.includes("returningList"))return true;return false}getRelationDefinitions(){return this.result.filter(({node:t})=>"CreateStmt"in t).map(({node:t})=>t.CreateStmt).map(t=>({relation:{relname:t.relation?.relname??"",inh:t.relation?.inh,relpersistence:t.relation?.relpersistence},columns:t.tableElts?.map(n=>{let r=n.ColumnDef?.typeName?.names?.map(o=>"String"in o?o.String.sval:""),s=r?.some(o=>o.toLowerCase().includes("pg_catalog"));return {name:n.ColumnDef?.colname??"",is_local:n.ColumnDef?.is_local,pg_catalog:s,type:r?.filter(o=>!o.toLowerCase().includes("pg_catalog"))[0]??"",types:r,constraints:n.ColumnDef?.constraints}})}))}getRelationColumnTypes(){return {has_non_pg_catalog_types:this.getRelationDefinitions().some(e=>e.columns?.some(t=>!t.pg_catalog)),types:Array.from(new Set(this.getRelationDefinitions().flatMap(e=>e.columns?.map(t=>t.type))))}}};});var Pn,$n,Fn,qn,X,ve,jt=g(()=>{Y();Pn=["DECLARE","IF","ELSIF","ELSE","LOOP","WHILE","FOR","FOREACH","EXCEPTION","RAISE","PERFORM","EXECUTE","SELECT"],$n=/^NEW\.(\w+)\s*(?::=|=)\s*(.+)$/is,Fn=/^RETURN\s+(NEW|OLD)$/i,qn=/^(INSERT|UPDATE|DELETE)\b/i,X=class extends j{constructor(t,n,r){super(r??`Unsupported PL/pgSQL: ${t}`);this.hint=t;this.body=n;}},ve=class{parse(e){let t=this.extractBlock(e),n=this.splitStatements(t),r=[],s=null;for(let o of n){let a=o.trim();if(!a)continue;this.rejectUnsupported(a);let l=a.match(Fn);if(l){s=l[1].toUpperCase(),r.push({type:"return",value:s});continue}let u=a.match($n);if(u){r.push({type:"assignment",column:u[1],expression:u[2].trim()});continue}if(qn.test(a)){r.push({type:"dml",sql:a});continue}throw new X(`"${a.substring(0,80)}" is not translatable to SQLite`,t)}if(!s)throw new j("Trigger function body must end with RETURN NEW or RETURN OLD");return {statements:r,returnValue:s}}extractBlock(e){let t=e.trim(),n=t.toUpperCase();if(/^\s*DECLARE\b/i.test(t))throw new X('"DECLARE" is not translatable to SQLite',e);let r=n.indexOf("BEGIN"),s=n.lastIndexOf("END");if(r===-1||s===-1||s<=r)throw new X("Expected BEGIN ... END block in trigger function body",e);return t.slice(r+5,s).trim()}splitStatements(e){let t=[],n="",r=0,s=false,o="";for(let l=0;l<e.length;l++){let u=e[l];if(s){n+=u,u===o&&(l+1<e.length&&e[l+1]===o?n+=e[++l]:s=false);continue}if(u==="'"||u==='"'){s=true,o=u,n+=u;continue}if(u==="("){r++,n+=u;continue}if(u===")"){r--,n+=u;continue}if(u===";"&&r===0){t.push(n.trim()),n="";continue}n+=u;}let a=n.trim();return a&&t.push(a),t}rejectUnsupported(e){let t=e.match(/^(\w+)/)?.[1]?.toUpperCase();if(t&&Pn.includes(t))throw new X(`"${t}" is not translatable to SQLite`,e)}};});var te,Qe=g(()=>{te=class extends Error{constructor(t,n,r,s){super(`check constraint "${r}" violated for ${t}.${n}`);this.table=t;this.column=n;this.constraint=r;this.value=s;this.name="CheckConstraintError";}};});var _,v=g(()=>{Qe();_=class{context;constructor(e){this.context=e;}get isShimBacked(){return false}checkConstraint(){return null}serialize(e){return e}deserialize(e){return e}validateStorage(e){return {status:"pass",message:null}}validationFail(e,t){return {status:"fail",message:e,action:t}}validationPass(){return {status:"pass",message:null}}isNullish(e){return e==null}toColumnDDL(e){let{includeNullable:t=true}=e??{},n=[],r=this.context.column;n.push(this.quoteIfNeeded(r)),n.push(this.sqliteType),this.context.isPrimaryKey&&n.push("PRIMARY KEY"),this.context.isSerial&&this.context.isPrimaryKey&&n.push("AUTOINCREMENT"),t&&!this.context.nullable&&!this.context.isPrimaryKey&&n.push("NOT NULL"),this.context.isUnique&&!this.context.isPrimaryKey&&n.push("UNIQUE"),this.context.defaultValue!==null&&n.push(`DEFAULT ${this.context.defaultValue}`);let s=this.checkConstraint();return s&&n.push(`CHECK (${s})`),n.join(" ")}checkError(e,t){return new te(this.context.table,this.context.column,e,t)}quoteIfNeeded(e){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)?e:`"${e}"`}};});var B,Le=g(()=>{v();B=class extends _{get sqliteType(){return "INTEGER"}};});var ne,Je=g(()=>{Le();ne=class extends B{constructor(e){super({...e,isSerial:true});}};});function Un(i,e){let{precision:t,scale:n}=e,r=10**n,s=10**(t-n);return Math.abs(Math.round(i*r)-i*r)<1e-4&&Math.abs(i)<s}var re,Ye=g(()=>{v();re=class extends _{numericPrecision;constructor(e,t){super(e),this.numericPrecision=t;}get isShimBacked(){return this.numericPrecision!==void 0}get sqliteType(){return "REAL"}checkConstraint(){if(this.numericPrecision){let{precision:e,scale:t}=this.numericPrecision,n=this.context.column,r=10**t,s=10**(e-t);return `ABS(ROUND(${n} * ${r}) - ${n} * ${r}) < 0.0001 AND ABS(${n}) < ${s}`}return null}validateStorage(e){if(this.isNullish(e))return this.validationPass();if(typeof e!="number"||!Number.isFinite(e))return this.validationFail("Expected finite number.","Patch rows with finite numbers.");if(this.numericPrecision){let{precision:t,scale:n}=this.numericPrecision;if(!Un(e,this.numericPrecision))return this.validationFail(`Does not fit numeric(${t}, ${n}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var x,A=g(()=>{v();x=class extends _{lengthConstraint;constructor(e,t){super(e),this.lengthConstraint=t;}get isShimBacked(){return this.lengthConstraint!==void 0}get sqliteType(){return "TEXT"}checkConstraint(){return this.lengthConstraint!==void 0?`length(${this.context.column}) <= ${this.lengthConstraint}`:null}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"?this.validationFail("Expected text.","Patch rows with text values."):this.lengthConstraint!==void 0&&Array.from(e).length>this.lengthConstraint?this.validationFail(`Exceeds length ${this.lengthConstraint}.`,"Patch rows with shorter text."):this.validationPass()}};});var se,Xe=g(()=>{v();se=class extends _{get sqliteType(){return "BLOB"}};});var ie,ze=g(()=>{v();ie=class extends _{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}checkConstraint(){return `${this.context.column} IN (0, 1)`}serialize(e){if(this.isNullish(e))return e;if(e===true||e===1)return 1;if(e===false||e===0)return 0;throw this.checkError("boolean_range",e)}deserialize(e){return this.isNullish(e)?e:e===1?true:e===0?false:e}validateStorage(e){return this.isNullish(e)?this.validationPass():e===1||e===0?this.validationPass():this.validationFail("Expected 0 or 1.","Patch rows with boolean values.")}};});function Bt(i){try{return {ok:!0,value:JSON.parse(i)}}catch{return {ok:false}}}var oe,He=g(()=>{v();oe=class extends _{get isShimBacked(){return true}get sqliteType(){return "TEXT"}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR json_valid(${e})`}serialize(e){if(this.isNullish(e))return e;try{return JSON.stringify(e)}catch{throw this.checkError("json_valid",e)}}deserialize(e){if(this.isNullish(e))return e;if(typeof e=="string"){let t=Bt(e);return t.ok?t.value:e}return e}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"?this.validationFail("Expected JSON text.","Patch rows with JSON values."):Bt(e).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function jn(i){if(!/^\d{4}-\d{2}-\d{2}$/.test(i))return false;let e=new Date(`${i}T00:00:00.000Z`);return !Number.isNaN(e.getTime())&&e.toISOString().slice(0,10)===i}var ae,Ze=g(()=>{A();ae=class extends x{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR date(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!jn(e)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function Bn(i){let e=i.match(/^(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?([+-](\d{2}):?(\d{2}))?$/);if(!e)return false;let t=Number(e[1]),n=Number(e[2]),r=e[3]===void 0?0:Number(e[3]),s=e[5]===void 0?null:Number(e[5]),o=e[6]===void 0?null:Number(e[6]),a=s===null||o!==null&&s<=15&&o<=59;return t<=24&&n<=59&&r<=59&&(t!==24||n===0&&r===0)&&a}var le,et=g(()=>{A();le=class extends x{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR time(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!Bn(e)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function Mn(i){let e=i.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?(?:Z|([+-](\d{2}):?(\d{2})))?$/);if(!e)return false;let t=Number(e[1]),n=Number(e[2]),r=Number(e[3]),s=Number(e[4]),o=Number(e[5]),a=e[6]===void 0?0:Number(e[6]),l=e[8]===void 0?null:Number(e[8]),u=e[9]===void 0?null:Number(e[9]),p=new Date(Date.UTC(t,n-1,r)),c=p.getUTCFullYear()===t&&p.getUTCMonth()===n-1&&p.getUTCDate()===r,d=s<=24&&o<=59&&a<=59&&(s!==24||o===0&&a===0),E=l===null||u!==null&&l<=15&&u<=59;return c&&d&&E}var ce,tt=g(()=>{A();ce=class extends x{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR datetime(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!Mn(e)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var ue,nt=g(()=>{A();ue=class extends x{get isShimBacked(){return true}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||e.trim().length===0?this.validationFail("Expected interval text.","Patch rows with interval strings."):/^-?\d+(?:\.\d+)?$/.test(e.trim())?this.validationFail("Ambiguous numeric interval.","Patch rows with explicit interval strings."):this.validationPass()}};});var pe,rt=g(()=>{A();pe=class extends x{enumValues;constructor(e,t){super(e),this.enumValues=t;}get isShimBacked(){return true}checkConstraint(){let e=this.context.column,t=this.enumValues.map(n=>`'${n.replace(/'/g,"''")}'`).join(", ");return `${e} IN (${t})`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string"||!this.enumValues.includes(e))throw this.checkError("enum_membership",e);return e}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!this.enumValues.includes(e)?this.validationFail("Invalid enum value.","Patch rows with declared enum values."):this.validationPass()}};});function Mt(i){try{return {ok:!0,value:JSON.parse(i)}}catch{return {ok:false}}}var z,st=g(()=>{v();z=class extends _{elementField;constructor(e,t){super(e),this.elementField=t;}get sqliteType(){return "TEXT"}get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR (json_valid(${e}) AND json_type(${e}) = 'array')`}serialize(e){if(this.isNullish(e))return e;if(!Array.isArray(e))throw this.checkError("array_type",e);return this.elementField?JSON.stringify(e.map(t=>this.elementField.serialize(t))):JSON.stringify(e)}deserialize(e){if(this.isNullish(e))return e;if(typeof e=="string"){let t=Mt(e);if(t.ok&&Array.isArray(t.value))return this.elementField?t.value.map(n=>this.elementField.deserialize(n)):t.value}return e}validateStorage(e){if(this.isNullish(e))return this.validationPass();if(typeof e!="string")return this.validationFail("Expected JSON array text.","Patch rows with array values.");let t=Mt(e);if(!t.ok)return this.validationFail("Invalid JSON array text.","Patch rows with array values.");if(!Array.isArray(t.value))return this.validationFail("Expected JSON array.","Patch rows with array values.");if(this.elementField)for(let n of t.value){let r=this.elementField.validateStorage(n);if(r.status==="fail")return this.validationFail(`Invalid ${this.elementField.context.pgTypeName} array element.`,r.action??"Patch rows with valid array elements.")}return this.validationPass()}};});function Wt(i){return Kn.test(i.toLowerCase())}var Wn,Kn,fe,it=g(()=>{A();Wn="????????-????-????-????-????????????",Kn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;fe=class extends x{get isShimBacked(){return true}checkConstraint(){let e=this.quoteIfNeeded(this.context.column);return `${e} IS NULL OR ${e} GLOB '${Wn}'`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string")throw this.checkError("uuid_format",e);let t=e.toLowerCase();if(!Wt(t))throw this.checkError("uuid_format",e);return t}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!Wt(e)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function Vn(i){let e=i.split("/");if(e.length>2)return null;let t=e[0];if(!t)return null;if(e.length===1)return {address:t,prefix:null};let n=e[1];return !n||!/^\d+$/.test(n)?null:{address:t,prefix:Number(n)}}function Gn(i){let e=i.split(".");return e.length!==4?false:e.every(t=>{if(!/^\d+$/.test(t))return false;let n=Number(t);return n>=0&&n<=255})}function Qn(i){if(!i.includes(":"))return false;try{return new URL(`http://[${i}]/`),!0}catch{return false}}function Kt(i){let e=Vn(i);return e?Gn(e.address)?e.prefix===null||e.prefix>=0&&e.prefix<=32:Qn(e.address)?e.prefix===null||e.prefix>=0&&e.prefix<=128:false:false}var me,ot=g(()=>{A();me=class extends x{get isShimBacked(){return true}checkConstraint(){let e=this.quoteIfNeeded(this.context.column);return `${e} IS NULL OR (length(${e}) BETWEEN 3 AND 49 AND (instr(${e}, '.') > 0 OR instr(${e}, ':') > 0))`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string")throw this.checkError("inet_format",e);let t=e.trim();if(!Kt(t))throw this.checkError("inet_format",e);return t}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!Kt(e.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var de,at=g(()=>{A();de=class extends x{serialize(e){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}deserialize(e){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}toColumnDDL(){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}};});function M(i,e){if(e?.isArray){let n=M(i,{...e,isArray:false});return new z(i,n)}if(e?.enumValues)return new pe(i,e.enumValues);let t=i.pgTypeName.toLowerCase().trim();if(t.startsWith("_")||t.endsWith("[]")){let n=t.startsWith("_")?t.slice(1):t.slice(0,-2),r={...i,pgTypeName:n},s=M(r);return new z(i,s)}return Yn.has(t)?new ne(i):Jn.has(t)?new B(i):Zn.has(t)?new ie(i):er.has(t)?new oe(i):sr.has(t)?new ae(i):ir.has(t)?new le(i):or.has(t)?new ce(i):ar.has(t)?new ue(i):Hn.has(t)?new se(i):Xn.has(t)?new re(i,e?.numericPrecision):tr.has(t)?new fe(i):nr.has(t)?new x(i,63):rr.has(t)?new me(i):zn.has(t)?new x(i,e?.lengthConstraint):new de(i)}var Jn,Yn,Xn,zn,Hn,Zn,er,tr,nr,rr,sr,ir,or,ar,lt=g(()=>{Le();Je();Ye();A();Xe();ze();He();Ze();et();tt();nt();rt();st();it();ot();at();Jn=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),Yn=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),Xn=new Set(["float4","real","float8","double precision","numeric","decimal"]),zn=new Set(["text","varchar","character varying","char","character","bpchar"]),Hn=new Set(["bytea"]),Zn=new Set(["bool","boolean"]),er=new Set(["json","jsonb"]),tr=new Set(["uuid"]),nr=new Set(["name"]),rr=new Set(["inet"]),sr=new Set(["date"]),ir=new Set(["time","timetz","time without time zone","time with time zone"]),or=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),ar=new Set(["interval"]);});function ct(i,e="auto"){let t=i.toLowerCase(),n=De[t];if(!n)return null;switch(e){case "translate":{if(!n.sqlite)throw new Error(`No SQLite translation for function "${i}"`);return {sqliteExpr:n.sqlite(),jsFn:null}}case "synthetic":{if(!n.js)throw new Error(`No JS implementation for function "${i}"`);return {sqliteExpr:null,jsFn:n.js}}case "auto":return n.js?{sqliteExpr:null,jsFn:n.js}:n.sqlite?{sqliteExpr:n.sqlite(),jsFn:null}:null}}var Vt,De,ut=g(()=>{Vt="lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))",De={gen_random_uuid:{sqlite:()=>Vt,js:()=>crypto.randomUUID()},uuid_generate_v4:{sqlite:()=>Vt,js:()=>crypto.randomUUID()},now:{sqlite:()=>"datetime('now')",js:()=>new Date().toISOString()},current_timestamp:{sqlite:()=>"datetime('now')",js:()=>new Date().toISOString()},current_date:{sqlite:()=>"date('now')",js:()=>new Date().toISOString().split("T")[0]},current_time:{sqlite:()=>"time('now')",js:()=>new Date().toISOString().split("T")[1].replace("Z","")},random:{sqlite:()=>"random()",js:()=>Math.random()},length:{sqlite:()=>"length",js:null},lower:{sqlite:()=>"lower",js:null},upper:{sqlite:()=>"upper",js:null},substr:{sqlite:()=>"substr",js:null},substring:{sqlite:()=>"substr",js:null},trim:{sqlite:()=>"trim",js:null},ltrim:{sqlite:()=>"ltrim",js:null},rtrim:{sqlite:()=>"rtrim",js:null},replace:{sqlite:()=>"replace",js:null},coalesce:{sqlite:()=>"coalesce",js:null},nullif:{sqlite:()=>"nullif",js:null},count:{sqlite:()=>"count",js:null},sum:{sqlite:()=>"sum",js:null},avg:{sqlite:()=>"avg",js:null},min:{sqlite:()=>"min",js:null},max:{sqlite:()=>"max",js:null},localtime:{sqlite:()=>"time('now', 'localtime')",js:null},localtimestamp:{sqlite:()=>"datetime('now', 'localtime')",js:null}};});var Pe,Gt=g(()=>{Y();U();U();Ut();Me();jt();Ve();Ke();Ge();Se();lt();ut();Pe=class extends Deparser{enums;schemaHandling;warnings=[];helper;config;triggerFunctions=new Map;plpgsqlParser=new ve;introspection;functionResolution;constructor(e,{enums:t,schemaHandling:n,introspection:r,...s}={}){super(e,s),this.schemaHandling=n??"default",this.enums=t??new Map,this.helper=new Oe(e),this.config=s,this.introspection=r,this.functionResolution=s?.functionResolution??"translate";}visit(e,t){let n=J(e),r=Ie.get(n);if(r){if(r.react==="error")throw new S({[n]:e},`Unsupported node type: ${n}`);return r.react==="warn"&&this.warnings.push({type:n,node:e}),""}return super.visit(e,t)}deparse(e,t){if(e==null)return null;if(!t){let n=new SqlFormatter;t=new DeparserContext({formatter:n});}return typeof e=="number"||e instanceof Number?e.toString():this.visit(e,t)}RawStmt(e,t){if(!e.stmt||e.stmt.CommentStmt)return "";let n=this.deparse(e.stmt,t);return !n||n.length===0?"":e.stmt_len?n+";":n}RangeVar(e,t){this.ensureRelation(e);let n=this.effectiveSchema(e.schemaname),r=e.relname,s=this.quoteBareIfNeeded(r);n&&(this.schemaHandling==="prefix"?s=`${n}__${r}`:s=`"${n}.${r}"`);let o=e.alias?" "+this.Alias(e.alias,t):"";return s+o}getRelationName(e){this.ensureRelation(e);let t=this.effectiveSchema(e.schemaname),n=e.relname;return t?this.schemaHandling==="prefix"?`${t}__${n}`:`${t}.${n}`:n}quoteBareIfNeeded(e){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(e)?e:`"${e.replace(/"/g,'""')}"`}effectiveSchema(e){if(e){if(this.config.forceDefaultSchema||this.schemaHandling!=="default")return e;if(e!=="public")return e}}ensureRelation(e){let t=this.config.forceDefaultSchema;t&&(!e||typeof e!="object"||t.length===0||e.schemaname||(e.schemaname=t));}CreateStmt(e,t){if(e.inhRelations&&e.inhRelations.length>0)throw new S({CreateStmt:e},"Inheritance is not supported in SQLite");if(e.ofTypename!==void 0)throw new S({CreateStmt:e},"Typed tables (CREATE TABLE ... OF type_name) are not supported. Define columns directly in the CREATE TABLE statement instead.");if(e.options&&e.options.length>0&&(e.options=void 0),!e.tableElts||e.tableElts.length===0)throw new S({CreateStmt:e},"Empty tables are not supported in SQLite. Define at least one column.");return e.accessMethod&&(e.accessMethod=void 0),super.CreateStmt(e,t)+" STRICT"}TableLikeClause(e,t){throw new S({TableLikeClause:e},"CREATE TABLE ... (LIKE ...) is not supported in SQLite. Define the table columns explicitly instead.")}DefElem(e,t){if(["oids","fillfactor",/^autovacuum_/i,"toast_tuple_target","parallel_workers","user_catalog_table"].some(s=>wt(e.defname??"",s)))return "";let r=super.DefElem(e,t);throw new S({DefElem:e},`DefElem "${e.defname}" (${r}) not supported`)}TypeName(e,t){if(!e.names)return "";let n=e.names.map(s=>s.String?s.String.sval||s.String.str:"").filter(Boolean);if(n.length===0)return "";let r=n.length===2&&n[0]==="pg_catalog"?n[1]:n.join(".");return e.arrayBounds&&e.arrayBounds.length>0||this.enums.has(r.toLowerCase())?"TEXT":qt(r)}ColumnDef(e,t){let n=[],r=e.colname;r&&n.push(this.quoteIfNeeded(r));let s=false,o=false,a=null,l=null,u=null,p=false;if(e.typeName){let c=e.typeName.names?.map(y=>y.String?.sval||y.String?.str).filter(Boolean);u=c&&(c.length===2&&c[0]==="pg_catalog"?c[1]:c[0]),s=!!(u&&Re(u)),p=!!(e.typeName.arrayBounds&&e.typeName.arrayBounds.length>0);let d=Array.isArray(e.typeName.typmods)?e.typeName.typmods:[],E=y=>d[y]?.A_Const?.ival?.ival??d[y]?.A_Const?.val?.ival?.ival;if(u&&Ae(u)&&d.length>0){let y=E(0);typeof y=="number"&&y>0&&(a={maxLen:y});}if(u&&ke(u)&&d.length>=2){let y=E(0),m=E(1);typeof y=="number"&&typeof m=="number"&&y>0&&m>=0&&(l={precision:y,scale:m});}if(e.constraints){let y=Array.isArray(e.constraints)?e.constraints:[];o=y.some(m=>m.Constraint?.contype==="CONSTR_PRIMARY"),y.some(m=>m.Constraint?.contype==="CONSTR_IDENTITY")&&(s=true);}n.push(this.TypeName(e.typeName,t));}if(e.constraints){let c=Array.isArray(e.constraints)?e.constraints:[],d=c.map(y=>this.visit(y,t));n.push(...d.filter(Boolean));let E=c.some(y=>y.Constraint?.contype==="CONSTR_CHECK");s&&o&&!E&&n.push("AUTOINCREMENT");}if(r&&u){let c={isArray:p};a&&(c.lengthConstraint=a.maxLen),l&&(c.numericPrecision=l);let d=this.enums.get(u.toLowerCase());d&&(c.enumValues=d);let m=M({schema:"public",table:"",column:r,pgTypeName:u,nullable:true,defaultValue:null,defaultFn:null,isPrimaryKey:o,isUnique:false,isSerial:s},c).checkConstraint();m&&n.push(`CHECK (${m})`);}return n.join(" ")}Constraint(e,t){let n=e.contype;if(n==="CONSTR_IDENTITY"||n==="CONSTR_ATTR_DEFERRABLE"||n==="CONSTR_ATTR_NOT_DEFERRABLE"||n==="CONSTR_ATTR_DEFERRED"||n==="CONSTR_ATTR_IMMEDIATE")return "";if(n==="CONSTR_NULL")return "NULL";if(n==="CONSTR_NOTNULL")return "NOT NULL";if(n==="CONSTR_DEFAULT"&&e.raw_expr){let r=this.visit(e.raw_expr,t);return r.includes("(")&&!r.startsWith("(")?`DEFAULT (${r})`:`DEFAULT ${r}`}if(n==="CONSTR_CHECK"&&e.raw_expr){let r=[];e.conname&&r.push("CONSTRAINT",Ne(e.conname)),r.push("CHECK");let s=this.visit(e.raw_expr,t);return r.push(`(${s})`),r.join(" ")}if(n==="CONSTR_PRIMARY")return e.keys&&e.keys.length>0?`PRIMARY KEY (${q(e.keys).map(s=>this.visit(s,t)).join(", ")})`:"PRIMARY KEY";if(n==="CONSTR_UNIQUE")return e.keys&&e.keys.length>0?`UNIQUE (${q(e.keys).map(s=>this.visit(s,t)).join(", ")})`:"UNIQUE";if(n==="CONSTR_FOREIGN")return super.Constraint(e,t).replace(/FOREIGN\s+KEY\s+REFERENCES/gi,"REFERENCES");if(n==="CONSTR_GENERATED"&&e.raw_expr)return `GENERATED ALWAYS AS (${this.visit(e.raw_expr,t)}) STORED`;if(n==="CONSTR_EXCLUSION")throw new S({Constraint:e},"EXCLUSION constraints are not supported in SQLite");return ""}FuncCall(e,t){let r=(e.funcname||[]).map(u=>u.String?.sval||u.String?.str).filter(Boolean);if(r.length===0)throw new Error("Function call has no name");let s=r[r.length-1].toLowerCase();if(s==="extract"&&e.args&&e.args.length>=2){let u=e.args[0];if((u?.A_Const?.sval?.sval||u?.String?.sval)==="epoch")return `strftime('%s', ${this.visit(e.args[1],t)})`}let a=(e.args??[]).map(u=>this.visit(u,t));if(e.agg_star)return `${s}(*)`;if(e.agg_distinct)return `${s}(DISTINCT ${a.join(", ")})`;let l=ct(s,this.functionResolution);if(l){if(l.sqliteExpr!==null){let u=l.sqliteExpr;return u.includes("(")?u:`${u}(${a.join(", ")})`}if(l.jsFn!==null){let u=De[s];if(u?.sqlite){let p=u.sqlite();return p.includes("(")?p:`${p}(${a.join(", ")})`}}}throw new S({FuncCall:e},`Function call "${s}" not supported`)}SQLValueFunction(e,t){switch(e.op){case "SVFOP_CURRENT_TIMESTAMP":return "datetime('now')";case "SVFOP_CURRENT_DATE":return "date('now')";case "SVFOP_CURRENT_TIME":return "time('now')";default:throw new S({SQLValueFunction:e},`SQLValueFunction "${e.op}" not supported`)}}ResTarget(e,t){if(e.indirection&&e.indirection.length>0)throw new S({ResTarget:e},"Indirections are not supported in SQLite");let n=[];return t.update&&e.name?(n.push(this.quoteIfNeeded(e.name)),n.push("="),e.val&&n.push(this.deparse(e.val,t))):t.insertColumns&&e.name?n.push(this.quoteIfNeeded(e.name)):(e.val&&n.push(this.deparse(e.val,t)),e.name&&n.push(this.Alias({aliasname:e.name},t))),n.join(" ")}A_Expr(e,t){if(["AEXPR_OP_ALL","AEXPR_OP_ANY"].includes(e.kind))throw new S({A_Expr:e},"ALL/ANY/SOME comparison operators are not supported. Use NOT EXISTS or IN instead");if(e.name&&e.name.length>0){if(e.name.length>1)throw new S({A_Expr:e},"Schema-qualified OPERATOR() syntax is not supported in SQLite");let n=e.name[0]?.String?.sval||e.name[0]?.String?.str;if(n){if(!e.lexpr||!e.rexpr)throw new S({A_Expr:e},"A_Expr missing left or right expression");if(!Ft.includes(n.toUpperCase()))throw new S({A_Expr:e},`Operator "${n}" is not supported in SQLite`);if(n==="~~"||n==="~~*"){let r=this.visit(e.lexpr,t),s=this.visit(e.rexpr,t);return `${r} LIKE ${s}`}if(n==="!~~"||n==="!~~*"){let r=this.visit(e.lexpr,t),s=this.visit(e.rexpr,t);return `${r} NOT LIKE ${s}`}if(n==="~"||n==="~*"){let r=this.visit(e.lexpr,t),s=this.visit(e.rexpr,t);return `${r} GLOB ${s}`}}}return super.A_Expr(e,t)}IndexStmt(e,t){let n=["CREATE"];e.unique&&n.push("UNIQUE"),n.push("INDEX"),e.if_not_exists&&n.push("IF NOT EXISTS"),e.idxname&&n.push(Ne(e.idxname)),n.push("ON"),e.relation&&n.push(this.RangeVar(e.relation,t));let r=(e.indexParams??[]).map(s=>"IndexElem"in s?this.IndexElem(s.IndexElem,t):this.visit(s,t)).filter(Boolean);return n.push(`(${r.join(", ")})`),n.join(" ")}IndexElem(e,t){let n=[];return e.name?n.push(Ne(e.name)):e.expr&&n.push(`(${this.visit(e.expr,t)})`),e.ordering==="SORTBY_ASC"&&n.push("ASC"),e.ordering==="SORTBY_DESC"&&n.push("DESC"),e.nulls_ordering==="SORTBY_NULLS_FIRST"&&n.push("NULLS FIRST"),e.nulls_ordering==="SORTBY_NULLS_LAST"&&n.push("NULLS LAST"),n.join(" ")}TypeCast(e,t){if(!e.arg||!e.typeName)return super.TypeCast(e,t);if([...this.helper.walk(e)].filter(({node:o})=>"A_Star"in o).length>0)throw new S({TypeCast:e},"A.* in type casts are not supported in SQLite");if(e.typeName.arrayBounds&&e.typeName.arrayBounds.length>0){if("A_Const"in e.arg&&e.arg.A_Const.sval){let o=e.arg.A_Const.sval.sval;if(o.startsWith("{")&&o.endsWith("}")){let a=e.typeName.names?.map(c=>c.String?.sval).filter(Boolean)??[],l=a.length===2&&a[0]==="pg_catalog"?a[1]:a[0],p=["text","varchar","character varying","char","bpchar","name","uuid"].includes(l?.toLowerCase());try{let c=this.parsePgArrayLiteral(o,p);return `'${JSON.stringify(c).replace(/'/g,"''")}'`}catch{}}}return this.visit(e.arg,t)}let r=this.visit(e.arg,t),s=this.TypeName(e.typeName,t);return `CAST(${r} AS ${s})`}A_ArrayExpr(e,t){let n=q(e.elements),r=this.tryExtractStaticArray(n);return r!==void 0?`'${JSON.stringify(r).replace(/'/g,"''")}'`:`json_array(${n.map(o=>this.visit(o,t)).join(", ")})`}tryExtractStaticArray(e){let t=[];for(let n of e)if("A_ArrayExpr"in n){let r=q(n.A_ArrayExpr.elements),s=this.tryExtractStaticArray(r);if(s===void 0)return;t.push(s);}else if("A_Const"in n){let r=n.A_Const;if(r.isnull)t.push(null);else if(r.ival)t.push(r.ival.ival);else if(r.fval)t.push(parseFloat(r.fval.fval));else if(r.sval)t.push(r.sval.sval);else if("boolval"in r)t.push(r.boolval.boolval===true);else return}else return;return t}parsePgArrayLiteral(e,t){if(!e.startsWith("{")||!e.endsWith("}"))throw new Error("Not a PG array literal");let n=e.slice(1,-1);if(n.length===0)return [];let r=[],s=0;for(;s<n.length;)if(n[s]==="{"){let o=0,a=s;for(;a<n.length;){if(n[a]==="{")o++;else if(n[a]==="}"&&(o--,o===0))break;a++;}r.push(this.parsePgArrayLiteral(n.slice(s,a+1),t)),s=a+1,n[s]===","&&s++;}else if(n[s]==='"'){let o=s+1,a="";for(;o<n.length&&n[o]!=='"';)n[o]==="\\"&&o++,a+=n[o],o++;r.push(a),s=o+1,n[s]===","&&s++;}else {let o=s;for(;o<n.length&&n[o]!==","&&n[o]!=="}";)o++;if(o===s)throw new Error("Malformed PG array literal");let a=n.slice(s,o);if(a==="NULL")r.push(null);else if(t)r.push(a);else {let l=Number(a);r.push(isNaN(l)?a:l);}s=o,n[s]===","&&s++;}return r}BetweenExpr(e,t){return super.A_Expr(e,t)}AlterTableStmt(e,t){let n=e.cmds??[],r=["AT_EnableRowSecurity","AT_ForceRowSecurity"],s=n.filter(p=>"AlterTableCmd"in p&&!r.includes(p.AlterTableCmd.subtype));if(s.length===0)return "";if(!["OBJECT_TABLE","OBJECT_INDEX","OBJECT_VIEW"].includes(e.objtype))throw new S({AlterTableStmt:e},`AlterTableStmt with objtype ${e.objtype} is not supported`);let o=["AT_AddColumn","AT_DropColumn"],a=["AT_AlterColumnType","AT_SetNotNull","AT_DropNotNull","AT_ColumnDefault","AT_AddConstraint","AT_DropConstraint"],l=[],u=[];for(let p of s){let c=p.AlterTableCmd.subtype;if(o.includes(c)){let d={...e,cmds:[p]};l.push(super.AlterTableStmt(d,t));}else if(a.includes(c))u.push(p.AlterTableCmd);else throw new S({AlterTableStmt:e},`AlterTableCmd with subtype ${c} is not supported in SQLite`)}if(u.length>0){let p=this.getRelationName(e.relation);l.push(this.generateRebuildSql(p,u));}return l.join(`;
15
- `)}AlterTableCmd(e,t){if(!["AT_AddColumn","AT_DropColumn"].includes(e.subtype))throw new S({AlterTableCmd:e},`AlterTableCmd with subtype ${e.subtype} is not supported`);return e.subtype==="AT_DropColumn"&&e.behavior?super.AlterTableCmd({...e,behavior:void 0},t):super.AlterTableCmd(e,t)}DefineStmt(e,t){if(e.kind==="OBJECT_AGGREGATE")throw new Error("AGGREGATE definitions are not supported in SQLite");return super.DefineStmt(e,t)}InsertStmt(e,t){if("selectStmt"in e){let r=(e.selectStmt?.SelectStmt?.valuesLists??[]).map(s=>s.List?.items?.map(o=>"SetToDefault"in o));if(r.length===1&&r[0]?.every(s=>s===true))return super.InsertStmt({...e,selectStmt:void 0,cols:void 0},t);if(r.some(s=>s.some(o=>o===true)))throw new S({InsertStmt:e},"Insert with partial DEFAULT values is not supported")}return super.InsertStmt(e,t)}SelectStmt(e,t){if(this.helper.hasUnsafeStar())throw new S({SelectStmt:e},"Row-wise comparison using .* is not supported in SQLite. Expand to explicit per-column comparisons instead.");if(e.intoClause)throw new S({SelectStmt:e},"SELECT ... INTO clause is not supported in SQLite");if(e.distinctClause){let r=q(e.distinctClause);if(r.length>0&&Object.keys(r[0]).length>0)throw new S({SelectStmt:e},"DISTINCT ON clause is not supported in SQLite. Use window functions instead.")}if(e.limitOffset&&!e.limitCount)throw new S({SelectStmt:e},"OFFSET without LIMIT is not supported in SQLite");let n=super.SelectStmt(e,t);if(/^SELECT\s+FROM/.test(n))throw new S({SelectStmt:e},"SELECT without a target list is not supported in SQLite");return n}JoinExpr(e,t){return e.alias&&this.Alias(e.alias,t),super.JoinExpr(e,t)}A_Const(e,t){if(e.bsval!==void 0)throw new S({A_Const:e},"Bit string literals are not supported in SQLite");let n=super.A_Const(e,t);return typeof n=="string"&&n.startsWith("E'")?n.substring(2,n.length-1):n}SortBy(e,t){if(e.sortby_dir==="SORTBY_USING"){let n=q(e.useOp),r=n[0]?.String?.sval;if(n.length>1||!["<",">"].includes(r??""))throw new S({SortBy:e},"Only `USING <` or `USING >` are supported.");e.sortby_dir=r==="<"?"SORTBY_DESC":"SORTBY_ASC",e.useOp=void 0;}return super.SortBy(e,t)}RangeSubselect(e,t){if(e.lateral)throw new S({RangeSubselect:e},"LATERAL subqueries are not supported in SQLite");return super.RangeSubselect(e,t)}SubLink(e,t){if(["ANY_SUBLINK","ALL_SUBLINK"].includes(e.subLinkType))throw new S({SubLink:e},"ANY/ALL/SOME subqueries are not supported. Use NOT EXISTS or IN instead");if(e.subLinkType==="ARRAY_SUBLINK")throw new S({SubLink:e},"ARRAY subqueries are not supported in SQLite");return super.SubLink(e,t)}LockingClause(e,t){return ""}UpdateStmt(e,t){if(t.parentNodeTypes.includes("SelectStmt"))throw new S({UpdateStmt:e},"UPDATE ... FROM (SELECT ...) is not supported in SQLite");return super.UpdateStmt(e,t)}Alias(e,t){if(e.colnames&&e.colnames.length>0)throw new S({Alias:e},"Aliasing with column names is not supported in SQLite");return `AS "${e.aliasname}"`}CreateFunctionStmt(e,t){let n=e.options??[],r=e.returnType?.names?.map(u=>u.String?.sval).filter(Boolean).join("."),s=n.find(u=>u.DefElem?.defname==="language")?.DefElem?.arg?.String?.sval;if(r!=="trigger"||s!=="plpgsql")throw new S({CreateFunctionStmt:e},"Only trigger functions with LANGUAGE plpgsql are supported");let o=e.funcname?.map(u=>u.String?.sval).filter(Boolean).pop();if(!o)throw new Error("Function has no name");let a=n.find(u=>u.DefElem?.defname==="as")?.DefElem?.arg?.List?.items?.[0]?.String?.sval;if(!a)throw new Error("Function has no body");let l=this.plpgsqlParser.parse(a);return this.triggerFunctions.set(o,l),""}CreateTrigStmt(e,t){let n=e.trigname,r=this.RangeVar(e.relation,t),s=e.funcname?.map(c=>c.String?.sval).filter(Boolean).pop();if(!s)throw new Error(`Trigger "${n}" has no function reference`);let o=this.triggerFunctions.get(s);if(!o)throw new S({CreateTrigStmt:e},`Trigger "${n}" references unknown function "${s}"`);let a=e.timing===2?"BEFORE":e.timing===64?"INSTEAD OF":"AFTER",l=[];if(e.events&4&&l.push("INSERT"),e.events&8&&l.push("DELETE"),e.events&16)if(e.columns?.length){let c=e.columns.map(d=>d.String?.sval).filter(Boolean);l.push(`UPDATE OF ${c.join(", ")}`);}else l.push("UPDATE");let u=l.join(" OR "),p=this.buildTriggerBody(o,r,t);return [`CREATE TRIGGER ${n}`,`${a} ${u} ON ${r}`,"FOR EACH ROW","BEGIN",...p.map(c=>` ${c};`),"END"].join(`
16
- `)}buildTriggerBody(e,t,n){let r=[],s=[];for(let o of e.statements)if(o.type!=="return"){if(o.type==="assignment"){s.push(o);continue}s.length>0&&(r.push(this.buildAssignmentUpdate(s,t,n)),s.length=0),o.type==="dml"&&r.push(this.translateDml(o.sql,n));}return s.length>0&&r.push(this.buildAssignmentUpdate(s,t,n)),r}buildAssignmentUpdate(e,t,n){let r=e.map(s=>{let o=this.translateExpression(s.expression,n);return `${s.column} = ${o}`});return `UPDATE ${t} SET ${r.join(", ")} WHERE rowid = NEW.rowid`}translateExpression(e,t){try{let n=`SELECT ${e}`,r=e.trim().toLowerCase();return r==="now()"||r==="current_timestamp"?"datetime('now')":e}catch{return e}}translateDml(e,t){return e.replace(/\bnow\(\)/gi,"datetime('now')").replace(/\bcurrent_timestamp\b/gi,"datetime('now')").replace(/\bgen_random_uuid\(\)/gi,this.uuidExpression()).replace(/\buuid_generate_v4\(\)/gi,this.uuidExpression())}uuidExpression(){return "lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))"}NullTest(e,t){if(e.arg?.ColumnRef?.fields?.length>1)throw new S({NullTest:e},"row-level NULL tests are not supported in SQLite");return super.NullTest(e,t)}RenameStmt(e,t){if(!e.renameType)throw new Error("RenameStmt requires renameType");let n=["OBJECT_TABLE","OBJECT_VIEW","OBJECT_COLUMN"];if(e.renameType==="OBJECT_COLUMN"&&(e.relationType==="OBJECT_FOREIGN_TABLE"||e.relationType==="OBJECT_VIEW"))throw new S({RenameStmt:e},`RenameStmt with relationType ${e.relationType} is not supported`);if(!n.includes(e.renameType))throw new S({RenameStmt:e},`RenameStmt with renameType ${e.renameType} is not supported in SQLite`);return super.RenameStmt(e,t)}DropStmt(e,t){let n=e.removeType;if(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_INDEX","OBJECT_TRIGGER"].includes(n))return super.DropStmt(e,t);if(["OBJECT_POLICY"].includes(n))return "";throw new S({DropStmt:e},`DROP with removeType ${n} is not supported in SQLite`)}generateRebuildSql(e,t){if(!this.introspection)throw new Error(`ALTER TABLE on "${e}" requires 12-step rebuild but no introspection was provided. Pass introspection in DeparseOptions to enable column type changes, NOT NULL, defaults, and constraint modifications.`);let n=this.buildDesiredSchema(this.introspection,e,t),r=new V,s=new G,o=r.diff(this.introspection,n);return o.has_changes?s.plan(o,this.introspection,n).steps.filter(l=>!["disable_foreign_keys","begin_transaction","commit_transaction","enable_foreign_keys"].includes(l.type)).map(l=>l.sql).join(`
17
- `):""}buildDesiredSchema(e,t,n){let r={...e,tables:e.tables.map(s=>({...s})),columns:e.columns.map(s=>({...s})),indexes:e.indexes.map(s=>({...s})),foreign_keys:e.foreign_keys.map(s=>({...s})),primary_keys:e.primary_keys.map(s=>({...s})),views:e.views.map(s=>({...s})),triggers:(e.triggers??[]).map(s=>({...s})),check_constraints:e.check_constraints.map(s=>({...s})),unique_constraints:(e.unique_constraints??[]).map(s=>({...s})),comments:(e.comments??[]).map(s=>({...s})),custom_types:e.custom_types.map(s=>({...s}))};for(let s of n){let o=r.columns.findIndex(a=>a.table===t&&a.name===s.name);switch(s.subtype){case "AT_AlterColumnType":{if(o===-1)break;let a=this.extractTypeName(s);a&&(r.columns[o]={...r.columns[o],type:a.toLowerCase()});break}case "AT_SetNotNull":{if(o===-1)break;r.columns[o]={...r.columns[o],nullable:false};break}case "AT_DropNotNull":{if(o===-1)break;r.columns[o]={...r.columns[o],nullable:true};break}case "AT_ColumnDefault":{if(o===-1)break;if(s.def){let a=this.extractDefaultValue(s);r.columns[o]={...r.columns[o],default_value:a};}else r.columns[o]={...r.columns[o],default_value:null};break}case "AT_AddConstraint":case "AT_DropConstraint":{let a=r.tables.findIndex(l=>l.name===t);a!==-1&&(r.tables[a]={...r.tables[a],sql:r.tables[a].sql+" /* modified */"});break}}}return this.rebuildTableSql(r,t),r}rebuildTableSql(e,t){let n=e.tables.findIndex(c=>c.name===t);if(n===-1)return;let r=e.columns.filter(c=>c.table===t),s=e.foreign_keys.filter(c=>c.table===t),o=e.check_constraints.filter(c=>c.table===t),a=r.map(c=>{let d=`${h(c.name)} ${c.type||"TEXT"}`;return c.is_primary_key&&(d+=" PRIMARY KEY"),c.nullable||(d+=" NOT NULL"),c.default_value!=null&&(d+=` DEFAULT ${c.default_value}`),d}),l=s.map(c=>`FOREIGN KEY (${h(c.column)}) REFERENCES ${h(c.ref_table)}(${h(c.ref_column)}) ON UPDATE ${c.on_update} ON DELETE ${c.on_delete}`),u=o.map(c=>`CHECK (${c.expression})`),p=[...a,...l,...u];e.tables[n]={...e.tables[n],sql:`CREATE TABLE ${h(t)} (${p.join(", ")}) STRICT`};}extractTypeName(e){let t=e.def?.ColumnDef;return t?.typeName?.TypeName?(t.typeName.TypeName.names??[]).map(r=>r.String?.sval).filter(Boolean).pop()??null:null}extractDefaultValue(e){return e.def?"Integer"in e.def?String(e.def.Integer.ival):"Float"in e.def?e.def.Float.fval:"String"in e.def?`'${e.def.String.sval}'`:null:null}};});var R,W,pt=g(()=>{U();Y();R=class extends S{constructor(e,t){super(e,`Unsupported expression: ${t}`);}},W=class{deparse(e){if("A_Const"in e){let r=e.A_Const;if(r.boolval!==void 0)return r.boolval.boolval?{}:{$always:false}}let t=Object.keys(e)[0],n=this[t];if(!n)throw new R({[t]:e},`Unsupported expression: ${t}`);return n.call(this,e[t])}deparseValue(e){if("A_Const"in e)return this.A_Const(e.A_Const);if("ColumnRef"in e)return this.ColumnRef(e.ColumnRef);if("FuncCall"in e)return this.FuncCall(e.FuncCall);if("SubLink"in e)return this.SubLink(e.SubLink);if("TypeCast"in e)return this.TypeCast(e.TypeCast);if("A_Expr"in e){let n=this.isJwtAccessor(e.A_Expr);return n||this.A_Expr(e.A_Expr)}if("BoolExpr"in e)return this.BoolExpr(e.BoolExpr);let t=Object.keys(e)[0];throw new R({[t]:e},`deparseValue: ${t}`)}A_Expr(e){if(e.kind==="AEXPR_OP"){let t=e.name?.[0],n=t?ee(t):void 0;if(!n)throw new R({A_Expr:e},"A_Expr missing operator");let r=this.isJwtAccessor(e);if(r)return {[r]:{}};let s=e.lexpr?this.deparseValue(e.lexpr):void 0,o=e.rexpr?this.deparseValue(e.rexpr):void 0,a=this.mapOperator(n);if(!a)throw new R({A_Expr:e},`Unsupported operator: ${n}`);let l=e.rexpr!=null&&"ColumnRef"in e.rexpr;if(typeof s=="string"&&s.startsWith("{{")&&l)return {[o]:{[a]:s}};let u=l&&typeof o=="string"?{$ref:o}:o;return {[s]:{[a]:u}}}if(e.kind==="AEXPR_LIKE"||e.kind==="AEXPR_ILIKE"){let t=e.lexpr?this.deparseValue(e.lexpr):void 0,n=e.rexpr?this.deparseValue(e.rexpr):void 0,s=(e.name?.[0]?ee(e.name[0]):"~~")==="!~~"?"$notLike":"$like";return {[t]:{[s]:n}}}if(e.kind==="AEXPR_IN"){let t=e.lexpr?this.deparseValue(e.lexpr):void 0,n=e.rexpr&&"List"in e.rexpr&&e.rexpr.List.items?e.rexpr.List.items.map(r=>this.deparseValue(r)):[];return {[t]:{$in:n}}}throw new R({A_Expr:e},`A_Expr kind: ${e.kind}`)}BoolExpr(e){let t=e.args??[];switch(e.boolop){case "AND_EXPR":return {$and:t.map(n=>this.deparse(n))};case "OR_EXPR":return {$or:t.map(n=>this.deparse(n))};case "NOT_EXPR":return {$not:this.deparse(t[0])};default:throw new R({BoolExpr:e},`BoolExpr op: ${e.boolop}`)}}NullTest(e){let t=e.arg?this.deparseValue(e.arg):void 0;return e.nulltesttype==="IS_NULL"?{[t]:{$is:null}}:{[t]:{$isNot:null}}}SubLink(e){if(e.subLinkType==="ANY_SUBLINK"){let t=e.testexpr?this.deparseValue(e.testexpr):void 0,n=e.subselect?this.SelectStmt(e.subselect.SelectStmt):void 0;return {[t]:{$in:n}}}if(e.subLinkType==="EXISTS_SUBLINK")return {$exists:e.subselect?this.SelectStmt(e.subselect.SelectStmt):void 0};if(e.subLinkType==="EXPR_SUBLINK"){let t=e.subselect?e.subselect.SelectStmt:void 0;if(t?.fromClause?.length)return this.SelectStmt(t);if(t?.targetList?.[0]){let n=t.targetList[0],r="ResTarget"in n?n.ResTarget:void 0;if(r?.val){let s=this.deparseValue(r.val);return s}}}throw new R({SubLink:e},`SubLink type: ${e.subLinkType}`)}SelectStmt(e){let{from:t,schema:n,join:r}=this.deparseFromClause(e.fromClause??[]),s=[];for(let d of e.targetList??[]){let E="ResTarget"in d?d.ResTarget:void 0;if(E?.val){let y=this.deparseValue(E.val);Array.isArray(y)?s.push(...y.map(String)):y!=null&&y!==""&&s.push(String(y));}}let o=e.whereClause?this.deparse(e.whereClause):void 0,a=this.deparseSortClause(e.sortClause),l=this.deparseLimit(e.limitCount),u=this.deparseLimit(e.limitOffset),p=this.deparseGroupClause(e.groupClause),c={type:"query",from:t,select:s};return n&&(c.schema=n),Object.keys(r).length>0&&(c.join=r),o&&(c.where=o),a.length>0&&(c.order=a),l!==void 0&&(c.limit=l),u!==void 0&&(c.offset=u),p.length>0&&(c.group=p),c}FuncCall(e){let t=this.isAuthFunc(e.funcname??[]);if(t)return t;throw new R({FuncCall:e},`FuncCall: ${F(e.funcname??[]).join(".")}`)}ColumnRef(e){let t=F(e.fields??[]);return t.length===1?t[0]:t.join(".")}A_Const(e){if(e.boolval!==void 0)return e.boolval.boolval;if(e.ival!==void 0)return e.ival.ival??0;if(e.fval!==void 0)return parseFloat(e.fval.fval??"0");if(e.sval!==void 0)return e.sval.sval??"";if(e.isnull)return null;throw new R({A_Const:e},"A_Const: unknown variant")}TypeCast(e){if(!e.arg)throw new R({TypeCast:e},"TypeCast: missing arg");return this.deparseValue(e.arg)}BooleanTest(e){let t=e.arg?this.deparseValue(e.arg):void 0;return e.booltesttype==="IS_TRUE"?{[t]:{$eq:true}}:{[t]:{$eq:false}}}deparseFromClause(e){let t={};if(e.length===0)return {from:"",join:t};let n=e[0];if("RangeVar"in n){let r=n.RangeVar;return {from:r.relname??"",schema:r.schemaname,join:t}}if("JoinExpr"in n){let{from:r,schema:s}=this.walkJoinExpr(n.JoinExpr,t);return {from:r,schema:s,join:t}}return {from:"",join:t}}walkJoinExpr(e,t){let n={from:""};if(e.larg)if("RangeVar"in e.larg){let r=e.larg.RangeVar;n={from:r.relname??"",schema:r.schemaname};}else "JoinExpr"in e.larg&&(n=this.walkJoinExpr(e.larg.JoinExpr,t));if(e.rarg&&"RangeVar"in e.rarg){let r=e.rarg.RangeVar,s=r.relname??"",o=r.alias?.aliasname??s,a=e.jointype==="JOIN_LEFT"?"left":"inner",l={from:s,type:a};e.quals&&(l.on=this.deparse(e.quals));let u=o;if(u in t){let p=2;for(;`${u}_${p}`in t;)p++;u=`${u}_${p}`;}t[u]=l;}return n}deparseSortClause(e){if(!e)return [];let t=[];for(let n of e){if(!("SortBy"in n))continue;let r=n.SortBy;if(!r.node)continue;let s=String(this.deparseValue(r.node)),o=r.sortby_dir==="SORTBY_DESC"?"desc":"asc",a={column:s,direction:o};r.sortby_nulls==="SORTBY_NULLS_FIRST"?a.nullsFirst=true:r.sortby_nulls==="SORTBY_NULLS_LAST"&&(a.nullsFirst=false),t.push(a);}return t}deparseLimit(e){if(!e)return;let t=this.deparseValue(e);return typeof t=="number"?t:Number(t)}deparseGroupClause(e){return e?e.map(t=>String(this.deparseValue(t))):[]}isAuthFunc(e){let t=F(e);if(t.length===2&&t[0]==="auth"){if(t[1]==="uid")return "{{auth.uid}}";if(t[1]==="jwt")return "{{auth.jwt}}";if(t[1]==="role")return "{{auth.role}}";throw new Error(`Unsupported auth function: "${t.slice(1).join(".")}"`)}return null}isJwtAccessor(e){if(e.kind!=="AEXPR_OP")return null;let t=e.name?.[0]?ee(e.name[0]):void 0;if(t!=="->"&&t!=="->>")return null;let n=e.rexpr&&"A_Const"in e.rexpr?e.rexpr.A_Const.sval?.sval:void 0;if(n===void 0)return null;if(e.lexpr&&"FuncCall"in e.lexpr)return this.isAuthFunc(e.lexpr.FuncCall.funcname??[])==="{{auth.jwt}}"?`{{auth.jwt.${n}}}`:null;if(e.lexpr&&"A_Expr"in e.lexpr){let r=this.isJwtAccessor(e.lexpr.A_Expr);if(r)return `${r.slice(0,-2)}.${n}}}`}return null}mapOperator(e){switch(e){case "=":return "$eq";case "<>":case "!=":return "$neq";case ">":return "$gt";case ">=":return "$gte";case "<":return "$lt";case "<=":return "$lte";case "~~":return "$like";case "!~~":return "$notLike";default:return}}};});var he,Qt=g(()=>{he=class{table;schema;fields;constructor(e,t="public",n=new Map){this.table=e,this.schema=t,this.fields=n;}get(e){return this.fields.get(e)}has(e){return this.fields.has(e)}set(e,t){this.fields.set(e,t);}columns(){return Array.from(this.fields.keys())}all(){return Array.from(this.fields.values())}serializeRow(e){let t={};for(let[n,r]of Object.entries(e)){let s=this.fields.get(n);t[n]=s?s.serialize(r):r;}return t}deserializeRow(e){let t={};for(let[n,r]of Object.entries(e)){let s=this.fields.get(n);t[n]=s?s.deserialize(r):r;}return t}applyDefaults(e){let t={...e};for(let[n,r]of this.fields)!(n in t)&&r.context.defaultFn&&(t[n]=r.context.defaultFn());return t}};});var Jt=g(()=>{v();Qe();Le();Je();Ye();A();Xe();ze();He();Ze();et();tt();nt();rt();st();it();ot();at();lt();ut();Qt();});function Xt(i){let e=new Map;for(let t of i.stmts??[]){if(!t.stmt||!("CreateEnumStmt"in t.stmt))continue;let n=t.stmt.CreateEnumStmt,r=F(n.typeName??[]).join(".");if(!r||!n.vals)continue;let s=F(n.vals);e.set(r.toLowerCase(),s);}return e}function zt(i){let e=new Map;for(let t of i.stmts??[]){if(!t.stmt||!("VariableSetStmt"in t.stmt))continue;let n=t.stmt.VariableSetStmt,r=n.name,s=$t(n.args?.[0]??{});e.set(r,{value:s,local:n.is_local});}return e}function Ht(i){let e=new W,t=new Set,n=[];for(let r of i.stmts??[])if(r.stmt){if("CreatePolicyStmt"in r.stmt){let s=r.stmt.CreatePolicyStmt,o=s.table?.relname??"",a=s.table?.schemaname,l={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},u=s.cmd_name?l[s.cmd_name]??"ALL":"ALL",p=s.permissive===true,c=[],d=false;for(let T of s.roles??[])if("RoleSpec"in T){let f=T.RoleSpec;f.roletype==="ROLESPEC_PUBLIC"?f.location===-1&&(d=true):f.roletype==="ROLESPEC_CSTRING"&&f.rolename&&c.push(f.rolename);}if(d){let T=a?`${a}.${o}`:o,f=s.policy_name??"",C=`${T}::${f}`;Yt.has(C)||(Yt.add(C),console.warn(`[supalite] policy "${f}" on "${T}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`));}let E=s.qual?e.deparse(s.qual):void 0,y=s.with_check?e.deparse(s.with_check):void 0,m=new D({name:s.policy_name??"",table:o,schema:a,command:u,permissive:p,roles:c,using:E,withCheck:y});n.push(m);}if("AlterTableStmt"in r.stmt){let s=r.stmt.AlterTableStmt;if((s.cmds??[]).some(l=>"AlterTableCmd"in l&&(l.AlterTableCmd.subtype==="AT_EnableRowSecurity"||l.AlterTableCmd.subtype==="AT_ForceRowSecurity"))){let l=s.relation?.relname??"";t.add(l);}}}return {policies:n,tables:t}}function Zt(i,e){let t=new Map;for(let n of i.stmts??[]){if(!n.stmt||!("CreateStmt"in n.stmt))continue;let r=n.stmt.CreateStmt,s=r.relation?.relname??"",o=r.relation?.schemaname??"public";if(!s)continue;let a=new he(s,o);for(let l of r.tableElts??[]){if(!("ColumnDef"in l))continue;let u=l.ColumnDef,p=u.colname;if(!p)continue;let c=u.typeName?.names?.map(b=>b.String?.sval||b.String?.str).filter(Boolean),d=c&&(c.length===2&&c[0]==="pg_catalog"?c[1]:c[0]);if(!d)continue;let E=!!u.typeName?.arrayBounds?.length,y=Array.isArray(u.typeName?.typmods)?u.typeName.typmods:[],m=b=>y[b]?.A_Const?.ival?.ival??y[b]?.A_Const?.val?.ival?.ival,T={isArray:E};if(Ae(d)&&y.length>0){let b=m(0);typeof b=="number"&&b>0&&(T.lengthConstraint=b);}if(ke(d)&&y.length>=2){let b=m(0),K=m(1);typeof b=="number"&&typeof K=="number"&&b>0&&K>=0&&(T.numericPrecision={precision:b,scale:K});}let f=e.get(d.toLowerCase());f&&(T.enumValues=f);let C=Array.isArray(u.constraints)?u.constraints:[],N=C.some(b=>b.Constraint?.contype==="CONSTR_PRIMARY"),w=Re(d)||C.some(b=>b.Constraint?.contype==="CONSTR_IDENTITY"),k=C.some(b=>b.Constraint?.contype==="CONSTR_NOTNULL"),I=C.find(b=>b.Constraint?.contype==="CONSTR_UNIQUE"),P=C.find(b=>b.Constraint?.contype==="CONSTR_GENERATED"),mt=C.find(b=>b.Constraint?.contype==="CONSTR_FOREIGN"),dt=C.find(b=>b.Constraint?.contype==="CONSTR_CHECK"),ht;if(mt){let b=mt.Constraint,K=b.pktable?.relname,cn=b.pktable?.schemaname,gt=b.pk_attrs?.[0]?.String?.sval;K&&gt&&(ht={refSchema:cn,refTable:K,refColumn:gt,constraintName:b.conname||void 0});}let ln={schema:o,table:s,column:p,pgTypeName:d,nullable:!k&&!N,defaultValue:null,defaultFn:null,isPrimaryKey:N,isUnique:!!I,isSerial:w,isGenerated:!!P,fkRef:ht,hasCheck:!!dt,checkConstraintName:dt?.Constraint?.conname||void 0,uniqueConstraintName:I?.Constraint?.conname||void 0};a.set(p,M(ln,T));}t.set(`${o}.${s}`,a);}return t}function en(i){let e=[];for(let t of i.stmts??[]){if(!t.stmt||!("CreateStmt"in t.stmt))continue;let n=t.stmt.CreateStmt,r=n.relation?.relname??"",s=n.relation?.schemaname??"public";if(r)for(let o of n.tableElts??[]){if("ColumnDef"in o)continue;let a=o;if(!a.Constraint)continue;let l=a.Constraint,u=l.contype;if(u==="CONSTR_UNIQUE"){let p=(l.keys??[]).map(c=>c.String?.sval??c.String?.str).filter(Boolean);if(p.length===0)continue;e.push({schema:s,table:r,kind:"unique",name:l.conname||void 0,columns:p});}else if(u==="CONSTR_CHECK")e.push({schema:s,table:r,kind:"check",name:l.conname||void 0,columns:[]});else if(u==="CONSTR_FOREIGN"){let p=(l.fk_attrs??[]).map(E=>E.String?.sval??E.String?.str).filter(Boolean),c=(l.pk_attrs??[]).map(E=>E.String?.sval??E.String?.str).filter(Boolean),d=l.pktable?.relname;if(!d)continue;e.push({schema:s,table:r,kind:"foreign_key",name:l.conname||void 0,columns:p,refSchema:l.pktable?.schemaname,refTable:d,refColumns:c});}}}return e}function tn(i){let e=[];for(let t of i.stmts??[]){if(!t.stmt||!("CommentStmt"in t.stmt))continue;let n=t.stmt.CommentStmt,r=n.comment??"";if(!r)continue;let s=n.objtype,o=(n.object?.List?.items??n.object?.items??[]).map(a=>a.String?.sval??a.String?.str).filter(Boolean);if(o.length!==0){if(s==="OBJECT_TABLE"||s==="OBJECT_VIEW"){let[a,l]=o.length>=2?o:["public",o[0]];e.push({schema:a,table:l,text:r});}else if(s==="OBJECT_COLUMN"){let a="public",l,u;o.length>=3?[a,l,u]=o:[l,u]=o,e.push({schema:a,table:l,column:u,text:r});}}}return e}var Yt,nn=g(()=>{pt();U();be();Jt();Y();Yt=new Set;});var sn={};pn(sn,{Policy:()=>D,deparseDdl:()=>ft,deparseExpression:()=>dr,deparsePostgresDdl:()=>mr,deparseSelect:()=>hr,parse:()=>Q,parseExpression:()=>rn,translatePostgresDdl:()=>fr});async function fr(i,e={}){let t=await Q(i);return ft(t,e).ddl}async function mr(i,e={}){let t=await Q(i);return {ast:t,...ft(t,e)}}function ft(i,e={}){let t=Xt(i),n=Zt(i,t),r=zt(i),s=en(i),o=tn(i),a=new Pe(i,{...e,enums:t}),{policies:l,tables:u}=Ht(i);if(e.strict)for(let p of l){if(!n.get(`${p.data.schema??"public"}.${p.data.table}`))throw new Error(`Policy "${p.data.name}" references unknown table "${p.data.table}"`);if(!u.has(p.data.table))throw new Error(`RLS is not enabled on table "${p.data.table}"`)}return {ddl:a.deparseQuery(),enums:t,rls:{tables:u,policies:l},schema:n,vars:r,tableConstraints:s,comments:o}}async function rn(i){let t=(await Q(`SELECT 1 WHERE ${i}`)).stmts?.[0]?.stmt;if(!t||!("SelectStmt"in t))throw new Error("expected SelectStmt");let n=t.SelectStmt.whereClause;if(!n)throw new Error("no whereClause");return n}async function dr(i){let e=await rn(i);return new W().deparse(e)}async function hr(i){let t=(await Q(i)).stmts?.[0]?.stmt;if(!t||!("SelectStmt"in t))throw new Error("expected SelectStmt");return new W().deparse(t)}var on=g(()=>{Pt();Gt();pt();nn();be();});Me();var dn=(i={})=>{let e=(t="m")=>[...i.exclude_tables??[],"sqlite_%"].map(n=>n.includes("%")?`${t}.name NOT LIKE '${n}'`:`${t}.name != '${n}'`).join(" AND ");return `WITH table_info AS (SELECT
18
- json_group_array(
19
- json_object(
20
- 'name', m.name,
21
- 'sql', m.sql,
22
- 'schema', '',
23
- 'type', m.type,
24
- 'rows', -1,
25
- 'engine', '',
26
- 'collation', ''
27
- )
28
- ) AS data
29
- FROM sqlite_master m
30
- WHERE m.type IN ('table', 'view') AND ${e()}),
31
- column_info AS (SELECT
32
- json_group_array(
33
- json_object(
34
- 'table', m.name,
35
- 'name', p.name,
36
- 'type', CASE
37
- WHEN INSTR(LOWER(p.type), '(') > 0
38
- THEN SUBSTR(LOWER(p.type), 1,
39
- INSTR(LOWER(p.type), '(') - 1)
40
- ELSE LOWER(p.type)
41
- END,
42
- 'nullable', CASE
43
- WHEN p."notnull" = 0 THEN json('true')
44
- ELSE json('false') END,
45
- 'default_value', p.dflt_value,
46
- 'is_primary_key',
47
- CASE WHEN p.pk > 0 THEN json('true') ELSE json('false') END,
48
- 'schema', '',
49
- 'ordinal_position', p.cid,
50
- 'collation', '',
51
- 'character_maximum_length',
52
- CASE
53
- WHEN LOWER(p.type) LIKE 'char%' OR
54
- LOWER(p.type) LIKE 'varchar%' THEN
55
- CASE
56
- WHEN INSTR(p.type, '(') > 0 THEN
57
- REPLACE(SUBSTR(p.type, INSTR(p.type, '(') + 1,
58
- LENGTH(p.type) -
59
- INSTR(p.type, '(') - 1), ')', '')
60
- ELSE null
61
- END
62
- ELSE null
63
- END,
64
- 'precision',
65
- CASE
66
- WHEN LOWER(p.type) LIKE 'decimal%' OR
67
- LOWER(p.type) LIKE 'numeric%' THEN
68
- CASE
69
- WHEN INSTR(p.type, '(') > 0 THEN
70
- json_object(
71
- 'precision',
72
- CAST(SUBSTR(p.type, INSTR(p.type, '(') + 1,
73
- INSTR(p.type, ',') -
74
- INSTR(p.type, '(') -
75
- 1) AS INTEGER),
76
- 'scale',
77
- CAST(SUBSTR(p.type, INSTR(p.type, ',') + 1,
78
- INSTR(p.type, ')') -
79
- INSTR(p.type, ',') -
80
- 1) AS INTEGER)
81
- )
82
- ELSE null
83
- END
84
- ELSE null
85
- END,
86
- 'is_identity',
87
- CASE
88
- WHEN p.pk = 1 AND LOWER(p.type) LIKE '%int%'
89
- THEN json('true')
90
- WHEN LOWER((SELECT sql FROM sqlite_master WHERE
91
- name = m.name)) LIKE
92
- '%' || p.name || '%autoincrement%' THEN json('true')
93
- ELSE json('false')
94
- END,
95
- 'is_generated',
96
- CASE WHEN p.hidden IN (2, 3)
97
- THEN json('true') ELSE json('false') END
98
- )
99
- ) AS data
100
- FROM sqlite_master m
101
- JOIN pragma_table_xinfo(m.name) p
102
- ON m.type IN ('table', 'view') AND ${e()}
103
- WHERE p.hidden != 1),
104
- index_info AS (SELECT
105
- json_group_array(
106
- json_object(
107
- 'table', idx_data.tbl,
108
- 'name', idx_data.idx_name,
109
- 'unique', CASE
110
- WHEN idx_data.is_unique = 1 THEN json('true')
111
- ELSE json('false') END,
112
- 'columns', json(idx_data.cols),
113
- 'schema', ''
114
- )
115
- ) AS data
116
- FROM (SELECT
117
- m.name AS tbl,
118
- idx.name AS idx_name,
119
- idx."unique" AS is_unique,
120
- json_group_array(ic.name ORDER BY ic.seqno) AS cols
121
- FROM sqlite_master m
122
- JOIN pragma_index_list(m.name) idx
123
- ON m.type = 'table' AND ${e()}
124
- JOIN pragma_index_info(idx.name) ic
125
- -- only include explicit CREATE INDEX objects; skip autoindexes from PK/UNIQUE constraints
126
- WHERE idx.origin = 'c' AND idx.name NOT LIKE 'sqlite_autoindex_%'
127
- GROUP BY m.name, idx.name, idx."unique") idx_data),
128
- fk_info AS (SELECT
129
- json_group_array(
130
- json_object(
131
- 'table', m.name,
132
- 'column', fk."from",
133
- 'ref_table', fk."table",
134
- 'ref_column', fk."to",
135
- 'on_update', fk.on_update,
136
- 'on_delete', fk.on_delete,
137
- 'schema', '',
138
- 'is_visible', true,
139
- 'foreign_key_name',
140
- 'fk_' || m.name || '_' || fk.id || '_' || fk."table",
141
- 'fk_def',
142
- 'FOREIGN KEY (' || fk."from" || ') REFERENCES ' || fk."table" ||
143
- '(' || fk."to" || ')' ||
144
- ' ON UPDATE ' || fk.on_update || ' ON DELETE ' || fk.on_delete
145
- )
146
- ) AS data
147
- FROM sqlite_master m
148
- JOIN pragma_foreign_key_list(m.name) fk
149
- ON m.type = 'table' AND ${e()}),
150
- pk_info AS (SELECT
151
- json_group_array(
152
- json_object(
153
- 'table', pk.tbl,
154
- 'columns', json(pk.cols),
155
- 'schema', '',
156
- 'field_count', pk.field_count
157
- )
158
- ) AS data
159
- FROM (SELECT
160
- m.name AS tbl,
161
- json_group_array(p.name ORDER BY p.pk) AS cols,
162
- COUNT(p.name) AS field_count
163
- FROM sqlite_master m
164
- JOIN pragma_table_info(m.name) p
165
- ON m.type = 'table' AND ${e()} AND p.pk > 0
166
- GROUP BY m.name) pk),
167
- view_info AS (SELECT
168
- json_group_array(
169
- json_object('name', m.name, 'sql', m.sql, 'schema', '')
170
- ) AS data
171
- FROM sqlite_master m
172
- WHERE m.type = 'view' AND ${e()}),
173
- trigger_info AS (SELECT
174
- json_group_array(
175
- json_object(
176
- 'table', m.tbl_name,
177
- 'name', m.name,
178
- 'sql', m.sql,
179
- 'schema', ''
180
- )
181
- ) AS data
182
- FROM sqlite_master m
183
- WHERE m.type = 'trigger' AND ${e("m")}),
184
- unique_info AS (SELECT
185
- json_group_array(
186
- json_object(
187
- 'table', uc.tbl,
188
- 'name', uc.idx_name,
189
- 'columns', json(uc.cols),
190
- 'schema', ''
191
- )
192
- ) AS data
193
- FROM (SELECT
194
- m.name AS tbl,
195
- idx.name AS idx_name,
196
- json_group_array(ic.name ORDER BY ic.seqno) AS cols
197
- FROM sqlite_master m
198
- JOIN pragma_index_list(m.name) idx
199
- ON m.type = 'table' AND ${e()}
200
- JOIN pragma_index_info(idx.name) ic
201
- WHERE idx.origin = 'u'
202
- GROUP BY m.name, idx.name) uc)
203
- SELECT
204
- (SELECT data FROM table_info) AS tables,
205
- (SELECT data FROM column_info) AS columns,
206
- (SELECT data FROM index_info) AS indexes,
207
- (SELECT data FROM fk_info) AS foreign_keys,
208
- (SELECT data FROM pk_info) AS primary_keys,
209
- (SELECT data FROM view_info) AS views,
210
- (SELECT data FROM trigger_info) AS triggers,
211
- (SELECT data FROM unique_info) AS unique_constraints,
212
- ${i.name?`'${i.name}'`:"'sqlite'"} AS database_name,
213
- ${i.version?`'${i.version}'`:"sqlite_version()"} AS version;`};function L(i){if(!i)return [];try{return Array.isArray(i)?i:JSON.parse(i)}catch{return []}}async function _t(i,e={}){let n=(await i.exec(dn(e)))?.rows?.[0]||{};return {tables:L(n.tables),columns:L(n.columns),indexes:L(n.indexes),foreign_keys:L(n.foreign_keys),primary_keys:L(n.primary_keys),views:L(n.views),triggers:L(n.triggers),check_constraints:[],unique_constraints:L(n.unique_constraints),comments:[],custom_types:[],database_name:n.database_name??"sqlite",version:n.version??""}}var Tn=new Set(["AlterTableNode","CreateIndexNode","CreateSchemaNode","CreateTableNode","CreateTypeNode","CreateViewNode","RefreshMaterializedViewNode","DeleteQueryNode","DropIndexNode","DropSchemaNode","DropTableNode","DropTypeNode","DropViewNode","InsertQueryNode","RawNode","SelectQueryNode","UpdateQueryNode","MergeQueryNode"]),We=class extends OperationNodeTransformer{constructor(t){super();this.config=t;}#t=new Set;#n=new Set;transformNodeImpl(t,n){if(!Tn.has(t.kind))return super.transformNodeImpl(t,n);let r=this.#i(t);for(let o of r)this.#n.add(o);let s=this.#s(t);for(let o of s)this.#t.add(o);try{return super.transformNodeImpl(t,n)}finally{for(let o of s)this.#t.delete(o);for(let o of r)this.#n.delete(o);}}transformSchemableIdentifier(t,n){let r=t.identifier.name,s=t.schema?.name,o=!s&&this.config.appendDefaultSchema&&this.config.defaultSchema&&!this.#n.has(r)&&this.#t.has(r),a=s??(o?this.config.defaultSchema:void 0);if(!a)return {kind:"SchemableIdentifierNode",schema:void 0,identifier:{kind:"IdentifierNode",name:r}};let l=this.config.approach==="snake_case"?"__":".";return {kind:"SchemableIdentifierNode",schema:void 0,identifier:{kind:"IdentifierNode",name:`${a}${l}${r}`}}}#s(t){let n=new Set;if(t?.name&&SchemableIdentifierNode.is(t.name)&&this.#r(t.name,n),t?.from?.froms)for(let r of t.from.froms)this.#e(r,n);if(t?.into&&this.#e(t.into,n),t?.table&&this.#e(t.table,n),t?.joins)for(let r of t.joins)this.#e(r.table,n);return t?.using&&(JoinNode.is(t.using)?this.#e(t.using.table,n):this.#e(t.using,n)),n}#e(t,n){if(TableNode.is(t)){this.#r(t.table,n);return}if(AliasNode.is(t)&&TableNode.is(t.node)){this.#r(t.node.table,n);return}if(ListNode.is(t)){for(let r of t.items)this.#e(r,n);return}if(UsingNode.is(t))for(let r of t.tables)this.#e(r,n);}#r(t,n){let r=t.identifier.name;this.#n.has(r)||n.add(r);}#i(t){let n=new Set;if(t?.with?.expressions)for(let r of t.with.expressions){let s=r?.name?.table?.table?.identifier?.name;s&&n.add(s);}return n}},Ee=class{#t;constructor(e){this.#t=new We(e);}transformQuery(e){return this.#t.transformNode(e.node)}async transformResult(e){return e.result}};be();Ke();Ge();function Z(i){return i==="migrations"||i==="supabase_migrations.schema_migrations"||i==="supabase_migrations.seed_files"}function Rt(i){return {...i,tables:i.tables.filter(e=>!Z(e.name)),columns:i.columns.filter(e=>!Z(e.table)),indexes:i.indexes.filter(e=>!Z(e.table)),foreign_keys:i.foreign_keys.filter(e=>!Z(e.table)),primary_keys:i.primary_keys.filter(e=>!Z(e.table))}}var Te=class{constructor(e,t,n={}){this.conn=e;this.desiredSchema=t;this.options=n;this.differ=new V,this.planner=new G;}differ;planner;translationResult;async getDesiredSchema(){let e=await this.conn.translateDdl(this.desiredSchema);return this.translationResult=e,await this.options.onTranslation?.(e),e.ddl}async diff(){let e=await this.conn.introspect({postprocess:false}),t=await this.getDesiredSchema();if(!t||t.trim().length===0)return {current:e,desired:e,diff:{tables:[],columns:[],indexes:[],foreign_keys:[],has_changes:false},plan:{steps:[],warnings:[],unsafe:false}};let{createConnection:n}=await import('@supabase/lite/sqlite'),r=await n({url:":memory:"});try{await r.exec(t);let s=await r.introspect({postprocess:!1}),o=Rt(e),a=Rt(s),l=this.differ.diff(o,a),u=this.planner.plan(l,o,a);return {current:e,desired:s,diff:l,plan:u}}finally{await r.close();}}safeSortPlanSteps(e){return invariant(Array.isArray(e),"steps must be an array"),e.sort((t,n)=>{let r=s=>s===PlanStepType.DROP_COLUMN?1:s===PlanStepType.DROP_TABLE?2:s===PlanStepType.RENAME_TABLE?3:0;return r(t.type)-r(n.type)})}async migratePlan(e,t){if(e.steps.length===0)return;if(e.unsafe&&!t?.force)throw new DataLossError(e.warnings??[]);let n=this.safeSortPlanSteps(e.steps).filter(r=>![PlanStepType.DISABLE_FOREIGN_KEYS,PlanStepType.BEGIN_TRANSACTION,PlanStepType.COMMIT_TRANSACTION,PlanStepType.ENABLE_FOREIGN_KEYS].includes(r.type));await this.conn.transaction(n.map(r=>r.sql),{intent:"migration"});}async migrate(e){let t=await this.diff();return await this.migratePlan(t.plan,e),t}};ye();var kt=/^\{\{(.+)\}\}$/;function It(i){return typeof i=="string"&&kt.test(i)}function Nn(i){return kt.exec(i)[1]}var At=Symbol("unresolved");function Ot(i,e){let t=Nn(i),n=H(e,t,At);if(n===At)throw new Error(`Unresolved variable: {{${t}}}`);return n}function O(i,e){let t={};for(let[n,r]of Object.entries(i)){if(n==="$or"||n==="$and"){t[n]=r.map(s=>O(s,e));continue}if(n==="$not"){t[n]=O(r,e);continue}if(n==="$always"){t[n]=r;continue}if(n==="$exists"){let s=r;t[n]={...s,where:s?.where?O(s.where,e):s?.where};continue}if(It(n)){let s=Ot(n,e),a=An(s,r);t.$always=a;continue}if(r!=null&&typeof r=="object"&&!Array.isArray(r)){t[n]=vt(r,e);continue}t[n]=r;}return t}function vt(i,e){let t={};for(let[n,r]of Object.entries(i))n==="$not"&&r!=null&&typeof r=="object"?t[n]=vt(r,e):Rn(r)?t[n]={...r,where:r?.where?O(r?.where,e):void 0}:It(r)?t[n]=Ot(r,e):t[n]=r;return t}function Rn(i){return i!=null&&typeof i=="object"&&i.type==="query"}function An(i,e){for(let[t,n]of Object.entries(e))switch(t){case "$eq":if(i!==n)return false;break;case "$neq":if(i===n)return false;break;case "$in":if(!Array.isArray(n)||!n.includes(i))return false;break;case "$notIn":if(Array.isArray(n)&&n.includes(i))return false;break;default:throw new Error(`Cannot statically evaluate operator ${t} on placeholder key`)}return true}ye();var we=class extends Error{constructor(t){super(`new row violates row-level security policy for table "${t.data.table}"`);this.policy=t;this.name="PolicyViolation";}};var xe=class{constructor(e,t,n){this.tables=e;this.policies=t;this.defaultSchema=n;}enforce(e,t){let n=e.from;if(!n||!this.isRlsEnabled(n,e.schema))return e;let r=kn(e.type);if(!r)return e;let s=H(t,"auth.role")??"anon",{permissive:o,restrictive:a}=this.resolvePolicies(n,e.schema,r,s);switch(r){case "SELECT":case "DELETE":{let l=this.combineUsing(o,a,t);return {...e,where:Lt(e.where,l)}}case "UPDATE":{let l=this.combineUsing(o,a,t),u={...e,where:Lt(e.where,l)};if(l.$always===false)return u;let p=this.combineWithCheck(o,a,t,r);if(e.values&&Object.keys(p).length>0){let c=new Set(Object.keys(e.values));this.validateWithCheck(p,e.values,o,a,c);}return u}case "INSERT":{let l=this.combineWithCheck(o,a,t,r);if(e.values){let u=Array.isArray(e.values)?e.values:[e.values];for(let p of u)this.validateWithCheck(l,p,o,a);}return e}default:return e}}isRlsEnabled(e,t){return this.tables.has(e)}resolvePolicies(e,t,n,r){let s=this.policies.filter(o=>o.data.table===e&&this.schemasMatch(o.data.schema,t)&&o.appliesTo(n)&&o.appliesToRole(r));return {permissive:s.filter(o=>o.data.permissive),restrictive:s.filter(o=>!o.data.permissive)}}schemasMatch(e,t){let n=e||this.defaultSchema,r=t||this.defaultSchema;return n===r}combineUsing(e,t,n){if(e.length===0)return {$always:false};let r=e.map(o=>o.data.using).filter(o=>o!=null&&Object.keys(o).length>0).map(o=>O(o,n)),s;r.length===0?s={}:r.length===1?s=r[0]:s={$or:r};for(let o of t)if(o.data.using&&Object.keys(o.data.using).length>0){let a=O(o.data.using,n);s=Object.keys(s).length===0?a:{$and:[s,a]};}return s}combineWithCheck(e,t,n,r){if(e.length===0)return {$always:false};let s=e.map(a=>a.data.withCheck??(r==="UPDATE"?a.data.using:void 0)).filter(a=>a!=null&&Object.keys(a).length>0).map(a=>O(a,n)),o;s.length===0?o={}:s.length===1?o=s[0]:o={$or:s};for(let a of t){let l=a.data.withCheck??(r==="UPDATE"?a.data.using:void 0);if(l&&Object.keys(l).length>0){let u=O(l,n);o=Object.keys(o).length===0?u:{$and:[o,u]};}}return o}validateWithCheck(e,t,n,r,s){if(Object.keys(e).length===0)return;if(!Ce(e,t,s)){let a=n[0]??r[0];throw a?new we(a):new Error("RLS policy violation")}}};function kn(i){switch(i){case "query":return "SELECT";case "insert":case "upsert":case "put":return "INSERT";case "update":return "UPDATE";case "delete":return "DELETE";default:return}}function Lt(i,e){return !i||Object.keys(i).length===0?e:Object.keys(e).length===0?i:{$and:[i,e]}}function Ce(i,e,t){for(let[n,r]of Object.entries(i)){if(n==="$always"){if(r===false)return false;continue}if(n==="$and"){if(!r.every(l=>Ce(l,e,t)))return false;continue}if(n==="$or"){if(!r.some(l=>Ce(l,e,t)))return false;continue}if(n==="$not"){if(Ce(r,e,t))return false;continue}if(t&&!t.has(n))continue;let s=r,o=e[n];for(let[a,l]of Object.entries(s))if(!In(o,a,l))return false}return true}function In(i,e,t){switch(e){case "$eq":return i===t;case "$neq":return i!==t;case "$gt":return i>t;case "$gte":return i>=t;case "$lt":return i<t;case "$lte":return i<=t;case "$in":return Array.isArray(t)&&t.includes(i);case "$notIn":return !Array.isArray(t)||!t.includes(i);case "$is":return i===t;case "$isNot":return i!==t;default:throw new Error(`Cannot evaluate operator "${e}" client-side for WITH CHECK`)}}var _e=class{transformQuery(e){return e.node}transformResult(e){return e.result.rows?Promise.resolve({...e.result,rows:e.result.rows.map(t=>{let n={};for(let r in t){let s=t[r];if(typeof s=="string"&&(s[0]==="{"||s[0]==="["))try{n[r]=JSON.parse(s);}catch{n[r]=s;}else n[r]=s;}return n})}):Promise.resolve(e.result)}};function Dt(i){let e={};for(let t in i){let n=i[t];if(typeof n=="string"&&(n[0]==="["||n[0]==="{"))try{e[t]=JSON.parse(n);}catch{e[t]=n;}else e[t]=n;}return e}var ge=class i extends Connection{dialect="sqlite";deserializeRow(e){return this.config.ddlDialect==="postgres"?Dt(e):e}constructor(e={}){super({...e,translation:{...e.translation,schemas:{appendDefaultSchema:false,approach:"quote",defaultSchema:"public",...e.translation?.schemas},deparse:i.parseDeparseInfo(e.translation?.deparse)},introspection:{name:"sqlite",...e.introspection,exclude_tables:Array.from(new Set([...e.introspection?.exclude_tables??[],"sqlite_%","supabase_migrations.%","migrations"]))}});}static parseDeparseInfo(e){try{if(typeof e!="object"||e===null)return {};let t=e?.rls?.tables instanceof Set?e.rls.tables:new Set(e.rls?.tables??[]),n=e?.rls?.policies.map(s=>new D(JSON.parse(JSON.stringify(s)))),r=e?.vars instanceof Map?e.vars:new Map(Object.entries(e.vars??{}));return {rls:{tables:t,policies:n},vars:r}}catch(t){return console.log("error parsing deparse info",t),{}}}updateDeparseInfo(e){this.config.translation={...this.config.translation,deparse:e};}withSqlitePlugins(e=[]){let t=[];return this.config.ddlDialect==="sqlite"&&t.push(new _e),t.push(new Ee(Fe({appendDefaultSchema:false,approach:"quote",defaultSchema:"public"},{...this.config.translation?.schemas}))),[...t,...e]}async translateDdl(e){if(e.trim().length===0)return {ddl:e};if(this.config.ddlDialect==="sqlite")return {ddl:e};let t=this.config.translation?.schemas?.defaultSchema&&this.config.translation?.schemas?.appendDefaultSchema?this.config.translation?.schemas?.defaultSchema:false,n=await this.introspect({postprocess:false}).catch(()=>{}),{deparsePostgresDdl:r}=await Promise.resolve().then(()=>(on(),sn));return await r(e,{forceDefaultSchema:t,introspection:n,schemaHandling:this.config.translation?.schemas?.approach==="snake_case"?"prefix":"default"})}async introspect(e){bt(typeof e=="object"||e===void 0,"options must be an object");let t=e?.useCache??false;if(e?.postprocess!==false){let s=await this.readCachedIntrospection({useCache:t});if(s)return s}let n=await _t(this,this.config.introspection),r=this.config.translation?.schemas?.approach==="snake_case"?"__":".";if(this.config.ddlDialect==="postgres"&&e?.postprocess!==false){let s=this.config.translation?.schemas?.defaultSchema??this.config.translation?.schemas?.appendDefaultSchema?"public":void 0,o=(l="table")=>u=>{let p=u[l],c=u.schema??s;return !c&&s&&p.includes(r)&&([c,p]=p.split(r)),{...u,[l]:p,schema:c??s}},a=l=>{let u=o()(l),p=u.ref_table,c=u.ref_schema??s;return p?.includes(r)&&([c,p]=p.split(r)),{...u,ref_table:p,ref_schema:c??s}};n={...n,tables:n.tables.map(o("name")),columns:n.columns.map(o()),indexes:n.indexes.map(o()),primary_keys:n.primary_keys.map(o()),foreign_keys:n.foreign_keys.map(a),views:n.views.map(o("name")),check_constraints:n.check_constraints.map(o("table"))};}return this.config.ddlDialect==="postgres"&&e?.postprocess!==false&&(n=this.mergeDeparseMetadata(n)),n=this.markForeignKeyVisibility(n),n={...n,ddl_dialect:this.config.ddlDialect??"postgres",schema_separator:r},e?.postprocess!==false&&await this.writeCachedIntrospection(n,{useDriver:t}),n}async transaction(e,t){t?.intent==="migration"&&await this.exec("PRAGMA foreign_keys=OFF;"),await this.exec("BEGIN");try{for(let n of e)try{await this.exec(n);}catch(r){throw console.error(`Failed to execute statement: ${n}`),r}await this.exec("COMMIT");}catch(n){throw await this.exec("ROLLBACK"),n}finally{t?.intent==="migration"&&(await this.exec("PRAGMA foreign_keys=ON;"),await this.clearSchemaCache());}}async close(){}mergeDeparseMetadata(e){let t=this.config.translation?.deparse;if(!t?.schema)return e;let n=e.columns.map(l=>({...l})),r=e.foreign_keys.map(l=>({...l})),s=[...e.unique_constraints??[]],o=[...e.check_constraints??[]];for(let[,l]of t.schema)for(let u of l.all()){let p=u.context,c=n.find(d=>d.table===p.table&&d.name===p.column);if(c&&(c.pg_type=p.pgTypeName,p.isGenerated!==void 0&&(c.is_generated=p.isGenerated)),p.fkRef?.constraintName){let d=r.find(E=>E.table===p.table&&E.column===p.column&&E.ref_table===p.fkRef.refTable&&E.ref_column===p.fkRef.refColumn);d&&(d.foreign_key_name=p.fkRef.constraintName);}p.uniqueConstraintName&&s.push({schema:p.schema,table:p.table,name:p.uniqueConstraintName,columns:[p.column]}),p.hasCheck&&o.push({schema:p.schema,table:p.table,expression:"",name:p.checkConstraintName,column:p.column});}for(let l of t.tableConstraints??[])if(l.kind==="unique")s.push({schema:l.schema,table:l.table,name:l.name??"",columns:l.columns});else if(l.kind==="check")o.push({schema:l.schema,table:l.table,expression:"",name:l.name});else if(l.kind==="foreign_key"&&l.name){let u=l.refTable;for(let p=0;p<l.columns.length;p++){let c=r.find(d=>d.table===l.table&&d.column===l.columns[p]&&d.ref_table===u&&d.ref_column===(l.refColumns?.[p]??""));c&&(c.foreign_key_name=l.name);}}let a=[...e.comments??[],...t.comments??[]];return {...e,columns:n,foreign_keys:r,unique_constraints:s,check_constraints:o,comments:a}}markForeignKeyVisibility(e){let t=new Set(e.views.map(r=>r.name)),n=r=>r.startsWith("private_")?t.has(r.slice(8)):true;return {...e,foreign_keys:e.foreign_keys.map(r=>({...r,is_visible:n(r.table)&&n(r.ref_table)}))}}createMigrator(e){let t=[this.config.baseSchema,e].filter(Boolean).join(`
214
-
215
- `);return new Te(this,t,{onTranslation:async n=>{if(this.config.translation){let r={enums:n.enums,rls:n.rls,schema:n.schema,vars:n.vars,tableConstraints:n.tableConstraints??[],comments:n.comments??[]};this.config.translation.deparse=r;}}})}get maxBoundParameters(){return this.config.maxBoundParameters??100}assertParamLimit(e){let t=e?.length??0,n=this.maxBoundParameters;if(!(t<=n))throw Object.assign(new Error(`Query exceeds max bound parameters (${t} > ${n}). SQLite drivers vary in how many parameters they accept per statement; @supabase/lite enforces a conservative limit of ${n} for portability. Split the query (e.g. chunk large .in() filters or batch INSERTs) on the caller.`),{code:"54000"})}prepareBindParams(e){return this.assertParamLimit(e),this.normalizeBindParams(e)}normalizeBindParams(e){if(!e||e.length===0)return [];let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(r===void 0)continue;if(r===null){t.push(r);continue}let s=typeof r;if(s==="boolean"){t.push(r?1:0);continue}if(s==="number"||s==="bigint"||s==="string"){t.push(r);continue}if(r instanceof Uint8Array||r instanceof ArrayBuffer||r instanceof Date){t.push(r);continue}throw new Error(`Cannot bind value at parameter ${n+1}: unsupported type ${Array.isArray(r)?"array":s}`)}return t}normalizeDbError(e){let t=e,n=t?.cause?.code??t?.code,r=t?.cause?.message??t?.message??String(e);if(n==="SQLITE_CONSTRAINT_NOTNULL")return Object.assign(new Error(r),{code:"23502",detail:r});if(n==="SQLITE_CONSTRAINT_UNIQUE"||n==="SQLITE_CONSTRAINT_PRIMARYKEY")return Object.assign(new Error(r),{code:"23505",detail:r});if(n==="SQLITE_CONSTRAINT_FOREIGNKEY")return Object.assign(new Error(r),{code:"23503",detail:r});if(typeof r=="string"){if(/too many SQL variables/i.test(r)){let a=this.maxBoundParameters;return Object.assign(new Error(`Query exceeds SQLite bound-parameter limit. @supabase/lite enforces a conservative limit of ${a} for portability across drivers. Split the query (e.g. chunk large .in() filters or batch INSERTs) on the caller.`),{code:"54000",detail:r})}let s=r.match(/no such table:\s*([A-Za-z0-9_.]+)/i);if(s){let a=s[1],l=a.lastIndexOf("."),u=l>=0?a.slice(0,l):void 0,p=l>=0?a.slice(l+1):a;return new RelationNotFoundError(u,p)}let o=r.match(/no such column:\s*([A-Za-z0-9_.]+)/i);if(o)return Object.assign(new Error(`column ${o[1]} does not exist`),{code:"42703",detail:r})}return e}async onPostgrestAST(e,t){if(this.config.ddlDialect==="sqlite")return e.schema=void 0,this.applyRls(e,t);let n=this.config.translation?.schemas?.appendDefaultSchema,r=this.config.translation?.schemas?.defaultSchema;if(e.schema&&e.schema===r&&!n?e.schema=void 0:!e.schema&&r&&n&&(e.schema=r),!e.from)return e;let s=await this.introspect({useCache:true}),o=e.schema??(n&&r?r:""),a=e.from;if(!(s.tables.some(u=>u.name===a&&(u.schema??"")===o)||s.views.some(u=>u.name===a&&(u.schema??"")===o))){if(!(s.tables.some(p=>p.name===a&&["","public",r].includes(p.schema??""))||s.views.some(p=>p.name===a&&["","public",r].includes(p.schema??""))))throw new RelationNotFoundError(o,a);e.schema=void 0;}return this.applyRls(e,t)}applyRls(e,t){let n=this.config.translation?.deparse?.rls;if(!n||!t)return e;let r=this.config.translation?.schemas?.defaultSchema||void 0;return new xe(n.tables,n.policies,r).enforce(e,t)}};var $e=class extends ge{constructor(t){super({...t,introspection:{...t.introspection,version:"3.47.0"}});this.config=t;}dialect="sqlite";driver=null;kysely=null;fetch(t,n){let r=t instanceof URL?new URL(t.toString(),this.config.host):new URL(t,this.config.host);return fetch(r,{...n,headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.config.token}`,...n?.headers}})}async introspect(t){let n=new URLSearchParams({useCache:t?.useCache?"1":"0",postprocess:t?.postprocess?"1":"0"}),r=await this.fetch(`/v1/projects/${this.config.projectRef}/db/introspect?${n}`),s=await r.text();if(!r.ok)throw console.error(s),new Error(`Failed to get project introspect: ${r.status} ${r.statusText}`);try{let o=JSON.parse(s);if(!o)throw new Error("Failed to get project introspect");return o}catch(o){throw console.error(o),console.log(s),new Error(`Failed to parse introspect response: "${s}"`)}}async transaction(t,n){let r=await this.fetch(`/v1/projects/${this.config.projectRef}/db/transaction?intent=${n?.intent??"migration"}`,{method:"POST",body:JSON.stringify({statements:t})});if(!r.ok)throw new Error(`Failed to execute transaction: ${r.status} ${r.statusText}`)}async exec(t,...n){let r=await this.fetch(`/v1/projects/${this.config.projectRef}/db/exec`,{method:"POST",body:JSON.stringify({statement:t,parameters:n})}),s=await r.text();if(!r.ok)throw console.error(s),new Error(`Failed to execute statement: ${r.status} ${r.statusText}`);try{return JSON.parse(s)}catch(o){throw console.error(o),new Error(`Failed to parse exec response: "${s}"`)}}async close(){}};function yr(i){return new $e(i)}async function _o(i){throw new Error("Unknown runtime")}export{$e as CloudConnection,ge as SqliteConnection,yr as cloud,_o as createConnection};
12
+ async function o(n){throw new Error("Unknown runtime")}export{o as createConnection};