palgres 0.64.0 → 0.66.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.
@@ -0,0 +1,2 @@
1
+ /*! palgres 0.66.0 — Palbase SDK License (see LICENSE) */
2
+ var i=new Set(["uuid","text","integer","bigint","numeric","boolean","timestamp","date","enum"]),u={number:{fromDb:e=>e==null?e:Number(e),toDb:e=>{if(e==null||typeof e!="number")return e==null?e:String(e);if(!Number.isFinite(e))throw new Error(`asNumber() cannot write ${e}: it is not a finite number, and the column holds one.`);if(Number.isInteger(e)&&!Number.isSafeInteger(e))throw new Error(`asNumber() cannot write ${e}: it is outside the safe integer range and would be stored as a different number. Declare .asDecimal() and hand this column a string.`);return String(e)},tsType:"number"},decimal:{fromDb:e=>e==null?e:String(e),toDb:e=>e==null?e:String(e),tsType:"string"}},r=class e{_def;constructor(n,t){this._def=t??{type:n,nullable:!1,primaryKey:!1}}primaryKey(){return this._def.primaryKey=!0,new e(this._def.type,this._def)}notNull(){return this._def.nullable=!1,new e(this._def.type,this._def)}nullable(){if(this._def.identity!==void 0)throw new Error(".nullable() on an identity column: an identity is always NOT NULL");return this._def.nullable=!0,new e(this._def.type,this._def)}default(n){return this._def.defaultValue=n,new e(this._def.type,this._def)}defaultRandom(){return this._def.defaultRandom=!0,new e(this._def.type,this._def)}defaultNow(){return this._def.defaultNow=!0,new e(this._def.type,this._def)}defaultSql(n){if(typeof n!="string"||n.trim()==="")throw new Error("defaultSql() takes the SQL of the default");return this._def.defaultSql=n,new e(this._def.type,this._def)}dbAssigned(){return this._def.dbAssigned=!0,new e(this._def.type,this._def)}array(){let n=this._def.type;if(!i.has(n))throw new Error(`${n} column: .array() is available on uuid(), text(), integer(), bigint(), numeric(), boolean(), timestamp(), date() and enumType()`);if(this._def.defaultValue!==void 0||this._def.defaultNow||this._def.defaultRandom||this._def.defaultSql!==void 0)throw new Error(`.array() comes before the default \u2014 write ${n}().array().default([])`);if(this._def.codec!==void 0||this._def.transform!==void 0)throw new Error(".array() cannot follow a codec or a transform \u2014 they convert one value, not a list of them");let t=`${n}[]`;return new e(t,{...this._def,type:t})}identity(n){if(this._def.type!=="integer"&&this._def.type!=="bigint"&&!(this._def.type==="sql"&&this._def.sqlType==="smallint"))throw new Error(`${this._def.type} column: .identity() is for integer(), bigint() and sqlType('smallint') columns`);if(this._def.defaultValue!==void 0||this._def.defaultNow||this._def.defaultRandom||this._def.defaultSql!==void 0||this._def.fill!==void 0)throw new Error(".identity() is the column's value \u2014 it cannot also have a default or a fill");let t=n?.always===!1?"byDefault":"always";return new e(this._def.type,{...this._def,nullable:!1,identity:t})}generated(n,t={}){if(typeof n!="string"||n.trim()==="")throw new Error(".generated() takes the SQL expression the column is");if(this._def.defaultValue!==void 0||this._def.defaultNow||this._def.defaultRandom||this._def.defaultSql!==void 0||this._def.fill!==void 0||this._def.identity!==void 0)throw new Error(".generated() is the column's value \u2014 it cannot also have a default, a fill or an identity");return new e(this._def.type,{...this._def,generated:{expr:n,stored:t.stored===!0}})}fillWith(n){return new e(this._def.type,{...this._def,fill:n})}renamedFrom(n){return this._def.renamedFrom=n,this}ignored(){return new e(this._def.type,{...this._def,ignored:!0})}encrypted(n={}){if(this._def.type!=="text")throw new Error(`.encrypted() is for a text() column \u2014 a ${this._def.type} column's value is not text to seal; keep it in a text() column (JSON.stringify it)`);return new e("text",{...this._def,encrypted:{lookup:n.lookup===!0}})}references(n,t){if(typeof n!="function")throw new Error('references(...) takes a callback: write references(() => otherTable.column). The two-string form references("table", "column") is gone \u2014 a string cannot be type-checked and cannot point at a table that does not exist yet.');return this._def.referencesThunk=n,t?.as!==void 0&&(this._def.refAs=t.as),t?.reverseAs!==void 0&&(this._def.reverseAs=t.reverseAs),t?.onDelete!==void 0&&(this._def.onDeleteAction=t.onDelete),t?.onUpdate!==void 0&&(this._def.onUpdateAction=t.onUpdate),t?.index===!1&&(this._def.index=!1),t?.deferrable===!1&&(this._def.deferrable=!1),new e(this._def.type,this._def)}selfReferences(n,t){return this._def.selfRefColumn=n,t?.as!==void 0&&(this._def.refAs=t.as),t?.onDelete!==void 0&&(this._def.onDeleteAction=t.onDelete),new e(this._def.type,this._def)}onDelete(n){return this._def.onDeleteAction=n,new e(this._def.type,this._def)}unique(){return this._def.unique=!0,new e(this._def.type,this._def)}asNumber(){return this.withCodec("number","asNumber")}asDecimal(){return this.withCodec("decimal","asDecimal")}withCodec(n,t){if(this._def.type!=="bigint"&&this._def.type!=="numeric")throw new Error(`${this._def.type} column: .${t}() is only available on bigint()/numeric() \u2014 those are the exact-precision types that surface as string.`);if(this._def.transform!==void 0)throw new Error(`.${t}() and .transform() are two ways to say the same thing on one column \u2014 keep .${t}().`);if(this._def.codec!==void 0)throw new Error(`column already declares .as${this._def.codec==="number"?"Number":"Decimal"}(); a column has ONE codec.`);return new e(this._def.type,{...this._def,codec:n})}transform(n){if(this._def.codec!==void 0)throw new Error("column already declares a named codec; .transform() and .as*() are two ways to say the same thing \u2014 keep the codec.");return new e(this._def.type,{...this._def,transform:n})}};function s(){return new r("uuid")}function a(){return new r("text")}function d(){return new r("integer")}function f(){return new r("bigint")}function m(e){if(e===void 0)return new r("numeric");let{precision:n,scale:t=0}=e;if(!Number.isInteger(n)||n<1||n>1e3)throw new Error(`numeric({ precision: ${n} }): precision is a whole number from 1 to 1000`);if(!Number.isInteger(t)||t<0||t>n)throw new Error(`numeric({ precision: ${n}, scale: ${t} }): scale is a whole number from 0 to the precision`);return new r("numeric",{type:"numeric",nullable:!1,primaryKey:!1,precision:n,scale:t})}function c(){return new r("date")}var o={uuid:"uuid()",text:"text()",integer:"integer()",int:"integer()",int4:"integer()",bigint:"bigint()",int8:"bigint()",numeric:"numeric()",decimal:"numeric()",boolean:"boolean()",bool:"boolean()",timestamptz:"timestamp()","timestamp with time zone":"timestamp()",date:"date()",jsonb:"jsonb()"};function y(e){let n=typeof e=="string"?e.trim():"";if(n==="")throw new Error('sqlType() takes the Postgres type, e.g. sqlType("inet")');let t=n.toLowerCase().replace(/\[\]$/,""),l=o[t];if(l!==void 0&&!(n.endsWith("[]")&&!i.has(l.slice(0,-2))))throw new Error(`sqlType(${JSON.stringify(n)}): the DSL has this type \u2014 declare it as ${l}${n.endsWith("[]")?".array()":""}`);return new r("sql",{type:"sql",nullable:!1,primaryKey:!1,sqlType:n})}var h=new Set(["smallint","real","double precision"]),p=new Set(["json"]);function b(){return new r("boolean")}function w(){return new r("timestamp")}function _(){return new r("jsonb")}function g(e,n){let t=new r("enum");return t._def.enumName=e,t._def.enumValues=[...n],t}function E(){let e=new r("text");return e._def.nullable=!1,e._def.user={onDelete:"cascade",owns:!0},e}function T(e){let n=new r("text");return n._def.user={onDelete:e.onDelete,owns:!1},e.as!==void 0&&(n._def.refAs=e.as),n}export{u as a,r as b,s as c,a as d,d as e,f,m as g,c as h,y as i,h as j,p as k,b as l,w as m,_ as n,g as o,E as p,T as q};
@@ -1,4 +1,4 @@
1
- /*! palgres 0.64.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palgres 0.66.0 — Palbase SDK License (see LICENSE) */
2
2
  import{createHash as Zn}from"node:crypto";function Js(t){return`${t}_lookup`}function zs(t,e){let n=o=>o==="cascade"||o==="set null"||o==="set default";return n(t)||n(e)}var pn=class extends Error{problems;constructor(e){super(`the schema is not valid:
3
3
  - ${e.join(`
4
4
  - `)}`),this.name="SchemaError",this.problems=e}},Qs=()=>({tables:[],enums:[],extensions:[],raw:[]}),_e=t=>`${t.schema}.${t.name}`,es={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 St(t){let e=t.trim().replace(/\s+/g," "),n="";for(;e.endsWith("[]");)n+="[]",e=e.slice(0,-2).trim();let o=/^((?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_ ]*?)(?:\.(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_]*))?)\s*(\(.*\))?$/.exec(e);if(!o)return t.trim()+n;let a=o[2]?o[2].replace(/\s+/g,""):"",i=ts(o[1]);return i===void 0?t.trim()+n:i.length===1&&i[0].quoted?`"${i[0].name.replace(/"/g,'""')}"${a}${n}`:i.length===1?`${es[i[0].name]??i[0].name}${a}${n}`:`${i.map(d=>Ot(d.name)).join(".")}${a}${n}`}var Ot=t=>/^[a-z_][a-z0-9_$]*$/.test(t)?t:`"${t.replace(/"/g,'""')}"`,Zs=(t,e)=>`${Ot(t)}.${Ot(e)}`;function ts(t){let e=[],n=0;for(;n<t.length;){if(t[n]==='"'){let o=n+1,a="";for(;;){if(o>=t.length)return;if(t[o]==='"'){if(t[o+1]==='"'){a+='"',o+=2;continue}break}a+=t[o++]}e.push({name:a,quoted:!0}),n=o+1}else{let o=/^[A-Za-z_][A-Za-z0-9_ ]*/.exec(t.slice(n));if(!o)return;e.push({name:o[0].trim().toLowerCase(),quoted:!1}),n+=o[0].length}if(n<t.length){if(t[n]!==".")return;n++}}return e}var ns=/^[A-Za-z_][A-Za-z0-9_$]*$/,ss=63;function ye(t,e,n=!1){if(typeof e!="string"||e==="")return`${t} has no name`;if(n?e.includes("\0"):!ns.test(e))return`${t} "${e}": a name is letters, digits and _ (starting with a letter or _)`;if(Buffer.byteLength(e)>ss)return`${t} "${e}": longer than Postgres' 63 bytes, it would be cut`;if(e.startsWith("palgres_")||e.startsWith("_palgres"))return`${t} "${e}": names starting with palgres_ are Palgres' own`}var os="vector",un=["cosine","euclidean","inner_product"],It=1536,rs=2e3,wt=4e3,is=/^(text|citext|public\.citext|character varying(\(\d+\))?)$/;function Ct(t,e,n){let o=[];e.primaryKey.length!==1&&o.push(`${t} 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(n.from)||n.from.length===0)&&o.push(`${t}: search.from is empty \u2014 name the text columns a row is found by (search: { from: ['title', 'body'], model })`);let a=new Set;for(let i of Array.isArray(n.from)?n.from:[]){a.has(i)&&o.push(`${t}: search.from names "${i}" twice \u2014 name each column once`),a.add(i);let d=e.columns.find(p=>p.name===i);d?d.ignored?o.push(`${t}: search.from names "${i}", which is ignored \u2014 take it out of search.from, or keep the column`):is.test(St(d.type))?d.generated&&o.push(`${t}: search.from names "${i}", 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`):o.push(`${t}: search.from names "${i}", which is ${d.type} \u2014 search reads text (text, varchar, citext): name a text column, or keep the text in one`):o.push(`${t}: search.from names "${i}", which the table does not have \u2014 name its text columns`)}return(typeof n.model!="string"||n.model.trim()==="")&&o.push(`${t}: search.model is empty \u2014 name the embedding model (search: { from, model: 'embedding' })`),un.includes(n.metric)||o.push(`${t}: search.metric is ${JSON.stringify(n.metric)} \u2014 it is ${un.map(i=>`'${i}'`).join(", ")}`),(!Number.isInteger(n.dimensions)||n.dimensions<1||n.dimensions>wt)&&o.push(`${t}: search.dimensions is ${String(n.dimensions)} \u2014 it is 1 to ${wt}: pgvector indexes a vector of at most ${rs} dimensions and a half-precision one of at most ${wt}; ask the model for fewer (search: { dimensions: ${It} })`),n.staleness!=="null"&&n.staleness!=="keep"&&o.push(`${t}: search.staleness is ${JSON.stringify(n.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(i=>i.name==="_score"&&!i.ignored)&&o.push(`${t} declares search and has a column "_score": search() answers each row with its _score \u2014 rename the column`),o}function eo(t){let e=[],n=p=>p&&e.push(p),o=new Map,a=new Map,i=(p,u,b)=>{let D=`${p}.${u}`,W=a.get(D);W?e.push(`${b} "${u}" has the name of ${W} in schema ${p}`):a.set(D,b)};for(let p of t.enums)n(ye("an enum",p.name)),p.values.length===0&&e.push(`enum ${p.schema}.${p.name} has no values`),new Set(p.values).size!==p.values.length&&e.push(`enum ${p.schema}.${p.name} names a value twice`);for(let p of t.tables){let u=_e(p);n(ye("a schema",p.schema)),n(ye("a table",p.name)),o.has(u)&&e.push(`table ${u} is declared twice`),o.set(u,p),i(p.schema,p.name,`table ${u}`);let b=new Map,D=(N,G)=>{let te=b.get(N);te?e.push(`${G} "${N}" has the name of a ${te} of table ${u}`):b.set(N,G)},W=new Map;for(let N of p.columns)n(ye(`column ${u}.${N.name}`,N.name)),W.has(N.name)&&e.push(`column ${u}.${N.name} is declared twice`),W.set(N.name,N),N.identity&&N.default!==void 0&&e.push(`column ${u}.${N.name}: an identity column has no default`),N.generated&&(N.default!==void 0||N.identity||N.fill!==void 0)&&e.push(`column ${u}.${N.name}: a generated column has no default, identity or fill`),N.generated&&!N.generated.expr.trim()&&e.push(`column ${u}.${N.name}: a generated column's expression is empty`),N.identity&&!["smallint","integer","bigint"].includes(St(N.type))&&e.push(`column ${u}.${N.name}: an identity column is smallint, integer or bigint`),N.identity&&N.nullable&&e.push(`column ${u}.${N.name}: an identity column is NOT NULL`);let H=(N,G)=>{let te=W.get(N);te?te.ignored&&e.push(`${G} names column "${N}", which is ignored`):e.push(`${G} names column "${N}", which ${u} does not have`)};for(let N of p.primaryKey)H(N,`the primary key of ${u}`);for(let N of p.primaryKey)W.get(N)?.nullable&&e.push(`column ${u}.${N} is in the primary key, so it is not nullable`);for(let N of p.uniques){n(ye(`a unique constraint of ${u}`,N.name,!0)),i(p.schema,N.name,`unique constraint ${u}.${N.name}`),D(N.name,"unique constraint"),N.columns.length===0&&e.push(`unique constraint ${N.name} names no column`);for(let G of N.columns)H(G,`unique constraint ${N.name}`)}for(let N of p.indexes){n(ye(`an index of ${u}`,N.name,!0)),i(p.schema,N.name,`index ${u}.${N.name}`),N.keys.length===0&&e.push(`index ${N.name} has no key`);for(let G of N.keys)"column"in G&&H(G.column,`index ${N.name}`);for(let G of N.include??[])H(G,`index ${N.name}`)}for(let N of p.checks)n(ye(`a check of ${u}`,N.name,!0)),D(N.name,"check"),N.expr.trim()||e.push(`check ${N.name} has no expression`);for(let N of p.foreignKeys){n(ye(`a foreign key of ${u}`,N.name,!0)),D(N.name,"foreign key"),(N.columns.length===0||N.columns.length!==N.refColumns.length)&&e.push(`foreign key ${N.name} names ${N.columns.length} column(s) and references ${N.refColumns.length}`);for(let G of N.columns)H(G,`foreign key ${N.name}`)}let Z=new Set;for(let N of p.policies)n(ye(`a policy of ${u}`,N.name,!0)),Z.has(N.name)&&e.push(`policy ${u}.${N.name} is declared twice`),Z.add(N.name),N.to.length===0&&e.push(`policy ${u}.${N.name} names no role`),N.for==="insert"&&N.using!==void 0&&e.push(`policy ${u}.${N.name}: an insert policy has only withCheck`),(N.for==="select"||N.for==="delete")&&N.withCheck!==void 0&&e.push(`policy ${u}.${N.name}: a ${N.for} policy has only using`);p.policies.length>0&&!p.rls&&e.push(`table ${u} has policies but row-level security off: they would do nothing`),p.search!==void 0&&e.push(...Ct(`table ${u}`,p,p.search))}for(let p of t.tables)for(let u of p.foreignKeys){let b=o.get(`${u.refSchema}.${u.refTable}`);if(!b){e.push(`foreign key ${u.name} of ${_e(p)} references ${u.refSchema}.${u.refTable}, which is not declared`);continue}b.ignored&&e.push(`foreign key ${u.name} of ${_e(p)} references ${_e(b)}, which is ignored`);for(let D of u.refColumns)b.columns.some(W=>W.name===D&&!W.ignored)||e.push(`foreign key ${u.name} references ${_e(b)}.${D}, which it does not have`)}let d=new Set;for(let p of t.raw)n(ye("a raw unit",p.name)),d.has(p.name)&&e.push(`raw unit ${p.name} is declared twice`),d.add(p.name),p.sql.trim()||e.push(`raw unit ${p.name} has no SQL`),p.before&&p.table!==void 0&&e.push(`raw unit ${p.name}: before is for a schema's unit, not a table's \u2014 a table's is made after its table`);return e}function dn(t){let e=n=>[...n].sort((o,a)=>o.name<a.name?-1:o.name>a.name?1:0);return{tables:[...t.tables].map(n=>({...n,schema:n.schema||"public",columns:n.columns.map(o=>({...o,type:St(o.type)})),uniques:e(n.uniques),indexes:e(n.indexes),checks:e(n.checks),foreignKeys:e(n.foreignKeys),policies:e(n.policies).map(o=>({...o,to:[...o.to].sort()}))})).sort((n,o)=>_e(n)<_e(o)?-1:_e(n)>_e(o)?1:0),enums:[...t.enums].sort((n,o)=>`${n.schema}.${n.name}`<`${o.schema}.${o.name}`?-1:1),extensions:[...new Set([...t.extensions,...t.tables.some(n=>n.search!==void 0)?[os]:[]])].sort(),raw:e(t.raw),...t.access!==void 0?{access:t.access}:{}}}function to(t){let e=dn(t),n=new Map(t.raw.map((o,a)=>[o.name,a]));return e.raw.sort((o,a)=>(n.get(o.name)??0)-(n.get(a.name)??0)),e}function xt(t){return Array.isArray(t)?`[${t.map(xt).join(",")}]`:t&&typeof t=="object"?`{${Object.entries(t).filter(([,n])=>n!==void 0).sort(([n],[o])=>n<o?-1:1).map(([n,o])=>`${JSON.stringify(n)}:${xt(o)}`).join(",")}}`:JSON.stringify(t)}function no(t){return Zn("sha256").update(xt(dn(t))).digest("hex").slice(0,32)}var Lt=Symbol.for("palbase.table.meta"),ke=Symbol.for("palbase.ref.target"),ut=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(n=>{let o=n.expr;if(o.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 o.name}),this}references(e,...n){if(n.length===0)throw new Error(`foreignKey(${this._def.name}).references(): needs at least one target column.`);return this._def.refColumns=[...n],typeof e=="function"?(Object.defineProperty(this._def,ke,{value:()=>e()[Lt],enumerable:!1,configurable:!0}),this):(this._def.refTable=e[Lt].name,Object.defineProperty(this._def,ke,{value:e[Lt],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 as(t){return new ut(t)}function mn(t){let e=t instanceof ut?t._def:t;if(e.columns.length===0)throw new Error(`foreignKey(${e.name}): needs at least one local column \u2014 call .on(...).`);let n=typeof e[ke]=="function";if(e.refColumns.length===0||e.refTable===""&&!n)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 w=class extends Error{code;line;constructor(e,n,o=0){super(o>0?`line ${o}: ${n}`:n),this.name="AccessError",this.code=e,this.line=o}};var re="user:*",ie="public",cs=["->","!=","<=",">=","<>",":",",","=","<",">","+","&","-","(",")",".","|","*"],En=256*1024,fn=256,gn=32;function ls(t){if(t.length>En)throw new w("too_large",`the schema is ${t.length} characters; at most ${En}`);let e=[],n=0,o=1,a=i=>{throw new w("syntax",i,o)};for(;n<t.length;){let i=t[n];if(i===`
@@ -0,0 +1,4 @@
1
+ /*! palgres 0.66.0 — Palbase SDK License (see LICENSE) */
2
+ var R=Symbol.for("palbase.backend.httpError"),b=Symbol.for("palbase.backend.engineRaised"),a=Object.freeze({uniqueViolation:"23505",foreignKeyViolation:"23503",serializationFailure:"40001",deadlockDetected:"40P01",queryCancelled:"57014",lockNotAvailable:"55P03",inFailedTransaction:"25P02",insufficientPrivilege:"42501"}),i=class extends Error{[R]=!0;status;error;errorDescription;data;retryAfter;constructor(n,o,e,r,s){super(e),this.name="HttpError",this.status=n,this.error=o,this.errorDescription=e,r!==void 0&&(this.data=r),s!==void 0&&(this.retryAfter=s)}};function O(t){return t[b]=!0,t}function q(t){return typeof t=="object"&&t!==null&&t[b]===!0}function c(t){let n=t.replace(/([a-z0-9])([A-Z])/g,"$1 $2");return n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()}var g=class extends i{constructor(n,o){super(400,"bad_request",o??c("BadRequest"),n),this.name="BadRequest"}},E=class extends i{constructor(n,o,e){super(404,o??"not_found",n??c("NotFound"),e),this.name="NotFound"}},l=class extends i{constructor(n,o,e){super(409,o??"conflict",n??c("Conflict"),e),this.name="Conflict"}},p=class extends l{constraint;sqlstate=a.uniqueViolation;static is(n){return typeof n=="object"&&n!==null&&n.name==="UniqueViolation"&&typeof n.constraint=="string"}constructor(n,o,e,r){super(o??"Unique constraint violated",e??"unique_violation",r),this.name="UniqueViolation",this.constraint=n}};function x(t){if(typeof t!="object"||t===null||t.retryable!==!0)return!1;let n=t.sqlstate;return n===a.serializationFailure||n===a.deadlockDetected}var m=class extends l{retryable=!0;sqlstate;static is(n){return typeof n=="object"&&n!==null&&n.name==="SerializationFailure"}constructor(n=a.serializationFailure,o,e){super(o??"the transaction could not be serialized with a concurrent one \u2014 run it again from the start (put the reads a decision rests on and its writes in $atomic, with { retry: n })","serialization_failure",e),this.name="SerializationFailure",this.sqlstate=n}},y=class extends l{retryable=!0;sqlstate;static is(n){return typeof n=="object"&&n!==null&&n.name==="DeadlockDetected"}constructor(n=a.deadlockDetected,o,e){super(o??"deadlock: two transactions waited on each other's locks and this one was cancelled \u2014 take locks in one order: Database.$lockRows(table, ids) when you have the ids, Database.$lockRowsWhere(table, filter) when you have a filter","deadlock_detected",e),this.name="DeadlockDetected",this.sqlstate=n}},w=class extends Error{sqlstate=a.inFailedTransaction;static is(n){return typeof n=="object"&&n!==null&&n.name==="TransactionAborted"}constructor(n,o){super(n,{cause:o}),this.name="TransactionAborted"}},k=class extends i{constructor(n,o){super(429,"too_many_requests",o??c("TooManyRequests"),n,n.retryAfter),this.name="TooManyRequests"}};function h(t){let n=t,o=e=>typeof e=="string"&&/^[0-9A-Z]{5}$/.test(e);if(o(n?.code))return n.code;if(o(n?.errno))return n.errno}var _=new Set(["57P03","53300","08001","08004","ERR_POSTGRES_CONNECTION_REFUSED","ERR_POSTGRES_CONNECTION_FAILED","ERR_POSTGRES_CONNECTION_TIMEOUT","ECONNREFUSED","CONNECT_TIMEOUT"]),N=new Set(["57P01","57P02","08000","08003","08006","08007","08P01","ERR_POSTGRES_CONNECTION_CLOSED","CONNECTION_CLOSED","CONNECTION_DESTROYED","ECONNRESET","ETIMEDOUT","EPIPE"]);function C(t){return t instanceof Error&&t.code===void 0&&t.message==="connection must be a PostgresSQLConnection"}function D(t){let n=t;for(let o=0;o<4&&typeof n=="object"&&n!==null;o++){let e=h(n),r=n.code,s=f=>e!==void 0&&f.has(e)||typeof r=="string"&&f.has(r);if(s(N))return"lost";if(s(_))return"never";n=n.cause}}function A(t){let n=t;for(let o=0;o<4&&typeof n=="object"&&n!==null;o++){let e=n.sqlstate,r=h(n)??(typeof e=="string"?e:void 0);if(r!==void 0)return!r.startsWith("08")&&!/^57P0[123]$/.test(r);n=n.cause}return!1}function I(t){let n=t,o=n?.constraint??n?.constraint_name;if(typeof o=="string"&&o.length>0)return o;let e=String(t?.message??"");return/violates unique constraint "([^"]+)"/.exec(e)?.[1]??""}var u=t=>`"${t.replace(/"/g,'""')}"`,P=(t,n)=>`${u(t)}.${u(n)}`,$=t=>`'${t.replace(/'/g,"''")}'`;function F(t){if(t.includes("\0"))throw new TypeError("a NUL character cannot be sent to Postgres");return`E'${t.replace(/\\/g,"\\\\").replace(/'/g,"''")}'`}var z=t=>t.map(u).join(", "),T=new Set(["now","current_timestamp","current_date","current_time","localtimestamp","localtime","transaction_timestamp","statement_timestamp"]);function M(t){return[...d(t)].some(n=>n.call&&!T.has(n.name.toLowerCase()))}function*d(t){let n=0;for(;n<t.length;){let o=t[n];if(o==="'"){for(n++;n<t.length;)if(t[n]==="'"&&t[n+1]==="'")n+=2;else{if(t[n]==="'")break;n++}n++;continue}if(o==="$"){let e=/^\$[A-Za-z_]*\$/.exec(t.slice(n));if(e){let r=t.indexOf(e[0],n+e[0].length);n=r<0?t.length:r+e[0].length;continue}}if(o==='"'){let e=n+1,r="";for(;e<t.length;)if(t[e]==='"'&&t[e+1]==='"')r+='"',e+=2;else{if(t[e]==='"')break;r+=t[e++]}let s=e+1;yield{start:n,end:s,name:r,quoted:!0,call:/^\s*\(/.test(t.slice(s))},n=s;continue}if(/[A-Za-z_]/.test(o)&&(n===0||!/[A-Za-z0-9_$]/.test(t[n-1]))){let e=/^[A-Za-z_][A-Za-z0-9_$]*/.exec(t.slice(n)),r=n+e[0].length;yield{start:n,end:r,name:e[0],quoted:!1,call:/^\s*\(/.test(t.slice(r))},n=r;continue}n++}}function j(t,n){for(let o of d(t))if(!o.call&&(o.quoted?o.name===n:o.name.toLowerCase()===n.toLowerCase()))return!0;return!1}function U(t,n){if(n.size===0)return t;let o="",e=0;for(let r of d(t)){if(r.call)continue;let s=n.get(r.quoted?r.name:S(n,r.name)??"");s!==void 0&&(o+=t.slice(e,r.start)+u(s),e=r.end)}return o+t.slice(e)}function S(t,n){if(t.has(n))return n;let o=n.toLowerCase();for(let e of t.keys())if(e.toLowerCase()===o)return e}var v=t=>`(NOT EXISTS (SELECT 1 FROM unnest(i.indclass::oid[]) AS oc(oid) JOIN pg_catalog.pg_opclass o ON o.oid = oc.oid WHERE NOT o.opcdefault)
3
+ AND NOT i.indnullsnotdistinct AND ${t}.reloptions IS NULL
4
+ AND NOT EXISTS (SELECT 1 FROM unnest(i.indcollation::oid[], i.indkey::int2[]) AS x(coll, att) JOIN pg_catalog.pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = x.att WHERE x.att > 0 AND x.coll <> a.attcollation))`;export{u as a,P as b,$ as c,F as d,z as e,M as f,j as g,U as h,v as i,R as j,b as k,a as l,i as m,O as n,q as o,g as p,E as q,l as r,p as s,x as t,m as u,y as v,w,k as x,h as y,_ as z,N as A,C as B,D as C,A as D,I as E};
package/dist/cli.js ADDED
@@ -0,0 +1,2 @@
1
+ /*! palgres 0.66.0 — Palbase SDK License (see LICENSE) */
2
+ import{E as f,s as p,y as d}from"./chunks/BWGT6CBO.js";import"./chunks/2VBY4HRX.js";import"./chunks/RN23MOOY.js";import"./chunks/NDFZTRRI.js";import{mkdirSync as w,writeFileSync as E}from"node:fs";import{join as c}from"node:path";async function S(t){let[e,s="."]=t,o=process.env.PALGRES_DATABASE_URL;if(e!=="pull"||t.length>2)return console.error("usage: PALGRES_DATABASE_URL=\u2026 palgres pull [directory]"),1;if(!o)return console.error("palgres pull: PALGRES_DATABASE_URL is the database to read"),1;let r=globalThis.Bun;if(!r)return console.error("palgres pull runs under Bun (use `palbase db:pull`)"),1;let a;try{a=new r.SQL({url:o,prepare:!1,max:2});let u=(await a.unsafe("SELECT nspname AS name FROM pg_namespace WHERE nspname NOT LIKE 'pg\\_%' AND nspname NOT IN ('information_schema', 'palgres', 'auth') AND nspname NOT LIKE 'palgres\\_%' ORDER BY 1")).map(n=>n.name),i=await p(a,u,d),{files:g,notes:m}=f(i.schema,{unmanaged:i.unmanaged,units:i.units});for(let[n,l]of g)w(c(s,"db"),{recursive:!0}),E(c(s,n),l),console.log(`wrote ${c(s,n)}`);let h=n=>n.replace(/[\u0000-\u001f\u007f-\u009f]/g,l=>`\\u${l.charCodeAt(0).toString(16).padStart(4,"0")}`);(await a.unsafe("SELECT 1 FROM pg_namespace WHERE nspname = 'auth'")).length>0&&m.push("schema auth: not pulled \u2014 it is the platform's (auth.users, auth.uid()); a schema of your own named auth would need another name");for(let n of[...m,...i.unmanaged])console.log(` ${h(n)}`);return 0}catch(u){return console.error(`palgres pull: ${A(u)}`),1}finally{await a?.close().catch(()=>{})}}function A(t){let e=t,s=[e?.code,e?.errno].find(r=>typeof r=="string"&&/^[0-9A-Z]{5}$/.test(r));if(s!==void 0&&typeof e?.message=="string")return`${e.message} (${s})`;let o=[e?.code,e?.errno].find(r=>typeof r=="string");return`${typeof e?.name=="string"?e.name:"Error"}${o?` ${o}`:""}: the database could not be read (its address is not repeated here)`}process.exitCode=await S(process.argv.slice(2));
package/dist/dsl.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! palgres 0.64.0 — Palbase SDK License (see LICENSE) */
2
- import{a as b,d as g,e as C,f as w,g as R,h as T,i as P,j as h,k as A,n as U,o as B,p as E,q as K,r as k,s as I}from"./chunks/VDXJB5ED.js";import{$ as c,R as n,S as i,T as f,U as a,V as l,W as p,X as u,Y as m,Z as s,_ as y,aa as d,ba as x,ca as D}from"./chunks/NS3WKWF5.js";function M(o,t,e){if(e===void 0)return{name:o,up:t};let r={name:o,up:t};return e.drop!==void 0&&(r.drop=e.drop),e.before===!0&&(r.before=!0),r}export{g as ColumnBuilder,n as ForeignKeyBuilder,a as IndexBuilder,c as PolicyBuilder,s as PolicyExprRef,p as TABLE_META,T as bigint,U as boolean,x as check,h as date,m as defineSchema,u as defineTable,K as enumType,y as exprCtx,i as foreignKey,l as index,R as integer,E as jsonb,P as numeric,k as ownedByUser,d as policy,D as policySQL,f as qualifiedTableKey,M as raw,A as sqlType,w as text,B as timestamp,b as toModel,I as userRef,C as uuid};
1
+ /*! palgres 0.66.0 — Palbase SDK License (see LICENSE) */
2
+ import{b as g,c as C,d as w,e as R,f as T,g as P,h,i as A,l as U,m as B,n as E,o as K,p as k,q as I}from"./chunks/LRDQMK6O.js";import{a as b}from"./chunks/2VBY4HRX.js";import{$ as c,R as n,S as i,T as f,U as a,V as l,W as p,X as u,Y as m,Z as s,_ as y,aa as d,ba as x,ca as D}from"./chunks/NDFZTRRI.js";function M(o,t,e){if(e===void 0)return{name:o,up:t};let r={name:o,up:t};return e.drop!==void 0&&(r.drop=e.drop),e.before===!0&&(r.before=!0),r}export{g as ColumnBuilder,n as ForeignKeyBuilder,a as IndexBuilder,c as PolicyBuilder,s as PolicyExprRef,p as TABLE_META,T as bigint,U as boolean,x as check,h as date,m as defineSchema,u as defineTable,K as enumType,y as exprCtx,i as foreignKey,l as index,R as integer,E as jsonb,P as numeric,k as ownedByUser,d as policy,D as policySQL,f as qualifiedTableKey,M as raw,A as sqlType,w as text,B as timestamp,b as toModel,I as userRef,C as uuid};