viborm 1.2.2 → 1.2.3
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/dist/cli.mjs +1 -1
- package/dist/{client-D291xo5z.mjs → client-B1p6Le_h.mjs} +17 -20
- package/dist/client-B1p6Le_h.mjs.map +1 -0
- package/dist/{client-BKKA2CQj.d.mts → client-GoDZgqdq.d.mts} +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/every-DCY4HV0X.mjs +2 -0
- package/dist/{every-BJLkY4qm.mjs.map → every-DCY4HV0X.mjs.map} +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{libsql-IdshHiw4.mjs → libsql-x0RPVRDS.mjs} +4 -4
- package/dist/{libsql-IdshHiw4.mjs.map → libsql-x0RPVRDS.mjs.map} +1 -1
- package/dist/{memory-DSEeJ7ps.mjs → memory-gv5jLGYm.mjs} +2 -2
- package/dist/{memory-DSEeJ7ps.mjs.map → memory-gv5jLGYm.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +3 -3
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +3 -3
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +3 -3
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/tenant.d.mts +2 -2
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations.d.mts +3 -3
- package/dist/migrations.mjs +1 -1
- package/dist/{mysql-B7VGoX6t.mjs → mysql-B5cqxG99.mjs} +8 -8
- package/dist/{mysql-B7VGoX6t.mjs.map → mysql-B5cqxG99.mjs.map} +1 -1
- package/dist/{object-store-DCxwbkys.d.mts → object-store-Cj8Cnnba.d.mts} +2 -2
- package/dist/{planner-BKHHRpvB.d.mts → planner-DH-K2gSq.d.mts} +4 -0
- package/dist/{postgres-CeSmp2Tj.mjs → postgres-DrXDok0O.mjs} +38 -38
- package/dist/postgres-DrXDok0O.mjs.map +1 -0
- package/dist/version-Bemp-64P.mjs +2 -0
- package/dist/{version-DxmSsAcv.mjs.map → version-Bemp-64P.mjs.map} +1 -1
- package/package.json +1 -1
- package/dist/client-D291xo5z.mjs.map +0 -1
- package/dist/every-BJLkY4qm.mjs +0 -2
- package/dist/postgres-CeSmp2Tj.mjs.map +0 -1
- package/dist/version-DxmSsAcv.mjs +0 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { An as Dialect, Vn as AnyModel } from "./index-BaK35ze2.mjs";
|
|
2
|
-
import { i as ResolveCallback, t as MigrationClient } from "./planner-
|
|
2
|
+
import { i as ResolveCallback, t as MigrationClient } from "./planner-DH-K2gSq.mjs";
|
|
3
3
|
import { i as Sha256, n as MigrationStorageWriter, r as PublishResult } from "./contract-CIIqgFyb.mjs";
|
|
4
|
-
import { B as MigrationCheckInput, V as MigrationDecisionV1 } from "./client-
|
|
4
|
+
import { B as MigrationCheckInput, V as MigrationDecisionV1 } from "./client-GoDZgqdq.mjs";
|
|
5
5
|
|
|
6
6
|
//#region src/adapters/databases/sqlite/storage/datetime.d.ts
|
|
7
7
|
|
|
@@ -33,6 +33,10 @@ interface MigrationLimits {
|
|
|
33
33
|
* `idle_in_transaction_session_timeout` and, on PostgreSQL 14+,
|
|
34
34
|
* `idle_session_timeout`: how long the server keeps a migration session
|
|
35
35
|
* whose client stopped talking — the one that vanished holding the lock.
|
|
36
|
+
* It also bounds the client's own pauses between two statements of a
|
|
37
|
+
* command, so the default (30 s) frees a dead client's lock within half a
|
|
38
|
+
* minute while a loaded client's pause between parts never ends the
|
|
39
|
+
* session (1 s did, before 1.2.3).
|
|
36
40
|
*/
|
|
37
41
|
readonly idleTimeout?: number;
|
|
38
42
|
/** How long the command waits for the migration lock another one holds. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t,n}from"./base-AdXAoy6l.mjs";import{t as r}from"./migrations-DTObIjAm.mjs";import{c as i}from"./registration-preflight-DEjv050M.mjs";import{N as a,g as o,y as s,yt as c}from"./geo-point-codec-lhxH42SK.mjs";import{a as l}from"./datetime-physical-codec-oIhiYZEP.mjs";import{o as u}from"./native-types-veeTk36s.mjs";import{a as d,r as f}from"./physical-6V_LNU3L.mjs";import{
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t,n}from"./base-AdXAoy6l.mjs";import{t as r}from"./migrations-DTObIjAm.mjs";import{c as i}from"./registration-preflight-DEjv050M.mjs";import{N as a,g as o,y as s,yt as c}from"./geo-point-codec-lhxH42SK.mjs";import{a as l}from"./datetime-physical-codec-oIhiYZEP.mjs";import{o as u}from"./native-types-veeTk36s.mjs";import{a as d,r as f}from"./physical-6V_LNU3L.mjs";import{B as p,J as m,M as h,O as g,P as _,b as v,g as y,m as b,ut as x,v as S,x as C,y as w,z as T}from"./client-B1p6Le_h.mjs";import{n as ee,t as E}from"./array-literal-BsbbSLw3.mjs";import{a as D,n as O}from"./identity-CLFhCTZx.mjs";import{N as te}from"./standard-sql-Bk4RZPqJ.mjs";import{a as k,i as A,n as ne,o as j,r as ie}from"./identifier-conversion-GgbwHc2G.mjs";const M=/;\s*$/,N=/-/g;function quoteIdentifier(e){return`"${e.replace(/"/g,`""`)}"`}function quoteLiteral(e){return`'${e.replace(/'/g,`''`)}'`}async function canonicalizeIndexPredicates(e,t,n,r,i){if(n.length===0)return[];let a=i??(async e=>{let t=[];for(let n of e)t.push(await r(n));return t}),deparse=async t=>{let n=[...t.keys()].filter(e=>t[e]!==void 0);if(n.length===0)return t.map(()=>void 0);let r=`viborm_index_predicate_${crypto.randomUUID().replace(N,``)}_`,i=n.map(e=>`${r}${e}`),o=i.map(t=>`${quoteIdentifier(e)}.${quoteIdentifier(t)}`),s=await a([...n.map((e,n)=>`CREATE VIEW ${o[n]} AS ${t[e]}`),`SELECT c.relname AS name, pg_catalog.pg_get_viewdef(c.oid) AS definition FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ${quoteLiteral(e)} AND c.relname IN (${i.map(quoteLiteral).join(`, `)})`,`DROP VIEW ${o.join(`, `)}`]),c=new Map(s[n.length]?.rows.map(e=>[e.name,e.definition]));return t.map((e,t)=>e===void 0?void 0:c.get(`${r}${t}`)??void 0)};return deparse((await deparse(n.map(e=>`SELECT 1 AS c FROM ${t} WHERE ${e}`))).map(e=>e?.replace(M,``)))}const P=/::(?:"(?:[^"]|"")+"|[a-zA-Z_][\w$]*)(?:\.(?:"(?:[^"]|"")+"|[a-zA-Z_][\w$]*))?(?:\s+(?:varying|precision|with time zone|without time zone))?(?:\(\d+(?:,\s*\d+)?\))?(?:\[\])?$/,F=new Set([`pg_catalog`,`information_schema`]),I={supportsVector:[`vector`,`halfvec`,`sparsevec`],geoPoint:[`geometry`,`geography`]};function admittedExtensionTypes(e){let t=e?.adapter;return new Set([...t?.capabilities.supportsVector?I.supportsVector:[],...t?.geoPoint?I.geoPoint:[]])}const L=`
|
|
2
2
|
SELECT tables.table_name, tables.table_name AS name, relation.relkind AS relation_kind, relation.relispartition AS is_partition
|
|
3
3
|
FROM information_schema.tables tables
|
|
4
4
|
JOIN pg_catalog.pg_class relation
|
|
@@ -18,8 +18,8 @@ WHERE tables.table_schema = $1
|
|
|
18
18
|
AND dependency.refclassid = 'pg_catalog.pg_extension'::pg_catalog.regclass
|
|
19
19
|
AND dependency.deptype = 'e'
|
|
20
20
|
)
|
|
21
|
-
`,
|
|
22
|
-
`,
|
|
21
|
+
`,R=`${L}ORDER BY tables.table_name;
|
|
22
|
+
`,z=`
|
|
23
23
|
SELECT
|
|
24
24
|
c.table_name,
|
|
25
25
|
c.column_name,
|
|
@@ -72,8 +72,8 @@ WHERE c.table_schema = $1
|
|
|
72
72
|
AND relation_dependency.refclassid = 'pg_catalog.pg_extension'::pg_catalog.regclass
|
|
73
73
|
AND relation_dependency.deptype = 'e'
|
|
74
74
|
)
|
|
75
|
-
`,
|
|
76
|
-
`,
|
|
75
|
+
`,ae=`${z}ORDER BY c.table_name, c.ordinal_position;
|
|
76
|
+
`,B=`
|
|
77
77
|
SELECT
|
|
78
78
|
tc.table_name,
|
|
79
79
|
tc.constraint_name,
|
|
@@ -85,7 +85,7 @@ JOIN information_schema.key_column_usage kcu
|
|
|
85
85
|
AND tc.table_schema = kcu.table_schema
|
|
86
86
|
WHERE tc.table_schema = $1
|
|
87
87
|
AND tc.constraint_type = 'PRIMARY KEY'
|
|
88
|
-
`,
|
|
88
|
+
`,V=`${B}ORDER BY tc.table_name, kcu.ordinal_position;
|
|
89
89
|
`,indexesSource=e=>`
|
|
90
90
|
SELECT
|
|
91
91
|
t.relname AS table_name,
|
|
@@ -113,7 +113,7 @@ WHERE n.nspname = $1
|
|
|
113
113
|
AND NOT ix.indisprimary
|
|
114
114
|
AND c.oid IS NULL
|
|
115
115
|
AND t.relkind = 'r'
|
|
116
|
-
`,
|
|
116
|
+
`,H=`
|
|
117
117
|
SELECT
|
|
118
118
|
owner.relname AS table_name,
|
|
119
119
|
con.conname AS constraint_name,
|
|
@@ -151,8 +151,8 @@ JOIN pg_catalog.pg_attribute referenced_att
|
|
|
151
151
|
WHERE con.contype = 'f'
|
|
152
152
|
AND owner_ns.nspname = $1
|
|
153
153
|
AND referenced_ns.nspname = $1
|
|
154
|
-
`,
|
|
155
|
-
`,
|
|
154
|
+
`,U=`${H}ORDER BY owner.relname, con.conname, local.ordinality;
|
|
155
|
+
`,W=`
|
|
156
156
|
SELECT
|
|
157
157
|
con.conname AS constraint_name,
|
|
158
158
|
owner_ns.nspname AS owning_schema,
|
|
@@ -166,8 +166,8 @@ JOIN pg_catalog.pg_class referenced ON referenced.oid = con.confrelid
|
|
|
166
166
|
JOIN pg_catalog.pg_namespace referenced_ns ON referenced_ns.oid = referenced.relnamespace
|
|
167
167
|
WHERE con.contype = 'f'
|
|
168
168
|
AND (owner_ns.nspname = $1) <> (referenced_ns.nspname = $1)
|
|
169
|
-
`,
|
|
170
|
-
`,
|
|
169
|
+
`,G=`${W}ORDER BY owner_ns.nspname, owner.relname, con.conname;
|
|
170
|
+
`,K=`
|
|
171
171
|
SELECT
|
|
172
172
|
tc.table_name,
|
|
173
173
|
tc.constraint_name,
|
|
@@ -179,8 +179,8 @@ JOIN information_schema.key_column_usage kcu
|
|
|
179
179
|
AND tc.table_schema = kcu.table_schema
|
|
180
180
|
WHERE tc.table_schema = $1
|
|
181
181
|
AND tc.constraint_type = 'UNIQUE'
|
|
182
|
-
`,
|
|
183
|
-
`,
|
|
182
|
+
`,q=`${K}ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position;
|
|
183
|
+
`,J=`
|
|
184
184
|
SELECT
|
|
185
185
|
t.typname AS enum_name,
|
|
186
186
|
e.enumlabel AS enum_value,
|
|
@@ -189,38 +189,38 @@ FROM pg_type t
|
|
|
189
189
|
JOIN pg_enum e ON t.oid = e.enumtypid
|
|
190
190
|
JOIN pg_namespace n ON n.oid = t.typnamespace
|
|
191
191
|
WHERE n.nspname = $1
|
|
192
|
-
`,
|
|
193
|
-
`;function baseTypeName(e){return e.startsWith(`_`)?e.slice(1):e}function stripExtensionSchema(e,t){for(let n of[`${t}.`,`"${t.replaceAll(`"`,`""`)}".`])if(e.startsWith(n))return e.slice(n.length);return e}function refuseUnrepresentableType(e,t){throw new r(`Column "${e.table_name}"."${e.column_name}" has type "${e.udt_schema}"."${baseTypeName(e.udt_name)}", which lives in another schema and no installed extension owns it. VibORM manages one schema ("${t.namespace}") and cannot represent that type in a snapshot or regenerate it as DDL.`,n.FEATURE_NOT_SUPPORTED,{meta:{table:e.table_name,column:e.column_name,type:baseTypeName(e.udt_name),feature:`external-type`}})}function formatColumnType(e,t){let i=baseTypeName(e.udt_name);if(e.type_extension===`postgis`&&(i===`geometry`||i===`geography`)&&!t.admittedExtensionTypes.has(i))throw new r(`Column "${e.table_name}"."${e.column_name}" uses PostGIS ${i}, but this PostgreSQL adapter has no GeoPoint protocol. Migration introspection refuses to erase its subtype and SRID into a bare extension type; construct the driver with \`postgis: true\` or use a client that does not manage this estate.`,n.DRIVER_NOT_SUPPORTED,{meta:{dialect:`postgresql`,table:e.table_name,column:e.column_name,type:i,feature:`GeoPoint`}});if(e.type_extension!==null&&e.type_extension_schema!==null&&t.admittedExtensionTypes.has(i))return stripExtensionSchema(e.formatted_type,e.type_extension_schema);e.type_extension===null&&e.udt_schema!==t.namespace&&!
|
|
194
|
-
`),l=await read(`foreign keys`,
|
|
192
|
+
`,oe=`${J}ORDER BY t.typname, e.enumsortorder;
|
|
193
|
+
`;function baseTypeName(e){return e.startsWith(`_`)?e.slice(1):e}function stripExtensionSchema(e,t){for(let n of[`${t}.`,`"${t.replaceAll(`"`,`""`)}".`])if(e.startsWith(n))return e.slice(n.length);return e}function refuseUnrepresentableType(e,t){throw new r(`Column "${e.table_name}"."${e.column_name}" has type "${e.udt_schema}"."${baseTypeName(e.udt_name)}", which lives in another schema and no installed extension owns it. VibORM manages one schema ("${t.namespace}") and cannot represent that type in a snapshot or regenerate it as DDL.`,n.FEATURE_NOT_SUPPORTED,{meta:{table:e.table_name,column:e.column_name,type:baseTypeName(e.udt_name),feature:`external-type`}})}function formatColumnType(e,t){let i=baseTypeName(e.udt_name);if(e.type_extension===`postgis`&&(i===`geometry`||i===`geography`)&&!t.admittedExtensionTypes.has(i))throw new r(`Column "${e.table_name}"."${e.column_name}" uses PostGIS ${i}, but this PostgreSQL adapter has no GeoPoint protocol. Migration introspection refuses to erase its subtype and SRID into a bare extension type; construct the driver with \`postgis: true\` or use a client that does not manage this estate.`,n.DRIVER_NOT_SUPPORTED,{meta:{dialect:`postgresql`,table:e.table_name,column:e.column_name,type:i,feature:`GeoPoint`}});if(e.type_extension!==null&&e.type_extension_schema!==null&&t.admittedExtensionTypes.has(i))return stripExtensionSchema(e.formatted_type,e.type_extension_schema);e.type_extension===null&&e.udt_schema!==t.namespace&&!F.has(e.udt_schema)&&refuseUnrepresentableType(e,t);let a=baseTypeName(e.udt_name),o=e.udt_name.startsWith(`_`)?`${a}[]`:a;return F.has(e.udt_schema)?e.formatted_type:o}function readDecimalDomain(e){if(e.data_type===`numeric`&&e.numeric_precision!==null)return requireDecimalDomain(e,e.numeric_precision,e.numeric_scale??0);if(e.udt_name!==`_numeric`)return;let t=se.exec(e.formatted_type);if(t)return requireDecimalDomain(e,t[1],t[2])}const se=/^numeric\((-?\d+),(-?\d+)\)\[\]$/;function requireDecimalDomain(e,t,i){let o=a(t,i,`pg`);if(o!==void 0)return o;throw new r(`PostgreSQL reported column "${e.table_name}"."${e.column_name}" as NUMERIC(${String(t)},${String(i)}), outside VibORM's fixed-decimal domain. Migration introspection is refused rather than publishing an invalid descriptor.`,n.MIGRATION_INVALID_STATE,{meta:{dialect:`postgresql`,table:e.table_name,column:e.column_name,type:`invalid-catalog-decimal-domain`}})}function isAutoIncrement(e){return e?e.includes(`nextval(`)||e.includes(`_seq'::regclass)`):!1}function terminalCastSpellings(t,n){let r=e(e=>`"${e.replaceAll(`"`,`""`)}"`,`quoted`),i=[``,`${t}.`,`${r(t)}.`],a=[n,r(n)],o=[];for(let e of i)for(let t of a)for(let n of[``,`[]`])o.push(`::${e}${t}${n}`);return o.sort((e,t)=>t.length-e.length)}function stripManagedEnumCast(e,t,n,r){let i=baseTypeName(t.udt_name);if(t.udt_schema!==n.namespace||!r.has(i))return e;for(let n of terminalCastSpellings(t.udt_schema,i))if(e.endsWith(n))return e.slice(0,-n.length);return e}function cleanDefault(e,t,n){let r=e.column_default;if(r&&!isAutoIncrement(r))return renderDecimalDefault(stripManagedEnumCast(r,e,t,n).replace(P,``).trim(),readDecimalDomain(e))}function renderDecimalDefault(e,t){if(t===void 0)return e;let n=o(e.startsWith(`'`)&&e.endsWith(`'`)&&e.length>1?e.slice(1,-1):e);return n===void 0?e:s(`pg`,n,t)}function assertNoCrossSchemaForeignKeys(e,t){let i=e.find(e=>t.tables===void 0||e.owning_schema===t.namespace&&t.tables.includes(e.owning_table)||e.referenced_schema===t.namespace&&t.tables.includes(e.referenced_table));if(!i)return;let a=i.owning_schema===t.namespace?`out of`:`into`;throw new r(`Foreign key "${i.constraint_name}" points ${a} the migration estate: "${i.owning_schema}"."${i.owning_table}" references "${i.referenced_schema}"."${i.referenced_table}". VibORM manages one schema ("${t.namespace}") per estate, so a constraint with one side outside it is an unsupported migration topology`+(e.length>1?` (${e.length} such constraints).`:`.`),n.FEATURE_NOT_SUPPORTED,{meta:{constraint:i.constraint_name,table:i.owning_table,relation:i.referenced_table,feature:`cross-schema-foreign-key`}})}async function introspectPostgresSchema(e,t){let i=[t.namespace],read=async(t,n,r=i)=>{try{return await e(n,r)}catch(e){throw y(t,e),e}},a=await read(`tables`,R),o=await read(`columns`,ae),s=await read(`primary keys`,V),c=await read(`indexes`,`${indexesSource((await read(`nulls not distinct`,`SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_attribute WHERE attrelid = 'pg_catalog.pg_index'::pg_catalog.regclass AND attname = 'indnullsnotdistinct' AND NOT attisdropped) AS present`,[])).rows[0]?.present===!0?`ix.indnullsnotdistinct`:`false`)}ORDER BY t.relname, i.relname, array_position(ix.indkey, a.attnum);
|
|
194
|
+
`),l=await read(`foreign keys`,U),u=await read(`cross-schema foreign keys`,G),d=await read(`unique constraints`,q),f=await read(`enums`,oe);assertNoCrossSchemaForeignKeys(u.rows,t);let p=A(o.rows,e=>e.table_name),m=A(s.rows,e=>e.table_name),h=k(c.rows,e=>e.table_name,e=>e.index_name),g=k(l.rows,e=>e.table_name,e=>e.constraint_name),_=k(d.rows,e=>e.table_name,e=>e.constraint_name),v=A(f.rows,e=>e.enum_name),b=new Set(v.keys()),x=[];for(let e of a.rows){let i=e.table_name,a=t.tables===void 0||t.tables.includes(i);if(a&&(e.relation_kind===`p`||e.is_partition===!0))throw new r(`PostgreSQL table "${i}" is partitioned or a partition. Synchronization refuses before effects because its physical definition cannot be represented.`,n.MIGRATION_INVALID_STATE,{meta:{table:i,feature:`partitioned table`}});let o=(p.get(i)??[]).find(e=>e.generated_kind!==void 0&&e.generated_kind!==``);if(a&&o)throw new r(`PostgreSQL column "${i}.${o.column_name}" is generated. Synchronization refuses before effects because its expression cannot be represented.`,n.MIGRATION_INVALID_STATE,{meta:{table:i,column:o.column_name,feature:`generated column`}});let s=(p.get(i)||[]).map(e=>({name:e.column_name,type:t.tables!==void 0&&!t.tables.includes(i)?e.udt_name.startsWith(`_`)?`${baseTypeName(e.udt_name)}[]`:e.udt_name:formatColumnType(e,t),nullable:e.is_nullable===`YES`,default:t.tables!==void 0&&!t.tables.includes(i)?void 0:cleanDefault(e,t,b),autoIncrement:isAutoIncrement(e.column_default),decimal:t.tables!==void 0&&!t.tables.includes(i)?void 0:readDecimalDomain(e)})),c,l=m.get(i);if(l&&l.length>0){l.sort((e,t)=>e.ordinal_position-t.ordinal_position);let e=l[0];e&&(c={columns:l.map(e=>e.column_name),name:e.constraint_name})}let u=[],d=h.get(i);if(d)for(let[e,a]of d){a.sort((e,t)=>e.ordinal_position-t.ordinal_position);let o=a[0];if(o){let s=o.index_type,c=t.tables===void 0||t.tables.includes(i);if(c&&o.is_valid===!1)throw new r(`PostgreSQL index "${i}.${e}" is INVALID: a CREATE INDEX CONCURRENTLY or REINDEX CONCURRENTLY build of it was interrupted or is still running, and PostgreSQL never reads through it. status() lists it; resolve() repairs it when the unfinished migration attempt's own CONCURRENTLY statement named it, otherwise drop it with DROP INDEX CONCURRENTLY or rebuild it with REINDEX INDEX CONCURRENTLY.`,n.MIGRATION_INVALID_INDEX,{meta:{table:i,indexName:e}});if(c&&(o.unsupported_structure!==!1||s!==`btree`&&s!==`hash`&&s!==`gin`&&s!==`gist`))throw new r(`PostgreSQL index "${i}.${e}" has physical method/order/expression/include/opclass/collation semantics that this index declaration cannot represent. Synchronization refuses before effects and preserves the index. Manage its table outside this synchronization scope until a faithful declaration is available.`,n.FEATURE_NOT_SUPPORTED,{meta:{table:i,indexName:e}});if(s!==`btree`&&s!==`hash`&&s!==`gin`&&s!==`gist`||a.some(e=>e.column_name===null))continue;u.push({name:e,columns:a.flatMap(e=>e.column_name===null?[]:[e.column_name]),unique:o.is_unique,type:s,where:o.filter_condition||void 0})}}let f=[],v=g.get(i);if(v)for(let[e,t]of v){t.sort((e,t)=>e.ordinal_position-t.ordinal_position);let n=t[0];n&&f.push({name:e,columns:t.map(e=>e.column_name),referencedTable:n.foreign_table_name,referencedColumns:t.map(e=>e.foreign_column_name),onDelete:j(n.delete_rule),onUpdate:j(n.update_rule)})}let y=[],S=_.get(i);if(S)for(let[e,t]of S)t.sort((e,t)=>e.ordinal_position-t.ordinal_position),y.push({name:e,columns:t.map(e=>e.column_name)});x.push({name:i,columns:s,primaryKey:c,indexes:u,foreignKeys:f,uniqueConstraints:y})}let S=[];for(let[e,t]of v)t.sort((e,t)=>e.sort_order-t.sort_order),S.push({name:e,values:t.map(e=>e.enum_value)});return{tables:x,enums:S.length>0?S:void 0}}const re=e=>`E'${e.replaceAll(`\\`,`\\\\`).replaceAll(`'`,`''`)}'`,Y=`[\\t\\n\\v\\f\\r \xA0 - \u2028\u2029 ]`,trim=e=>`regexp_replace(${e}, ${re(`^${Y}+|${Y}+$`)}, '', 'g')`,ce=[[`${Y}+`,` `],[`${Y}*,${Y}*`,`,`],[String.raw`${Y}+\[\]`,`[]`],[String.raw`\ycharacter varying\y`,`varchar`],[String.raw`\ycharacter\y`,`char`],[String.raw`\ybit varying\y`,`varbit`],[String.raw`\ytimestamptz(\([0-9]+\))?`,String.raw`timestamp\1 with time zone`],[String.raw`\ytimetz(\([0-9]+\))?`,String.raw`time\1 with time zone`],[String.raw`\y(timestamp|time)(\([0-9]+\))? without time zone`,String.raw`\1\2`],[String.raw`\yint4\y`,`integer`],[String.raw`\yint8\y`,`bigint`],[String.raw`\yint2\y`,`smallint`],[String.raw`\yfloat4\y`,`real`],[String.raw`\yfloat8\y`,`double precision`],[String.raw`\ybool\y`,`boolean`]],normalizeType=e=>ce.reduce((e,[t,n])=>`regexp_replace(${e}, ${re(t)}, ${re(n)}, 'g')`,`lower(${trim(e)} COLLATE "C")`),X=`(?:"(?:[^"]|"")+"|[a-zA-Z_][a-zA-Z0-9_$]*)`,le=String.raw`::${X}(?:\.${X})?(?:${Y}+(?:varying|precision|with time zone|without time zone))?(?:\([0-9]+(?:,${Y}*[0-9]+)?\))?(?:\[\])?$`,ue=String.raw`^(?:now\(\) at time zone 'utc'|timezone\(${Y}*'utc'${Y}*,${Y}*now\(\)${Y}*\))$`,de=String.raw`^timezone\(${Y}*'utc'${Y}*,${Y}*current_time(?:\(3\))?${Y}*\)$`,fe=String.raw`^[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:e[+-]?[0-9]+)?$`,quoted=e=>`(left(${e}, 1) = '''' AND right(${e}, 1) = '''')`,inner=e=>`CASE WHEN length(${e}) >= 2 THEN substr(${e}, 2, length(${e}) - 2) ELSE '' END`;function stripParentheses(e){let t=`regexp_replace(${inner(`regexp_replace(${e}, ${re(`'(?:[^']|'')*'|"(?:[^"]|"")*"`)}, 'q', 'g')`)}, '[^()]', '', 'g')`;for(let e=0;e<8;e+=1)t=`replace(${t}, '()', '')`;return`(SELECT CASE WHEN ${e} IS NULL OR NOT (left(${e}, 1) = '(' AND right(${e}, 1) = ')') THEN ${e} WHEN reduced = '' THEN ${trim(inner(e))} WHEN reduced ~ ${re(String.raw`^\)*\(*$`)} THEN ${e} END FROM (SELECT ${t} AS reduced OFFSET 0) parentheses)`}const pe=`(SELECT CASE
|
|
195
195
|
WHEN digits IS NULL THEN NULL
|
|
196
196
|
WHEN whole = '' AND fraction = '' THEN '0'
|
|
197
197
|
WHEN length(whole) <= 21 AND length(rtrim(ltrim(whole || fraction, '0'), '0')) <= 15 AND (whole <> '' OR length(fraction) - length(ltrim(fraction, '0')) <= 5)
|
|
198
198
|
THEN CASE WHEN digits[1] = '-' THEN '-' ELSE '' END || coalesce(nullif(whole, ''), '0') || CASE WHEN fraction = '' THEN '' ELSE '.' || fraction END
|
|
199
|
-
END FROM (SELECT digits, ltrim(digits[2], '0') AS whole, rtrim(coalesce(digits[3], ''), '0') AS fraction FROM (SELECT regexp_match(unquoted, ${re(String.raw`^([+-]?)([0-9]*)(?:\.([0-9]*))?$`)}) AS digits) parsed) parts)`,
|
|
199
|
+
END FROM (SELECT digits, ltrim(digits[2], '0') AS whole, rtrim(coalesce(digits[3], ''), '0') AS fraction FROM (SELECT regexp_match(unquoted, ${re(String.raw`^([+-]?)([0-9]*)(?:\.([0-9]*))?$`)}) AS digits) parsed) parts)`,me=`CASE
|
|
200
200
|
WHEN spelling IS NULL OR strpos(spelling, chr(8490)) > 0 THEN NULL
|
|
201
201
|
WHEN normalized = 'null' THEN 'null'
|
|
202
|
-
WHEN clock ~ ${re(
|
|
202
|
+
WHEN clock ~ ${re(ue)} THEN to_json('now() at time zone ''utc'''::text)::text
|
|
203
203
|
WHEN clock ~ '^date_trunc[(]' THEN NULL
|
|
204
|
-
WHEN clock ~ ${re(
|
|
204
|
+
WHEN clock ~ ${re(de)} THEN to_json(CASE WHEN strpos(clock, 'current_time(3)') > 0 THEN 'timezone(''utc'',current_time(3))' ELSE 'timezone(''utc'',current_time)' END)::text
|
|
205
205
|
WHEN normalized IN ('current_timestamp', 'now()') THEN '"now()"'
|
|
206
206
|
WHEN ntype = 'boolean' AND normalized IN ('true', '''t''', '1') THEN '"true"'
|
|
207
207
|
WHEN ntype = 'boolean' AND normalized IN ('false', '''f''', '0') THEN '"false"'
|
|
208
208
|
WHEN normalized ~ ${re(String.raw`^[a-z_][a-z0-9_]*\(\)$`)} THEN to_json(normalized)::text
|
|
209
209
|
WHEN ${quoted(`spelling`)} AND right(ntype, 2) = '[]' THEN CASE WHEN literal = '{}' THEN '"[]"' END
|
|
210
210
|
WHEN ${quoted(`spelling`)} AND ntype IN ('json', 'jsonb') THEN CASE WHEN literal IN ('{}', '[]', 'null', 'true', 'false') THEN to_json(literal)::text END
|
|
211
|
-
WHEN ntype ~ '^(integer|bigint|smallint|real|double precision|float|int|tinyint)' AND unquoted ~ ${re(
|
|
212
|
-
THEN to_json(CASE WHEN ntype ~ '^(integer|bigint|smallint|int|tinyint)' AND unquoted ~ '^[-+]?[0-9]+$' THEN (SELECT CASE WHEN digits[1] = '-' AND digits[2] <> '0' THEN '-' || digits[2] ELSE digits[2] END FROM (SELECT regexp_match(unquoted, '^([-+]?)0*([0-9]+)\$') AS digits) parsed) ELSE ${
|
|
211
|
+
WHEN ntype ~ '^(integer|bigint|smallint|real|double precision|float|int|tinyint)' AND unquoted ~ ${re(fe)}
|
|
212
|
+
THEN to_json(CASE WHEN ntype ~ '^(integer|bigint|smallint|int|tinyint)' AND unquoted ~ '^[-+]?[0-9]+$' THEN (SELECT CASE WHEN digits[1] = '-' AND digits[2] <> '0' THEN '-' || digits[2] ELSE digits[2] END FROM (SELECT regexp_match(unquoted, '^([-+]?)0*([0-9]+)\$') AS digits) parsed) ELSE ${pe} END)::text
|
|
213
213
|
WHEN ntype ~ '^(timestamp|time|date)' AND ${quoted(`spelling`)} THEN NULL
|
|
214
214
|
ELSE to_json(spelling)::text
|
|
215
|
-
END`,
|
|
216
|
-
tbl AS (${
|
|
217
|
-
col AS (${
|
|
218
|
-
pk AS (${
|
|
215
|
+
END`,he=`WITH
|
|
216
|
+
tbl AS (${L}),
|
|
217
|
+
col AS (${z}),
|
|
218
|
+
pk AS (${B}),
|
|
219
219
|
idx AS (${indexesSource(`strpos(pg_catalog.pg_get_indexdef(ix.indexrelid), ' NULLS NOT DISTINCT') > 0`)}),
|
|
220
|
-
fk AS (${
|
|
221
|
-
xfk AS (${
|
|
222
|
-
uq AS (${
|
|
223
|
-
en AS (${
|
|
220
|
+
fk AS (${H}),
|
|
221
|
+
xfk AS (${W}),
|
|
222
|
+
uq AS (${K}),
|
|
223
|
+
en AS (${J}),
|
|
224
224
|
scope AS (
|
|
225
225
|
SELECT table_name::text AS table_name,
|
|
226
226
|
($4::text[] IS NULL OR table_name::text = ANY ($4::text[])) AS selected,
|
|
@@ -265,7 +265,7 @@ columns AS (
|
|
|
265
265
|
WHERE c.udt_schema::text = $1::text AND b.base IN (SELECT enum_name::text FROM en) AND right(c.column_default, length(cast_text)) = cast_text
|
|
266
266
|
ORDER BY length(cast_text) DESC LIMIT 1
|
|
267
267
|
) e ON true
|
|
268
|
-
CROSS JOIN LATERAL (SELECT ${trim(`regexp_replace(coalesce(e.stripped, c.column_default), ${re(
|
|
268
|
+
CROSS JOIN LATERAL (SELECT ${trim(`regexp_replace(coalesce(e.stripped, c.column_default), ${re(le)}, '')`)} AS cleaned OFFSET 0) d
|
|
269
269
|
CROSS JOIN LATERAL (SELECT CASE WHEN dd.precision IS NULL OR NOT dd.valid OR NOT u ~ '^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$' THEN d.cleaned ELSE (
|
|
270
270
|
SELECT CASE WHEN dd.scale = 0 THEN CASE WHEN strpos(canonical, '.') = 0 THEN canonical ELSE left(canonical, strpos(canonical, '.') - 1) END
|
|
271
271
|
WHEN strpos(canonical, '.') = 0 THEN canonical || '.' || repeat('0', dd.scale::int)
|
|
@@ -282,7 +282,7 @@ columns AS (
|
|
|
282
282
|
replace(replace(lower(spelling COLLATE "C"), '::text', ''), 'current_timestamp', 'now()') AS clock,
|
|
283
283
|
replace(${inner(`spelling`)}, '''''', '''') AS literal,
|
|
284
284
|
CASE WHEN ${quoted(`lower(spelling COLLATE "C")`)} THEN ${inner(`lower(spelling COLLATE "C")`)} ELSE lower(spelling COLLATE "C") END AS unquoted OFFSET 0) v
|
|
285
|
-
CROSS JOIN LATERAL (SELECT ${
|
|
285
|
+
CROSS JOIN LATERAL (SELECT ${me} AS json OFFSET 0) f
|
|
286
286
|
),
|
|
287
287
|
indexes AS (
|
|
288
288
|
SELECT s.table_name, s.selected, s.kept, i.index_name::text AS name,
|
|
@@ -362,8 +362,8 @@ SELECT CASE WHEN
|
|
|
362
362
|
AND NOT EXISTS (SELECT 1 FROM columns c WHERE NOT c.selected AND c.kept AND ${elementType(`c.type`)} IN (SELECT name FROM enums))
|
|
363
363
|
AND NOT EXISTS (SELECT 1 FROM xfk WHERE $4::text[] IS NULL OR (owning_schema::text = $1::text AND owning_table::text = ANY ($4::text[])) OR (referenced_schema::text = $1::text AND referenced_table::text = ANY ($4::text[])))
|
|
364
364
|
AND NOT projection.json ~ ${re(`[-\\U0010FFFF]`)}
|
|
365
|
-
THEN encode(sha256(convert_to('${
|
|
366
|
-
FROM projection`;function elementType(e){return`regexp_replace(${e}, ${re(String.raw`\[\]$`)}, '')`}function managedOrControl(e){return`(${e}::text = ANY ($4::text[]) OR ${e}::text IN ($2::text, $3::text))`}function referentialAction(e){return`CASE ${e} WHEN 'CASCADE' THEN 'cascade' WHEN 'SET NULL' THEN 'setNull' WHEN 'RESTRICT' THEN 'restrict' WHEN 'SET DEFAULT' THEN 'setDefault' ELSE 'noAction' END`}function postgresCatalogDigestQuery(e,t,n=!1){let r=e.target.tables;return{sql:
|
|
365
|
+
THEN encode(sha256(convert_to('${O.snapshot}', 'UTF8') || decode('00', 'hex') || convert_to(projection.json, 'UTF8')), 'hex') END AS digest
|
|
366
|
+
FROM projection`;function elementType(e){return`regexp_replace(${e}, ${re(String.raw`\[\]$`)}, '')`}function managedOrControl(e){return`(${e}::text = ANY ($4::text[]) OR ${e}::text IN ($2::text, $3::text))`}function referentialAction(e){return`CASE ${e} WHEN 'CASCADE' THEN 'cascade' WHEN 'SET NULL' THEN 'setNull' WHEN 'RESTRICT' THEN 'restrict' WHEN 'SET DEFAULT' THEN 'setDefault' ELSE 'noAction' END`}function postgresCatalogDigestQuery(e,t,n=!1){let r=e.target.tables;return{sql:he,parameters:[C(e),t.state,t.log,r===void 0?null:E(r),E([...admittedExtensionTypes(e.executionDriver)]),n]}}async function postgresCatalogDigest(e,t,n){let{sql:r,parameters:i}=postgresCatalogDigestQuery(t,n);return readDigest((await e._executeRaw(r,i)).rows[0]?.digest)}function readDigest(e){return D(e)?e:void 0}const ge=/^(vector|halfvec|sparsevec)(?:\(\d+\))?(?:\[\])?$/i,Z=/\((\d+)\)/,_e=/\brows=(\d+)/,Q=new WeakMap;async function serverIsNeki(e,t){let n=Q.get(e);if(n!==void 0)return n;let{rows:r}=await t(`SELECT pg_catalog.version() LIKE '%(Neki)%' AS neki`),i=r[0]?.neki===!0;return Q.set(e,i),i}function nekiRefusal(e,{kind:t,change:i,statement:a},o){return new r(`On PlanetScale's Neki, ${t===`rows`?`a statement does not see a schema change made earlier in its own transaction`:`a statement cannot retype, rename or drop a column of a table created or renamed earlier in its own transaction (NK316)`}, and ${o?`statement ${a.position+1} of this migration runs ${a.words} after ${i.words} in one dispatch, which no commit can divide. Nothing ran. Put them in separate statements of the migration (one sql fragment each), or in states of their own.`:`this migration runs statement ${a.position+1} (${a.words}) after statement ${i.position+1} (${i.words}). Nothing ran. apply() commits between them; this command runs them in one transaction. Put the later statement in a state of its own after the earlier one, and apply up to the earlier one first (apply({ to })).`}`,n.MIGRATION_UNSUPPORTED_PROVIDER,{meta:{dialect:e,feature:o?`dependent statements in one dispatch`:t===`rows`?`data after schema change in one transaction`:`column change of a new relation in one transaction`}})}function snapshotUsesGeoPoint(e){let t=h.point.toLowerCase().replace(/\s+/g,``);return e.tables.some(e=>e.columns.some(e=>e.type.toLowerCase().replace(/\s+/g,``)===t))}const ve=/^'(.*)'$/s,storesEnum=(e,t)=>e.type===t||e.type===`${t}[]`;function enumDefaultLabels(e,t){if(!storesEnum(e,t))return[];let n=e.default?.match(ve)?.[1]?.replaceAll(`''`,`'`);return n===void 0?[]:e.type===t?[n]:ee(n)??[]}const $=/[\w$]/;function mayName(e,t){let n=e.toLowerCase(),r=t.replaceAll(`"`,`""`).toLowerCase();for(let e=n.indexOf(r);e>=0;e=n.indexOf(r,e+1))if(!($.test(n[e-1]??``)||$.test(n[e+r.length]??``)))return!0;return!1}function readsAddedValue(e,t,n,r){let defaultNamesAdded=n=>{let r=enumDefaultLabels(n,e);return t.some(e=>r.includes(e))},i=new Set([e]),addEnumColumns=t=>{for(let n of t)storesEnum(n,e)&&i.add(n.name)};for(let e of n)addEnumColumns(e.columns);let predicateNamesEnum=({where:e})=>e!==void 0&&[...i].some(t=>mayName(e,t));for(let t of r)switch(t.type){case`createTable`:if(addEnumColumns(t.table.columns),t.table.columns.some(defaultNamesAdded)||t.table.indexes.some(predicateNamesEnum))return!0;break;case`addColumn`:if(defaultNamesAdded(t.column))return!0;addEnumColumns([t.column]);break;case`alterColumn`:if(defaultNamesAdded(t.to)||storesEnum(t.to,e)&&!storesEnum(t.from,e))return!0;break;case`renameColumn`:i.has(t.from)&&i.add(t.to);break;case`createIndex`:if(predicateNamesEnum(t.index))return!0;break;default:break}return!1}const ye=new class PostgresMigrationDriver extends b{dialect=`postgresql`;driverName=`postgresql`;capabilities={supportsNativeEnums:!0,supportsAddEnumValueInTransaction:!0,supportsIndexTypes:[`btree`,`hash`,`gin`,`gist`],supportsNativeArrays:!0,supportsAddForeignKeyViaAlter:!0,introspectionReadsConstraintNames:!0};estateNamespace(){let e=this.target;return e?.dialect===`postgresql`?e.namespace:void 0}requireEstateNamespace(){let e=this.estateNamespace();if(e===void 0)throw new r("This PostgreSQL migration driver is not bound to an estate, so it has no schema to read the catalog for. Reach the driver through `getMigrationDriver(driver)`, which binds the adapter's namespace, instead of the registered singleton.",n.MIGRATION_INVALID_STATE,{meta:{dialect:this.dialect}});return e}qualify(e){return te(e=>this.escapeIdentifier(e),this.estateNamespace(),e)}tableRef(e){return this.qualify(e)}managedEnumNames(e){let t=new Set;for(let n of e.currentSchema?.enums??[])t.add(n.name);for(let n of e.precedingOperations??[])n.type===`createEnum`&&t.add(n.enumDef.name);return t}renderTypeToken(e,t){let n=e.endsWith(`[]`),r=n?e.slice(0,-2):e;if(!this.managedEnumNames(t).has(r))return e;let i=this.qualify(r);return n?`${i}[]`:i}async introspect(e){return await this.proveNamespaceExists(e),await introspectPostgresSchema(e,{namespace:this.requireEstateNamespace(),tables:this.target?.tables,admittedExtensionTypes:admittedExtensionTypes(this.executionDriver)})}catalogDigestQuery(e,t=!1){return postgresCatalogDigestQuery(this,e,t)}catalogDigest(e,t){return postgresCatalogDigest(e,this,t)}async preflightSchemaRequirements(e,i,a,o=!1){try{let{boundaries:s,first:c,inside:l}=v(a),u=s.length>0&&await serverIsNeki(this,i),d=u?l??(o?void 0:c):void 0;if(d)throw nekiRefusal(this.dialect,d,d===l);let{largeTableRows:f}=this.limits??x,p=f>0?w(a):[],m=[...new Set(p.map(({table:e})=>e))],h=m.length===0?[]:(await i(`SELECT pg_catalog.to_regclass(name)::text AS relation FROM unnest($1::text[]) WITH ORDINALITY AS input(name, position) ORDER BY position`,[E(m)])).rows;for(let[e,{relation:t}]of h.entries()){if(t===null)continue;let a=`EXPLAIN SELECT 1 FROM ${t}`,o=await i(a),s=Object.values(o.rows[0]??{})[0]??``,c=_e.exec(s)?.[1];if(c!==void 0&&Number(c)<=f)continue;let l=m[e],u=[...new Set(p.flatMap(e=>e.table===l?[e.operation]:[]))],d=u.join(` and `),h=u.every(e=>e.endsWith(` validation`))?` Or add the constraint NOT VALID and validate it (VALIDATE CONSTRAINT) in a later migration: neither step blocks writes. generate({ lowLock: true }) does this for foreign keys.`:``;throw new r(`This migration runs a ${d} on ${l}, ${c===void 0?`whose row estimate ${a} did not report (${JSON.stringify(s)}), so limits.largeTableRows (${f}) cannot admit it`:`which the planner estimates at ${c} rows, above limits.largeTableRows (${f})`}. It rewrites or scans the whole table while holding a lock that blocks it, longer than a request should wait. Nothing ran: the schema and data are unchanged. Run it outside the request with a client whose largeTableRows is higher, or 0 for no limit.${h}`,n.MIGRATION_INVALID_STATE,{meta:{table:l,operation:d,feature:`large table rewrite`}})}let g=new Set(e.flatMap(e=>e.tables.flatMap(e=>e.columns.flatMap(e=>ge.exec(e.type)?.[1]?.toLowerCase()??[]))));if(g.size>0&&!this.executionDriver?.adapter.capabilities.supportsVector)throw new r(`This migration requires pgvector support. Construct the PostgreSQL driver with pgvector: true and install the vector extension before applying it. VibORM never installs it.`,n.DRIVER_NOT_SUPPORTED,{meta:{dialect:this.dialect,feature:`vector`}});if(e.some(snapshotUsesGeoPoint)&&!this.executionDriver?.adapter.geoPoint)throw new r("This migration requires PostGIS GeoPoint support, but the bound PostgreSQL adapter has no GeoPoint protocol. Construct the driver with `postgis: true` and ensure PostGIS is installed before applying it.",n.DRIVER_NOT_SUPPORTED,{meta:{dialect:this.dialect,feature:`GeoPoint`}});let _=[...new Set(e.flatMap(e=>e.tables.map(e=>e.name)))];if(_.length>0){let e=(await i(`SELECT relation.relname AS name FROM pg_catalog.pg_class relation JOIN pg_catalog.pg_namespace namespace ON namespace.oid=relation.relnamespace WHERE namespace.nspname=$1 AND relation.relkind IN ('v','m') AND relation.relname=ANY($2::text[])`,[this.requireEstateNamespace(),E(_)])).rows.find(e=>_.includes(e.name));if(e)throw new r(`PostgreSQL relation "${e.name}" is a view or materialized view, but this schema declares a table. Synchronization refuses before effects and preserves the view.`,n.MIGRATION_INVALID_STATE,{meta:{table:e.name,feature:`view`}})}if(g.size>0){let e=await i(`SELECT NOT EXISTS (SELECT 1 FROM unnest($1::text[]) AS required(name) WHERE NOT EXISTS (SELECT 1 FROM pg_catalog.pg_extension AS e JOIN pg_catalog.pg_depend AS d ON d.refobjid=e.oid AND d.refclassid='pg_catalog.pg_extension'::regclass AND d.deptype='e' JOIN pg_catalog.pg_type AS t ON t.oid=d.objid AND d.classid='pg_catalog.pg_type'::regclass WHERE e.extname='vector' AND t.typname=required.name AND pg_catalog.pg_type_is_visible(t.oid))) AS ready`,[E([...g])]);if(e.rows.length!==1||e.rows[0]?.ready!==!0)throw new r(`pgvector preflight did not prove every required visible extension-owned vector type. Install the vector extension before migration effects; VibORM never installs it.`,n.MIGRATION_INVALID_STATE,{meta:{dialect:this.dialect,feature:`vector`}})}if(e.some(e=>(e.enums?.length??0)>0)){let e=await i(`SELECT current_setting('server_version_num') AS version`),t=Number(e.rows[0]?.version);if(!Number.isInteger(t)||t<12e4)throw new r(`PostgreSQL enum migrations require server_version_num >= 120000 for transactional enum safety`,n.MIGRATION_UNSUPPORTED_PROVIDER)}if(!e.some(snapshotUsesGeoPoint))return u;let y;try{y=(await i(`
|
|
367
367
|
WITH postgis AS (
|
|
368
368
|
SELECT oid
|
|
369
369
|
FROM pg_catalog.pg_extension
|
|
@@ -399,17 +399,17 @@ SELECT (
|
|
|
399
399
|
)
|
|
400
400
|
)
|
|
401
401
|
) AS ready
|
|
402
|
-
`)).rows}catch(e){throw new r(`PostGIS GeoPoint preflight could not prove the required extension, types, and functions before migration effects.`,n.MIGRATION_INVALID_STATE,{cause:t(e),meta:{dialect:this.dialect,feature:`GeoPoint
|
|
403
|
-
`)}\n)`];for(let e of n.indexes)i.push(this.generateCreateIndex({type:`createIndex`,tableName:n.name,index:e},t));for(let e of n.foreignKeys)i.push(this.generateAddForeignKey({type:`addForeignKey`,tableName:n.name,fk:e},t));return i}generateDropTable(e,t){return`DROP TABLE ${this.qualify(e.tableName)}`}generateRenameTable(e,t){return`ALTER TABLE ${this.qualify(e.from)} RENAME TO ${this.escapeIdentifier(e.to)}`}renameDerivedNames(e,t){return[...t].map(([t,{kind:n,to:r}])=>n===`constraint`?`ALTER TABLE ${this.qualify(e)} RENAME CONSTRAINT ${this.escapeIdentifier(t)} TO ${this.escapeIdentifier(r)}`:`ALTER ${n===`type`?`TYPE`:`INDEX`} ${this.qualify(t)} RENAME TO ${this.escapeIdentifier(r)}`)}generatedPrimaryKeyName(e,t){return t||
|
|
402
|
+
`)).rows}catch(e){throw new r(`PostGIS GeoPoint preflight could not prove the required extension, types, and functions before migration effects.`,n.MIGRATION_INVALID_STATE,{cause:t(e),meta:{dialect:this.dialect,feature:`GeoPoint`,...S(e)}})}if(y.length!==1||y[0]?.ready!==!0)throw new r(`PostGIS GeoPoint preflight did not prove the required extension, visible types, and exact function signatures. VibORM never installs PostGIS.`,n.MIGRATION_INVALID_STATE,{meta:{dialect:this.dialect,feature:`GeoPoint`}});return u}catch(e){throw e instanceof r?e:new r(`PostgreSQL schema preflight could not prove the required catalog facts before migration effects.`,n.MIGRATION_INVALID_STATE,{cause:t(e),meta:{dialect:this.dialect,feature:`schema catalog`,...S(e)}})}}async proveNamespaceExists(e){let t=this.requireEstateNamespace(),{rows:i}=await e(`SELECT 1 AS present FROM pg_catalog.pg_namespace WHERE nspname = $1`,[t]);if(i.length===0)throw new r(`The configured PostgreSQL schema "${t}" does not exist. VibORM never creates or drops a schema: create it (or fix the configured \`namespace\`) before running migrations.`,n.MIGRATION_INVALID_STATE,{meta:{dialect:this.dialect,driver:this.driverName,namespace:t}})}canonicalizeIndexPredicates(e,t,n,r){return canonicalizeIndexPredicates(this.requireEstateNamespace(),this.qualify(e),t,n,r)}mapScalarType(e,t,n){let r=e[`~`].nativeType,i=n===void 0?void 0:d(n,r,`pg`);if(i)return i.columnType;let a=u(r,`pg`);return a?t.array?`${a.type}[]`:a.type:_({type:t.type,array:t.array,withTimezone:t.withTimezone,dimension:t.dimension,decimal:t.decimal})}finalizeTable(e){return{...e,...e.primaryKey?.name?{primaryKey:{...e.primaryKey,name:g(e.primaryKey.name)}}:{},uniqueConstraints:e.uniqueConstraints.map(e=>({...e,name:g(e.name)})),foreignKeys:e.foreignKeys.map(e=>({...e,name:g(e.name)})),indexes:e.indexes.map(e=>({...e,name:g(e.name),...e.type===`spatial`?{type:`gist`}:{}}))}}getDefaultExpression(e,t){let n=t.hasDefault&&!t.autoGenerate&&!t.decimal&&(t.array||t.type===`datetime`||t.type===`date`)?this.literalDefaultValue(t):void 0;if(t.hasDefault&&!t.autoGenerate&&t.array&&Array.isArray(n)){if(t.decimal)return super.getDefaultExpression(e,t);let r=n.map(e=>(t.type===`datetime`||t.type===`date`)&&typeof e==`string`?l(e):e);return this.escapeValue(E(r))}if(t.hasDefault&&t.default===null)return;if(t.type===`datetime`&&t.autoGenerate?.kind===`now`){let n=this.mapScalarType(e,t).toLowerCase(),r=n.includes(`timestamptz`)||n.includes(`with time zone`)?`CURRENT_TIMESTAMP`:`(CURRENT_TIMESTAMP AT TIME ZONE 'UTC')`;return Number(Z.exec(n)?.[1]??6)>3?`date_trunc('milliseconds', ${r})`:r}if((t.type===`datetime`||t.type===`date`)&&t.autoGenerate===void 0&&t.hasDefault&&typeof n==`string`)return this.escapeValue(l(n));if(t.autoGenerate?.kind===`now`){if(t.type===`date`)return`(CURRENT_TIMESTAMP AT TIME ZONE 'UTC')`;if(t.type===`time`){let n=this.mapScalarType(e,t).toLowerCase();return Number(Z.exec(n)?.[1]??6)>3?`timezone('UTC', CURRENT_TIME(3))`:n.includes(`timetz`)||n.includes(`with time zone`)?`timezone('UTC', CURRENT_TIME)`:`(CURRENT_TIMESTAMP AT TIME ZONE 'UTC')`}}let r=f(t);if(!(r!==void 0&&d(r,e[`~`].nativeType,`pg`)?.representation===`bytes`)&&!(t.autoGenerate?.kind===`uuid`&&!i(t.default)))return super.getDefaultExpression(e,t)}getAutoGenerateExpression(e){switch(e?.kind){case`uuid`:return c(e.prefix)?void 0:`gen_random_uuid()`;case`now`:return`NOW()`;default:return}}getEnumColumnType(e,t,n){return g(`${e}_${t}_enum`)}static SERIAL_TYPE_MAP={integer:`SERIAL`,int4:`SERIAL`,int:`SERIAL`,bigint:`BIGSERIAL`,int8:`BIGSERIAL`,smallint:`SMALLSERIAL`,int2:`SMALLSERIAL`};formatColumnType(e,t){if(e.autoIncrement){let t=e.type.toLowerCase(),i=PostgresMigrationDriver.SERIAL_TYPE_MAP[t];if(!i)throw new r(`PostgreSQL auto-increment (SERIAL) requires an integer type (INTEGER, BIGINT, SMALLINT). Column "${e.name}" has type "${e.type}" which is not compatible with auto-increment.`,n.INVALID_INPUT,{meta:{column:e.name,type:e.type,autoIncrement:!0}});return i}return this.renderTypeToken(e.type,t)}generateCreateTable(e,t){let{table:n}=e,r=n.columns.map(e=>this.generateColumnDef(e,t));if(n.primaryKey){let e=n.primaryKey.columns.map(e=>this.escapeIdentifier(e)).join(`, `),t=`CONSTRAINT ${this.escapeIdentifier(this.generatedPrimaryKeyName(n.name,n.primaryKey.name))} `;r.push(`${t}PRIMARY KEY (${e})`)}for(let e of n.uniqueConstraints){let t=e.columns.map(e=>this.escapeIdentifier(e)).join(`, `);r.push(`CONSTRAINT ${this.escapeIdentifier(e.name)} UNIQUE (${t})`)}let i=[`CREATE TABLE ${this.qualify(n.name)} (\n ${r.join(`,
|
|
403
|
+
`)}\n)`];for(let e of n.indexes)i.push(this.generateCreateIndex({type:`createIndex`,tableName:n.name,index:e},t));for(let e of n.foreignKeys)i.push(this.generateAddForeignKey({type:`addForeignKey`,tableName:n.name,fk:e},t));return i}generateDropTable(e,t){return`DROP TABLE ${this.qualify(e.tableName)}`}generateRenameTable(e,t){return`ALTER TABLE ${this.qualify(e.from)} RENAME TO ${this.escapeIdentifier(e.to)}`}renameDerivedNames(e,t){return[...t].map(([t,{kind:n,to:r}])=>n===`constraint`?`ALTER TABLE ${this.qualify(e)} RENAME CONSTRAINT ${this.escapeIdentifier(t)} TO ${this.escapeIdentifier(r)}`:`ALTER ${n===`type`?`TYPE`:`INDEX`} ${this.qualify(t)} RENAME TO ${this.escapeIdentifier(r)}`)}generatedPrimaryKeyName(e,t){return t||g(`${e}_pkey`)}generateAddColumn(e,t){let n=this.generateColumnDef(e.column,t);return`ALTER TABLE ${this.qualify(e.tableName)} ADD COLUMN ${n}`}generateDropColumn(e,t){return`ALTER TABLE ${this.qualify(e.tableName)} DROP COLUMN ${this.escapeIdentifier(e.columnName)}`}generateRenameColumn(e,t){return`ALTER TABLE ${this.qualify(e.tableName)} RENAME COLUMN ${this.escapeIdentifier(e.from)} TO ${this.escapeIdentifier(e.to)}`}generateAlterColumn(e,t){let{tableName:n,columnName:r,from:i,to:a}=e,o=[],s=this.qualify(n),c=this.escapeIdentifier(r),l=p(i,a);if(l&&a.decimal){let e=this.renderTypeToken(a.type,t),n=this.escapeIdentifier(T(e.endsWith(`[]`)?`list`:`scalar`,a.decimal));o.push(`LOCK TABLE ${s} IN ACCESS EXCLUSIVE MODE`),o.push(`ALTER TABLE ${s} ADD CONSTRAINT ${n} CHECK (${m(c,e)})`)}if(i.type!==a.type){i.default!==void 0&&o.push(`ALTER TABLE ${s} ALTER COLUMN ${c} DROP DEFAULT`);let e=this.renderTypeToken(a.type,t);ne(i.type,e)&&o.push(ie(s,c));let n=i.type.endsWith(`[]`)?i.type.slice(0,-2):i.type,r=this.managedEnumNames(t).has(n)?`::text${i.type.endsWith(`[]`)?`[]`:``}`:``;o.push(`ALTER TABLE ${s} ALTER COLUMN ${c} TYPE ${e} USING ${c}${r}::${e}`)}if(i.nullable!==a.nullable&&(a.nullable?o.push(`ALTER TABLE ${s} ALTER COLUMN ${c} DROP NOT NULL`):o.push(`ALTER TABLE ${s} ALTER COLUMN ${c} SET NOT NULL`)),(i.default!==a.default||i.type!==a.type&&i.default!==void 0)&&(a.default===void 0?o.push(`ALTER TABLE ${s} ALTER COLUMN ${c} DROP DEFAULT`):o.push(`ALTER TABLE ${s} ALTER COLUMN ${c} SET DEFAULT ${a.default}`)),l&&a.decimal){let e=this.renderTypeToken(a.type,t);o.push(`ALTER TABLE ${s} DROP CONSTRAINT ${this.escapeIdentifier(T(e.endsWith(`[]`)?`list`:`scalar`,a.decimal))}`)}return o}generateCreateIndex(e,t){let{tableName:n,index:r}=e,i=r.type===`spatial`?`gist`:r.type;this.validateIndexType(i,r.name);let a=r.unique?`UNIQUE `:``,o=i?`USING ${i} `:``,s=r.columns.map(e=>this.escapeIdentifier(e)).join(`, `),c=r.where?` WHERE ${r.where}`:``;return`CREATE ${a}INDEX${t.lowLock===`add`?` CONCURRENTLY`:``} ${this.escapeIdentifier(r.name)} ON ${this.qualify(n)} ${o}(${s})${c}`}generateDropIndex(e,t){return`DROP INDEX ${this.qualify(e.indexName)}`}generateAddForeignKey(e,t){let{tableName:n,fk:r}=e;if(t.lowLock===`validate`)return`ALTER TABLE ${this.qualify(n)} VALIDATE CONSTRAINT ${this.escapeIdentifier(r.name)}`;let i=r.columns.map(e=>this.escapeIdentifier(e)).join(`, `),a=r.referencedColumns.map(e=>this.escapeIdentifier(e)).join(`, `),o=r.onDelete?` ON DELETE ${this.formatReferentialAction(r.onDelete)}`:``,s=r.onUpdate?` ON UPDATE ${this.formatReferentialAction(r.onUpdate)}`:``,c=t.lowLock===`add`?` NOT VALID`:``;return`ALTER TABLE ${this.qualify(n)} ADD CONSTRAINT ${this.escapeIdentifier(r.name)} FOREIGN KEY (${i}) REFERENCES ${this.qualify(r.referencedTable)} (${a})${o}${s}${c}`}generateDropForeignKey(e,t){return`ALTER TABLE ${this.qualify(e.tableName)} DROP CONSTRAINT ${this.escapeIdentifier(e.fkName)}`}generateAddUniqueConstraint(e,t){let{tableName:n,constraint:r}=e,i=r.columns.map(e=>this.escapeIdentifier(e)).join(`, `);return`ALTER TABLE ${this.qualify(n)} ADD CONSTRAINT ${this.escapeIdentifier(r.name)} UNIQUE (${i})`}generateDropUniqueConstraint(e,t){return`ALTER TABLE ${this.qualify(e.tableName)} DROP CONSTRAINT ${this.escapeIdentifier(e.constraintName)}`}generateAddPrimaryKey(e,t){let{tableName:n,primaryKey:r}=e,i=r.columns.map(e=>this.escapeIdentifier(e)).join(`, `),a=this.escapeIdentifier(this.generatedPrimaryKeyName(n,r.name));return`ALTER TABLE ${this.qualify(n)} ADD CONSTRAINT ${a} PRIMARY KEY (${i})`}generateDropPrimaryKey(e,t){return`ALTER TABLE ${this.qualify(e.tableName)} DROP CONSTRAINT ${this.escapeIdentifier(e.constraintName)}`}generateCreateEnum(e,t){let{enumDef:n}=e,r=n.values.map(e=>this.escapeValue(e)).join(`, `);return`CREATE TYPE ${this.qualify(n.name)} AS ENUM (${r})`}generateDropEnum(e,t){return`DROP TYPE ${this.qualify(e.enumName)}`}generateAcquireLock(e){let{lockWait:t}=this.limits??x;return`WITH RECURSIVE lock_attempt AS (
|
|
404
404
|
SELECT pg_try_advisory_xact_lock(${e}) AS acquired, clock_timestamp() + interval '${t/1e3} seconds' AS deadline
|
|
405
405
|
UNION ALL
|
|
406
406
|
SELECT pg_try_advisory_xact_lock(${e}), previous.deadline
|
|
407
407
|
FROM lock_attempt previous
|
|
408
408
|
CROSS JOIN LATERAL (SELECT pg_sleep(CASE WHEN previous.acquired THEN 0 ELSE 0.05 END)) waiting
|
|
409
409
|
WHERE NOT previous.acquired AND clock_timestamp() < previous.deadline
|
|
410
|
-
) SELECT acquired FROM lock_attempt ORDER BY acquired DESC LIMIT 1`}generateReleaseLock(e){return`SELECT pg_advisory_unlock(${e}) AS released`}generateSessionLock(e){return`SELECT pg_try_advisory_lock(${e}) AS acquired`}generateLockFree(e){return`pg_try_advisory_xact_lock(${e})`}provesLockAcquired(e){let t=e[0];return e.length===1&&typeof t==`object`&&!!t&&Reflect.get(t,`acquired`)===!0}provesLockReleased(e){if(e.length!==1)return!1;let t=e[0];return typeof t!=`object`||!t?!1:Reflect.get(t,`released`)===!0}generateInventoryTables(){return{sql:
|
|
410
|
+
) SELECT acquired FROM lock_attempt ORDER BY acquired DESC LIMIT 1`}generateReleaseLock(e){return`SELECT pg_advisory_unlock(${e}) AS released`}holdsSessionLock(e){return Q.delete(this),serverIsNeki(this,e)}generateSessionLock(e){return`SELECT pg_try_advisory_lock(${e}) AS acquired`}generateLockFree(e){return`pg_try_advisory_xact_lock(${e})`}provesLockAcquired(e){let t=e[0];return e.length===1&&typeof t==`object`&&!!t&&Reflect.get(t,`acquired`)===!0}provesLockReleased(e){if(e.length!==1)return!1;let t=e[0];return typeof t!=`object`||!t?!1:Reflect.get(t,`released`)===!0}generateInventoryTables(){return{sql:R,params:[this.requireEstateNamespace()]}}generateInventoryEnums(){return{sql:`SELECT t.typname AS name
|
|
411
411
|
FROM pg_type t
|
|
412
412
|
JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
|
|
413
413
|
WHERE t.typtype = 'e' AND n.nspname = $1
|
|
414
|
-
ORDER BY t.typname`,params:[this.requireEstateNamespace()]}}generateDropEnumSQL(e){return`DROP TYPE IF EXISTS ${this.qualify(e)}`}generateAlterEnum(e,t){let i={...t,currentSchema:this.schemaAtOperation(t)},{enumName:a,addValues:o=[],removeValues:s,newValues:c,dependentColumns:l}=e,u=[],d=this.qualify(a),f=i.currentSchema?.enums?.find(e=>e.name===a)?.values??[],p=c!==void 0&&f.filter(e=>c.includes(e)).join(`\0`)!==c.filter(e=>f.includes(e)).join(`\0`),m=readsAddedValue(a,o,i.currentSchema?.tables??[],t.followingOperations??[]);if(!(s?.length||p||m)){let e=new Set(f);for(let t of o){let n=c?.slice(c.indexOf(t)+1).find(t=>e.has(t));u.push(`ALTER TYPE ${d} ADD VALUE ${this.escapeValue(t)}${n===void 0?``:` BEFORE ${this.escapeValue(n)}`}`),e.add(t)}return u}if(!c?.length)throw new r(`Cannot alter enum "${a}" without its full destination values`,n.MIGRATION_INVALID_STATE);for(let{tableName:e,columnName:t}of l??[]){let n=i.currentSchema?.tables.find(t=>t.name===e)?.columns.find(e=>e.name===t),r=`${this.qualify(e)} ALTER COLUMN ${this.escapeIdentifier(t)}`;n?.default!==void 0&&u.push(`ALTER TABLE ${r} DROP DEFAULT`);let a=n?.type.endsWith(`[]`)?`text[]`:`text`;u.push(`ALTER TABLE ${r} TYPE ${a} USING ${this.escapeIdentifier(t)}::${a}`)}u.push(...this.buildEnumReplacementUpdates(e,i)),u.push(`DROP TYPE ${d}`),u.push(`CREATE TYPE ${d} AS ENUM (${c.map(e=>this.escapeValue(e)).join(`, `)})`);for(let{tableName:e,columnName:t}of l??[]){let n=i.currentSchema?.tables.find(t=>t.name===e)?.columns.find(e=>e.name===t),r=`${this.qualify(e)} ALTER COLUMN ${this.escapeIdentifier(t)}`,o=n?.type.endsWith(`[]`)?`${d}[]`:d;u.push(`ALTER TABLE ${r} TYPE ${o} USING ${this.escapeIdentifier(t)}::${o}`),n?.default!==void 0&&!enumDefaultLabels(n,a).some(e=>e!==null&&s?.includes(e))&&u.push(`ALTER TABLE ${r} SET DEFAULT ${n.default}`)}return u}enumColumnReplacementUpdates(e,t,n,r){if(!(r.currentSchema?.tables.find(e=>e.name===t)?.columns.find(e=>e.name===n)?.type)?.endsWith(`[]`))return super.enumColumnReplacementUpdates(e,t,n,r);let i=this.enumReplacementCases(e,t,n);if(i.length===0)return[];let a=this.escapeIdentifier(n);return[`UPDATE ${this.qualify(t)} SET ${a} = ARRAY(SELECT CASE value ${i.join(` `)} ELSE value END FROM unnest(${a}) WITH ORDINALITY AS member(value, position) ORDER BY position) WHERE ${a} IS NOT NULL`]}};export{
|
|
415
|
-
//# sourceMappingURL=postgres-
|
|
414
|
+
ORDER BY t.typname`,params:[this.requireEstateNamespace()]}}generateDropEnumSQL(e){return`DROP TYPE IF EXISTS ${this.qualify(e)}`}generateAlterEnum(e,t){let i={...t,currentSchema:this.schemaAtOperation(t)},{enumName:a,addValues:o=[],removeValues:s,newValues:c,dependentColumns:l}=e,u=[],d=this.qualify(a),f=i.currentSchema?.enums?.find(e=>e.name===a)?.values??[],p=c!==void 0&&f.filter(e=>c.includes(e)).join(`\0`)!==c.filter(e=>f.includes(e)).join(`\0`),m=readsAddedValue(a,o,i.currentSchema?.tables??[],t.followingOperations??[]);if(!(s?.length||p||m)){let e=new Set(f);for(let t of o){let n=c?.slice(c.indexOf(t)+1).find(t=>e.has(t));u.push(`ALTER TYPE ${d} ADD VALUE ${this.escapeValue(t)}${n===void 0?``:` BEFORE ${this.escapeValue(n)}`}`),e.add(t)}return u}if(!c?.length)throw new r(`Cannot alter enum "${a}" without its full destination values`,n.MIGRATION_INVALID_STATE);for(let{tableName:e,columnName:t}of l??[]){let n=i.currentSchema?.tables.find(t=>t.name===e)?.columns.find(e=>e.name===t),r=`${this.qualify(e)} ALTER COLUMN ${this.escapeIdentifier(t)}`;n?.default!==void 0&&u.push(`ALTER TABLE ${r} DROP DEFAULT`);let a=n?.type.endsWith(`[]`)?`text[]`:`text`;u.push(`ALTER TABLE ${r} TYPE ${a} USING ${this.escapeIdentifier(t)}::${a}`)}u.push(...this.buildEnumReplacementUpdates(e,i)),u.push(`DROP TYPE ${d}`),u.push(`CREATE TYPE ${d} AS ENUM (${c.map(e=>this.escapeValue(e)).join(`, `)})`);for(let{tableName:e,columnName:t}of l??[]){let n=i.currentSchema?.tables.find(t=>t.name===e)?.columns.find(e=>e.name===t),r=`${this.qualify(e)} ALTER COLUMN ${this.escapeIdentifier(t)}`,o=n?.type.endsWith(`[]`)?`${d}[]`:d;u.push(`ALTER TABLE ${r} TYPE ${o} USING ${this.escapeIdentifier(t)}::${o}`),n?.default!==void 0&&!enumDefaultLabels(n,a).some(e=>e!==null&&s?.includes(e))&&u.push(`ALTER TABLE ${r} SET DEFAULT ${n.default}`)}return u}enumColumnReplacementUpdates(e,t,n,r){if(!(r.currentSchema?.tables.find(e=>e.name===t)?.columns.find(e=>e.name===n)?.type)?.endsWith(`[]`))return super.enumColumnReplacementUpdates(e,t,n,r);let i=this.enumReplacementCases(e,t,n);if(i.length===0)return[];let a=this.escapeIdentifier(n);return[`UPDATE ${this.qualify(t)} SET ${a} = ARRAY(SELECT CASE value ${i.join(` `)} ELSE value END FROM unnest(${a}) WITH ORDINALITY AS member(value, position) ORDER BY position) WHERE ${a} IS NOT NULL`]}};export{ye as t};
|
|
415
|
+
//# sourceMappingURL=postgres-DrXDok0O.mjs.map
|