@inflector/optima-pg 1.0.1 → 1.0.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.
Files changed (2) hide show
  1. package/dist/index.js +912 -12
  2. package/package.json +8 -3
package/dist/index.js CHANGED
@@ -1,7 +1,579 @@
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=`
1
+ // src/where.ts
2
+ var COMPARISON_OPERATORS = [
3
+ "=",
4
+ "==",
5
+ "!=",
6
+ "<>",
7
+ ">",
8
+ ">=",
9
+ "<",
10
+ "<=",
11
+ "in",
12
+ "not in",
13
+ "is",
14
+ "is not",
15
+ "like",
16
+ "not like",
17
+ "match",
18
+ "ilike",
19
+ "not ilike",
20
+ "@>",
21
+ "<@",
22
+ "^@",
23
+ "&&",
24
+ "?",
25
+ "?&",
26
+ "?|",
27
+ "!<",
28
+ "!>",
29
+ "<=>",
30
+ "!~",
31
+ "~",
32
+ "~*",
33
+ "!~*",
34
+ "@@",
35
+ "@@@",
36
+ "!!",
37
+ "<->",
38
+ "regexp",
39
+ "is distinct from",
40
+ "is not distinct from"
41
+ ];
42
+ var ARITHMETIC_OPERATORS = [
43
+ "+",
44
+ "-",
45
+ "*",
46
+ "/",
47
+ "%",
48
+ "^",
49
+ "&",
50
+ "|",
51
+ "#",
52
+ "<<",
53
+ ">>"
54
+ ];
55
+ var JSON_OPERATORS = ["->", "->>"];
56
+ var BINARY_OPERATORS = [
57
+ ...COMPARISON_OPERATORS,
58
+ ...ARITHMETIC_OPERATORS,
59
+ "&&",
60
+ "||"
61
+ ];
62
+ var UNARY_FILTER_OPERATORS = ["exists", "not exists"];
63
+ var UNARY_OPERATORS = ["not", "-", "exists", "not exists"];
64
+ var OPERATORS = [
65
+ ...BINARY_OPERATORS,
66
+ ...JSON_OPERATORS,
67
+ ...UNARY_OPERATORS,
68
+ "between",
69
+ "between symmetric",
70
+ "array_append"
71
+ ];
72
+ function isArrayAppendExpr(v) {
73
+ return typeof v === "object" && v !== null && v.__kind === "array_append";
74
+ }
75
+ function isOpExpr(v) {
76
+ return typeof v === "object" && v !== null && v.__kind === "op";
77
+ }
78
+ function isBetweenExpr(v) {
79
+ return typeof v === "object" && v !== null && v.__kind === "between";
80
+ }
81
+ function isUnaryExpr(v) {
82
+ return typeof v === "object" && v !== null && v.__kind === "unary";
83
+ }
84
+ function isJsonExpr(v) {
85
+ return typeof v === "object" && v !== null && v.__kind === "json";
86
+ }
87
+ function isNestedTarget(v) {
88
+ return typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Date) && // The runtime object HAS these keys, so these checks return true
89
+ !isOpExpr(v) && !isBetweenExpr(v) && !isUnaryExpr(v) && !isJsonExpr(v) && !isArrayAppendExpr(v);
90
+ }
91
+ function flattenNested(col, currentPath, input) {
92
+ const nodes = [];
93
+ for (const [key, value] of Object.entries(input)) {
94
+ const nextPath = [...currentPath, key];
95
+ if (isNestedTarget(value)) {
96
+ nodes.push(...flattenNested(col, nextPath, value));
97
+ } else {
98
+ if (isOpExpr(value)) {
99
+ nodes.push({ col, path: nextPath, op: value.op, val: value.value });
100
+ } else if (isBetweenExpr(value)) {
101
+ nodes.push({ col, path: nextPath, op: ">=", val: value.low });
102
+ nodes.push({ col, path: nextPath, op: "<=", val: value.high });
103
+ } else if (isJsonExpr(value)) {
104
+ nodes.push({ col, path: value.path, op: value.op, val: value.value });
105
+ } else {
106
+ nodes.push({ col, path: nextPath, op: "=", val: value });
107
+ }
108
+ }
109
+ }
110
+ return nodes;
111
+ }
112
+ function buildWhere(input) {
113
+ const nodes = [];
114
+ for (const [key, value] of Object.entries(input)) {
115
+ if (key === "$and" && Array.isArray(value)) {
116
+ nodes.push({ and: value.flatMap((b) => buildWhere(b)) });
117
+ continue;
118
+ }
119
+ if (key === "$or" && Array.isArray(value)) {
120
+ nodes.push({ or: value.flatMap((b) => buildWhere(b)) });
121
+ continue;
122
+ }
123
+ if (isNestedTarget(value)) {
124
+ nodes.push(...flattenNested(key, [], value));
125
+ continue;
126
+ }
127
+ if (isBetweenExpr(value)) {
128
+ nodes.push({ col: key, op: value.op, low: value.low, high: value.high });
129
+ } else if (isUnaryExpr(value)) {
130
+ nodes.push({ col: key, op: value.op });
131
+ } else if (isJsonExpr(value)) {
132
+ nodes.push({
133
+ col: key,
134
+ //@ts-ignore
135
+ path: value.path,
136
+ //@ts-ignore
137
+ op: value.op,
138
+ //@ts-ignore
139
+ val: value.value
140
+ });
141
+ } else if (isOpExpr(value)) {
142
+ nodes.push({ col: key, op: value.op, val: value.value });
143
+ } else if (isArrayAppendExpr(value)) {
144
+ nodes.push({ col: key, op: "array_append", val: value.value });
145
+ } else {
146
+ nodes.push({ col: key, op: "=", val: value });
147
+ }
148
+ }
149
+ return nodes;
150
+ }
151
+ var o = (operator) => (value) => ({ __kind: "op", op: operator, value });
152
+ var eq = (val) => o("=")(val);
153
+ var eqq = (val) => o("==")(val);
154
+ var neq = (val) => o("!=")(val);
155
+ var neqAlt = (val) => o("<>")(val);
156
+ var gt = (val) => o(">")(val);
157
+ var gte = (val) => o(">=")(val);
158
+ var lt = (val) => o("<")(val);
159
+ var lte = (val) => o("<=")(val);
160
+ var notLt = (val) => o("!<")(val);
161
+ var notGt = (val) => o("!>")(val);
162
+ var nullSafeEq = (val) => o("<=>")(val);
163
+ var inList = (val) => o("in")(val);
164
+ var notIn = (val) => o("not in")(val);
165
+ var is = (val) => o("is")(val);
166
+ var isNot = (val) => o("is not")(val);
167
+ var isDistinct = (val) => o("is distinct from")(val);
168
+ var isNotDistinct = (val) => o("is not distinct from")(val);
169
+ var like = (val) => o("like")(val);
170
+ var notLike = (val) => o("not like")(val);
171
+ var ilike = (val) => o("ilike")(val);
172
+ var notIlike = (val) => o("not ilike")(val);
173
+ var match = (val) => o("match")(val);
174
+ var regex = (val) => o("~")(val);
175
+ var iregex = (val) => o("~*")(val);
176
+ var notRegex = (val) => o("!~")(val);
177
+ var notIregex = (val) => o("!~*")(val);
178
+ var regexp = (val) => o("regexp")(val);
179
+ var tsMatch = (val) => o("@@")(val);
180
+ var tsPhrase = (val) => o("@@@")(val);
181
+ var contains = (val) => o("@>")(val);
182
+ var containedBy = (val) => o("<@")(val);
183
+ var startsWith = (val) => o("^@")(val);
184
+ var overlaps = (val) => o("&&")(val);
185
+ var hasKey = (val) => o("?")(val);
186
+ var hasAllKeys = (val) => o("?&")(val);
187
+ var hasAnyKey = (val) => o("?|")(val);
188
+ var distance = (val) => o("<->")(val);
189
+ var bang = (val) => o("!!")(val);
190
+ var between = (low, high) => ({
191
+ __kind: "between",
192
+ op: "between",
193
+ low,
194
+ high
195
+ });
196
+ var betweenSymmetric = (low, high) => ({
197
+ __kind: "between",
198
+ op: "between symmetric",
199
+ low,
200
+ high
201
+ });
202
+ var unary = (operator) => ({
203
+ __kind: "unary",
204
+ op: operator
205
+ });
206
+ var add = (val) => ({
207
+ __kind: "array_append",
208
+ value: val
209
+ });
210
+ var op = (operator, val) => ({ __kind: "op", op: operator, value: val });
211
+
212
+ // src/database.ts
213
+ import { Kysely, PostgresDialect, sql as sql2 } from "kysely";
214
+ import { KyselyPGlite } from "kysely-pglite";
215
+ import { Pool, Client } from "pg";
216
+
217
+ // src/SyncFluent.ts
218
+ function createFluentBuilder(onBuild) {
219
+ const data = {};
220
+ const handler = {
221
+ get(target, prop) {
222
+ if (prop === "$build") {
223
+ return () => {
224
+ return onBuild ? onBuild(data) : data;
225
+ };
226
+ }
227
+ return (...args) => {
228
+ if (args.length === 0) {
229
+ data[prop] = true;
230
+ } else if (args.length === 1) {
231
+ data[prop] = args[0];
232
+ } else {
233
+ data[prop] = args;
234
+ }
235
+ return new Proxy(data, handler);
236
+ };
237
+ }
238
+ };
239
+ return new Proxy(data, handler);
240
+ }
241
+
242
+ // src/schema.ts
243
+ var Column = () => {
244
+ return createFluentBuilder();
245
+ };
246
+ var int = (bytes = 4) => {
247
+ const map = { "2": "smallint", "4": "integer", "8": "bigint" };
248
+ return Column().SQlType(map[bytes]);
249
+ };
250
+ var float = (bytes = 4) => {
251
+ const map = { "4": "real", "8": "double precision" };
252
+ return Column().SQlType(map[bytes]);
253
+ };
254
+ var uuid = () => {
255
+ return Column().SQlType("uuid");
256
+ };
257
+ var text = (length) => {
258
+ const type = length != null ? `varchar(${length})` : "text";
259
+ return Column().SQlType(type);
260
+ };
261
+ var json = () => {
262
+ return Column().SQlType("jsonb");
263
+ };
264
+ var array = (inner) => {
265
+ const innerType = inner().$build().SQlType;
266
+ return Column().SQlType(`${innerType}[]`);
267
+ };
268
+ var bool = () => {
269
+ return Column().SQlType("boolean");
270
+ };
271
+ var time = (withTimezone = false) => {
272
+ const type = withTimezone ? "time with time zone" : "time";
273
+ return Column().SQlType(type);
274
+ };
275
+ var timestamp = (withTimezone = true) => {
276
+ const type = withTimezone ? "timestamp with time zone" : "timestamp";
277
+ return Column().SQlType(type);
278
+ };
279
+ var bytea = () => {
280
+ return Column().SQlType("bytea");
281
+ };
282
+ var vector = (dimension) => {
283
+ return Column().SQlType("vector");
284
+ };
285
+ var table = (cols) => {
286
+ return cols;
287
+ };
288
+ function getDefSQL(tableName, cols) {
289
+ const formatDefault2 = (def) => {
290
+ if (typeof def === "string") return `'${def.replace(/'/g, "''")}'`;
291
+ if (typeof def === "boolean") return def ? "true" : "false";
292
+ return JSON.stringify(def);
293
+ };
294
+ const columns = Object.entries(cols).map(([name, col]) => {
295
+ const def = col.$build();
296
+ const parts = [`"${name}"`, def.SQlType ?? "text"];
297
+ if (def.primaryKey) parts.push("PRIMARY KEY");
298
+ if (def.notnull) parts.push("NOT NULL");
299
+ if (def.unique) parts.push("UNIQUE");
300
+ if (def.defaultNow) {
301
+ if (def.SQlType && (def.SQlType.toLowerCase().startsWith("timestamp") || def.SQlType.toLowerCase().startsWith("datetime") || def.SQlType.toLowerCase().startsWith("date"))) {
302
+ parts.push("DEFAULT NOW()");
303
+ }
304
+ }
305
+ if (def.defaultRandom) {
306
+ if (def.SQlType && def.SQlType.toLowerCase().includes("uuid")) {
307
+ parts.push("DEFAULT gen_random_uuid()");
308
+ }
309
+ }
310
+ if (def.default !== void 0 && def.SQlType != "jsonb") {
311
+ parts.push(`DEFAULT ${formatDefault2(def.default)}`);
312
+ }
313
+ if (def.default !== void 0 && def.SQlType == "jsonb") {
314
+ parts.push(`DEFAULT '${formatDefault2(def.default)}'::jsonb`);
315
+ }
316
+ return " " + parts.join(" ");
317
+ });
318
+ return `CREATE TABLE IF NOT EXISTS "${tableName}" (
319
+ ${columns.join(",\n")}
320
+ );`;
321
+ }
322
+
323
+ // src/table.ts
324
+ import { sql } from "kysely";
325
+
326
+ // src/AsyncFluent.ts
327
+ function createFluentBuilder2(onBuild) {
328
+ const data = {};
329
+ const handler = {
330
+ get(target, prop) {
331
+ if (prop === "then") {
332
+ return (resolve, reject) => {
333
+ const result = onBuild ? onBuild(target) : target;
334
+ Promise.resolve(result).then(resolve, reject);
335
+ };
336
+ }
337
+ return (...args) => {
338
+ if (args.length === 0) {
339
+ target[prop] = true;
340
+ } else if (args.length === 1) {
341
+ target[prop] = args[0];
342
+ } else {
343
+ target[prop] = args;
344
+ }
345
+ return new Proxy(target, handler);
346
+ };
347
+ }
348
+ };
349
+ return new Proxy(data, handler);
350
+ }
351
+
352
+ // src/table.ts
353
+ function buildJsonPath(col, path) {
354
+ let expr = sql`${sql.ref(col)}`;
355
+ for (let i = 0; i < path.length; i++) {
356
+ const key = path[i];
357
+ const isLast = i === path.length - 1;
358
+ const op2 = isLast ? "->>" : "->";
359
+ expr = typeof key === "number" ? sql`${expr}${sql.raw(op2)}${sql.val(key)}` : sql`${expr}${sql.raw(op2)}${sql.val(String(key))}`;
360
+ }
361
+ return expr;
362
+ }
363
+ function applyWhere(qb, nodes) {
364
+ for (const node of nodes) {
365
+ if ("and" in node) {
366
+ qb = qb.where(
367
+ (eb) => eb.and(node.and.map((n) => nodeToExpression(eb, n)))
368
+ );
369
+ } else if ("or" in node) {
370
+ qb = qb.where(
371
+ (eb) => eb.or(node.or.map((n) => nodeToExpression(eb, n)))
372
+ );
373
+ } else if ("low" in node) {
374
+ qb = qb.where(
375
+ sql`${sql.ref(node.col)} ${sql.raw(node.op)} ${sql.val(node.low)} AND ${sql.val(node.high)}`
376
+ );
377
+ } else if ("path" in node) {
378
+ qb = qb.where(
379
+ sql`${buildJsonPath(node.col, node.path)} ${sql.raw(node.op)} ${sql.val(node.val)}`
380
+ );
381
+ } else if ("val" in node) {
382
+ if (node.op === "array_append") {
383
+ qb = qb.set(
384
+ sql`${sql.ref(node.col)} = ${sql.ref(node.col)} || ARRAY[${sql.val(node.val)}]`
385
+ );
386
+ } else {
387
+ qb = qb.where(node.col, node.op, node.val);
388
+ }
389
+ } else {
390
+ qb = qb.where(sql`${sql.ref(node.col)} ${sql.raw(node.op)}`);
391
+ }
392
+ }
393
+ return qb;
394
+ }
395
+ function nodeToExpression(eb, node) {
396
+ if ("and" in node) {
397
+ return eb.and(node.and.map((n) => nodeToExpression(eb, n)));
398
+ }
399
+ if ("or" in node) {
400
+ return eb.or(node.or.map((n) => nodeToExpression(eb, n)));
401
+ }
402
+ if ("low" in node) {
403
+ return sql`${sql.ref(node.col)} ${sql.raw(node.op)} ${sql.val(node.low)} AND ${sql.val(node.high)}`;
404
+ }
405
+ if ("path" in node) {
406
+ return sql`${buildJsonPath(node.col, node.path)} ${sql.raw(node.op)} ${sql.val(node.val)}`;
407
+ }
408
+ if ("val" in node) {
409
+ return eb(node.col, node.op, node.val);
410
+ }
411
+ return sql`${sql.ref(node.col)} ${sql.raw(node.op)}`;
412
+ }
413
+ function resolveWhere(w) {
414
+ if (Array.isArray(w)) {
415
+ const [col, op2, val] = w;
416
+ return [{ col, op: op2, val }];
417
+ }
418
+ return buildWhere(w);
419
+ }
420
+ var Table = class {
421
+ constructor(name, schema, db, listenFn) {
422
+ this.name = "";
423
+ this.name = name;
424
+ this.db = db;
425
+ this.schema = schema;
426
+ this.listenFn = listenFn;
427
+ }
428
+ serializeDates(row) {
429
+ return Object.fromEntries(
430
+ Object.entries(row).map(([k, v]) => {
431
+ if (v instanceof Date) return [k, v.toISOString()];
432
+ if (Array.isArray(v) && v.every((i) => typeof i === "number")) {
433
+ return [k, `[${v.join(",")}]`];
434
+ }
435
+ if (typeof v === "object" && v !== null && v.__kind === "array_append") {
436
+ return [k, sql`${sql.ref(k)} || ARRAY[${sql.val(v.value)}]`];
437
+ }
438
+ return [k, v];
439
+ })
440
+ );
441
+ }
442
+ getVectorCols() {
443
+ return new Set(
444
+ Object.entries(this.schema).filter(([, col]) => col.$build().SQlType == "vector").map(([key]) => key)
445
+ );
446
+ }
447
+ deserializeRow(row) {
448
+ const vectorCols = this.getVectorCols();
449
+ return Object.fromEntries(
450
+ Object.entries(row).map(([k, v]) => {
451
+ if (vectorCols.has(k) && typeof v === "string") {
452
+ return [k, JSON.parse(v)];
453
+ }
454
+ return [k, v];
455
+ })
456
+ );
457
+ }
458
+ // ── CRUD ────────────────────────────────────────────────────────────────────
459
+ Get(cols) {
460
+ return createFluentBuilder2(async (data) => {
461
+ let query = this.db.selectFrom(this.name);
462
+ if (cols) {
463
+ query = query.select(cols);
464
+ } else {
465
+ query = query.selectAll();
466
+ }
467
+ if (data.where) {
468
+ query = applyWhere(query, resolveWhere(data.where));
469
+ }
470
+ if (data.distinct) {
471
+ query = query.distinct();
472
+ }
473
+ if (data.orderby) {
474
+ query = query.orderBy(data.orderby[0], data.orderby[1]);
475
+ }
476
+ if (data.limit) {
477
+ query = query.limit(data.limit);
478
+ }
479
+ if (data.offset) {
480
+ query = query.offset(data.offset);
481
+ }
482
+ const rows = await query.execute();
483
+ return rows.map((r) => this.deserializeRow(r));
484
+ });
485
+ }
486
+ GetOne(cols) {
487
+ return createFluentBuilder2(async (data) => {
488
+ let query = this.db.selectFrom(this.name);
489
+ if (data.where) {
490
+ query = applyWhere(query, resolveWhere(data.where));
491
+ }
492
+ query = query.limit(1);
493
+ const rows = await query.execute();
494
+ if (rows[0]) {
495
+ return this.deserializeRow(rows[0]);
496
+ }
497
+ return void 0;
498
+ });
499
+ }
500
+ Insert(values) {
501
+ return createFluentBuilder2(async (data) => {
502
+ if (values === "default") {
503
+ const query = this.db.insertInto(this.name).defaultValues();
504
+ if (data.returning) {
505
+ return await query.returningAll().execute();
506
+ }
507
+ await query.execute();
508
+ } else {
509
+ const raw = Array.isArray(values) ? values : [values];
510
+ const rows = raw.map((r) => this.serializeDates(r));
511
+ const query = this.db.insertInto(this.name).values(rows);
512
+ if (data.returning) {
513
+ return await query.returningAll().execute();
514
+ }
515
+ await query.execute();
516
+ }
517
+ return [];
518
+ });
519
+ }
520
+ Delete() {
521
+ return createFluentBuilder2(async (data) => {
522
+ let query = this.db.deleteFrom(this.name);
523
+ if (data.where) {
524
+ query = applyWhere(query, resolveWhere(data.where));
525
+ }
526
+ if (data.returning) {
527
+ return await query.returningAll().execute();
528
+ }
529
+ await query.execute();
530
+ return [];
531
+ });
532
+ }
533
+ Update(set) {
534
+ return createFluentBuilder2(async (data) => {
535
+ let query = this.db.updateTable(this.name).set(this.serializeDates(set));
536
+ if (data.where) {
537
+ query = applyWhere(query, resolveWhere(data.where));
538
+ }
539
+ if (data.returning) {
540
+ return await query.returningAll().execute();
541
+ }
542
+ await query.execute();
543
+ return [];
544
+ });
545
+ }
546
+ Count() {
547
+ return createFluentBuilder2(async (data) => {
548
+ let query = this.db.selectFrom(this.name);
549
+ if (data.where) {
550
+ query = applyWhere(query, resolveWhere(data.where));
551
+ }
552
+ const result = await query.select(this.db.fn.countAll().as("count")).executeTakeFirstOrThrow();
553
+ return Number(result.count);
554
+ });
555
+ }
556
+ Exist() {
557
+ return createFluentBuilder2(async (data) => {
558
+ let query = this.db.selectFrom(this.name);
559
+ if (data.where) {
560
+ query = applyWhere(query, resolveWhere(data.where));
561
+ }
562
+ const result = await query.selectAll().limit(1).execute();
563
+ return result.length > 0;
564
+ });
565
+ }
566
+ // ── Realtime ────────────────────────────────────────────────────────────────
567
+ Subscribe(callback) {
568
+ return this.listenFn(this.name, (payload) => {
569
+ callback(JSON.parse(payload));
570
+ });
571
+ }
572
+ };
573
+
574
+ // src/database.ts
575
+ var init = async (db, client, tables, isPGlite) => {
576
+ const notifyFnSQL = `
5
577
  CREATE OR REPLACE FUNCTION notify_table_change()
6
578
  RETURNS trigger AS $$
7
579
  BEGIN
@@ -16,12 +588,340 @@ ${n.join(`,
16
588
  RETURN NEW;
17
589
  END;
18
590
  $$ 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}"
591
+ `;
592
+ if (isPGlite) {
593
+ await client.query(notifyFnSQL);
594
+ } else {
595
+ await sql2.raw(notifyFnSQL).execute(db);
596
+ }
597
+ for (const [k, v] of Object.entries(tables)) {
598
+ const tableSQL = getDefSQL(k, v);
599
+ const triggerSQL = `
600
+ CREATE OR REPLACE TRIGGER "${k}_notify"
601
+ AFTER INSERT OR UPDATE OR DELETE ON "${k}"
22
602
  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};
603
+ `;
604
+ if (isPGlite) {
605
+ await client.query(tableSQL);
606
+ await client.query(triggerSQL);
607
+ } else {
608
+ await sql2.raw(tableSQL).execute(db);
609
+ await sql2.raw(triggerSQL).execute(db);
610
+ }
611
+ }
612
+ };
613
+ var Database = async (tables, conn = ":memory:", config) => {
614
+ let client;
615
+ let dialect;
616
+ let listenFn;
617
+ let notifyFn;
618
+ const isPGlite = !conn.startsWith("postgres://");
619
+ if (isPGlite) {
620
+ if (conn == ":memory:") {
621
+ const instance = await KyselyPGlite.create();
622
+ dialect = instance.dialect;
623
+ client = instance.client;
624
+ } else {
625
+ const instance = await KyselyPGlite.create(conn, config);
626
+ dialect = instance.dialect;
627
+ client = instance.client;
628
+ }
629
+ listenFn = async (channel, callback) => {
630
+ await client.listen(channel, callback);
631
+ return async () => {
632
+ await client.unlisten(channel);
633
+ };
634
+ };
635
+ notifyFn = async (channel, payload = "") => {
636
+ await client.query(`SELECT pg_notify($1, $2)`, [channel, typeof payload == "string" ? payload : JSON.stringify(payload)]);
637
+ };
638
+ } else {
639
+ dialect = new PostgresDialect({
640
+ pool: new Pool({ connectionString: conn })
641
+ });
642
+ client = new Client({ connectionString: conn });
643
+ await client.connect();
644
+ client.on("error", (err) => console.error("PG listener error:", err));
645
+ const listeners = /* @__PURE__ */ new Map();
646
+ client.on("notification", (msg) => {
647
+ const cbs = listeners.get(msg.channel);
648
+ if (cbs) cbs.forEach((cb) => cb(msg.payload ?? ""));
649
+ });
650
+ listenFn = async (channel, callback) => {
651
+ if (!listeners.has(channel)) {
652
+ listeners.set(channel, /* @__PURE__ */ new Set());
653
+ await client.query(`LISTEN "${channel}"`);
654
+ }
655
+ listeners.get(channel).add(callback);
656
+ return async () => {
657
+ const cbs = listeners.get(channel);
658
+ if (!cbs) return;
659
+ cbs.delete(callback);
660
+ if (cbs.size === 0) {
661
+ listeners.delete(channel);
662
+ await client.query(`UNLISTEN "${channel}"`);
663
+ }
664
+ };
665
+ };
666
+ notifyFn = async (channel, payload = "") => {
667
+ await sql2.raw(`SELECT pg_notify('${channel}', '${typeof payload == "string" ? payload : JSON.stringify(payload)}')`).execute(db);
668
+ };
669
+ }
670
+ const db = new Kysely({ dialect });
671
+ await init(db, client, tables, isPGlite);
672
+ const typedTables = Object.fromEntries(
673
+ Object.entries(tables).map(
674
+ ([k, v]) => [k, new Table(k, v, db, listenFn)]
675
+ )
676
+ );
677
+ const watchFn = async (table2, callback) => {
678
+ return listenFn(table2, (payload) => {
679
+ callback(JSON.parse(payload));
680
+ });
681
+ };
682
+ return {
683
+ ...typedTables,
684
+ $raw: async (rawSQL) => (await sql2.raw(rawSQL).execute(db)).rows,
685
+ $listen: listenFn,
686
+ $notify: notifyFn,
687
+ $watch: watchFn
688
+ };
689
+ };
690
+
691
+ // src/migration.ts
692
+ function build(col) {
693
+ return col.$build();
694
+ }
695
+ function formatDefault(def, sqlType) {
696
+ if (sqlType === "jsonb") {
697
+ const inner = typeof def === "string" ? `'${def.replace(/'/g, "''")}'` : `'${JSON.stringify(def)}'`;
698
+ return `${inner}::jsonb`;
699
+ }
700
+ if (typeof def === "string") return `'${def.replace(/'/g, "''")}'`;
701
+ if (typeof def === "boolean") return def ? "true" : "false";
702
+ return JSON.stringify(def);
703
+ }
704
+ function resolveDefault(col) {
705
+ if (col.defaultNow) {
706
+ const t = col.SQlType?.toLowerCase() ?? "";
707
+ if (t.startsWith("timestamp") || t.startsWith("datetime") || t.startsWith("date")) {
708
+ return "NOW()";
709
+ }
710
+ }
711
+ if (col.defaultRandom) {
712
+ if (col.SQlType?.toLowerCase().includes("uuid")) {
713
+ return "gen_random_uuid()";
714
+ }
715
+ }
716
+ if (col.default !== void 0) {
717
+ return formatDefault(col.default, col.SQlType);
718
+ }
719
+ return void 0;
720
+ }
721
+ function diffColumn(tableName, colName, prev, next) {
722
+ const stmts = [];
723
+ const q = `"${tableName}"."${colName}"`;
724
+ const t = `"${tableName}"`;
725
+ if ((prev.SQlType ?? "text") !== (next.SQlType ?? "text")) {
726
+ stmts.push({
727
+ kind: "alter_type",
728
+ sql: `ALTER TABLE ${t} ALTER COLUMN "${colName}" TYPE ${next.SQlType ?? "text"} USING "${colName}"::${next.SQlType ?? "text"};`
729
+ });
730
+ }
731
+ if (!prev.notnull && next.notnull) {
732
+ stmts.push({
733
+ kind: "set_notnull",
734
+ sql: `ALTER TABLE ${t} ALTER COLUMN "${colName}" SET NOT NULL;`
735
+ });
736
+ } else if (prev.notnull && !next.notnull) {
737
+ stmts.push({
738
+ kind: "drop_notnull",
739
+ sql: `ALTER TABLE ${t} ALTER COLUMN "${colName}" DROP NOT NULL;`
740
+ });
741
+ }
742
+ const prevDefault = resolveDefault(prev);
743
+ const nextDefault = resolveDefault(next);
744
+ if (prevDefault !== nextDefault) {
745
+ if (nextDefault !== void 0) {
746
+ stmts.push({
747
+ kind: "set_default",
748
+ sql: `ALTER TABLE ${t} ALTER COLUMN "${colName}" SET DEFAULT ${nextDefault};`
749
+ });
750
+ } else {
751
+ stmts.push({
752
+ kind: "drop_default",
753
+ sql: `ALTER TABLE ${t} ALTER COLUMN "${colName}" DROP DEFAULT;`
754
+ });
755
+ }
756
+ }
757
+ if (!prev.unique && next.unique) {
758
+ stmts.push({
759
+ kind: "add_unique",
760
+ sql: `ALTER TABLE ${t} ADD CONSTRAINT "uq_${tableName}_${colName}" UNIQUE ("${colName}");`
761
+ });
762
+ } else if (prev.unique && !next.unique) {
763
+ stmts.push({
764
+ kind: "drop_unique",
765
+ sql: `ALTER TABLE ${t} DROP CONSTRAINT IF EXISTS "uq_${tableName}_${colName}";`
766
+ });
767
+ }
768
+ if (!prev.primaryKey && next.primaryKey) {
769
+ stmts.push({
770
+ kind: "add_primary_key",
771
+ sql: `ALTER TABLE ${t} ADD CONSTRAINT "pk_${tableName}_${colName}" PRIMARY KEY ("${colName}");`
772
+ });
773
+ } else if (prev.primaryKey && !next.primaryKey) {
774
+ stmts.push({
775
+ kind: "drop_primary_key",
776
+ sql: `ALTER TABLE ${t} DROP CONSTRAINT IF EXISTS "pk_${tableName}_${colName}";`
777
+ });
778
+ }
779
+ return stmts;
780
+ }
781
+ function diffTable(tableName, prevCols, nextCols) {
782
+ const stmts = [];
783
+ const prevKeys = new Set(Object.keys(prevCols));
784
+ const nextKeys = new Set(Object.keys(nextCols));
785
+ for (const col of prevKeys) {
786
+ if (!nextKeys.has(col)) {
787
+ stmts.push({
788
+ kind: "drop_column",
789
+ sql: `ALTER TABLE "${tableName}" DROP COLUMN IF EXISTS "${col}";`
790
+ });
791
+ }
792
+ }
793
+ for (const col of nextKeys) {
794
+ if (!prevKeys.has(col) && nextCols[col]) {
795
+ const def = build(nextCols[col]);
796
+ const parts = [`"${col}"`, def.SQlType ?? "text"];
797
+ if (def.primaryKey) parts.push("PRIMARY KEY");
798
+ if (def.notnull) parts.push("NOT NULL");
799
+ if (def.unique) parts.push("UNIQUE");
800
+ const defaultExpr = resolveDefault(def);
801
+ if (defaultExpr !== void 0) parts.push(`DEFAULT ${defaultExpr}`);
802
+ stmts.push({
803
+ kind: "add_column",
804
+ sql: `ALTER TABLE "${tableName}" ADD COLUMN ${parts.join(" ")};`
805
+ });
806
+ }
807
+ }
808
+ for (const col of nextKeys) {
809
+ if (prevKeys.has(col) && nextCols[col] && prevCols[col]) {
810
+ const prev = build(prevCols[col]);
811
+ const next = build(nextCols[col]);
812
+ stmts.push(...diffColumn(tableName, col, prev, next));
813
+ }
814
+ }
815
+ return stmts;
816
+ }
817
+ function generateMigration(prev, next) {
818
+ const stmts = [];
819
+ const prevTables = new Set(Object.keys(prev));
820
+ const nextTables = new Set(Object.keys(next));
821
+ for (const table2 of prevTables) {
822
+ if (!nextTables.has(table2)) {
823
+ stmts.push({
824
+ kind: "drop_table",
825
+ sql: `DROP TABLE IF EXISTS "${table2}";`
826
+ });
827
+ }
828
+ }
829
+ for (const table2 of nextTables) {
830
+ if (!prevTables.has(table2)) {
831
+ const cols = next[table2];
832
+ const colDefs = Object.entries(cols).map(([colName, col]) => {
833
+ const def = build(col);
834
+ const parts = [`"${colName}"`, def.SQlType ?? "text"];
835
+ if (def.primaryKey) parts.push("PRIMARY KEY");
836
+ if (def.notnull) parts.push("NOT NULL");
837
+ if (def.unique) parts.push("UNIQUE");
838
+ const defaultExpr = resolveDefault(def);
839
+ if (defaultExpr !== void 0) parts.push(`DEFAULT ${defaultExpr}`);
840
+ return " " + parts.join(" ");
841
+ }).join(",\n");
842
+ stmts.push({
843
+ kind: "create_table",
844
+ sql: `CREATE TABLE IF NOT EXISTS "${table2}" (
845
+ ${colDefs}
846
+ );`
847
+ });
848
+ }
849
+ }
850
+ for (const table2 of nextTables) {
851
+ if (prevTables.has(table2)) {
852
+ stmts.push(...diffTable(table2, prev[table2], next[table2]));
853
+ }
854
+ }
855
+ return stmts.map((s) => s.sql).join("\n");
856
+ }
857
+ export {
858
+ ARITHMETIC_OPERATORS,
859
+ BINARY_OPERATORS,
860
+ COMPARISON_OPERATORS,
861
+ Column,
862
+ Database,
863
+ JSON_OPERATORS,
864
+ OPERATORS,
865
+ Table,
866
+ UNARY_FILTER_OPERATORS,
867
+ UNARY_OPERATORS,
868
+ add,
869
+ array,
870
+ bang,
871
+ between,
872
+ betweenSymmetric,
873
+ bool,
874
+ buildWhere,
875
+ bytea,
876
+ containedBy,
877
+ contains,
878
+ createFluentBuilder2 as createFluentBuilder,
879
+ distance,
880
+ eq,
881
+ eqq,
882
+ float,
883
+ generateMigration,
884
+ getDefSQL,
885
+ gt,
886
+ gte,
887
+ hasAllKeys,
888
+ hasAnyKey,
889
+ hasKey,
890
+ ilike,
891
+ inList,
892
+ int,
893
+ iregex,
894
+ is,
895
+ isDistinct,
896
+ isNot,
897
+ isNotDistinct,
898
+ json,
899
+ like,
900
+ lt,
901
+ lte,
902
+ match,
903
+ neq,
904
+ neqAlt,
905
+ notGt,
906
+ notIlike,
907
+ notIn,
908
+ notIregex,
909
+ notLike,
910
+ notLt,
911
+ notRegex,
912
+ nullSafeEq,
913
+ op,
914
+ overlaps,
915
+ regex,
916
+ regexp,
917
+ startsWith,
918
+ table,
919
+ text,
920
+ time,
921
+ timestamp,
922
+ tsMatch,
923
+ tsPhrase,
924
+ unary,
925
+ uuid,
926
+ vector
927
+ };
package/package.json CHANGED
@@ -1,8 +1,10 @@
1
1
  {
2
2
  "name": "@inflector/optima-pg",
3
- "version": "1.0.1",
4
- "module": "index.ts",
3
+ "version": "1.0.3",
5
4
  "type": "module",
5
+ "author": "Inflector",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.js",
6
8
  "devDependencies": {
7
9
  "@types/bun": "latest",
8
10
  "tsup": "^8.5.1",
@@ -11,10 +13,13 @@
11
13
  "files": [
12
14
  "dist"
13
15
  ],
16
+ "exports": {
17
+ ".": "./dist/index.js"
18
+ },
14
19
  "types": "./dist/index.d.ts",
15
20
  "scripts": {
16
21
  "dev": "bun index.ts",
17
- "build": "tsup src/index.ts src/types.ts --format esm --dts --clean --minify",
22
+ "build": "tsup src/index.ts --format esm --dts --clean",
18
23
  "prepublishOnly": "bun run build"
19
24
  },
20
25
  "peerDependencies": {