palgres 0.10.1 → 0.11.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/dist/chunks/{C5MB2TN2.js → FZ3ACJMC.js} +2 -2
- package/dist/chunks/JYA2QXWY.js +2 -0
- package/dist/chunks/LOOM3LFG.js +5 -0
- package/dist/dsl.js +2 -2
- package/dist/index.js +88 -84
- package/dist/testing.js +2 -2
- package/package.json +1 -1
- package/types/palgres/src/dsl/columns.d.ts +28 -0
- package/types/palgres/src/fields.d.ts +63 -0
- package/types/palgres/src/index.d.ts +1 -0
- package/types/palgres/src/migrate.d.ts +30 -0
- package/types/palgres/src/model.d.ts +12 -0
- package/types/palgres/src/plan.d.ts +27 -4
- package/types/palgres/src/query/catalog.d.ts +24 -1
- package/types/palgres/src/query/index.d.ts +23 -0
- package/types/palgres/src/query/typed.d.ts +37 -11
- package/dist/chunks/KCXVL4CY.js +0 -2
- package/dist/chunks/SCDFWCDV.js +0 -5
package/dist/chunks/SCDFWCDV.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
/*! palgres 0.10.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
-
import{createHash as z}from"node:crypto";function fe(n,e){let t=r=>r==="cascade"||r==="set null"||r==="set default";return t(n)||t(e)}var L=class extends Error{problems;constructor(e){super(`the schema is not valid:
|
|
3
|
-
- ${e.join(`
|
|
4
|
-
- `)}`),this.name="SchemaError",this.problems=e}},ue=()=>({tables:[],enums:[],extensions:[],raw:[]}),b=n=>`${n.schema}.${n.name}`,Q={int:"integer",int4:"integer",int2:"smallint",int8:"bigint",float4:"real",float8:"double precision",bool:"boolean",timestamptz:"timestamp with time zone",timestamp:"timestamp without time zone","timestamp without time zone":"timestamp without time zone",timetz:"time with time zone",time:"time without time zone",varchar:"character varying",char:"character",decimal:"numeric"};function D(n){let e=n.trim().replace(/\s+/g," "),t="";for(;e.endsWith("[]");)t+="[]",e=e.slice(0,-2).trim();let r=/^((?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_ ]*?)(?:\.(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_]*))?)\s*(\(.*\))?$/.exec(e);if(!r)return n.trim()+t;let c=r[2]?r[2].replace(/\s+/g,""):"",o=W(r[1]);return o===void 0?n.trim()+t:o.length===1&&o[0].quoted?`"${o[0].name.replace(/"/g,'""')}"${c}${t}`:o.length===1?`${Q[o[0].name]??o[0].name}${c}${t}`:`${o.map(l=>N(l.name)).join(".")}${c}${t}`}var N=n=>/^[a-z_][a-z0-9_$]*$/.test(n)?n:`"${n.replace(/"/g,'""')}"`,de=(n,e)=>`${N(n)}.${N(e)}`;function W(n){let e=[],t=0;for(;t<n.length;){if(n[t]==='"'){let r=t+1,c="";for(;;){if(r>=n.length)return;if(n[r]==='"'){if(n[r+1]==='"'){c+='"',r+=2;continue}break}c+=n[r++]}e.push({name:c,quoted:!0}),t=r+1}else{let r=/^[A-Za-z_][A-Za-z0-9_ ]*/.exec(n.slice(t));if(!r)return;e.push({name:r[0].trim().toLowerCase(),quoted:!1}),t+=r[0].length}if(t<n.length){if(n[t]!==".")return;t++}}return e}var J=/^[A-Za-z_][A-Za-z0-9_$]*$/,Z=63;function y(n,e,t=!1){if(typeof e!="string"||e==="")return`${n} has no name`;if(t?e.includes("\0"):!J.test(e))return`${n} "${e}": a name is letters, digits and _ (starting with a letter or _)`;if(Buffer.byteLength(e)>Z)return`${n} "${e}": longer than Postgres' 63 bytes, it would be cut`;if(e.startsWith("palgres_")||e.startsWith("_palgres"))return`${n} "${e}": names starting with palgres_ are Palgres' own`}var G="vector",F=["cosine","euclidean","inner_product"],A=1536,X=2e3,R=4e3,Y=/^(text|citext|public\.citext|character varying(\(\d+\))?)$/;function q(n,e,t){let r=[];e.primaryKey.length!==1&&r.push(`${n} declares search and has ${e.primaryKey.length===0?"no primary key":`a primary key of ${e.primaryKey.length} columns`}: a row's vector is kept by its key \u2014 give the table a single-column primary key (uuid().primaryKey())`),(!Array.isArray(t.from)||t.from.length===0)&&r.push(`${n}: search.from is empty \u2014 name the text columns a row is found by (search: { from: ['title', 'body'], model })`);let c=new Set;for(let o of Array.isArray(t.from)?t.from:[]){c.has(o)&&r.push(`${n}: search.from names "${o}" twice \u2014 name each column once`),c.add(o);let l=e.columns.find(i=>i.name===o);l?l.ignored?r.push(`${n}: search.from names "${o}", which is ignored \u2014 take it out of search.from, or keep the column`):Y.test(D(l.type))?l.generated&&r.push(`${n}: search.from names "${o}", a generated column \u2014 no write names it, so nothing would say when to embed the row again: name the columns it is computed from`):r.push(`${n}: search.from names "${o}", which is ${l.type} \u2014 search reads text (text, varchar, citext): name a text column, or keep the text in one`):r.push(`${n}: search.from names "${o}", which the table does not have \u2014 name its text columns`)}return(typeof t.model!="string"||t.model.trim()==="")&&r.push(`${n}: search.model is empty \u2014 name the embedding model (search: { from, model: 'embedding' })`),F.includes(t.metric)||r.push(`${n}: search.metric is ${JSON.stringify(t.metric)} \u2014 it is ${F.map(o=>`'${o}'`).join(", ")}`),(!Number.isInteger(t.dimensions)||t.dimensions<1||t.dimensions>R)&&r.push(`${n}: search.dimensions is ${String(t.dimensions)} \u2014 it is 1 to ${R}: pgvector indexes a vector of at most ${X} dimensions and a half-precision one of at most ${R}; ask the model for fewer (search: { dimensions: ${A} })`),t.staleness!=="null"&&t.staleness!=="keep"&&r.push(`${n}: search.staleness is ${JSON.stringify(t.staleness)} \u2014 it is 'null' (a changed row is not found by its old meaning) or 'keep' (it is, until embedded again)`),e.columns.some(o=>o.name==="_score"&&!o.ignored)&&r.push(`${n} declares search and has a column "_score": search() answers each row with its _score \u2014 rename the column`),r}function me(n){let e=[],t=i=>i&&e.push(i),r=new Map,c=new Map,o=(i,a,u)=>{let f=`${i}.${a}`,d=c.get(f);d?e.push(`${u} "${a}" has the name of ${d} in schema ${i}`):c.set(f,u)};for(let i of n.enums)t(y("an enum",i.name)),i.values.length===0&&e.push(`enum ${i.schema}.${i.name} has no values`),new Set(i.values).size!==i.values.length&&e.push(`enum ${i.schema}.${i.name} names a value twice`);for(let i of n.tables){let a=b(i);t(y("a schema",i.schema)),t(y("a table",i.name)),r.has(a)&&e.push(`table ${a} is declared twice`),r.set(a,i),o(i.schema,i.name,`table ${a}`);let u=new Map,f=(s,m)=>{let C=u.get(s);C?e.push(`${m} "${s}" has the name of a ${C} of table ${a}`):u.set(s,m)},d=new Map;for(let s of i.columns)t(y(`column ${a}.${s.name}`,s.name)),d.has(s.name)&&e.push(`column ${a}.${s.name} is declared twice`),d.set(s.name,s),s.fill!==void 0&&s.nullable&&e.push(`column ${a}.${s.name}: fillWith is for a column that is NOT NULL`),s.identity&&s.default!==void 0&&e.push(`column ${a}.${s.name}: an identity column has no default`),s.generated&&(s.default!==void 0||s.identity||s.fill!==void 0)&&e.push(`column ${a}.${s.name}: a generated column has no default, identity or fill`),s.generated&&!s.generated.expr.trim()&&e.push(`column ${a}.${s.name}: a generated column's expression is empty`),s.identity&&!["smallint","integer","bigint"].includes(D(s.type))&&e.push(`column ${a}.${s.name}: an identity column is smallint, integer or bigint`),s.identity&&s.nullable&&e.push(`column ${a}.${s.name}: an identity column is NOT NULL`);let g=(s,m)=>{let C=d.get(s);C?C.ignored&&e.push(`${m} names column "${s}", which is ignored`):e.push(`${m} names column "${s}", which ${a} does not have`)};for(let s of i.primaryKey)g(s,`the primary key of ${a}`);for(let s of i.primaryKey)d.get(s)?.nullable&&e.push(`column ${a}.${s} is in the primary key, so it is not nullable`);for(let s of i.uniques){t(y(`a unique constraint of ${a}`,s.name,!0)),o(i.schema,s.name,`unique constraint ${a}.${s.name}`),f(s.name,"unique constraint"),s.columns.length===0&&e.push(`unique constraint ${s.name} names no column`);for(let m of s.columns)g(m,`unique constraint ${s.name}`)}for(let s of i.indexes){t(y(`an index of ${a}`,s.name,!0)),o(i.schema,s.name,`index ${a}.${s.name}`),s.keys.length===0&&e.push(`index ${s.name} has no key`);for(let m of s.keys)"column"in m&&g(m.column,`index ${s.name}`);for(let m of s.include??[])g(m,`index ${s.name}`)}for(let s of i.checks)t(y(`a check of ${a}`,s.name,!0)),f(s.name,"check"),s.expr.trim()||e.push(`check ${s.name} has no expression`);for(let s of i.foreignKeys){t(y(`a foreign key of ${a}`,s.name,!0)),f(s.name,"foreign key"),(s.columns.length===0||s.columns.length!==s.refColumns.length)&&e.push(`foreign key ${s.name} names ${s.columns.length} column(s) and references ${s.refColumns.length}`);for(let m of s.columns)g(m,`foreign key ${s.name}`)}let k=new Set;for(let s of i.policies)t(y(`a policy of ${a}`,s.name,!0)),k.has(s.name)&&e.push(`policy ${a}.${s.name} is declared twice`),k.add(s.name),s.to.length===0&&e.push(`policy ${a}.${s.name} names no role`),s.for==="insert"&&s.using!==void 0&&e.push(`policy ${a}.${s.name}: an insert policy has only withCheck`),(s.for==="select"||s.for==="delete")&&s.withCheck!==void 0&&e.push(`policy ${a}.${s.name}: a ${s.for} policy has only using`);i.policies.length>0&&!i.rls&&e.push(`table ${a} has policies but row-level security off: they would do nothing`),i.search!==void 0&&e.push(...q(`table ${a}`,i,i.search))}for(let i of n.tables)for(let a of i.foreignKeys){let u=r.get(`${a.refSchema}.${a.refTable}`);if(!u){e.push(`foreign key ${a.name} of ${b(i)} references ${a.refSchema}.${a.refTable}, which is not declared`);continue}u.ignored&&e.push(`foreign key ${a.name} of ${b(i)} references ${b(u)}, which is ignored`);for(let f of a.refColumns)u.columns.some(d=>d.name===f&&!d.ignored)||e.push(`foreign key ${a.name} references ${b(u)}.${f}, which it does not have`)}let l=new Set;for(let i of n.raw)t(y("a raw unit",i.name)),l.has(i.name)&&e.push(`raw unit ${i.name} is declared twice`),l.add(i.name),i.sql.trim()||e.push(`raw unit ${i.name} has no SQL`),i.before&&i.table!==void 0&&e.push(`raw unit ${i.name}: before is for a schema's unit, not a table's \u2014 a table's is made after its table`);return e}function j(n){let e=t=>[...t].sort((r,c)=>r.name<c.name?-1:r.name>c.name?1:0);return{tables:[...n.tables].map(t=>({...t,schema:t.schema||"public",columns:t.columns.map(r=>({...r,type:D(r.type)})),uniques:e(t.uniques),indexes:e(t.indexes),checks:e(t.checks),foreignKeys:e(t.foreignKeys),policies:e(t.policies).map(r=>({...r,to:[...r.to].sort()}))})).sort((t,r)=>b(t)<b(r)?-1:b(t)>b(r)?1:0),enums:[...n.enums].sort((t,r)=>`${t.schema}.${t.name}`<`${r.schema}.${r.name}`?-1:1),extensions:[...new Set([...n.extensions,...n.tables.some(t=>t.search!==void 0)?[G]:[]])].sort(),raw:e(n.raw)}}function pe(n){let e=j(n),t=new Map(n.raw.map((r,c)=>[r.name,c]));return e.raw.sort((r,c)=>(t.get(r.name)??0)-(t.get(c.name)??0)),e}function O(n){return Array.isArray(n)?`[${n.map(O).join(",")}]`:n&&typeof n=="object"?`{${Object.entries(n).filter(([,t])=>t!==void 0).sort(([t],[r])=>t<r?-1:1).map(([t,r])=>`${JSON.stringify(t)}:${O(r)}`).join(",")}}`:JSON.stringify(n)}function he(n){return z("sha256").update(O(j(n))).digest("hex").slice(0,32)}var M=Symbol.for("palbase.table.meta"),x=Symbol.for("palbase.ref.target"),S=class{_def;constructor(e){if(e.trim()==="")throw new Error("foreignKey(name): a foreign key's name cannot be empty \u2014 Palbase reconciles constraints by name.");this._def={name:e,columns:[],refTable:"",refColumns:[]}}on(...e){return this._def.columns=e.map(t=>{let r=t.expr;if(r.kind!=="col")throw new Error(`foreignKey(${this._def.name}).on(): takes column references only \u2014 an expression cannot be part of a foreign key.`);return r.name}),this}references(e,...t){if(t.length===0)throw new Error(`foreignKey(${this._def.name}).references(): needs at least one target column.`);return this._def.refColumns=[...t],typeof e=="function"?(Object.defineProperty(this._def,x,{value:()=>e()[M],enumerable:!1,configurable:!0}),this):(this._def.refTable=e[M].name,Object.defineProperty(this._def,x,{value:e[M],enumerable:!1,configurable:!0}),this)}onUpdate(e){return this._def.onUpdate=e,this}onDelete(e){return this._def.onDelete=e,this}match(e){return this._def.match=e,this}index(e){if(e!==!1)throw new Error(`foreignKey(${this._def.name}).index(): only index(false) \u2014 an index is made unasked`);return this._def.index=!1,this}deferrable(e){if(e!==!1)throw new Error(`foreignKey(${this._def.name}).deferrable(): only deferrable(false) \u2014 a key with an action is deferrable unasked`);return this._def.deferrable=!1,this}};function V(n){return new S(n)}function B(n){let e=n instanceof S?n._def:n;if(e.columns.length===0)throw new Error(`foreignKey(${e.name}): needs at least one local column \u2014 call .on(...).`);let t=typeof e[x]=="function";if(e.refColumns.length===0||e.refTable===""&&!t)throw new Error(`foreignKey(${e.name}): needs the target table and its columns \u2014 call .references(...).`);if(e.columns.length!==e.refColumns.length)throw new Error(`foreignKey(${e.name}): ${e.columns.length} local column(s) (${e.columns.join(", ")}) but ${e.refColumns.length} target column(s) (${e.refColumns.join(", ")}) \u2014 the two lists must be the same length.`);return e}var h=class n{expr;constructor(e){this.expr=e}bin(e,t){return new n({kind:"binop",op:e,left:this.expr,right:ee(t)})}eq(e){return this.bin("eq",e)}neq(e){return this.bin("neq",e)}gt(e){return this.bin("gt",e)}gte(e){return this.bin("gte",e)}lt(e){return this.bin("lt",e)}lte(e){return this.bin("lte",e)}isNull(e=!1){return new n({kind:"isNull",expr:this.expr,negated:e})}and(...e){return new n({kind:"and",parts:[this.expr,...e.map(t=>t.expr)]})}or(...e){return new n({kind:"or",parts:[this.expr,...e.map(t=>t.expr)]})}not(){return new n({kind:"not",expr:this.expr})}};function ee(n){return n instanceof h?n.expr:{kind:"lit",value:n}}function E(n,e=0,t=""){let r=`pb_e${e}`;return{col:c=>new h(e===0?{kind:"col",name:c}:{kind:"col",name:c,alias:r}),auth:{uid:()=>new h({kind:"authUid"})},lit:c=>new h({kind:"lit",value:c}),and:(...c)=>new h({kind:"and",parts:c.map(o=>o.expr)}),or:(...c)=>new h({kind:"or",parts:c.map(o=>o.expr)}),not:c=>new h({kind:"not",expr:c.expr}),existsIn:(c,o)=>{let l=c[_],i=E(Object.keys(l.columns),e+1,t),a={kind:"exists",table:l.name,alias:`pb_e${e+1}`,outer:t,predicate:o(i).expr};return Object.defineProperty(a,x,{value:l,enumerable:!1,configurable:!0}),new h(a)}}}function p(n){return`"${n.replace(/"/g,'""')}"`}var P=class{_def;constructor(e){this._def={name:e,command:"all",roles:["authenticated"],using:null,withCheck:null,permissive:!0}}for(e){return this._def.command=e,this}to(...e){return this._def.roles=e,this}using(e){return this._def.using=e instanceof h?e.expr:e,this}memberOf(e,t,r={}){if(this._def.using!==null)throw new Error(`policy(${this._def.name}).memberOf(): this policy already has a using() expression. Write one or the other \u2014 memberOf IS the using expression.`);let c=r.column??"id",o=r.userColumn??"user_id";return this._def.using=`${p(c)} IN (SELECT ${p(t)} FROM ${p(e)} WHERE ${p(o)} = (select auth.uid()))`,this}withCheck(e){return this._def.withCheck=e instanceof h?e.expr:e,this}withoutIndexes(){return this._def.indexes=!1,this}as(e){return this._def.permissive=e==="permissive",this}};function $e(n){return new P(n)}function T(n,e){switch(n.kind){case"exists":throw new Error(`check(${e}): \`existsIn(...)\` is a subquery and PostgreSQL forbids subqueries in a CHECK constraint \u2014 express a cross-table rule as a composite FOREIGN KEY (foreignKeys), or as a guard.`);case"authUid":throw new Error(`check(${e}): \`auth.uid()\` renders as a subquery \`(SELECT auth.uid())\` and PostgreSQL forbids subqueries in a CHECK constraint \u2014 a caller-dependent rule belongs in an RLS policy, not a CHECK.`);case"binop":T(n.left,e),T(n.right,e);return;case"and":case"or":for(let t of n.parts)T(t,e);return;case"not":case"isNull":T(n.expr,e);return;default:return}}var ne={eq:"=",neq:"<>",gt:">",gte:">=",lt:"<",lte:"<="};function U(n){if(n===null)return"NULL";if(typeof n=="boolean")return n?"true":"false";if(typeof n=="number"){if(!Number.isFinite(n))throw new Error(`check(): ${n} is not an SQL number literal.`);return String(n)}return`'${n.replace(/'/g,"''")}'`}function w(n,e){switch(n.kind){case"col":return p(n.name);case"lit":return U(n.value);case"binop":{let t=ne[n.op];if(t===void 0)throw new Error(`check(${e}): \`${n.op}\` is not supported in a CHECK expression.`);return`(${w(n.left,e)} ${t} ${w(n.right,e)})`}case"and":case"or":{if(n.parts.length===0)return n.kind==="and"?"(true)":"(false)";let t=n.kind==="and"?" AND ":" OR ";return`(${n.parts.map(r=>w(r,e)).join(t)})`}case"not":return`(NOT ${w(n.expr,e)})`;case"isNull":return`(${w(n.expr,e)} IS ${n.negated?"NOT NULL":"NULL"})`;default:{let t=n.kind;throw new Error(`check(${e}): a \`${t}\` node is not one a CHECK expression takes.`)}}}function te(n,e){if(n.trim()==="")throw new Error("check(): the constraint's name cannot be empty \u2014 Palbase reconciles CHECKs by name.");return T(e.expr,n),{name:n,expr:w(e.expr,n)}}function we(n){if(n!==null)return typeof n=="string"?n:$(n,"")}var re={eq:"=",neq:"<>",gt:">",gte:">=",lt:"<",lte:"<="};function H(n){let e=n.indexOf(".");return e<0?`${p("public")}.${p(n)}`:`${p(n.slice(0,e))}.${p(n.slice(e+1))}`}function $(n,e){switch(n.kind){case"col":return n.alias!==void 0?`${p(n.alias)}.${p(n.name)}`:e===""?p(n.name):`${H(e)}.${p(n.name)}`;case"authUid":return"(SELECT auth.uid())";case"lit":return U(n.value);case"binop":{let t=re[n.op];if(t===void 0)throw new Error(`policy expression: \`${n.op}\` is not an operator a policy can use`);return`(${$(n.left,e)} ${t} ${$(n.right,e)})`}case"and":case"or":return n.parts.length===0?n.kind==="and"?"(true)":"(false)":`(${n.parts.map(t=>$(t,e)).join(n.kind==="and"?" AND ":" OR ")})`;case"not":return`(NOT ${$(n.expr,e)})`;case"isNull":return`(${$(n.expr,e)} IS ${n.negated?"NOT NULL":"NULL"})`;case"exists":if(n.outer==="")throw new Error("policy expression: an existsIn carries no outer table \u2014 its correlation would collapse to x = x and filter nothing");return`EXISTS (SELECT 1 FROM ${H(n.table)} ${p(n.alias)} WHERE (${$(n.predicate,n.outer)}))`}}function v(n,e){return n===""||n==="public"?e:`${n}.${e}`}var K=class{_def;constructor(e){if(e.trim()==="")throw new Error("index(name): an index's name cannot be empty \u2014 Palbase reconciles indexes by name.");this._def={name:e}}unique(){return this._def.unique=!0,this}on(...e){return this._def.columns=e.map(t=>{let r=t.expr;if(r.kind!=="col")throw new Error(`index(${this._def.name}).on(): takes column references only \u2014 for an expression, use onExpression("\u2026").`);return r.name}),this}onExpression(e){return this._def.expression=e,this}where(e){return this._def.where=e.expr,this}desc(){return this._def.sort="desc",this}asc(){return this._def.sort="asc",this}nulls(e){return this._def.nulls=e,this}include(e){return this._def.include=e,this}};function Se(n){return new K(n)}function ie(n){return n instanceof P?n._def:n}var _=Symbol.for("palbase.table.meta");function _e(n,e){if(n.trim()==="")throw new Error("defineTable(name, \u2026): name must not be empty");let t=(e.policies?.(E(Object.keys(e.columns),0,n))??[]).map(ie),r=t.length>0||e.rls!==!1,c={};for(let[f,d]of Object.entries(e.columns)){let g=d;ae(n,f,g._def);let k=Object.create(Object.getPrototypeOf(g));Object.defineProperty(k,"_def",{value:{...g._def},enumerable:!0,writable:!0}),c[f]=k}let o={name:n,columns:c,rls:r,policies:t};if(e.primaryKey!==void 0&&(o.primaryKey=[...e.primaryKey]),e.search!==void 0&&(o.search=se(n,e.search,c,o.primaryKey)),e.unique!==void 0&&(o.unique=e.unique.map(f=>({name:f.name,columns:[...f.columns]}))),e.raw!==void 0&&e.raw.length>0){for(let f of e.raw)if(f.drop!==void 0)throw new Error(`defineTable(${JSON.stringify(n)}): raw ${JSON.stringify(f.name)} carries a drop, but a table-level raw() has no teardown \u2014 a drop is run only for a schema-level unit: defineSchema(name, { tables, raw: [raw(name, up, { drop })] })`);o.raw=e.raw.slice()}let l=typeof e.checks=="function"?e.checks(E(Object.keys(e.columns),0,n)):e.checks?.slice()??[];l.length>0&&(o.checks=l);let i=(e.indexes?.(E(Object.keys(e.columns),0,n))??[]).map(f=>f instanceof K?f._def:f);i.length>0&&(o.indexes=i);let a=(e.foreignKeys?.(E(Object.keys(e.columns),0,n))??[]).map(B);a.length>0&&(o.foreignKeys=a),e.ignored===!0&&(o.ignored=!0);for(let f of Object.values(c))f._def.ownerTable=o;let u={...c};return Object.defineProperty(u,_,{value:o,enumerable:!1}),u}function se(n,e,t,r){if(e===null||typeof e!="object")throw new Error(`defineTable(${JSON.stringify(n)}): search is { from: [...columns], model } \u2014 got ${e===null?"null":typeof e}`);let c={from:Array.isArray(e.from)?[...e.from]:e.from,model:e.model,dimensions:e.dimensions??A,metric:e.metric??"cosine",staleness:e.staleness??"null"},o=Object.entries(t).map(([i,a])=>({name:i,def:a._def})),l=q(`defineTable(${JSON.stringify(n)})`,{columns:o.map(({name:i,def:a})=>({name:i,type:a.type==="sql"?a.sqlType??"sql":a.type,...a.ignored?{ignored:!0}:{},...a.generated?{generated:a.generated}:{}})),primaryKey:r??o.filter(({def:i})=>i.primaryKey===!0).map(({name:i})=>i)},c);if(l.length>0)throw new Error(l.join(`
|
|
5
|
-
`));return c}var I=new WeakMap;function oe(n,e){for(let t of Object.values(n))le(t,`table "${t.name}"`,e);for(let t of Object.values(n))for(let[r,c]of Object.entries(t.columns)){let o=c._def;if(o.selfRefColumn!==void 0){if(!(o.selfRefColumn in t.columns))throw new Error(`table "${t.name}" column "${r}": selfReferences("${o.selfRefColumn}") \u2014 no such column on this table`);o.references={table:v(e,t.name),column:o.selfRefColumn};continue}if(o.referencesThunk===void 0)continue;let l=o.referencesThunk(),i=l?._def?.ownerTable;if(i===void 0)throw new Error(`table "${t.name}" column "${r}": references(() => \u2026) must point at a column of a table declared with defineTable(...)`);let a=Object.entries(i.columns).find(([,f])=>f._def===l._def)?.[0];if(a===void 0)throw new Error(`table "${t.name}" column "${r}": the referenced column was not found on table "${i.name}"`);let u=I.get(i);if(u===void 0)throw new Error(`table "${t.name}" column "${r}": references(() => \u2026) points at table "${i.name}", which no defineSchema(...) has claimed yet \u2014 a foreign key cannot be written without its target's schema. Declare that table's schema first (one file per schema: db/public.ts, db/billing.ts \u2026, imported by this one).`);o.references={table:v(u,i.name),column:a}}}function ae(n,e,t){if(t.fill===void 0)return;let r=t.nullable===!0?"the column is .nullable() \u2014 .fillWith() fills a NOT NULL column; keep one of the two":t.ignored===!0?"the column is .ignored() \u2014 this release never writes it, so there is nothing to fill for it":t.defaultValue!==void 0||t.defaultRandom===!0||t.defaultNow===!0||t.defaultSql!==void 0?"the column has a default \u2014 the default already fills every row; keep one of the two":null;if(r!==null)throw new Error(`defineTable(${JSON.stringify(n)}): column "${e}" \u2014 .fillWith(): ${r}`)}function Ke(n,e){if(typeof n!="string")throw new Error(`defineSchema(...) takes the schema NAME first: defineSchema("public", { tables: [todos, lists] }). The one-argument form defineSchema({ tables: { \u2026 } }) is gone \u2014 a schema that does not say its own name cannot be told apart from another schema's table of the same name, which is what a cross-schema foreign key has to do. Migrate db/public.ts (one file per schema: db/public.ts, db/billing.ts \u2026): name the schema, and lift each table key onto the table itself with defineTable("todos", { columns: { \u2026 } }), then list the tables in the array.`);if(n.trim()==="")throw new Error("defineSchema(name, \u2026): name must not be empty");let t={};for(let l of e.tables){let i=l[_];if(t[i.name]!==void 0)throw new Error(`defineSchema("${n}"): two tables declare the name "${i.name}" \u2014 table names must be unique within a schema`);t[i.name]=i,I.set(i,n)}oe(t,n);let r=[...new Set(e.extensions??[])],c=(e.raw??[]).slice(),o=new Set;for(let l of c){if(typeof l.name!="string"||l.name.trim()==="")throw new Error(`defineSchema("${n}"): a raw unit needs a name`);if(o.has(l.name))throw new Error(`defineSchema("${n}"): two raw units are named "${l.name}" \u2014 a unit's name identifies it`);o.add(l.name)}return{name:n,tables:t,extensions:r,raw:c}}function le(n,e,t){let r=(l,i)=>{let a=l[x];if(a===void 0)return;let u;try{u=typeof a=="function"?a():a}catch(g){throw new Error(`${e}: ${i} names its target through a callback that failed: ${g.message}`)}if(u==null||typeof u.name!="string")throw new Error(`${e}: ${i}'s callback does not answer a table \u2014 write references(() => otherTable, \u2026)`);let f=I.get(u);if(f===void 0)throw new Error(`${e}: ${i} points at table "${u.name}", which no defineSchema(...) has claimed yet \u2014 a cross-table reference cannot be written without its target's schema. Declare that table's schema first (one file per schema: db/public.ts, db/billing.ts \u2026, imported by this one).`);let d=v(f,u.name);l.refTable!==void 0&&(l.refTable=d),l.table!==void 0&&(l.table=d)};for(let l of n.foreignKeys??[])r(l,`foreignKey("${l.name}")`);let c=`${t}.${n.name}`,o=(l,i)=>{if(!(l==null||typeof l=="string"))switch(l.kind){case"exists":r(l,i),l.table.includes(".")||(l.table=`public.${l.table}`),l.outer=c,o(l.predicate,i);return;case"binop":o(l.left,i),o(l.right,i);return;case"and":case"or":for(let a of l.parts)o(a,i);return;case"not":case"isNull":o(l.expr,i);return;default:return}};for(let l of n.policies)o(l.using,`policy("${l.name}")`),o(l.withCheck,`policy("${l.name}")`);for(let l of n.indexes??[])o(l.where,`index("${l.name}")`)}export{fe as a,L as b,ue as c,b as d,D as e,de as f,X as g,q as h,me as i,j,pe as k,he as l,S as m,V as n,v as o,K as p,Se as q,_ as r,_e as s,Ke as t,h as u,E as v,P as w,$e as x,te as y,we as z};
|