@inflector/optima-pg 1.0.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/index.js ADDED
@@ -0,0 +1,27 @@
1
+ var D=["=","==","!=","<>",">",">=","<","<=","in","not in","is","is not","like","not like","match","ilike","not ilike","@>","<@","^@","&&","?","?&","?|","!<","!>","<=>","!~","~","~*","!~*","@@","@@@","!!","<->","regexp","is distinct from","is not distinct from"],B=["+","-","*","/","%","^","&","|","#","<<",">>"],Q=["->","->>"],U=[...D,...B,"&&","||"],H=["exists","not exists"],W=["not","-","exists","not exists"],V=[...U,...Q,...W,"between","between symmetric","array_append"];function _(e){return typeof e=="object"&&e!==null&&e.__kind==="array_append"}function $(e){return typeof e=="object"&&e!==null&&e.__kind==="op"}function k(e){return typeof e=="object"&&e!==null&&e.__kind==="between"}function L(e){return typeof e=="object"&&e!==null&&e.__kind==="unary"}function I(e){return typeof e=="object"&&e!==null&&e.__kind==="json"}function K(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Date)&&!$(e)&&!k(e)&&!L(e)&&!I(e)&&!_(e)}function C(e,t,r){let n=[];for(let[o,a]of Object.entries(r)){let s=[...t,o];K(a)?n.push(...C(e,s,a)):$(a)?n.push({col:e,path:s,op:a.op,val:a.value}):k(a)?(n.push({col:e,path:s,op:">=",val:a.low}),n.push({col:e,path:s,op:"<=",val:a.high})):I(a)?n.push({col:e,path:a.path,op:a.op,val:a.value}):n.push({col:e,path:s,op:"=",val:a})}return n}function w(e){let t=[];for(let[r,n]of Object.entries(e)){if(r==="$and"&&Array.isArray(n)){t.push({and:n.flatMap(o=>w(o))});continue}if(r==="$or"&&Array.isArray(n)){t.push({or:n.flatMap(o=>w(o))});continue}if(K(n)){t.push(...C(r,[],n));continue}k(n)?t.push({col:r,op:n.op,low:n.low,high:n.high}):L(n)?t.push({col:r,op:n.op}):I(n)?t.push({col:r,path:n.path,op:n.op,val:n.value}):$(n)?t.push({col:r,op:n.op,val:n.value}):_(n)?t.push({col:r,op:"array_append",val:n.value}):t.push({col:r,op:"=",val:n})}return t}var i=e=>t=>({__kind:"op",op:e,value:t}),Z=e=>i("=")(e),ee=e=>i("==")(e),te=e=>i("!=")(e),ne=e=>i("<>")(e),re=e=>i(">")(e),oe=e=>i(">=")(e),se=e=>i("<")(e),ae=e=>i("<=")(e),ie=e=>i("!<")(e),le=e=>i("!>")(e),ue=e=>i("<=>")(e),pe=e=>i("in")(e),ce=e=>i("not in")(e),ye=e=>i("is")(e),fe=e=>i("is not")(e),Te=e=>i("is distinct from")(e),de=e=>i("is not distinct from")(e),he=e=>i("like")(e),me=e=>i("not like")(e),Se=e=>i("ilike")(e),ge=e=>i("not ilike")(e),xe=e=>i("match")(e),Re=e=>i("~")(e),we=e=>i("~*")(e),Ee=e=>i("!~")(e),Ae=e=>i("!~*")(e),be=e=>i("regexp")(e),Oe=e=>i("@@")(e),$e=e=>i("@@@")(e),ke=e=>i("@>")(e),Ie=e=>i("<@")(e),_e=e=>i("^@")(e),Le=e=>i("&&")(e),Ke=e=>i("?")(e),Ce=e=>i("?&")(e),Ne=e=>i("?|")(e),Pe=e=>i("<->")(e),Fe=e=>i("!!")(e),ve=(e,t)=>({__kind:"between",op:"between",low:e,high:t}),De=(e,t)=>({__kind:"between",op:"between symmetric",low:e,high:t}),Be=e=>({__kind:"unary",op:e}),Qe=e=>({__kind:"array_append",value:e}),Ue=(e,t)=>({__kind:"op",op:e,value:t});import{Kysely as j,PostgresDialect as q,sql as R}from"kysely";import{KyselyPGlite as v}from"kysely-pglite";import{Pool as M,Client as Y}from"pg";function N(e){let t={},r={get(n,o){return o==="$build"?()=>e?e(t):t:(...a)=>(a.length===0?t[o]=!0:a.length===1?t[o]=a[0]:t[o]=a,new Proxy(t,r))}};return new Proxy(t,r)}var T=()=>N(),Me=(e=4)=>{let t={2:"smallint",4:"integer",8:"bigint"};return T().SQlType(t[e])},Ye=(e=4)=>{let t={4:"real",8:"double precision"};return T().SQlType(t[e])},Je=()=>T().SQlType("uuid"),Ge=e=>{let t=e!=null?`varchar(${e})`:"text";return T().SQlType(t)},ze=()=>T().SQlType("jsonb"),Xe=e=>{let t=e().$build().SQlType;return T().SQlType(`${t}[]`)},He=()=>T().SQlType("boolean"),Ve=(e=!1)=>{let t=e?"time with time zone":"time";return T().SQlType(t)},Ze=(e=!0)=>{let t=e?"timestamp with time zone":"timestamp";return T().SQlType(t)},et=()=>T().SQlType("bytea"),tt=e=>T().SQlType("vector"),nt=e=>e;function P(e,t){let r=o=>typeof o=="string"?`'${o.replace(/'/g,"''")}'`:typeof o=="boolean"?o?"true":"false":JSON.stringify(o),n=Object.entries(t).map(([o,a])=>{let s=a.$build(),p=[`"${o}"`,s.SQlType??"text"];return s.primaryKey&&p.push("PRIMARY KEY"),s.notnull&&p.push("NOT NULL"),s.unique&&p.push("UNIQUE"),s.defaultNow&&s.SQlType&&(s.SQlType.toLowerCase().startsWith("timestamp")||s.SQlType.toLowerCase().startsWith("datetime")||s.SQlType.toLowerCase().startsWith("date"))&&p.push("DEFAULT NOW()"),s.defaultRandom&&s.SQlType&&s.SQlType.toLowerCase().includes("uuid")&&p.push("DEFAULT gen_random_uuid()"),s.default!==void 0&&s.SQlType!="jsonb"&&p.push(`DEFAULT ${r(s.default)}`),s.default!==void 0&&s.SQlType=="jsonb"&&p.push(`DEFAULT '${r(s.default)}'::jsonb`)," "+p.join(" ")});return`CREATE TABLE IF NOT EXISTS "${e}" (
2
+ ${n.join(`,
3
+ `)}
4
+ );`}import{sql as l}from"kysely";function d(e){let t={},r={get(n,o){return o==="then"?(a,s)=>{let p=e?e(n):n;Promise.resolve(p).then(a,s)}:(...a)=>(a.length===0?n[o]=!0:a.length===1?n[o]=a[0]:n[o]=a,new Proxy(n,r))}};return new Proxy(t,r)}function F(e,t){let r=l`${l.ref(e)}`;for(let n=0;n<t.length;n++){let o=t[n],s=n===t.length-1?"->>":"->";r=typeof o=="number"?l`${r}${l.raw(s)}${l.val(o)}`:l`${r}${l.raw(s)}${l.val(String(o))}`}return r}function m(e,t){for(let r of t)"and"in r?e=e.where(n=>n.and(r.and.map(o=>E(n,o)))):"or"in r?e=e.where(n=>n.or(r.or.map(o=>E(n,o)))):"low"in r?e=e.where(l`${l.ref(r.col)} ${l.raw(r.op)} ${l.val(r.low)} AND ${l.val(r.high)}`):"path"in r?e=e.where(l`${F(r.col,r.path)} ${l.raw(r.op)} ${l.val(r.val)}`):"val"in r?r.op==="array_append"?e=e.set(l`${l.ref(r.col)} = ${l.ref(r.col)} || ARRAY[${l.val(r.val)}]`):e=e.where(r.col,r.op,r.val):e=e.where(l`${l.ref(r.col)} ${l.raw(r.op)}`);return e}function E(e,t){return"and"in t?e.and(t.and.map(r=>E(e,r))):"or"in t?e.or(t.or.map(r=>E(e,r))):"low"in t?l`${l.ref(t.col)} ${l.raw(t.op)} ${l.val(t.low)} AND ${l.val(t.high)}`:"path"in t?l`${F(t.col,t.path)} ${l.raw(t.op)} ${l.val(t.val)}`:"val"in t?e(t.col,t.op,t.val):l`${l.ref(t.col)} ${l.raw(t.op)}`}function S(e){if(Array.isArray(e)){let[t,r,n]=e;return[{col:t,op:r,val:n}]}return w(e)}var A=class{constructor(t,r,n,o){this.name="";this.name=t,this.db=n,this.schema=r,this.listenFn=o}serializeDates(t){return Object.fromEntries(Object.entries(t).map(([r,n])=>n instanceof Date?[r,n.toISOString()]:Array.isArray(n)&&n.every(o=>typeof o=="number")?[r,`[${n.join(",")}]`]:typeof n=="object"&&n!==null&&n.__kind==="array_append"?[r,l`${l.ref(r)} || ARRAY[${l.val(n.value)}]`]:[r,n]))}getVectorCols(){return new Set(Object.entries(this.schema).filter(([,t])=>t.$build().SQlType=="vector").map(([t])=>t))}deserializeRow(t){let r=this.getVectorCols();return Object.fromEntries(Object.entries(t).map(([n,o])=>r.has(n)&&typeof o=="string"?[n,JSON.parse(o)]:[n,o]))}Get(t){return d(async r=>{let n=this.db.selectFrom(this.name);return t?n=n.select(t):n=n.selectAll(),r.where&&(n=m(n,S(r.where))),r.distinct&&(n=n.distinct()),r.orderby&&(n=n.orderBy(r.orderby[0],r.orderby[1])),r.limit&&(n=n.limit(r.limit)),r.offset&&(n=n.offset(r.offset)),(await n.execute()).map(a=>this.deserializeRow(a))})}GetOne(t){return d(async r=>{let n=this.db.selectFrom(this.name);r.where&&(n=m(n,S(r.where))),n=n.limit(1);let o=await n.execute();if(o[0])return this.deserializeRow(o[0])})}Insert(t){return d(async r=>{if(t==="default"){let n=this.db.insertInto(this.name).defaultValues();if(r.returning)return await n.returningAll().execute();await n.execute()}else{let o=(Array.isArray(t)?t:[t]).map(s=>this.serializeDates(s)),a=this.db.insertInto(this.name).values(o);if(r.returning)return await a.returningAll().execute();await a.execute()}return[]})}Delete(){return d(async t=>{let r=this.db.deleteFrom(this.name);return t.where&&(r=m(r,S(t.where))),t.returning?await r.returningAll().execute():(await r.execute(),[])})}Update(t){return d(async r=>{let n=this.db.updateTable(this.name).set(this.serializeDates(t));return r.where&&(n=m(n,S(r.where))),r.returning?await n.returningAll().execute():(await n.execute(),[])})}Count(){return d(async t=>{let r=this.db.selectFrom(this.name);t.where&&(r=m(r,S(t.where)));let n=await r.select(this.db.fn.countAll().as("count")).executeTakeFirstOrThrow();return Number(n.count)})}Exist(){return d(async t=>{let r=this.db.selectFrom(this.name);return t.where&&(r=m(r,S(t.where))),(await r.selectAll().limit(1).execute()).length>0})}Subscribe(t){return this.listenFn(this.name,r=>{t(JSON.parse(r))})}};var J=async(e,t,r,n)=>{let o=`
5
+ CREATE OR REPLACE FUNCTION notify_table_change()
6
+ RETURNS trigger AS $$
7
+ BEGIN
8
+ PERFORM pg_notify(
9
+ TG_TABLE_NAME,
10
+ json_build_object(
11
+ 'op', TG_OP,
12
+ 'new', row_to_json(NEW),
13
+ 'old', row_to_json(OLD)
14
+ )::text
15
+ );
16
+ RETURN NEW;
17
+ END;
18
+ $$ LANGUAGE plpgsql;
19
+ `;n?await t.query(o):await R.raw(o).execute(e);for(let[a,s]of Object.entries(r)){let p=P(a,s),y=`
20
+ CREATE OR REPLACE TRIGGER "${a}_notify"
21
+ AFTER INSERT OR UPDATE OR DELETE ON "${a}"
22
+ FOR EACH ROW EXECUTE FUNCTION notify_table_change();
23
+ `;n?(await t.query(p),await t.query(y)):(await R.raw(p).execute(e),await R.raw(y).execute(e))}},Tt=async(e,t=":memory:",r)=>{let n,o,a,s,p=!t.startsWith("postgres://");if(p){if(t==":memory:"){let u=await v.create();o=u.dialect,n=u.client}else{let u=await v.create(t,r);o=u.dialect,n=u.client}a=async(u,c)=>(await n.listen(u,c),async()=>{await n.unlisten(u)}),s=async(u,c="")=>{await n.query("SELECT pg_notify($1, $2)",[u,typeof c=="string"?c:JSON.stringify(c)])}}else{o=new q({pool:new M({connectionString:t})}),n=new Y({connectionString:t}),await n.connect(),n.on("error",c=>console.error("PG listener error:",c));let u=new Map;n.on("notification",c=>{let f=u.get(c.channel);f&&f.forEach(x=>x(c.payload??""))}),a=async(c,f)=>(u.has(c)||(u.set(c,new Set),await n.query(`LISTEN "${c}"`)),u.get(c).add(f),async()=>{let x=u.get(c);x&&(x.delete(f),x.size===0&&(u.delete(c),await n.query(`UNLISTEN "${c}"`)))}),s=async(c,f="")=>{await R.raw(`SELECT pg_notify('${c}', '${typeof f=="string"?f:JSON.stringify(f)}')`).execute(y)}}let y=new j({dialect:o});return await J(y,n,e,p),{...Object.fromEntries(Object.entries(e).map(([u,c])=>[u,new A(u,c,y,a)])),$raw:async u=>(await R.raw(u).execute(y)).rows,$listen:a,$notify:s,$watch:async(u,c)=>a(u,f=>{c(JSON.parse(f))})}};function b(e){return e.$build()}function G(e,t){return t==="jsonb"?`${typeof e=="string"?`'${e.replace(/'/g,"''")}'`:`'${JSON.stringify(e)}'`}::jsonb`:typeof e=="string"?`'${e.replace(/'/g,"''")}'`:typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function O(e){if(e.defaultNow){let t=e.SQlType?.toLowerCase()??"";if(t.startsWith("timestamp")||t.startsWith("datetime")||t.startsWith("date"))return"NOW()"}if(e.defaultRandom&&e.SQlType?.toLowerCase().includes("uuid"))return"gen_random_uuid()";if(e.default!==void 0)return G(e.default,e.SQlType)}function z(e,t,r,n){let o=[],a=`"${e}"."${t}"`,s=`"${e}"`;(r.SQlType??"text")!==(n.SQlType??"text")&&o.push({kind:"alter_type",sql:`ALTER TABLE ${s} ALTER COLUMN "${t}" TYPE ${n.SQlType??"text"} USING "${t}"::${n.SQlType??"text"};`}),!r.notnull&&n.notnull?o.push({kind:"set_notnull",sql:`ALTER TABLE ${s} ALTER COLUMN "${t}" SET NOT NULL;`}):r.notnull&&!n.notnull&&o.push({kind:"drop_notnull",sql:`ALTER TABLE ${s} ALTER COLUMN "${t}" DROP NOT NULL;`});let p=O(r),y=O(n);return p!==y&&(y!==void 0?o.push({kind:"set_default",sql:`ALTER TABLE ${s} ALTER COLUMN "${t}" SET DEFAULT ${y};`}):o.push({kind:"drop_default",sql:`ALTER TABLE ${s} ALTER COLUMN "${t}" DROP DEFAULT;`})),!r.unique&&n.unique?o.push({kind:"add_unique",sql:`ALTER TABLE ${s} ADD CONSTRAINT "uq_${e}_${t}" UNIQUE ("${t}");`}):r.unique&&!n.unique&&o.push({kind:"drop_unique",sql:`ALTER TABLE ${s} DROP CONSTRAINT IF EXISTS "uq_${e}_${t}";`}),!r.primaryKey&&n.primaryKey?o.push({kind:"add_primary_key",sql:`ALTER TABLE ${s} ADD CONSTRAINT "pk_${e}_${t}" PRIMARY KEY ("${t}");`}):r.primaryKey&&!n.primaryKey&&o.push({kind:"drop_primary_key",sql:`ALTER TABLE ${s} DROP CONSTRAINT IF EXISTS "pk_${e}_${t}";`}),o}function X(e,t,r){let n=[],o=new Set(Object.keys(t)),a=new Set(Object.keys(r));for(let s of o)a.has(s)||n.push({kind:"drop_column",sql:`ALTER TABLE "${e}" DROP COLUMN IF EXISTS "${s}";`});for(let s of a)if(!o.has(s)&&r[s]){let p=b(r[s]),y=[`"${s}"`,p.SQlType??"text"];p.primaryKey&&y.push("PRIMARY KEY"),p.notnull&&y.push("NOT NULL"),p.unique&&y.push("UNIQUE");let g=O(p);g!==void 0&&y.push(`DEFAULT ${g}`),n.push({kind:"add_column",sql:`ALTER TABLE "${e}" ADD COLUMN ${y.join(" ")};`})}for(let s of a)if(o.has(s)&&r[s]&&t[s]){let p=b(t[s]),y=b(r[s]);n.push(...z(e,s,p,y))}return n}function ht(e,t){let r=[],n=new Set(Object.keys(e)),o=new Set(Object.keys(t));for(let a of n)o.has(a)||r.push({kind:"drop_table",sql:`DROP TABLE IF EXISTS "${a}";`});for(let a of o)if(!n.has(a)){let s=t[a],p=Object.entries(s).map(([y,g])=>{let h=b(g),u=[`"${y}"`,h.SQlType??"text"];h.primaryKey&&u.push("PRIMARY KEY"),h.notnull&&u.push("NOT NULL"),h.unique&&u.push("UNIQUE");let c=O(h);return c!==void 0&&u.push(`DEFAULT ${c}`)," "+u.join(" ")}).join(`,
24
+ `);r.push({kind:"create_table",sql:`CREATE TABLE IF NOT EXISTS "${a}" (
25
+ ${p}
26
+ );`})}for(let a of o)n.has(a)&&r.push(...X(a,e[a],t[a]));return r.map(a=>a.sql).join(`
27
+ `)}export{B as ARITHMETIC_OPERATORS,U as BINARY_OPERATORS,D as COMPARISON_OPERATORS,T as Column,Tt as Database,Q as JSON_OPERATORS,V as OPERATORS,A as Table,H as UNARY_FILTER_OPERATORS,W as UNARY_OPERATORS,Qe as add,Xe as array,Fe as bang,ve as between,De as betweenSymmetric,He as bool,w as buildWhere,et as bytea,Ie as containedBy,ke as contains,d as createFluentBuilder,Pe as distance,Z as eq,ee as eqq,Ye as float,ht as generateMigration,P as getDefSQL,re as gt,oe as gte,Ce as hasAllKeys,Ne as hasAnyKey,Ke as hasKey,Se as ilike,pe as inList,Me as int,we as iregex,ye as is,Te as isDistinct,fe as isNot,de as isNotDistinct,ze as json,he as like,se as lt,ae as lte,xe as match,te as neq,ne as neqAlt,le as notGt,ge as notIlike,ce as notIn,Ae as notIregex,me as notLike,ie as notLt,Ee as notRegex,ue as nullSafeEq,Ue as op,Le as overlaps,Re as regex,be as regexp,_e as startsWith,nt as table,Ge as text,Ve as time,Ze as timestamp,Oe as tsMatch,$e as tsPhrase,Be as unary,Je as uuid,tt as vector};
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "@inflector/optima-pg",
3
+ "version": "1.0.0",
4
+ "module": "index.ts",
5
+ "type": "module",
6
+ "devDependencies": {
7
+ "@types/bun": "latest",
8
+ "tsup": "^8.5.1",
9
+ "typescript": "^5.9.3"
10
+ },
11
+ "files": [
12
+ "dist"
13
+ ],
14
+ "scripts": {
15
+ "dev": "bun index.ts",
16
+ "build": "tsup src/index.ts src/types.ts --format esm --dts --clean --minify",
17
+ "prepublishOnly": "bun run build"
18
+ },
19
+ "peerDependencies": {
20
+ "typescript": "^5"
21
+ },
22
+ "dependencies": {
23
+ "@electric-sql/pglite": "^0.3.15",
24
+ "@types/pg": "^8.16.0",
25
+ "kysely": "^0.28.11",
26
+ "kysely-pglite": "^0.6.1",
27
+ "pg": "^8.18.0"
28
+ }
29
+ }