@supabase/lite 0.2.1-next.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -2
- package/STATUS.md +7 -6
- package/dist/{Connection-rAPmec1m.d.ts → Connection-CSVCuMv-.d.ts} +1 -152
- package/dist/cli/index.js +152 -128
- package/dist/cli/lib.js +39 -36
- package/dist/db/browser/index.d.ts +3 -532
- package/dist/db/browser/index.js +3 -207
- package/dist/db/bun/index.d.ts +3 -532
- package/dist/db/bun/index.js +3 -207
- package/dist/db/fallback.d.ts +4 -180
- package/dist/db/fallback.js +2 -205
- package/dist/db/node/index.d.ts +3 -532
- package/dist/db/node/index.js +3 -207
- package/dist/db/postgres/{BasePostgresConnection-B7zHDAib.d.ts → BasePostgresConnection-Clykq58D.d.ts} +1 -1
- package/dist/db/postgres/PostgresConnection.d.ts +1 -1
- package/dist/db/postgres/PostgresConnection.js +21 -25
- package/dist/db/postgres/pglite/PgliteConnection.d.ts +1 -1
- package/dist/db/postgres/pglite/PgliteConnection.js +25 -27
- package/dist/db/workerd/index.d.ts +6 -535
- package/dist/db/workerd/index.js +2 -206
- package/dist/index.d.ts +329 -7
- package/dist/index.js +252 -54
- package/dist/vite/index.js +2 -6
- package/package.json +4 -8
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import F from'postgres';import {PostgresJSDialect}from'kysely-postgres-js';import {Kysely,sql}from'kysely';import {Connection,invariant,RelationNotFoundError}from'@supabase/lite';try {
|
|
2
2
|
/**
|
|
3
3
|
* Adding this to avoid warnings from node:sqlite being experimental
|
|
4
4
|
*/
|
|
@@ -8,7 +8,12 @@ import x from'postgres';import {PostgresJSDialect}from'kysely-postgres-js';impor
|
|
|
8
8
|
return emitWarning(warning, ...args);
|
|
9
9
|
};
|
|
10
10
|
} catch {}
|
|
11
|
-
var
|
|
11
|
+
var k=["anon","authenticated","service_role"];function x(r){return r==="service_role"?"NOLOGIN BYPASSRLS":"NOLOGIN"}function $(r){return r.size===0?"":`DO $$ BEGIN${[...r].map(s=>`
|
|
12
|
+
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '${s}') THEN
|
|
13
|
+
CREATE ROLE ${s} ${x(s)};
|
|
14
|
+
END IF;`).join("")}
|
|
15
|
+
END $$;
|
|
16
|
+
`}var g=$(new Set(k));var m="anon, authenticated, service_role";function U(r){return `"${r.replace(/"/g,'""')}"`}var d=class extends Error{constructor(s){super("Force rollback");this.result=s;}},S=class extends Connection{dialect="postgres";constructor(n){super({...n,baseSchema:`
|
|
12
17
|
${n.baseSchema??""}
|
|
13
18
|
|
|
14
19
|
CREATE SCHEMA IF NOT EXISTS auth;
|
|
@@ -35,7 +40,7 @@ var E=class extends Error{constructor(o){super("Force rollback");this.result=o;}
|
|
|
35
40
|
'{}'
|
|
36
41
|
)::jsonb;
|
|
37
42
|
$$ LANGUAGE SQL STABLE;
|
|
38
|
-
`});}async introspect(n){invariant(typeof n=="object"||n===void 0,"options must be an object");let
|
|
43
|
+
`});}async introspect(n){invariant(typeof n=="object"||n===void 0,"options must be an object");let s=n?.useCache??false,t=await this.readCachedIntrospection({useCache:s});if(t)return t;try{let i=(await sql`
|
|
39
44
|
SELECT
|
|
40
45
|
tbls.table_name AS "name",
|
|
41
46
|
tbls.table_schema AS "schema",
|
|
@@ -48,7 +53,7 @@ var E=class extends Error{constructor(o){super("Force rollback");this.result=o;}
|
|
|
48
53
|
tbls.table_schema NOT IN ('information_schema', 'pg_catalog')
|
|
49
54
|
AND tbls.table_type IN ('BASE TABLE', 'FOREIGN TABLE')
|
|
50
55
|
ORDER BY tbls.table_schema, tbls.table_name
|
|
51
|
-
`.execute(this.kysely)).rows.map(e=>({name:e.name,schema:e.schema,type:"table",rows:Number(e.rows),sql:"",engine:"",collation:""})),
|
|
56
|
+
`.execute(this.kysely)).rows.map(e=>({name:e.name,schema:e.schema,type:"table",rows:Number(e.rows),sql:"",engine:"",collation:""})),u=(await sql`
|
|
52
57
|
SELECT
|
|
53
58
|
cols.table_name AS "table",
|
|
54
59
|
cols.table_schema AS "schema",
|
|
@@ -100,7 +105,7 @@ var E=class extends Error{constructor(o){super("Force rollback");this.result=o;}
|
|
|
100
105
|
LEFT JOIN pg_catalog.pg_type pt ON pt.oid = attr.atttypid
|
|
101
106
|
WHERE cols.table_schema NOT IN ('information_schema', 'pg_catalog')
|
|
102
107
|
ORDER BY cols.table_schema, cols.table_name, cols.ordinal_position
|
|
103
|
-
`.execute(this.kysely)).rows.map(e=>({table:e.table,schema:e.schema,name:e.name,type:e.type,nullable:e.nullable,default_value:e.default_value,is_primary_key:!1,ordinal_position:Number(e.ordinal_position),character_maximum_length:e.character_maximum_length??null,precision:e.precision??null,is_identity:e.is_identity,collation:e.collation,pg_type:e.udt_name??void 0,is_generated:e.is_generated??!1})),
|
|
108
|
+
`.execute(this.kysely)).rows.map(e=>({table:e.table,schema:e.schema,name:e.name,type:e.type,nullable:e.nullable,default_value:e.default_value,is_primary_key:!1,ordinal_position:Number(e.ordinal_position),character_maximum_length:e.character_maximum_length??null,precision:e.precision??null,is_identity:e.is_identity,collation:e.collation,pg_type:e.udt_name??void 0,is_generated:e.is_generated??!1})),E=(await sql`
|
|
104
109
|
SELECT
|
|
105
110
|
ns.nspname AS "schema",
|
|
106
111
|
cl.relname AS "table",
|
|
@@ -125,7 +130,7 @@ var E=class extends Error{constructor(o){super("Force rollback");this.result=o;}
|
|
|
125
130
|
'information_schema'
|
|
126
131
|
, 'pg_catalog')
|
|
127
132
|
ORDER BY ns.nspname, cl.relname, con.conname, cols.ord
|
|
128
|
-
`.execute(this.kysely)).rows.map(e=>({table:e.table,column:e.column,schema:e.schema,ref_table:e.ref_table,ref_column:e.ref_column,foreign_key_name:e.foreign_key_name,fk_def:e.fk_def,on_update:"",on_delete:""})),
|
|
133
|
+
`.execute(this.kysely)).rows.map(e=>({table:e.table,column:e.column,schema:e.schema,ref_table:e.ref_table,ref_column:e.ref_column,foreign_key_name:e.foreign_key_name,fk_def:e.fk_def,on_update:"",on_delete:""})),l=(await sql`
|
|
129
134
|
SELECT
|
|
130
135
|
ns.nspname AS "schema",
|
|
131
136
|
cl.relname AS "table",
|
|
@@ -142,7 +147,7 @@ var E=class extends Error{constructor(o){super("Force rollback");this.result=o;}
|
|
|
142
147
|
'information_schema'
|
|
143
148
|
, 'pg_catalog')
|
|
144
149
|
GROUP BY ns.nspname, cl.relname, con.oid
|
|
145
|
-
`.execute(this.kysely)).rows.map(e=>({table:e.table,columns:e.columns,schema:e.schema,field_count:e.columns.length})),
|
|
150
|
+
`.execute(this.kysely)).rows.map(e=>({table:e.table,columns:e.columns,schema:e.schema,field_count:e.columns.length})),A=new Set(l.flatMap(e=>e.columns.map(C=>`${e.schema}.${e.table}.${C}`)));for(let e of u)e.is_primary_key=A.has(`${e.schema}.${e.table}.${e.name}`);let R=(await sql`
|
|
146
151
|
SELECT
|
|
147
152
|
tnsp.nspname AS "schema",
|
|
148
153
|
cl.relname AS "table",
|
|
@@ -163,7 +168,7 @@ var E=class extends Error{constructor(o){super("Force rollback");this.result=o;}
|
|
|
163
168
|
'information_schema'
|
|
164
169
|
, 'pg_catalog')
|
|
165
170
|
GROUP BY tnsp.nspname, cl.relname, ic.relname, idx.indisunique
|
|
166
|
-
`.execute(this.kysely)).rows.map(e=>({table:e.table,name:e.name,unique:e.unique,columns:e.columns,schema:e.schema})),
|
|
171
|
+
`.execute(this.kysely)).rows.map(e=>({table:e.table,name:e.name,unique:e.unique,columns:e.columns,schema:e.schema})),h=(await sql`
|
|
167
172
|
SELECT
|
|
168
173
|
views.schemaname AS "schema",
|
|
169
174
|
views.viewname AS "name",
|
|
@@ -171,7 +176,7 @@ var E=class extends Error{constructor(o){super("Force rollback");this.result=o;}
|
|
|
171
176
|
FROM pg_views views
|
|
172
177
|
WHERE views.schemaname NOT IN ('information_schema', 'pg_catalog')
|
|
173
178
|
ORDER BY views.schemaname, views.viewname
|
|
174
|
-
`.execute(this.kysely)).rows.map(e=>({name:e.name,schema:e.schema,sql:e.sql??""})),
|
|
179
|
+
`.execute(this.kysely)).rows.map(e=>({name:e.name,schema:e.schema,sql:e.sql??""})),y=(await sql`
|
|
175
180
|
SELECT
|
|
176
181
|
n.nspname AS "schema",
|
|
177
182
|
cl.relname AS "table",
|
|
@@ -183,7 +188,7 @@ var E=class extends Error{constructor(o){super("Force rollback");this.result=o;}
|
|
|
183
188
|
c.contype = 'c'
|
|
184
189
|
AND n.nspname NOT IN ('information_schema', 'pg_catalog')
|
|
185
190
|
ORDER BY n.nspname, cl.relname
|
|
186
|
-
`.execute(this.kysely)).rows.map(e=>({schema:e.schema,table:e.table,expression:e.expression??""})),
|
|
191
|
+
`.execute(this.kysely)).rows.map(e=>({schema:e.schema,table:e.table,expression:e.expression??""})),O=(await sql`
|
|
187
192
|
SELECT
|
|
188
193
|
n.nspname AS "schema",
|
|
189
194
|
cl.relname AS "table",
|
|
@@ -198,7 +203,7 @@ var E=class extends Error{constructor(o){super("Force rollback");this.result=o;}
|
|
|
198
203
|
c.contype = 'u'
|
|
199
204
|
AND n.nspname NOT IN ('information_schema', 'pg_catalog')
|
|
200
205
|
GROUP BY n.nspname, cl.relname, c.conname, c.oid
|
|
201
|
-
`.execute(this.kysely)).rows.map(e=>({schema:e.schema,table:e.table,name:e.name,columns:e.columns})),
|
|
206
|
+
`.execute(this.kysely)).rows.map(e=>({schema:e.schema,table:e.table,name:e.name,columns:e.columns})),T=(await sql`
|
|
202
207
|
SELECT
|
|
203
208
|
n.nspname AS "schema",
|
|
204
209
|
cl.relname AS "table",
|
|
@@ -213,7 +218,7 @@ var E=class extends Error{constructor(o){super("Force rollback");this.result=o;}
|
|
|
213
218
|
n.nspname NOT IN ('information_schema', 'pg_catalog')
|
|
214
219
|
AND cl.relkind IN ('r', 'v', 'm', 'f', 'p')
|
|
215
220
|
AND d.description IS NOT NULL
|
|
216
|
-
`.execute(this.kysely)).rows.map(e=>({schema:e.schema,table:e.table,column:e.column??void 0,text:e.text})),
|
|
221
|
+
`.execute(this.kysely)).rows.map(e=>({schema:e.schema,table:e.table,column:e.column??void 0,text:e.text})),L=await sql`
|
|
217
222
|
SELECT
|
|
218
223
|
n.nspname AS "schema",
|
|
219
224
|
t.typname AS "type",
|
|
@@ -224,7 +229,7 @@ var E=class extends Error{constructor(o){super("Force rollback");this.result=o;}
|
|
|
224
229
|
JOIN pg_namespace n ON n.oid = t.typnamespace
|
|
225
230
|
WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
|
|
226
231
|
GROUP BY n.nspname, t.typname
|
|
227
|
-
`.execute(this.kysely),
|
|
232
|
+
`.execute(this.kysely),b=await sql`
|
|
228
233
|
SELECT
|
|
229
234
|
n.nspname AS "schema",
|
|
230
235
|
t.typname AS "type",
|
|
@@ -246,19 +251,10 @@ var E=class extends Error{constructor(o){super("Force rollback");this.result=o;}
|
|
|
246
251
|
AND NOT a.attisdropped
|
|
247
252
|
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
|
|
248
253
|
GROUP BY n.nspname, t.typname
|
|
249
|
-
`.execute(this.kysely),
|
|
254
|
+
`.execute(this.kysely),I=[...L.rows.map(e=>({schema:e.schema,type:e.type,kind:"enum",values:e.values})),...b.rows.map(e=>({schema:e.schema,type:e.type,kind:"composite",fields:e.fields}))],w=(await sql`SELECT current_database() AS "name"`.execute(this.kysely)).rows[0]?.name??"postgres",_={tables:i,columns:u,indexes:R,foreign_keys:E,primary_keys:l,views:h,triggers:[],check_constraints:y,unique_constraints:O,comments:T,custom_types:I,database_name:w,version:""};return await this.writeCachedIntrospection(_,{useDriver:s}),_}catch(o){return console.error("Introspection failed:",o),{tables:[],columns:[],indexes:[],foreign_keys:[],primary_keys:[],views:[],triggers:[],check_constraints:[],unique_constraints:[],comments:[],custom_types:[],database_name:"postgres",version:""}}}rlsState="unknown";async ensureRlsContext(){if(this.rlsState!=="unknown")return this.rlsState==="active";let n=await sql`
|
|
250
255
|
SELECT count(*) ::text as count FROM pg_class WHERE relrowsecurity = true
|
|
251
|
-
`.execute(this.kysely);if(!(Number(n.rows[0]?.count??0)>0))return this.rlsState="inactive",false;this.rlsState="active",await sql`
|
|
252
|
-
DO $$ BEGIN
|
|
253
|
-
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'anon') THEN
|
|
254
|
-
CREATE ROLE anon NOLOGIN;
|
|
255
|
-
END IF;
|
|
256
|
-
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'authenticated') THEN
|
|
257
|
-
CREATE ROLE authenticated NOLOGIN;
|
|
258
|
-
END IF;
|
|
259
|
-
END $$
|
|
260
|
-
`.execute(this.kysely);let t=await sql`
|
|
256
|
+
`.execute(this.kysely);if(!(Number(n.rows[0]?.count??0)>0))return this.rlsState="inactive",false;this.rlsState="active",await sql.raw(g).execute(this.kysely);let t=await sql`
|
|
261
257
|
SELECT DISTINCT n.nspname FROM pg_class c
|
|
262
258
|
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
263
259
|
WHERE c.relrowsecurity = true
|
|
264
|
-
`.execute(this.kysely);for(let{nspname:
|
|
260
|
+
`.execute(this.kysely);for(let{nspname:o}of t.rows){let i=U(o);await sql.raw(`GRANT USAGE ON SCHEMA ${i} TO ${m}`).execute(this.kysely),await sql.raw(`GRANT ALL ON ALL TABLES IN SCHEMA ${i} TO ${m}`).execute(this.kysely),await sql.raw(`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${i} TO ${m}`).execute(this.kysely),await sql.raw(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${i} GRANT ALL ON TABLES TO ${m}`).execute(this.kysely),await sql.raw(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${i} GRANT ALL ON SEQUENCES TO ${m}`).execute(this.kysely);}return true}async withContext(n,s,t){let o=t?.forceRollback===true;if(!o&&!n)return s(this.kysely);let i=n?await this.ensureRlsContext():false;if(!o&&!i)return s(this.kysely);try{return await this.kysely.transaction().execute(async c=>{if(n&&i){let p=n.auth,E=p?.role||"anon",f=String(p?.uid??""),l=p?.jwt;await sql`SELECT set_config('role', ${E}, true)`.execute(c),await sql`SELECT set_config('request.jwt.claim.sub', ${f}, true)`.execute(c),await sql`SELECT set_config('request.jwt.claim.role', ${E}, true)`.execute(c),l&&typeof l=="object"&&await sql`SELECT set_config('request.jwt.claims', ${JSON.stringify(l)}, true)`.execute(c);}let u=await s(c);if(o)throw new d(u);return u})}catch(c){if(c instanceof d)return c.result;throw c}}async onPostgrestAST(n){if(!n.from)return n;let s=n.schema??"public",t=n.from,o=await this.introspect({useCache:true});if(!o.tables.some(i=>i.name===t&&i.schema===s)&&!o.views.some(i=>i.name===t&&i.schema===s))throw new RelationNotFoundError(s,t);return n}async transaction(n,s){await this.exec("BEGIN");try{for(let t of n)await this.exec(t);await this.exec("COMMIT");}catch(t){throw await this.exec("ROLLBACK"),t}finally{s?.intent==="migration"&&await this.clearSchemaCache();}}};var N=class extends S{driver;dialect="postgres";constructor(n){super(n),this.driver=F(n.url??"",{types:{bigint:{to:20,from:[20],serialize:t=>t.toString(),parse:t=>{let o=Number(t);return Number.isSafeInteger(o)?o:BigInt(t)}},json:{to:114,from:[114],serialize:t=>JSON.stringify(t),parse:t=>JSON.parse(t)},jsonb:{to:3802,from:[3802],serialize:t=>JSON.stringify(t),parse:t=>JSON.parse(t)},numeric:{to:1700,from:[1700],serialize:t=>String(t),parse:t=>{let o=Number(t);return Number.isFinite(o)&&String(o)===t?o:t}},date:{to:1082,from:[1082],serialize:t=>t,parse:t=>t},time:{to:1083,from:[1083],serialize:t=>t,parse:t=>t},timestamp:{to:1114,from:[1114],serialize:t=>t,parse:t=>t},timestamptz:{to:1184,from:[1184],serialize:t=>t,parse:t=>t},timetz:{to:1266,from:[1266],serialize:t=>t,parse:t=>t}}});let s=new PostgresJSDialect({postgres:this.driver});this.kysely=new Kysely({dialect:s});}async close(){await this.driver.end();}};function ne(r){return new N(r)}export{N as PostgresConnection,ne as createPostgresConnection};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { PGliteOptions, PGlite } from '@electric-sql/pglite';
|
|
2
2
|
export { PGlite } from '@electric-sql/pglite';
|
|
3
|
-
import { I as IBasePostgresConnectionConfig, B as BasePostgresConnection } from '../BasePostgresConnection-
|
|
3
|
+
import { I as IBasePostgresConnectionConfig, B as BasePostgresConnection } from '../BasePostgresConnection-Clykq58D.js';
|
|
4
4
|
import { ConnectionMigrator, SchemaDiffResult, PlanResult, PlanStep } from '@supabase/lite';
|
|
5
5
|
import 'kysely';
|
|
6
6
|
|
|
@@ -8,8 +8,14 @@ import {PGlite}from'@electric-sql/pglite';export{PGlite}from'@electric-sql/pglit
|
|
|
8
8
|
return emitWarning(warning, ...args);
|
|
9
9
|
};
|
|
10
10
|
} catch {}
|
|
11
|
-
async function
|
|
12
|
-
|
|
11
|
+
async function te(n){let t;if(typeof n=="string"&&(t=n),typeof n=="object"&&n.dataDir&&(t=n.dataDir),t){let{mkdir:e}=await import('node:fs');e(t,{recursive:true},s=>{if(s)throw s});}}var T=class{#e;#t;constructor(t,e){this.#e=t,this.#t=e;}async acquireConnection(){return new O(this.#e)}async beginTransaction(t,e){await t.executeQuery(CompiledQuery.raw("BEGIN"));}async commitTransaction(t){await t.executeQuery(CompiledQuery.raw("COMMIT"));}async rollbackTransaction(t){await t.executeQuery(CompiledQuery.raw("ROLLBACK"));}async destroy(){this.#t&&await this.#e.close();}async init(){}async releaseConnection(t){}},O=class{#e;constructor(t){this.#e=t;}async executeQuery(t){let e=await this.#e.query(t.sql,[...t.parameters]),s=e.affectedRows;return {rows:e.rows,numAffectedRows:typeof s=="number"?BigInt(s):void 0}}async*streamQuery(){throw new Error("PGlite does not support streaming.")}},y=class{client;#e=true;constructor(t,e){te(t);let s={...e};if(typeof t=="object"&&t instanceof PGlite){this.client=t,this.#e=false;return}typeof t=="string"?s={dataDir:t,...s}:s=t??{},this.client=new PGlite(s);}dialect={createAdapter:()=>new PostgresAdapter,createDriver:()=>new T(this.client,this.#e),createIntrospector:t=>new PostgresIntrospector(t),createQueryCompiler:()=>new PostgresQueryCompiler}};var S=["anon","authenticated","service_role"];function ne(n){return n==="service_role"?"NOLOGIN BYPASSRLS":"NOLOGIN"}function h(n){return n.size===0?"":`DO $$ BEGIN${[...n].map(e=>`
|
|
12
|
+
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '${e}') THEN
|
|
13
|
+
CREATE ROLE ${e} ${ne(e)};
|
|
14
|
+
END IF;`).join("")}
|
|
15
|
+
END $$;
|
|
16
|
+
`}var B=h(new Set(S));function g(n,t){return n?n.quoted?n.value===t:n.value.toLowerCase()===t:false}function m(n){return n?.quoted?n.value:n?.value.toLowerCase()}function se(n,t){let e="",s=t+1;for(;s<n.length;){if(n[s]==='"'&&n[s+1]==='"'){e+='"',s+=2;continue}if(n[s]==='"')return {token:{value:e,quoted:true},end:s+1};e+=n[s],s++;}return {token:{value:e,quoted:true},end:s}}function ae(n,t){let e=t+1;for(;e<n.length;){if(n[e]==="'"&&n[e+1]==="'"){e+=2;continue}if(n[e]==="'")return e+1;e++;}return e}function oe(n,t){let e=/^\$[A-Za-z_][A-Za-z0-9_]*\$|^\$\$/.exec(n.slice(t))?.[0];if(!e)return;let s=t+e.length,o=n.indexOf(e,s);return o===-1?n.length:o+e.length}function b(n){let t=[],e=0;for(;e<n.length;){let s=n[e],o=n[e+1];if(/\s/.test(s)){e++;continue}if(s==="-"&&o==="-"){for(e+=2;e<n.length&&n[e]!==`
|
|
17
|
+
`;)e++;continue}if(s==="/"&&o==="*"){for(e+=2;e<n.length&&!(n[e]==="*"&&n[e+1]==="/");)e++;e=e<n.length?e+2:e;continue}if(s==="'"){e=ae(n,e);continue}if(s==="$"){let r=oe(n,e);if(r!==void 0){e=r;continue}}if(s==='"'){let{token:r,end:i}=se(n,e);t.push(r),e=i;continue}if(s===","||s===";"){t.push({value:s,quoted:false}),e++;continue}if(/[A-Za-z_]/.test(s)){let r=e;for(e++;e<n.length&&/[A-Za-z0-9_$]/.test(n[e]);)e++;t.push({value:n.slice(r,e).toLowerCase(),quoted:false});continue}e++;}return t}function $(n,t){let e=m(n[t]),s=m(n[t+1]);if((e==="create"||e==="alter")&&(s==="role"||s==="user"||s==="group"))return n[t+2]}function N(n){let t=new Set,e=b(n);for(let s=0;s<e.length;s++){if(m(e[s])!=="create")continue;let o=$(e,s);for(let r of S)g(o,r)&&t.add(r);}return t}function L(n,t,e){let s=new Set([";","as","by","check","for","granted","in","on","option","using","where","with"]);for(let o=t;o<n.length;o++){let r=m(n[o]);if(!r||s.has(r))return;for(let i of S)g(n[o],i)&&e.add(i);}}function re(n){let t=[],e=[];for(let s of n){if(m(s)===";"){e.length>0&&t.push(e),e=[];continue}e.push(s);}return e.length>0&&t.push(e),t}function D(n,t){return n.some(e=>m(e)===t)}function ie(n){let t=new Set,e=re(b(n));for(let s of e){let o=m(s[0]);for(let c=0;c<s.length;c++){let u=m(s[c]);u==="to"&&(D(s,"grant")||D(s,"policy")||m(s[c-1])==="owner")&&L(s,c+1,t),u==="from"&&o==="revoke"&&L(s,c+1,t);}let r=s.findIndex(c=>m(c)==="to"),i=s.findIndex(c=>m(c)==="on");o==="grant"&&r>1&&(i===-1||r<i)&&L(s,1,t);}return t}function C(n){let t=N(n);return new Set([...ie(n)].filter(e=>!t.has(e)))}function v(n){let t=N(n);return new Set(S.filter(e=>!t.has(e)))}function U(n,t){let e=b(n);if(e.length===0)return false;let s=$(e,0);if(s){for(let i of t)if(g(s,i))return true;return false}let o=m(e[0]),r=m(e[1]);if(o==="drop"&&(r==="role"||r==="user"||r==="group")){for(let i of e.slice(2))for(let c of t)if(g(i,c))return true}if(o==="comment"&&m(e[1])==="on"&&m(e[2])==="role"){for(let i of t)if(g(e[3],i))return true}return false}var E="anon, authenticated, service_role";function me(n){return `"${n.replace(/"/g,'""')}"`}var _=class extends Error{constructor(e){super("Force rollback");this.result=e;}},A=class extends Connection{dialect="postgres";constructor(t){super({...t,baseSchema:`
|
|
18
|
+
${t.baseSchema??""}
|
|
13
19
|
|
|
14
20
|
CREATE SCHEMA IF NOT EXISTS auth;
|
|
15
21
|
|
|
@@ -35,7 +41,7 @@ async function B(n){let e;if(typeof n=="string"&&(e=n),typeof n=="object"&&n.dat
|
|
|
35
41
|
'{}'
|
|
36
42
|
)::jsonb;
|
|
37
43
|
$$ LANGUAGE SQL STABLE;
|
|
38
|
-
`});}async introspect(
|
|
44
|
+
`});}async introspect(t){invariant(typeof t=="object"||t===void 0,"options must be an object");let e=t?.useCache??false,s=await this.readCachedIntrospection({useCache:e});if(s)return s;try{let r=(await sql`
|
|
39
45
|
SELECT
|
|
40
46
|
tbls.table_name AS "name",
|
|
41
47
|
tbls.table_schema AS "schema",
|
|
@@ -48,7 +54,7 @@ async function B(n){let e;if(typeof n=="string"&&(e=n),typeof n=="object"&&n.dat
|
|
|
48
54
|
tbls.table_schema NOT IN ('information_schema', 'pg_catalog')
|
|
49
55
|
AND tbls.table_type IN ('BASE TABLE', 'FOREIGN TABLE')
|
|
50
56
|
ORDER BY tbls.table_schema, tbls.table_name
|
|
51
|
-
`.execute(this.kysely)).rows.map(
|
|
57
|
+
`.execute(this.kysely)).rows.map(a=>({name:a.name,schema:a.schema,type:"table",rows:Number(a.rows),sql:"",engine:"",collation:""})),c=(await sql`
|
|
52
58
|
SELECT
|
|
53
59
|
cols.table_name AS "table",
|
|
54
60
|
cols.table_schema AS "schema",
|
|
@@ -100,7 +106,7 @@ async function B(n){let e;if(typeof n=="string"&&(e=n),typeof n=="object"&&n.dat
|
|
|
100
106
|
LEFT JOIN pg_catalog.pg_type pt ON pt.oid = attr.atttypid
|
|
101
107
|
WHERE cols.table_schema NOT IN ('information_schema', 'pg_catalog')
|
|
102
108
|
ORDER BY cols.table_schema, cols.table_name, cols.ordinal_position
|
|
103
|
-
`.execute(this.kysely)).rows.map(
|
|
109
|
+
`.execute(this.kysely)).rows.map(a=>({table:a.table,schema:a.schema,name:a.name,type:a.type,nullable:a.nullable,default_value:a.default_value,is_primary_key:!1,ordinal_position:Number(a.ordinal_position),character_maximum_length:a.character_maximum_length??null,precision:a.precision??null,is_identity:a.is_identity,collation:a.collation,pg_type:a.udt_name??void 0,is_generated:a.is_generated??!1})),p=(await sql`
|
|
104
110
|
SELECT
|
|
105
111
|
ns.nspname AS "schema",
|
|
106
112
|
cl.relname AS "table",
|
|
@@ -125,7 +131,7 @@ async function B(n){let e;if(typeof n=="string"&&(e=n),typeof n=="object"&&n.dat
|
|
|
125
131
|
'information_schema'
|
|
126
132
|
, 'pg_catalog')
|
|
127
133
|
ORDER BY ns.nspname, cl.relname, con.conname, cols.ord
|
|
128
|
-
`.execute(this.kysely)).rows.map(
|
|
134
|
+
`.execute(this.kysely)).rows.map(a=>({table:a.table,column:a.column,schema:a.schema,ref_table:a.ref_table,ref_column:a.ref_column,foreign_key_name:a.foreign_key_name,fk_def:a.fk_def,on_update:"",on_delete:""})),d=(await sql`
|
|
129
135
|
SELECT
|
|
130
136
|
ns.nspname AS "schema",
|
|
131
137
|
cl.relname AS "table",
|
|
@@ -142,7 +148,7 @@ async function B(n){let e;if(typeof n=="string"&&(e=n),typeof n=="object"&&n.dat
|
|
|
142
148
|
'information_schema'
|
|
143
149
|
, 'pg_catalog')
|
|
144
150
|
GROUP BY ns.nspname, cl.relname, con.oid
|
|
145
|
-
`.execute(this.kysely)).rows.map(
|
|
151
|
+
`.execute(this.kysely)).rows.map(a=>({table:a.table,columns:a.columns,schema:a.schema,field_count:a.columns.length})),G=new Set(d.flatMap(a=>a.columns.map(V=>`${a.schema}.${a.table}.${V}`)));for(let a of c)a.is_primary_key=G.has(`${a.schema}.${a.table}.${a.name}`);let q=(await sql`
|
|
146
152
|
SELECT
|
|
147
153
|
tnsp.nspname AS "schema",
|
|
148
154
|
cl.relname AS "table",
|
|
@@ -163,7 +169,7 @@ async function B(n){let e;if(typeof n=="string"&&(e=n),typeof n=="object"&&n.dat
|
|
|
163
169
|
'information_schema'
|
|
164
170
|
, 'pg_catalog')
|
|
165
171
|
GROUP BY tnsp.nspname, cl.relname, ic.relname, idx.indisunique
|
|
166
|
-
`.execute(this.kysely)).rows.map(
|
|
172
|
+
`.execute(this.kysely)).rows.map(a=>({table:a.table,name:a.name,unique:a.unique,columns:a.columns,schema:a.schema})),J=(await sql`
|
|
167
173
|
SELECT
|
|
168
174
|
views.schemaname AS "schema",
|
|
169
175
|
views.viewname AS "name",
|
|
@@ -171,7 +177,7 @@ async function B(n){let e;if(typeof n=="string"&&(e=n),typeof n=="object"&&n.dat
|
|
|
171
177
|
FROM pg_views views
|
|
172
178
|
WHERE views.schemaname NOT IN ('information_schema', 'pg_catalog')
|
|
173
179
|
ORDER BY views.schemaname, views.viewname
|
|
174
|
-
`.execute(this.kysely)).rows.map(
|
|
180
|
+
`.execute(this.kysely)).rows.map(a=>({name:a.name,schema:a.schema,sql:a.sql??""})),M=(await sql`
|
|
175
181
|
SELECT
|
|
176
182
|
n.nspname AS "schema",
|
|
177
183
|
cl.relname AS "table",
|
|
@@ -183,7 +189,7 @@ async function B(n){let e;if(typeof n=="string"&&(e=n),typeof n=="object"&&n.dat
|
|
|
183
189
|
c.contype = 'c'
|
|
184
190
|
AND n.nspname NOT IN ('information_schema', 'pg_catalog')
|
|
185
191
|
ORDER BY n.nspname, cl.relname
|
|
186
|
-
`.execute(this.kysely)).rows.map(
|
|
192
|
+
`.execute(this.kysely)).rows.map(a=>({schema:a.schema,table:a.table,expression:a.expression??""})),W=(await sql`
|
|
187
193
|
SELECT
|
|
188
194
|
n.nspname AS "schema",
|
|
189
195
|
cl.relname AS "table",
|
|
@@ -198,7 +204,7 @@ async function B(n){let e;if(typeof n=="string"&&(e=n),typeof n=="object"&&n.dat
|
|
|
198
204
|
c.contype = 'u'
|
|
199
205
|
AND n.nspname NOT IN ('information_schema', 'pg_catalog')
|
|
200
206
|
GROUP BY n.nspname, cl.relname, c.conname, c.oid
|
|
201
|
-
`.execute(this.kysely)).rows.map(
|
|
207
|
+
`.execute(this.kysely)).rows.map(a=>({schema:a.schema,table:a.table,name:a.name,columns:a.columns})),j=(await sql`
|
|
202
208
|
SELECT
|
|
203
209
|
n.nspname AS "schema",
|
|
204
210
|
cl.relname AS "table",
|
|
@@ -213,7 +219,7 @@ async function B(n){let e;if(typeof n=="string"&&(e=n),typeof n=="object"&&n.dat
|
|
|
213
219
|
n.nspname NOT IN ('information_schema', 'pg_catalog')
|
|
214
220
|
AND cl.relkind IN ('r', 'v', 'm', 'f', 'p')
|
|
215
221
|
AND d.description IS NOT NULL
|
|
216
|
-
`.execute(this.kysely)).rows.map(
|
|
222
|
+
`.execute(this.kysely)).rows.map(a=>({schema:a.schema,table:a.table,column:a.column??void 0,text:a.text})),Q=await sql`
|
|
217
223
|
SELECT
|
|
218
224
|
n.nspname AS "schema",
|
|
219
225
|
t.typname AS "type",
|
|
@@ -224,7 +230,7 @@ async function B(n){let e;if(typeof n=="string"&&(e=n),typeof n=="object"&&n.dat
|
|
|
224
230
|
JOIN pg_namespace n ON n.oid = t.typnamespace
|
|
225
231
|
WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
|
|
226
232
|
GROUP BY n.nspname, t.typname
|
|
227
|
-
`.execute(this.kysely),
|
|
233
|
+
`.execute(this.kysely),Y=await sql`
|
|
228
234
|
SELECT
|
|
229
235
|
n.nspname AS "schema",
|
|
230
236
|
t.typname AS "type",
|
|
@@ -246,23 +252,15 @@ async function B(n){let e;if(typeof n=="string"&&(e=n),typeof n=="object"&&n.dat
|
|
|
246
252
|
AND NOT a.attisdropped
|
|
247
253
|
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
|
|
248
254
|
GROUP BY n.nspname, t.typname
|
|
249
|
-
`.execute(this.kysely),
|
|
255
|
+
`.execute(this.kysely),K=[...Q.rows.map(a=>({schema:a.schema,type:a.type,kind:"enum",values:a.values})),...Y.rows.map(a=>({schema:a.schema,type:a.type,kind:"composite",fields:a.fields}))],z=(await sql`SELECT current_database() AS "name"`.execute(this.kysely)).rows[0]?.name??"postgres",x={tables:r,columns:c,indexes:q,foreign_keys:p,primary_keys:d,views:J,triggers:[],check_constraints:M,unique_constraints:W,comments:j,custom_types:K,database_name:z,version:""};return await this.writeCachedIntrospection(x,{useDriver:e}),x}catch(o){return console.error("Introspection failed:",o),{tables:[],columns:[],indexes:[],foreign_keys:[],primary_keys:[],views:[],triggers:[],check_constraints:[],unique_constraints:[],comments:[],custom_types:[],database_name:"postgres",version:""}}}rlsState="unknown";async ensureRlsContext(){if(this.rlsState!=="unknown")return this.rlsState==="active";let t=await sql`
|
|
250
256
|
SELECT count(*) ::text as count FROM pg_class WHERE relrowsecurity = true
|
|
251
|
-
`.execute(this.kysely);if(!(Number(
|
|
252
|
-
DO $$ BEGIN
|
|
253
|
-
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'anon') THEN
|
|
254
|
-
CREATE ROLE anon NOLOGIN;
|
|
255
|
-
END IF;
|
|
256
|
-
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'authenticated') THEN
|
|
257
|
-
CREATE ROLE authenticated NOLOGIN;
|
|
258
|
-
END IF;
|
|
259
|
-
END $$
|
|
260
|
-
`.execute(this.kysely);let o=await sql`
|
|
257
|
+
`.execute(this.kysely);if(!(Number(t.rows[0]?.count??0)>0))return this.rlsState="inactive",false;this.rlsState="active",await sql.raw(B).execute(this.kysely);let s=await sql`
|
|
261
258
|
SELECT DISTINCT n.nspname FROM pg_class c
|
|
262
259
|
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
263
260
|
WHERE c.relrowsecurity = true
|
|
264
|
-
`.execute(this.kysely);for(let{nspname:
|
|
261
|
+
`.execute(this.kysely);for(let{nspname:o}of s.rows){let r=me(o);await sql.raw(`GRANT USAGE ON SCHEMA ${r} TO ${E}`).execute(this.kysely),await sql.raw(`GRANT ALL ON ALL TABLES IN SCHEMA ${r} TO ${E}`).execute(this.kysely),await sql.raw(`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${r} TO ${E}`).execute(this.kysely),await sql.raw(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${r} GRANT ALL ON TABLES TO ${E}`).execute(this.kysely),await sql.raw(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${r} GRANT ALL ON SEQUENCES TO ${E}`).execute(this.kysely);}return true}async withContext(t,e,s){let o=s?.forceRollback===true;if(!o&&!t)return e(this.kysely);let r=t?await this.ensureRlsContext():false;if(!o&&!r)return e(this.kysely);try{return await this.kysely.transaction().execute(async i=>{if(t&&r){let u=t.auth,p=u?.role||"anon",f=String(u?.uid??""),d=u?.jwt;await sql`SELECT set_config('role', ${p}, true)`.execute(i),await sql`SELECT set_config('request.jwt.claim.sub', ${f}, true)`.execute(i),await sql`SELECT set_config('request.jwt.claim.role', ${p}, true)`.execute(i),d&&typeof d=="object"&&await sql`SELECT set_config('request.jwt.claims', ${JSON.stringify(d)}, true)`.execute(i);}let c=await e(i);if(o)throw new _(c);return c})}catch(i){if(i instanceof _)return i.result;throw i}}async onPostgrestAST(t){if(!t.from)return t;let e=t.schema??"public",s=t.from,o=await this.introspect({useCache:true});if(!o.tables.some(r=>r.name===s&&r.schema===e)&&!o.views.some(r=>r.name===s&&r.schema===e))throw new RelationNotFoundError(e,s);return t}async transaction(t,e){await this.exec("BEGIN");try{for(let s of t)await this.exec(s);await this.exec("COMMIT");}catch(s){throw await this.exec("ROLLBACK"),s}finally{e?.intent==="migration"&&await this.clearSchemaCache();}}};var F=(n,t=e=>e)=>{if(!n||n==="{}")return [];let e=n.slice(1,-1);if(e==="")return [];let s=[],o="",r=false,i=0;for(let c=0;c<e.length;c++){let u=e[c];u==='"'&&e[c-1]!=="\\"?(r=!r,o+=u):u==="{"&&!r?(i++,o+=u):u==="}"&&!r?(i--,o+=u):u===","&&!r&&i===0?(s.push(t(o)),o=""):o+=u;}return o!==""&&s.push(t(o)),s},pe=n=>n==="NULL"?null:n.startsWith('"')&&n.endsWith('"')?n.slice(1,-1).replace(/\\(.)/g,"$1"):n,fe=n=>n==="NULL"?null:Number.parseInt(n,10);function H(n){return typeof n=="object"&&n!==null&&"text"in n&&"values"in n}function de(n,t){if(n==null)return n;switch(t){case 20:return typeof n=="bigint"?n:BigInt(n);case 22:return Array.isArray(n)?n:typeof n=="string"?n.split(" ").map(Number).filter(e=>!Number.isNaN(e)):n;case 1002:case 1009:case 1015:return typeof n=="string"?F(n,pe):n;case 1005:case 1007:case 1016:return typeof n=="string"?F(n,fe):n;default:return n}}function I(n){return {async query(t,e){let s=H(t)?t.text:t,o=H(t)?t.values:e??[],r=await n.driver.query(s,[...o]);return {rows:r.rows.map(c=>Object.fromEntries(r.fields.map(u=>[u.name,de(c[u.name],u.dataTypeID)])))}}}}async function Ee(){try{return await import('@supabase/pg-delta')}catch(n){throw new Error("Postgres/PGlite schema diffing now requires a Bun/Node-compatible runtime with pg-delta available.",{cause:n})}}function ye(n){let t=/^drop table (.+)$/.exec(n);if(t)return {table:t[1],reason:"drop table"};let e=/^drop column (.+) on (.+)$/.exec(n);if(e)return {table:e[2],reason:`drop column ${e[1]}`};let s=/^drop sequence (.+)$/.exec(n);return s?{table:s[1],reason:"drop sequence"}:{table:"unknown",reason:n}}var R=class{constructor(t,e){this.from=t;this.desiredSchema=e;}#e;async#t(t){if(this.#e)return this.#e;let e=new this.from.constructor;try{let s=h(C(this.desiredSchema));return s&&await e.exec(s),await e.exec(this.desiredSchema),this.#e=await t(I(e)),this.#e}finally{await e.close();}}async diff(){let{createPlan:t,extractCatalog:e}=await Ee(),s=I(this.from),o=await this.#t(e),r=await e(s),i=await t(r,o);if(!i)return {diff:"",plan:{steps:[],warnings:[],unsafe:false}};let c=i.plan.risk?.level==="data_loss"?i.plan.risk.statements.map(ye):[],u=v(this.desiredSchema),p=i.plan.statements.filter(f=>!U(f,u));return {diff:p.join(`
|
|
265
262
|
|
|
266
|
-
`),plan:{steps:
|
|
263
|
+
`),plan:{steps:p.map(f=>({sql:f})),warnings:c,unsafe:i.plan.risk?.level==="data_loss"}}}async migratePlan(t,e){if(t.steps.length===0)return;if(t.unsafe&&!e?.force)throw new DataLossError(t.warnings??[]);let s=t.steps.map(c=>c.sql).join(`
|
|
264
|
+
`),o=N(s),r=new Set(t.steps.flatMap(c=>[...C(c.sql)]).filter(c=>!o.has(c))),i=h(r);i&&await this.from.exec(i),await this.from.transaction(t.steps.map(c=>c.sql),{intent:"migration"});}async migrate(t){let e=await this.diff();return await this.migratePlan(e.plan,t),e}safeSortPlanSteps(t){return t}};var k=class extends A{driver;dialect="postgres";#e=false;constructor(t={}){let e=new PGlite({...t.pgliteOptions,dataDir:t.url??void 0,extensions:{...t.pgliteOptions?.extensions,isn:isn,ltree:ltree,file_fdw:file_fdw,pgcrypto:pgcrypto},parsers:{20:o=>{let r=Number(o);return Number.isSafeInteger(r)?r:BigInt(o)},114:o=>JSON.parse(o),3802:o=>JSON.parse(o),1700:o=>{let r=Number(o);return Number.isFinite(r)&&String(r)===o?r:o},1082:o=>o,1083:o=>o,1114:o=>o,1184:o=>o,1266:o=>o,...t.pgliteOptions?.parsers}}),{dialect:s}=new y(e);super(t),this.driver=e,this.kysely=new Kysely({dialect:s});}async exec(t,...e){try{if(e.length>0){let{rows:o}=await sql(t,...e??[]).execute(this.kysely);return {rows:o}}return {rows:(await this.driver.exec(t))[0].rows}}catch(s){throw console.error(s),new Error(`Failed to execute query: ${t}`)}}async close(){this.#e||(this.#e=true,await this.clearSchemaCache(),await this.kysely.destroy(),await this.driver.close());}createMigrator(t){let e=[this.config.baseSchema,t].filter(Boolean).join(`
|
|
267
265
|
|
|
268
|
-
`);return new
|
|
266
|
+
`);return new R(this,e)}};async function et(n={}){return new k(n)}export{k as PgliteConnection,et as createPgliteConnection};
|