query-weaver 0.2.0-alpha.4 → 0.2.0-alpha.5

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/README.md CHANGED
@@ -160,6 +160,9 @@ db.insert(tableName, [{ ...fieldValuePairs }, ...]); // => db.query`INSERT INTO
160
160
  ```js
161
161
  sql.update(tableName, { ...fieldValuePairs }, { ...whereCondition }); // => sql`UPDATE ...`
162
162
  db.update(tableName, { ...fieldValuePairs }, { ...whereCondition }); // => db.query`UPDATE ...`
163
+
164
+ // Empty conditions throw for safety.
165
+ db.update(tableName, { name: 'updated' }, { id: undefined });
163
166
  ```
164
167
 
165
168
  ### DELETE Builder and Helper
@@ -169,6 +172,9 @@ db.update(tableName, { ...fieldValuePairs }, { ...whereCondition }); // => db.q
169
172
  ```js
170
173
  sql.delete(tableName, { ...whereCondition }); // => sql`DELETE FROM ...`
171
174
  db.delete(tableName, { ...whereCondition }); // => db.query`DELETE FROM ...`
175
+
176
+ // Empty conditions throw for safety.
177
+ db.delete(tableName, { id: undefined });
172
178
  ```
173
179
 
174
180
  ### Transaction Helper
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});function e(e,t,n){return Math.min(Math.max(e,t),n)}var t=class{#e;#t=0;#n;constructor(e){this.#e=e,this.#n=e.length}get position(){return this.#t}get size(){return this.#n}get remain(){return this.size-this.position}eof(){return this.remain<=0}seek(t){return this.#t=e(t,0,this.size),this}skip(e){return this.seek(this.#t+(e??1))}startsWith(e){if(this.eof())return null;let t=this.#e.slice(this.position);return(typeof e==`string`?t.startsWith(e)&&[e]:t.match(new RegExp(e,e.sticky?e.flags:e.flags+`y`)))||null}match(e,t){let n=this.startsWith(e);return n?(this.skip(n[0].length),t?t(n):n):null}#r(e,t){let n=this.#e.slice(this.position),r=typeof e==`string`?n.indexOf(e):n.search(e);return r<0?null:t(r)}search(e,t){return this.#r(e,n=>{let r=this.read(n),i=this.match(e);if(!i)return null;let a={skipped:r,matched:i};return t?t(a):a})}skipUntil(e){return this.#r(e,e=>this.skip(e))!==null}readUntil(e){return this.#r(e,e=>this.read(e))}read(e){if(this.eof())return``;if(e??=1,e<0)throw RangeError(`read(n): n must be >= 0`);let t=this.#e.slice(this.position,this.position+e);return this.skip(e),t}};const n=`AES128.AES256.ALL.ALLOWOVERWRITE.ANALYSE.ANALYZE.AND.ANY.ARRAY.AS.ASC.AUTHORIZATION.BACKUP.BETWEEN.BINARY.BLANKSASNULL.BOTH.BYTEDICT.CASE.CAST.CHECK.COLLATE.COLUMN.CONSTRAINT.CREATE.CREDENTIALS.CROSS.CURRENT_DATE.CURRENT_TIME.CURRENT_TIMESTAMP.CURRENT_USER.CURRENT_USER_ID.DEFAULT.DEFERRABLE.DEFLATE.DEFRAG.DELTA.DELTA32K.DESC.DISABLE.DISTINCT.DO.ELSE.EMPTYASNULL.ENABLE.ENCODE.ENCRYPT.ENCRYPTION.END.EXCEPT.EXPLICIT.FALSE.FOR.FOREIGN.FREEZE.FROM.FULL.GLOBALDICT256.GLOBALDICT64K.GRANT.GROUP.GZIP.HAVING.IDENTITY.IGNORE.ILIKE.IN.INITIALLY.INNER.INTERSECT.INTO.IS.ISNULL.JOIN.LEADING.LEFT.LIKE.LIMIT.LOCALTIME.LOCALTIMESTAMP.LUN.LUNS.LZO.LZOP.MINUS.MOSTLY13.MOSTLY32.MOSTLY8.NATURAL.NEW.NOT.NOTNULL.NULL.NULLS.OFF.OFFLINE.OFFSET.OLD.ON.ONLY.OPEN.OR.ORDER.OUTER.OVERLAPS.PARALLEL.PARTITION.PERCENT.PLACING.PRIMARY.RAW.READRATIO.RECOVER.REFERENCES.REJECTLOG.RESORT.RESTORE.RIGHT.SELECT.SESSION_USER.SIMILAR.SOME.SYSDATE.SYSTEM.TABLE.TAG.TDES.TEXT255.TEXT32K.THEN.TO.TOP.TRAILING.TRUE.TRUNCATECOLUMNS.UNION.UNIQUE.USER.USING.VERBOSE.WALLET.WHEN.WHERE.WITH.WITHOUT`.split(`.`);function r(e){return e.match(/^[a-zA-Z_][0-9a-zA-Z_$]*$/)&&!n.includes(e.toUpperCase())?e:`"${e.replace(/"/g,`""`)}"`}function i(e){return`${e.includes(`'`)?`E`:``}'${e.replace(/'/g,`''`).replace(/\\/g,`\\\\`)}'`}function a(e,t){return e.split(`.`).map(e=>r(e)).join(`.`)}function o(e,t){return e===null?`NULL`:typeof e==`boolean`?e?`true`:`false`:Array.isArray(e)?`ARRAY[`+e.map(e=>o(e)).join(`,`)+`]`:typeof e==`object`?`toJSON`in e&&typeof e.toJSON==`function`?i(String(e.toJSON())):i(e.toString()):i(String(e))}function s(e,n){let r=new t(n);for(;!r.eof();)if(e.dollarQuoted){if(!r.search(e.dollarQuoted))break;e.dollarQuoted=void 0}else if(e.inEscapedSingleQuote){if(!r.skipUntil(/[\\']/))break;if(r.match(`''`)||r.match(/\\./))continue;if(!r.match(`'`))break;e.inEscapedSingleQuote=!1}else if(e.inSingleQuote){if(!r.skipUntil(`'`))break;if(r.match(`''`))continue;if(!r.match(`'`))break;e.inSingleQuote=!1}else if(e.inBlockComment){if(!r.skipUntil(/\/\*|\*\//))break;if(r.match(`/*`,()=>++e.inBlockComment))continue;if(!r.match(`*/`))break;e.inBlockComment--}else if(e.inLineComment){if(!r.search(/\r\n|\r|\n/))break;e.inLineComment=!1}else{if(!r.skipUntil(/[-$E'/]/))break;if(r.match(/\$[a-zA-Z0-9_]*\$/,t=>e.dollarQuoted=t[0])||r.match(`E'`,()=>e.inEscapedSingleQuote=!0)||r.match(`'`,()=>e.inSingleQuote=!0)||r.match(`--`,()=>e.inLineComment=!0)||r.match(`/*`,()=>e.inBlockComment=1))continue;r.skip()}}function c(e){return e?!!(e.dollarQuoted||e.inLineComment||e.inBlockComment||e.inSingleQuote||e.inEscapedSingleQuote):!1}var l=class{text=``;values=[];sql=``;statement=``;embed=``;#e(e){return this.toString({valueFn:(t,n)=>c(n)?``:e(t),context:{},contextHandler:s})}constructor(){Object.defineProperties(this,{text:{enumerable:!0,get:()=>{let e=1;return this.#e(()=>`$`+ e++)}},values:{enumerable:!0,get:()=>{let e=[];return this.#e(t=>(e.push(t),``)),e}},sql:{enumerable:!1,get:()=>this.#e(()=>`?`)},statement:{enumerable:!1,get:()=>{let e=1;return this.#e(()=>`:`+ e++)}},embed:{enumerable:!0,get:()=>this.#e(e=>o(e))}})}},u=class extends l{#e;constructor(e){super(),this.#e=e}toString(e){return(e?.valueFn??o)(this.#e,e?.context)}},d=class extends l{#e;constructor(e){super(),this.#e=e}toString(e){return(e?.identFn??a)(this.#e,e?.context)}},f=class extends l{#e;constructor(e){super(),this.#e=String(e)}toString(e){return e?.context&&e?.contextHandler&&e.contextHandler(e.context,this.#e),this.#e}};function p(e){return e instanceof l}function m(e){return new d(e)}function h(e){return e===void 0||p(e)?e:new u(e)}function g(e){return e===void 0||p(e)?e:Array.isArray(e)?new b(e.map(g)):new f(e)}function _(e){return e===void 0||p(e)?e:g(JSON.stringify(e))}const v=e=>{if(!Array.isArray(e)||typeof e?.[0]!=`object`||e[0]===null||!(`raw`in e[0])||!Array.isArray(e[0]))return!1;let[t,...n]=e;return t.length-1===n.length};function y(e,t){if(e.length-1!==t.length)throw Error(`Template literal received a mismatched number of values.`);return e.flatMap((e,n)=>n?[t[n-1],e]:[e])}var b=class extends l{#e=[];#t;constructor(...e){if(super(),this.#t={prefix:``,glue:``,suffix:``,empty:``,wrapperFn:e=>e},Array.isArray(e[0])){let[t,n]=e;this.#t={...this.#t,...n},this.push(...t)}else{let[t]=e;this.#t={...this.#t,...t}}}setSewingPattern(e=``,t=``,n=``,r=``){return this.#t={...this.#t,prefix:e,glue:t,suffix:n,empty:r},this}push(...e){return this.#e.push(...e.map(g).filter(e=>e!==void 0)),this}append(...e){return this.push(...e)}join(e=`, `){return this.#t.glue=e,this}prefix(e=` `){return this.#t.prefix=e,this}suffix(e=` `){return this.#t.suffix=e,this}empty(e=``){return this.#t.empty=e,this}toString(e){let t=this.#e.map(t=>t.toString(e)).filter(e=>e).join(this.#t.glue);return t?this.#t.prefix+this.#t.wrapperFn(t,e)+this.#t.suffix:this.#t.empty}};function x(...e){let t;if(v(e)){let[n,...r]=e;t=[new b(y(n.map(g),r.map(h)))]}else t=e.map(h);return new b(t)}const S=m;function C(...e){return new b(e.map(g))}function w(...e){let t,n=(e,t)=>(t?.valueFn||o)(e,t?.context);if(v(e)){let[r,...i]=e;t=[new b(y(r.map(g),i.map(_)),{wrapperFn:n})]}else t=e.map(e=>new b([_(e)],{wrapperFn:n}));return new b(t)}function T(...e){let t=new b,n=e=>{if(e!=null){if(typeof e==`string`){t.push(g(e));return}if(p(e)){t.push(e);return}if(Array.isArray(e)){e.forEach(n);return}if(typeof e==`object`){for(let n in e)if(e[n]!==void 0){if(p(e[n])){t.push(x`${m(n)} ${e[n]}`);continue}if(e[n]===null){t.push(x`${m(n)} IS NULL`);continue}if(Array.isArray(e[n])){let r=e[n];r.length===0?t.push(x`FALSE`):t.push(x`${m(n)} = ANY (${r})`);continue}t.push(x`${m(n)} = ${e[n]}`)}return}}};return n(e),t}function E(...e){return T(e).setSewingPattern(`((`,`) OR (`,`))`,``)}function D(...e){return T(e).setSewingPattern(`((`,`) AND (`,`))`,``)}function O(...e){return T(e).setSewingPattern(`WHERE ((`,`) AND (`,`))`,``)}function k(...e){return T(e).setSewingPattern(`WHERE ((`,`) OR (`,`))`,``)}function A(...e){return C(...e).join(` UNION ALL `)}function j(...e){return C(...e).join(` UNION `)}function M(e){return e==null?x``:(e=Number(e),e>=0?x`LIMIT ${e}`:x``)}function N(e){return e==null?x``:(e=Number(e),e>=0?x`OFFSET ${e}`:x``)}function P(e){let t=Array.isArray(e)?e:[e];if(t.length===0)throw Error(`At least one field value is required.`);let n=t[0],r=n&&Array.isArray(n);if(!n||!r&&typeof n!=`object`)throw Error(`Field values must be arrays or plain objects.`);let i=t.map(e=>{if(Array.isArray(e)!==r)throw Error(`All entries must share the same structure.`);return Object.fromEntries((Array.isArray(e)?e.map((e,t)=>[String(t),e]):Object.entries(e)).filter(([,e])=>e!==void 0))}),a=Object.keys(i[0]),o=i.map(e=>{if(Object.keys(e).length!==a.length)throw Error(`All entries must share the same structure.`);return a.map(t=>{if(!Object.prototype.hasOwnProperty.call(e,t))throw Error(`All entries must share the same structure.`);return e[t]})});return{keys:r?void 0:a,rows:o}}function F(e){let{keys:t,rows:n}=P(e);return{keys:t,fields:t?x(...t.map(m)).setSewingPattern(`(`,`, `,`)`):void 0,VALUES:x`VALUES ${x(...n.map(e=>x(...e).join(`, `))).setSewingPattern(`(`,`), (`,`)`)}`}}function I(e){let{fields:t}=F(e);if(!t)throw Error(`buildKeys requires FieldValues to be objects.`);return t}function L(e){return F(e).VALUES}function R(e,t,n){let{fields:r,VALUES:i}=F(t);if(!r)throw Error(`buildInsert requires FieldValues to be objects.`);return x`INSERT INTO ${m(e)} ${r} ${i}`.append(n).join(` `)}function z(e,t,n,r){let i=new b,a=!1;for(let e in t){let n=t[e];n!==void 0&&(i.push(x`${m(e)} = ${n}`),a=!0)}if(!a)throw Error(`buildUpdate requires at least one field to update.`);return x`UPDATE ${m(e)} SET ${i.join(`, `)} ${O(n)}`.append(r).join(` `)}function B(e,t,n){return x`DELETE FROM ${m(e)} ${O(t)}`.append(n).join(` `)}function V(e,t,n,r){if(!n.length)throw Error(`buildUpsert requires at least one conflict key.`);let{keys:i,fields:a,VALUES:o}=F(t);if(!i||!a)throw Error(`buildUpsert requires FieldValues to be objects.`);let s=x(...n.map(m)).setSewingPattern(`ON CONFLICT (`,`, `,`)`),c=i.filter(e=>!n.includes(e)),l=c.length===0?x`DO NOTHING`:x(...c.map(e=>x`${S(e)} = EXCLUDED.${S(e)}`)).setSewingPattern(`DO UPDATE SET `,`, `);return x`INSERT INTO ${m(e)} ${a} ${o} ${s} ${l}`.append(r).join(` `)}const H=E,U=D,W=O,G=O,K=O,q=k;function J(e,t){return Object.fromEntries(t.map(t=>[t,e[t]]))}var Y=class{#e;#t;#n=0;constructor(e,t={}){if(this.#e=e,this.#t={...t},!this.#t.query){if(!(`query`in e)||typeof e.query!=`function`)throw Error(`No valid query function provided.`);this.#t.query=e.query}}#r(e){if(v(e)){let[t,...n]=e;return x(t,...n)}let[t,n]=e;return typeof t==`object`&&t&&`text`in t?{text:t.text,values:t.values||[],embed:`embed`in t&&typeof t.embed==`string`?t.embed:void 0,sql:`sql`in t&&typeof t.sql==`string`?t.sql:void 0,statement:`statement`in t&&typeof t.statement==`string`?t.statement:void 0}:{text:t,values:n??[]}}#i(e){let t=this.#t.query;if(!t)throw Error(`Query function is not configured.`);return t.call(this.#e,e)}async#a(e){let t=this.#r(e);this.#t?.beforeQuery?.(t);let n=await this.#i(t).catch(e=>{throw this.#t?.onError?.(t,e),e});return typeof n.rowCount!=`number`&&(n.rowCount=n.rows?.length??0),this.#t?.afterQuery?.(t,J(n,[`command`,`rowCount`,`rows`])),n}async insert(e,t,n){let r=R(e,t,n);return await this.#a([r])}async update(e,t,n,r){let i=z(e,t,n,r);return await this.#a([i])}async delete(e,t,n){let r=B(e,t,n);return await this.#a([r])}async upsert(e,t,n,r){let i=V(e,t,n,r);return await this.#a([i])}async query(...e){return this.#a(e)}async getRows(...e){return this.#a(e).then(e=>e.rows)}async getRow(...e){return this.#a(e).then(e=>e.rows?.[0])}async getOne(...e){return this.#a(e).then(e=>Object.values(e.rows?.[0]??{})?.[0])}async getCount(...e){return this.#a(e).then(e=>e.rowCount)}async exec(...e){return this.#a(e).then(e=>e.rowCount)}async begin(e){this.#n===0&&await this.#i({text:`BEGIN`,values:[]}),this.#n+=1;try{let t=await e(this);return this.#n===1&&await this.#i({text:`COMMIT`,values:[]}),t}catch(e){if(this.#n===1)try{await this.#i({text:`ROLLBACK`,values:[]})}catch{throw Error(`Rollback error`,{cause:e})}throw e}finally{--this.#n}}static get prisma(){return async function({text:e,values:t}){if(`$queryRawUnsafe`in this&&typeof this.$queryRawUnsafe==`function`){let n=await this.$queryRawUnsafe(e,...t);return{rows:n,rowCount:n.length}}throw Error(`Prisma adapter requires a $queryRawUnsafe function.`)}}static get typeorm(){return async function({text:e,values:t}){if(`query`in this&&typeof this.query==`function`){let n=await this.query(e,t);return n.length===2&&Array.isArray(n[0])&&typeof n[1]==`number`?{rows:n[0],rowCount:n[1]}:{rows:n,rowCount:n.length}}throw Error(`TypeORM adapter requires a query function.`)}}static get sqlite(){return async function(e){if(`prepare`in this&&typeof this.prepare==`function`){let t=this.prepare(e.sql||e.text).all(...e.values);return{rows:t,rowCount:t.length}}throw Error(`SQLite adapter requires a prepare function.`)}}};function X(e,t){let n=new Y(e,t),r=new Proxy(e,{get(e,t,i){let a=t in n?n:t in e?e:void 0,o=a&&Reflect.get(a,t);return o&&o instanceof Function?function(...t){let n=this===i||this===r||this==null?a:this,s=o.apply(n,t);return s===e?r:s}:o===e?r:o}});return r}exports.AND=D,exports.LIMIT=M,exports.OFFSET=N,exports.OR=E,exports.QueryFragments=b,exports.QueryHelper=Y,exports.UNION=j,exports.UNION_ALL=A,exports.WHERE=O,exports.WHERE_AND=G,exports.WHERE_OR=k,exports.and=U,exports.buildClauses=T,exports.buildDelete=B,exports.buildInsert=R,exports.buildKeys=I,exports.buildUpdate=z,exports.buildUpsert=V,exports.buildValues=L,exports.ident=S,exports.isQueryFragment=p,exports.isQueryTemplateStyle=v,exports.json=w,exports.or=H,exports.pgIdent=a,exports.pgString=o,exports.raw=C,exports.sql=x,exports.where=W,exports.where_and=K,exports.where_or=q,exports.withQueryHelper=X;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});function e(e,t,n){return Math.min(Math.max(e,t),n)}var t=class{#e;#t=0;#n;constructor(e){this.#e=e,this.#n=e.length}get position(){return this.#t}get size(){return this.#n}get remain(){return this.size-this.position}eof(){return this.remain<=0}seek(t){return this.#t=e(t,0,this.size),this}skip(e){return this.seek(this.#t+(e??1))}startsWith(e){if(this.eof())return null;let t=this.#e.slice(this.position);return(typeof e==`string`?t.startsWith(e)&&[e]:t.match(new RegExp(e,e.sticky?e.flags:e.flags+`y`)))||null}match(e,t){let n=this.startsWith(e);return n?(this.skip(n[0].length),t?t(n):n):null}#r(e,t){let n=this.#e.slice(this.position),r=typeof e==`string`?n.indexOf(e):n.search(e);return r<0?null:t(r)}search(e,t){return this.#r(e,n=>{let r=this.read(n),i=this.match(e);if(!i)return null;let a={skipped:r,matched:i};return t?t(a):a})}skipUntil(e){return this.#r(e,e=>this.skip(e))!==null}readUntil(e){return this.#r(e,e=>this.read(e))}read(e){if(this.eof())return``;if(e??=1,e<0)throw RangeError(`read(n): n must be >= 0`);let t=this.#e.slice(this.position,this.position+e);return this.skip(e),t}};const n=`AES128.AES256.ALL.ALLOWOVERWRITE.ANALYSE.ANALYZE.AND.ANY.ARRAY.AS.ASC.AUTHORIZATION.BACKUP.BETWEEN.BINARY.BLANKSASNULL.BOTH.BYTEDICT.CASE.CAST.CHECK.COLLATE.COLUMN.CONSTRAINT.CREATE.CREDENTIALS.CROSS.CURRENT_DATE.CURRENT_TIME.CURRENT_TIMESTAMP.CURRENT_USER.CURRENT_USER_ID.DEFAULT.DEFERRABLE.DEFLATE.DEFRAG.DELTA.DELTA32K.DESC.DISABLE.DISTINCT.DO.ELSE.EMPTYASNULL.ENABLE.ENCODE.ENCRYPT.ENCRYPTION.END.EXCEPT.EXPLICIT.FALSE.FOR.FOREIGN.FREEZE.FROM.FULL.GLOBALDICT256.GLOBALDICT64K.GRANT.GROUP.GZIP.HAVING.IDENTITY.IGNORE.ILIKE.IN.INITIALLY.INNER.INTERSECT.INTO.IS.ISNULL.JOIN.LEADING.LEFT.LIKE.LIMIT.LOCALTIME.LOCALTIMESTAMP.LUN.LUNS.LZO.LZOP.MINUS.MOSTLY13.MOSTLY32.MOSTLY8.NATURAL.NEW.NOT.NOTNULL.NULL.NULLS.OFF.OFFLINE.OFFSET.OLD.ON.ONLY.OPEN.OR.ORDER.OUTER.OVERLAPS.PARALLEL.PARTITION.PERCENT.PLACING.PRIMARY.RAW.READRATIO.RECOVER.REFERENCES.REJECTLOG.RESORT.RESTORE.RIGHT.SELECT.SESSION_USER.SIMILAR.SOME.SYSDATE.SYSTEM.TABLE.TAG.TDES.TEXT255.TEXT32K.THEN.TO.TOP.TRAILING.TRUE.TRUNCATECOLUMNS.UNION.UNIQUE.USER.USING.VERBOSE.WALLET.WHEN.WHERE.WITH.WITHOUT`.split(`.`);function r(e){return e.match(/^[a-zA-Z_][0-9a-zA-Z_$]*$/)&&!n.includes(e.toUpperCase())?e:`"${e.replace(/"/g,`""`)}"`}function i(e){return`${e.includes(`'`)?`E`:``}'${e.replace(/'/g,`''`).replace(/\\/g,`\\\\`)}'`}const a=`DELETE requires a non-empty WHERE condition.`,o=`UPDATE requires a non-empty WHERE condition.`;function s(e,t){return e.split(`.`).map(e=>r(e)).join(`.`)}function c(e,t){return e===null?`NULL`:typeof e==`boolean`?e?`true`:`false`:Array.isArray(e)?`ARRAY[`+e.map(e=>c(e)).join(`,`)+`]`:typeof e==`object`?`toJSON`in e&&typeof e.toJSON==`function`?i(String(e.toJSON())):i(e.toString()):i(String(e))}function l(e,n){let r=new t(n);for(;!r.eof();)if(e.dollarQuoted){if(!r.search(e.dollarQuoted))break;e.dollarQuoted=void 0}else if(e.inEscapedSingleQuote){if(!r.skipUntil(/[\\']/))break;if(r.match(`''`)||r.match(/\\./))continue;if(!r.match(`'`))break;e.inEscapedSingleQuote=!1}else if(e.inSingleQuote){if(!r.skipUntil(`'`))break;if(r.match(`''`))continue;if(!r.match(`'`))break;e.inSingleQuote=!1}else if(e.inBlockComment){if(!r.skipUntil(/\/\*|\*\//))break;if(r.match(`/*`,()=>++e.inBlockComment))continue;if(!r.match(`*/`))break;e.inBlockComment--}else if(e.inLineComment){if(!r.search(/\r\n|\r|\n/))break;e.inLineComment=!1}else{if(!r.skipUntil(/[-$E'/]/))break;if(r.match(/\$[a-zA-Z0-9_]*\$/,t=>e.dollarQuoted=t[0])||r.match(`E'`,()=>e.inEscapedSingleQuote=!0)||r.match(`'`,()=>e.inSingleQuote=!0)||r.match(`--`,()=>e.inLineComment=!0)||r.match(`/*`,()=>e.inBlockComment=1))continue;r.skip()}}function u(e){return e?!!(e.dollarQuoted||e.inLineComment||e.inBlockComment||e.inSingleQuote||e.inEscapedSingleQuote):!1}var d=class{text=``;values=[];sql=``;statement=``;embed=``;#e(e){return this.toString({valueFn:(t,n)=>u(n)?``:e(t),context:{},contextHandler:l})}constructor(){Object.defineProperties(this,{text:{enumerable:!0,get:()=>{let e=1;return this.#e(()=>`$`+ e++)}},values:{enumerable:!0,get:()=>{let e=[];return this.#e(t=>(e.push(t),``)),e}},sql:{enumerable:!1,get:()=>this.#e(()=>`?`)},statement:{enumerable:!1,get:()=>{let e=1;return this.#e(()=>`:`+ e++)}},embed:{enumerable:!0,get:()=>this.#e(e=>c(e))}})}},f=class extends d{#e;constructor(e){super(),this.#e=e}toString(e){return(e?.valueFn??c)(this.#e,e?.context)}},p=class extends d{#e;constructor(e){super(),this.#e=e}toString(e){return(e?.identFn??s)(this.#e,e?.context)}},m=class extends d{#e;constructor(e){super(),this.#e=String(e)}toString(e){return e?.context&&e?.contextHandler&&e.contextHandler(e.context,this.#e),this.#e}};function h(e){return e instanceof d}function g(e){return new p(e)}function _(e){return e===void 0||h(e)?e:new f(e)}function v(e){return e===void 0||h(e)?e:Array.isArray(e)?new S(e.map(v)):new m(e)}function y(e){return e===void 0||h(e)?e:v(JSON.stringify(e))}const b=e=>{if(!Array.isArray(e)||typeof e?.[0]!=`object`||e[0]===null||!(`raw`in e[0])||!Array.isArray(e[0]))return!1;let[t,...n]=e;return t.length-1===n.length};function x(e,t){if(e.length-1!==t.length)throw Error(`Template literal received a mismatched number of values.`);return e.flatMap((e,n)=>n?[t[n-1],e]:[e])}var S=class extends d{#e=[];#t;constructor(...e){if(super(),this.#t={prefix:``,glue:``,suffix:``,empty:``,wrapperFn:e=>e},Array.isArray(e[0])){let[t,n]=e;this.#t={...this.#t,...n},this.push(...t)}else{let[t]=e;this.#t={...this.#t,...t}}}setSewingPattern(e=``,t=``,n=``,r=``){return this.#t={...this.#t,prefix:e,glue:t,suffix:n,empty:r},this}push(...e){return this.#e.push(...e.map(v).filter(e=>e!==void 0)),this}append(...e){return this.push(...e)}join(e=`, `){return this.#t.glue=e,this}prefix(e=` `){return this.#t.prefix=e,this}suffix(e=` `){return this.#t.suffix=e,this}empty(e=``){return this.#t.empty=e,this}toString(e){let t=this.#e.map(t=>t.toString(e)).filter(e=>e).join(this.#t.glue);return t?this.#t.prefix+this.#t.wrapperFn(t,e)+this.#t.suffix:this.#t.empty}};function C(...e){let t;if(b(e)){let[n,...r]=e;t=[new S(x(n.map(v),r.map(_)))]}else t=e.map(_);return new S(t)}const w=g;function T(...e){return new S(e.map(v))}function E(...e){let t,n=(e,t)=>(t?.valueFn||c)(e,t?.context);if(b(e)){let[r,...i]=e;t=[new S(x(r.map(v),i.map(y)),{wrapperFn:n})]}else t=e.map(e=>new S([y(e)],{wrapperFn:n}));return new S(t)}function D(...e){let t=new S,n=e=>{if(e!=null){if(typeof e==`string`){t.push(v(e));return}if(h(e)){t.push(e);return}if(Array.isArray(e)){e.forEach(n);return}if(typeof e==`object`){for(let n in e)if(e[n]!==void 0){if(h(e[n])){t.push(C`${g(n)} ${e[n]}`);continue}if(e[n]===null){t.push(C`${g(n)} IS NULL`);continue}if(Array.isArray(e[n])){let r=e[n];r.length===0?t.push(C`FALSE`):t.push(C`${g(n)} = ANY (${r})`);continue}t.push(C`${g(n)} = ${e[n]}`)}return}}};return n(e),t}function O(...e){return D(e).setSewingPattern(`((`,`) OR (`,`))`,``)}function k(...e){return D(e).setSewingPattern(`((`,`) AND (`,`))`,``)}function A(...e){return D(e).setSewingPattern(`WHERE ((`,`) AND (`,`))`,``)}function j(...e){return D(e).text.length===0}function M(...e){return D(e).setSewingPattern(`WHERE ((`,`) OR (`,`))`,``)}function N(...e){return T(...e).join(` UNION ALL `)}function P(...e){return T(...e).join(` UNION `)}function F(e){return e==null?C``:(e=Number(e),e>=0?C`LIMIT ${e}`:C``)}function I(e){return e==null?C``:(e=Number(e),e>=0?C`OFFSET ${e}`:C``)}function L(e){let t=Array.isArray(e)?e:[e];if(t.length===0)throw Error(`At least one field value is required.`);let n=t[0],r=n&&Array.isArray(n);if(!n||!r&&typeof n!=`object`)throw Error(`Field values must be arrays or plain objects.`);let i=t.map(e=>{if(Array.isArray(e)!==r)throw Error(`All entries must share the same structure.`);return Object.fromEntries((Array.isArray(e)?e.map((e,t)=>[String(t),e]):Object.entries(e)).filter(([,e])=>e!==void 0))}),a=Object.keys(i[0]),o=i.map(e=>{if(Object.keys(e).length!==a.length)throw Error(`All entries must share the same structure.`);return a.map(t=>{if(!Object.prototype.hasOwnProperty.call(e,t))throw Error(`All entries must share the same structure.`);return e[t]})});return{keys:r?void 0:a,rows:o}}function R(e){let{keys:t,rows:n}=L(e);return{keys:t,fields:t?C(...t.map(g)).setSewingPattern(`(`,`, `,`)`):void 0,VALUES:C`VALUES ${C(...n.map(e=>C(...e).join(`, `))).setSewingPattern(`(`,`), (`,`)`)}`}}function z(e){let{fields:t}=R(e);if(!t)throw Error(`buildKeys requires FieldValues to be objects.`);return t}function B(e){return R(e).VALUES}function V(e,t,n){let{fields:r,VALUES:i}=R(t);if(!r)throw Error(`buildInsert requires FieldValues to be objects.`);return C`INSERT INTO ${g(e)} ${r} ${i}`.append(n).join(` `)}function H(e,t,n,r){let i=new S,a=!1;for(let e in t){let n=t[e];n!==void 0&&(i.push(C`${g(e)} = ${n}`),a=!0)}if(!a)throw Error(`buildUpdate requires at least one field to update.`);if(j(n))throw Error(o);return C`UPDATE ${g(e)} SET ${i.join(`, `)} ${A(n)}`.append(r).join(` `)}function U(e,t,n){if(j(t))throw Error(a);return C`DELETE FROM ${g(e)} ${A(t)}`.append(n).join(` `)}function W(e,t,n,r){if(!n.length)throw Error(`buildUpsert requires at least one conflict key.`);let{keys:i,fields:a,VALUES:o}=R(t);if(!i||!a)throw Error(`buildUpsert requires FieldValues to be objects.`);let s=C(...n.map(g)).setSewingPattern(`ON CONFLICT (`,`, `,`)`),c=i.filter(e=>!n.includes(e)),l=c.length===0?C`DO NOTHING`:C(...c.map(e=>C`${w(e)} = EXCLUDED.${w(e)}`)).setSewingPattern(`DO UPDATE SET `,`, `);return C`INSERT INTO ${g(e)} ${a} ${o} ${s} ${l}`.append(r).join(` `)}const G=O,K=k,q=A,J=A,Y=A,X=M;function Z(e,t){return Object.fromEntries(t.map(t=>[t,e[t]]))}var Q=class{#e;#t;#n=0;constructor(e,t={}){if(this.#e=e,this.#t={...t},!this.#t.query){if(!(`query`in e)||typeof e.query!=`function`)throw Error(`No valid query function provided.`);this.#t.query=e.query}}#r(e){if(b(e)){let[t,...n]=e;return C(t,...n)}let[t,n]=e;return typeof t==`object`&&t&&`text`in t?{text:t.text,values:t.values||[],embed:`embed`in t&&typeof t.embed==`string`?t.embed:void 0,sql:`sql`in t&&typeof t.sql==`string`?t.sql:void 0,statement:`statement`in t&&typeof t.statement==`string`?t.statement:void 0}:{text:t,values:n??[]}}#i(e){let t=this.#t.query;if(!t)throw Error(`Query function is not configured.`);return t.call(this.#e,e)}async#a(e){let t=this.#r(e);this.#t?.beforeQuery?.(t);let n=await this.#i(t).catch(e=>{throw this.#t?.onError?.(t,e),e});return typeof n.rowCount!=`number`&&(n.rowCount=n.rows?.length??0),this.#t?.afterQuery?.(t,Z(n,[`command`,`rowCount`,`rows`])),n}async insert(e,t,n){let r=V(e,t,n);return await this.#a([r])}async update(e,t,n,r){if(j(n))throw Error(o);let i=H(e,t,n,r);return await this.#a([i])}async delete(e,t,n){if(j(t))throw Error(a);let r=U(e,t,n);return await this.#a([r])}async upsert(e,t,n,r){let i=W(e,t,n,r);return await this.#a([i])}async query(...e){return this.#a(e)}async getRows(...e){return this.#a(e).then(e=>e.rows)}async getRow(...e){return this.#a(e).then(e=>e.rows?.[0])}async getOne(...e){return this.#a(e).then(e=>Object.values(e.rows?.[0]??{})?.[0])}async getCount(...e){return this.#a(e).then(e=>e.rowCount)}async exec(...e){return this.#a(e).then(e=>e.rowCount)}async begin(e){this.#n===0&&await this.#i({text:`BEGIN`,values:[]}),this.#n+=1;try{let t=await e(this);return this.#n===1&&await this.#i({text:`COMMIT`,values:[]}),t}catch(e){if(this.#n===1)try{await this.#i({text:`ROLLBACK`,values:[]})}catch{throw Error(`Rollback error`,{cause:e})}throw e}finally{--this.#n}}static get prisma(){return async function({text:e,values:t}){if(`$queryRawUnsafe`in this&&typeof this.$queryRawUnsafe==`function`){let n=await this.$queryRawUnsafe(e,...t);return{rows:n,rowCount:n.length}}throw Error(`Prisma adapter requires a $queryRawUnsafe function.`)}}static get typeorm(){return async function({text:e,values:t}){if(`query`in this&&typeof this.query==`function`){let n=await this.query(e,t);return n.length===2&&Array.isArray(n[0])&&typeof n[1]==`number`?{rows:n[0],rowCount:n[1]}:{rows:n,rowCount:n.length}}throw Error(`TypeORM adapter requires a query function.`)}}static get sqlite(){return async function(e){if(`prepare`in this&&typeof this.prepare==`function`){let t=this.prepare(e.sql||e.text).all(...e.values);return{rows:t,rowCount:t.length}}throw Error(`SQLite adapter requires a prepare function.`)}}};function $(e,t){let n=new Q(e,t),r=new Proxy(e,{get(e,t,i){let a=t in n?n:t in e?e:void 0,o=a&&Reflect.get(a,t);return o&&o instanceof Function?function(...t){let n=this===i||this===r||this==null?a:this,s=o.apply(n,t);return s===e?r:s}:o===e?r:o}});return r}exports.AND=k,exports.DELETE_ALL_WITHOUT_FORCE_ERROR=a,exports.LIMIT=F,exports.OFFSET=I,exports.OR=O,exports.QueryFragments=S,exports.QueryHelper=Q,exports.UNION=P,exports.UNION_ALL=N,exports.UPDATE_ALL_WITHOUT_FORCE_ERROR=o,exports.WHERE=A,exports.WHERE_AND=J,exports.WHERE_OR=M,exports.and=K,exports.buildClauses=D,exports.buildDelete=U,exports.buildInsert=V,exports.buildKeys=z,exports.buildUpdate=H,exports.buildUpsert=W,exports.buildValues=B,exports.ident=w,exports.isQueryFragment=h,exports.isQueryTemplateStyle=b,exports.isWhereEmpty=j,exports.json=E,exports.or=G,exports.pgIdent=s,exports.pgString=c,exports.raw=T,exports.sql=C,exports.where=q,exports.where_and=Y,exports.where_or=X,exports.withQueryHelper=$;
package/dist/index.d.cts CHANGED
@@ -11,6 +11,8 @@ type Context = {
11
11
  type EscapeFunction = (v: unknown, context?: Context) => string;
12
12
  type FieldValues = Record<string, unknown>;
13
13
  type WhereArg = string | FieldValues | QueryFragment | undefined | WhereArg[];
14
+ declare const DELETE_ALL_WITHOUT_FORCE_ERROR = "DELETE requires a non-empty WHERE condition.";
15
+ declare const UPDATE_ALL_WITHOUT_FORCE_ERROR = "UPDATE requires a non-empty WHERE condition.";
14
16
  declare function pgIdent(s: string, _ctx?: Context): string;
15
17
  declare function pgString(s: unknown, _ctx?: Context): string;
16
18
  type QueryFragmentToStringOptions = {
@@ -94,6 +96,7 @@ declare function buildClauses(...args: WhereArg[]): QueryFragments;
94
96
  declare function OR(...fv: WhereArg[]): QueryFragments;
95
97
  declare function AND(...fv: WhereArg[]): QueryFragments;
96
98
  declare function WHERE(...fv: WhereArg[]): QueryFragments;
99
+ declare function isWhereEmpty(...fv: WhereArg[]): boolean;
97
100
  declare function WHERE_OR(...fv: WhereArg[]): QueryFragments;
98
101
  declare function UNION_ALL(...fv: unknown[]): QueryFragments;
99
102
  declare function UNION(...fv: unknown[]): QueryFragments;
@@ -173,7 +176,7 @@ declare class QueryHelper<X extends object = object> {
173
176
  * @example
174
177
  * await db.delete('table', { id: 'root' }, 'RETURNING *');
175
178
  */
176
- delete<T extends QueryResultRow>(table: string, where: WhereArg, appendix?: string | QueryFragment): Promise<pgQueryResult<X, T>>;
179
+ delete<T extends QueryResultRow>(table: string, where: WhereArg, appendix?: string | QueryFragment): Promise<QueryResult<T>>;
177
180
  /**
178
181
  * Upsert (INSERT ... ON CONFLICT) builder
179
182
  *
@@ -275,4 +278,4 @@ type WithQueryHelper<T extends object = object> = Override<T, QueryHelper<T>>;
275
278
  declare function withQueryHelper<T extends Queryable<object>>(db: T, opts?: QueryHelperOptions & Partial<QueryableWithThis<T>>): WithQueryHelper<T>;
276
279
  declare function withQueryHelper<T extends object>(db: T, opts: QueryHelperOptions & QueryableWithThis<T>): WithQueryHelper<T>;
277
280
  //#endregion
278
- export { AND, FieldValues, LIMIT, OFFSET, OR, QueryConfig, QueryFragment, QueryFragments, QueryHelper, QueryHelperOptions, QueryResult, QueryResultRow, QueryTemplateStyle, Queryable, QueryableFunction, UNION, UNION_ALL, WHERE, WHERE_AND, WHERE_OR, WhereArg, WithQueryHelper, and, buildClauses, buildDelete, buildInsert, buildKeys, buildUpdate, buildUpsert, buildValues, ident, isQueryFragment, isQueryTemplateStyle, json, or, pgIdent, pgString, raw, sql, where, where_and, where_or, withQueryHelper };
281
+ export { AND, DELETE_ALL_WITHOUT_FORCE_ERROR, FieldValues, LIMIT, OFFSET, OR, QueryConfig, QueryFragment, QueryFragments, QueryHelper, QueryHelperOptions, QueryResult, QueryResultRow, QueryTemplateStyle, Queryable, QueryableFunction, UNION, UNION_ALL, UPDATE_ALL_WITHOUT_FORCE_ERROR, WHERE, WHERE_AND, WHERE_OR, WhereArg, WithQueryHelper, and, buildClauses, buildDelete, buildInsert, buildKeys, buildUpdate, buildUpsert, buildValues, ident, isQueryFragment, isQueryTemplateStyle, isWhereEmpty, json, or, pgIdent, pgString, raw, sql, where, where_and, where_or, withQueryHelper };
package/dist/index.d.ts CHANGED
@@ -11,6 +11,8 @@ type Context = {
11
11
  type EscapeFunction = (v: unknown, context?: Context) => string;
12
12
  type FieldValues = Record<string, unknown>;
13
13
  type WhereArg = string | FieldValues | QueryFragment | undefined | WhereArg[];
14
+ declare const DELETE_ALL_WITHOUT_FORCE_ERROR = "DELETE requires a non-empty WHERE condition.";
15
+ declare const UPDATE_ALL_WITHOUT_FORCE_ERROR = "UPDATE requires a non-empty WHERE condition.";
14
16
  declare function pgIdent(s: string, _ctx?: Context): string;
15
17
  declare function pgString(s: unknown, _ctx?: Context): string;
16
18
  type QueryFragmentToStringOptions = {
@@ -94,6 +96,7 @@ declare function buildClauses(...args: WhereArg[]): QueryFragments;
94
96
  declare function OR(...fv: WhereArg[]): QueryFragments;
95
97
  declare function AND(...fv: WhereArg[]): QueryFragments;
96
98
  declare function WHERE(...fv: WhereArg[]): QueryFragments;
99
+ declare function isWhereEmpty(...fv: WhereArg[]): boolean;
97
100
  declare function WHERE_OR(...fv: WhereArg[]): QueryFragments;
98
101
  declare function UNION_ALL(...fv: unknown[]): QueryFragments;
99
102
  declare function UNION(...fv: unknown[]): QueryFragments;
@@ -173,7 +176,7 @@ declare class QueryHelper<X extends object = object> {
173
176
  * @example
174
177
  * await db.delete('table', { id: 'root' }, 'RETURNING *');
175
178
  */
176
- delete<T extends QueryResultRow>(table: string, where: WhereArg, appendix?: string | QueryFragment): Promise<pgQueryResult<X, T>>;
179
+ delete<T extends QueryResultRow>(table: string, where: WhereArg, appendix?: string | QueryFragment): Promise<QueryResult<T>>;
177
180
  /**
178
181
  * Upsert (INSERT ... ON CONFLICT) builder
179
182
  *
@@ -275,4 +278,4 @@ type WithQueryHelper<T extends object = object> = Override<T, QueryHelper<T>>;
275
278
  declare function withQueryHelper<T extends Queryable<object>>(db: T, opts?: QueryHelperOptions & Partial<QueryableWithThis<T>>): WithQueryHelper<T>;
276
279
  declare function withQueryHelper<T extends object>(db: T, opts: QueryHelperOptions & QueryableWithThis<T>): WithQueryHelper<T>;
277
280
  //#endregion
278
- export { AND, FieldValues, LIMIT, OFFSET, OR, QueryConfig, QueryFragment, QueryFragments, QueryHelper, QueryHelperOptions, QueryResult, QueryResultRow, QueryTemplateStyle, Queryable, QueryableFunction, UNION, UNION_ALL, WHERE, WHERE_AND, WHERE_OR, WhereArg, WithQueryHelper, and, buildClauses, buildDelete, buildInsert, buildKeys, buildUpdate, buildUpsert, buildValues, ident, isQueryFragment, isQueryTemplateStyle, json, or, pgIdent, pgString, raw, sql, where, where_and, where_or, withQueryHelper };
281
+ export { AND, DELETE_ALL_WITHOUT_FORCE_ERROR, FieldValues, LIMIT, OFFSET, OR, QueryConfig, QueryFragment, QueryFragments, QueryHelper, QueryHelperOptions, QueryResult, QueryResultRow, QueryTemplateStyle, Queryable, QueryableFunction, UNION, UNION_ALL, UPDATE_ALL_WITHOUT_FORCE_ERROR, WHERE, WHERE_AND, WHERE_OR, WhereArg, WithQueryHelper, and, buildClauses, buildDelete, buildInsert, buildKeys, buildUpdate, buildUpsert, buildValues, ident, isQueryFragment, isQueryTemplateStyle, isWhereEmpty, json, or, pgIdent, pgString, raw, sql, where, where_and, where_or, withQueryHelper };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- function e(e,t,n){return Math.min(Math.max(e,t),n)}var t=class{#e;#t=0;#n;constructor(e){this.#e=e,this.#n=e.length}get position(){return this.#t}get size(){return this.#n}get remain(){return this.size-this.position}eof(){return this.remain<=0}seek(t){return this.#t=e(t,0,this.size),this}skip(e){return this.seek(this.#t+(e??1))}startsWith(e){if(this.eof())return null;let t=this.#e.slice(this.position);return(typeof e==`string`?t.startsWith(e)&&[e]:t.match(new RegExp(e,e.sticky?e.flags:e.flags+`y`)))||null}match(e,t){let n=this.startsWith(e);return n?(this.skip(n[0].length),t?t(n):n):null}#r(e,t){let n=this.#e.slice(this.position),r=typeof e==`string`?n.indexOf(e):n.search(e);return r<0?null:t(r)}search(e,t){return this.#r(e,n=>{let r=this.read(n),i=this.match(e);if(!i)return null;let a={skipped:r,matched:i};return t?t(a):a})}skipUntil(e){return this.#r(e,e=>this.skip(e))!==null}readUntil(e){return this.#r(e,e=>this.read(e))}read(e){if(this.eof())return``;if(e??=1,e<0)throw RangeError(`read(n): n must be >= 0`);let t=this.#e.slice(this.position,this.position+e);return this.skip(e),t}};const n=`AES128.AES256.ALL.ALLOWOVERWRITE.ANALYSE.ANALYZE.AND.ANY.ARRAY.AS.ASC.AUTHORIZATION.BACKUP.BETWEEN.BINARY.BLANKSASNULL.BOTH.BYTEDICT.CASE.CAST.CHECK.COLLATE.COLUMN.CONSTRAINT.CREATE.CREDENTIALS.CROSS.CURRENT_DATE.CURRENT_TIME.CURRENT_TIMESTAMP.CURRENT_USER.CURRENT_USER_ID.DEFAULT.DEFERRABLE.DEFLATE.DEFRAG.DELTA.DELTA32K.DESC.DISABLE.DISTINCT.DO.ELSE.EMPTYASNULL.ENABLE.ENCODE.ENCRYPT.ENCRYPTION.END.EXCEPT.EXPLICIT.FALSE.FOR.FOREIGN.FREEZE.FROM.FULL.GLOBALDICT256.GLOBALDICT64K.GRANT.GROUP.GZIP.HAVING.IDENTITY.IGNORE.ILIKE.IN.INITIALLY.INNER.INTERSECT.INTO.IS.ISNULL.JOIN.LEADING.LEFT.LIKE.LIMIT.LOCALTIME.LOCALTIMESTAMP.LUN.LUNS.LZO.LZOP.MINUS.MOSTLY13.MOSTLY32.MOSTLY8.NATURAL.NEW.NOT.NOTNULL.NULL.NULLS.OFF.OFFLINE.OFFSET.OLD.ON.ONLY.OPEN.OR.ORDER.OUTER.OVERLAPS.PARALLEL.PARTITION.PERCENT.PLACING.PRIMARY.RAW.READRATIO.RECOVER.REFERENCES.REJECTLOG.RESORT.RESTORE.RIGHT.SELECT.SESSION_USER.SIMILAR.SOME.SYSDATE.SYSTEM.TABLE.TAG.TDES.TEXT255.TEXT32K.THEN.TO.TOP.TRAILING.TRUE.TRUNCATECOLUMNS.UNION.UNIQUE.USER.USING.VERBOSE.WALLET.WHEN.WHERE.WITH.WITHOUT`.split(`.`);function r(e){return e.match(/^[a-zA-Z_][0-9a-zA-Z_$]*$/)&&!n.includes(e.toUpperCase())?e:`"${e.replace(/"/g,`""`)}"`}function i(e){return`${e.includes(`'`)?`E`:``}'${e.replace(/'/g,`''`).replace(/\\/g,`\\\\`)}'`}function a(e,t){return e.split(`.`).map(e=>r(e)).join(`.`)}function o(e,t){return e===null?`NULL`:typeof e==`boolean`?e?`true`:`false`:Array.isArray(e)?`ARRAY[`+e.map(e=>o(e)).join(`,`)+`]`:typeof e==`object`?`toJSON`in e&&typeof e.toJSON==`function`?i(String(e.toJSON())):i(e.toString()):i(String(e))}function s(e,n){let r=new t(n);for(;!r.eof();)if(e.dollarQuoted){if(!r.search(e.dollarQuoted))break;e.dollarQuoted=void 0}else if(e.inEscapedSingleQuote){if(!r.skipUntil(/[\\']/))break;if(r.match(`''`)||r.match(/\\./))continue;if(!r.match(`'`))break;e.inEscapedSingleQuote=!1}else if(e.inSingleQuote){if(!r.skipUntil(`'`))break;if(r.match(`''`))continue;if(!r.match(`'`))break;e.inSingleQuote=!1}else if(e.inBlockComment){if(!r.skipUntil(/\/\*|\*\//))break;if(r.match(`/*`,()=>++e.inBlockComment))continue;if(!r.match(`*/`))break;e.inBlockComment--}else if(e.inLineComment){if(!r.search(/\r\n|\r|\n/))break;e.inLineComment=!1}else{if(!r.skipUntil(/[-$E'/]/))break;if(r.match(/\$[a-zA-Z0-9_]*\$/,t=>e.dollarQuoted=t[0])||r.match(`E'`,()=>e.inEscapedSingleQuote=!0)||r.match(`'`,()=>e.inSingleQuote=!0)||r.match(`--`,()=>e.inLineComment=!0)||r.match(`/*`,()=>e.inBlockComment=1))continue;r.skip()}}function c(e){return e?!!(e.dollarQuoted||e.inLineComment||e.inBlockComment||e.inSingleQuote||e.inEscapedSingleQuote):!1}var l=class{text=``;values=[];sql=``;statement=``;embed=``;#e(e){return this.toString({valueFn:(t,n)=>c(n)?``:e(t),context:{},contextHandler:s})}constructor(){Object.defineProperties(this,{text:{enumerable:!0,get:()=>{let e=1;return this.#e(()=>`$`+ e++)}},values:{enumerable:!0,get:()=>{let e=[];return this.#e(t=>(e.push(t),``)),e}},sql:{enumerable:!1,get:()=>this.#e(()=>`?`)},statement:{enumerable:!1,get:()=>{let e=1;return this.#e(()=>`:`+ e++)}},embed:{enumerable:!0,get:()=>this.#e(e=>o(e))}})}},u=class extends l{#e;constructor(e){super(),this.#e=e}toString(e){return(e?.valueFn??o)(this.#e,e?.context)}},d=class extends l{#e;constructor(e){super(),this.#e=e}toString(e){return(e?.identFn??a)(this.#e,e?.context)}},f=class extends l{#e;constructor(e){super(),this.#e=String(e)}toString(e){return e?.context&&e?.contextHandler&&e.contextHandler(e.context,this.#e),this.#e}};function p(e){return e instanceof l}function m(e){return new d(e)}function h(e){return e===void 0||p(e)?e:new u(e)}function g(e){return e===void 0||p(e)?e:Array.isArray(e)?new b(e.map(g)):new f(e)}function _(e){return e===void 0||p(e)?e:g(JSON.stringify(e))}const v=e=>{if(!Array.isArray(e)||typeof e?.[0]!=`object`||e[0]===null||!(`raw`in e[0])||!Array.isArray(e[0]))return!1;let[t,...n]=e;return t.length-1===n.length};function y(e,t){if(e.length-1!==t.length)throw Error(`Template literal received a mismatched number of values.`);return e.flatMap((e,n)=>n?[t[n-1],e]:[e])}var b=class extends l{#e=[];#t;constructor(...e){if(super(),this.#t={prefix:``,glue:``,suffix:``,empty:``,wrapperFn:e=>e},Array.isArray(e[0])){let[t,n]=e;this.#t={...this.#t,...n},this.push(...t)}else{let[t]=e;this.#t={...this.#t,...t}}}setSewingPattern(e=``,t=``,n=``,r=``){return this.#t={...this.#t,prefix:e,glue:t,suffix:n,empty:r},this}push(...e){return this.#e.push(...e.map(g).filter(e=>e!==void 0)),this}append(...e){return this.push(...e)}join(e=`, `){return this.#t.glue=e,this}prefix(e=` `){return this.#t.prefix=e,this}suffix(e=` `){return this.#t.suffix=e,this}empty(e=``){return this.#t.empty=e,this}toString(e){let t=this.#e.map(t=>t.toString(e)).filter(e=>e).join(this.#t.glue);return t?this.#t.prefix+this.#t.wrapperFn(t,e)+this.#t.suffix:this.#t.empty}};function x(...e){let t;if(v(e)){let[n,...r]=e;t=[new b(y(n.map(g),r.map(h)))]}else t=e.map(h);return new b(t)}const S=m;function C(...e){return new b(e.map(g))}function w(...e){let t,n=(e,t)=>(t?.valueFn||o)(e,t?.context);if(v(e)){let[r,...i]=e;t=[new b(y(r.map(g),i.map(_)),{wrapperFn:n})]}else t=e.map(e=>new b([_(e)],{wrapperFn:n}));return new b(t)}function T(...e){let t=new b,n=e=>{if(e!=null){if(typeof e==`string`){t.push(g(e));return}if(p(e)){t.push(e);return}if(Array.isArray(e)){e.forEach(n);return}if(typeof e==`object`){for(let n in e)if(e[n]!==void 0){if(p(e[n])){t.push(x`${m(n)} ${e[n]}`);continue}if(e[n]===null){t.push(x`${m(n)} IS NULL`);continue}if(Array.isArray(e[n])){let r=e[n];r.length===0?t.push(x`FALSE`):t.push(x`${m(n)} = ANY (${r})`);continue}t.push(x`${m(n)} = ${e[n]}`)}return}}};return n(e),t}function E(...e){return T(e).setSewingPattern(`((`,`) OR (`,`))`,``)}function D(...e){return T(e).setSewingPattern(`((`,`) AND (`,`))`,``)}function O(...e){return T(e).setSewingPattern(`WHERE ((`,`) AND (`,`))`,``)}function k(...e){return T(e).setSewingPattern(`WHERE ((`,`) OR (`,`))`,``)}function A(...e){return C(...e).join(` UNION ALL `)}function j(...e){return C(...e).join(` UNION `)}function M(e){return e==null?x``:(e=Number(e),e>=0?x`LIMIT ${e}`:x``)}function N(e){return e==null?x``:(e=Number(e),e>=0?x`OFFSET ${e}`:x``)}function P(e){let t=Array.isArray(e)?e:[e];if(t.length===0)throw Error(`At least one field value is required.`);let n=t[0],r=n&&Array.isArray(n);if(!n||!r&&typeof n!=`object`)throw Error(`Field values must be arrays or plain objects.`);let i=t.map(e=>{if(Array.isArray(e)!==r)throw Error(`All entries must share the same structure.`);return Object.fromEntries((Array.isArray(e)?e.map((e,t)=>[String(t),e]):Object.entries(e)).filter(([,e])=>e!==void 0))}),a=Object.keys(i[0]),o=i.map(e=>{if(Object.keys(e).length!==a.length)throw Error(`All entries must share the same structure.`);return a.map(t=>{if(!Object.prototype.hasOwnProperty.call(e,t))throw Error(`All entries must share the same structure.`);return e[t]})});return{keys:r?void 0:a,rows:o}}function F(e){let{keys:t,rows:n}=P(e);return{keys:t,fields:t?x(...t.map(m)).setSewingPattern(`(`,`, `,`)`):void 0,VALUES:x`VALUES ${x(...n.map(e=>x(...e).join(`, `))).setSewingPattern(`(`,`), (`,`)`)}`}}function I(e){let{fields:t}=F(e);if(!t)throw Error(`buildKeys requires FieldValues to be objects.`);return t}function L(e){return F(e).VALUES}function R(e,t,n){let{fields:r,VALUES:i}=F(t);if(!r)throw Error(`buildInsert requires FieldValues to be objects.`);return x`INSERT INTO ${m(e)} ${r} ${i}`.append(n).join(` `)}function z(e,t,n,r){let i=new b,a=!1;for(let e in t){let n=t[e];n!==void 0&&(i.push(x`${m(e)} = ${n}`),a=!0)}if(!a)throw Error(`buildUpdate requires at least one field to update.`);return x`UPDATE ${m(e)} SET ${i.join(`, `)} ${O(n)}`.append(r).join(` `)}function B(e,t,n){return x`DELETE FROM ${m(e)} ${O(t)}`.append(n).join(` `)}function V(e,t,n,r){if(!n.length)throw Error(`buildUpsert requires at least one conflict key.`);let{keys:i,fields:a,VALUES:o}=F(t);if(!i||!a)throw Error(`buildUpsert requires FieldValues to be objects.`);let s=x(...n.map(m)).setSewingPattern(`ON CONFLICT (`,`, `,`)`),c=i.filter(e=>!n.includes(e)),l=c.length===0?x`DO NOTHING`:x(...c.map(e=>x`${S(e)} = EXCLUDED.${S(e)}`)).setSewingPattern(`DO UPDATE SET `,`, `);return x`INSERT INTO ${m(e)} ${a} ${o} ${s} ${l}`.append(r).join(` `)}const H=E,U=D,W=O,G=O,K=O,q=k;function J(e,t){return Object.fromEntries(t.map(t=>[t,e[t]]))}var Y=class{#e;#t;#n=0;constructor(e,t={}){if(this.#e=e,this.#t={...t},!this.#t.query){if(!(`query`in e)||typeof e.query!=`function`)throw Error(`No valid query function provided.`);this.#t.query=e.query}}#r(e){if(v(e)){let[t,...n]=e;return x(t,...n)}let[t,n]=e;return typeof t==`object`&&t&&`text`in t?{text:t.text,values:t.values||[],embed:`embed`in t&&typeof t.embed==`string`?t.embed:void 0,sql:`sql`in t&&typeof t.sql==`string`?t.sql:void 0,statement:`statement`in t&&typeof t.statement==`string`?t.statement:void 0}:{text:t,values:n??[]}}#i(e){let t=this.#t.query;if(!t)throw Error(`Query function is not configured.`);return t.call(this.#e,e)}async#a(e){let t=this.#r(e);this.#t?.beforeQuery?.(t);let n=await this.#i(t).catch(e=>{throw this.#t?.onError?.(t,e),e});return typeof n.rowCount!=`number`&&(n.rowCount=n.rows?.length??0),this.#t?.afterQuery?.(t,J(n,[`command`,`rowCount`,`rows`])),n}async insert(e,t,n){let r=R(e,t,n);return await this.#a([r])}async update(e,t,n,r){let i=z(e,t,n,r);return await this.#a([i])}async delete(e,t,n){let r=B(e,t,n);return await this.#a([r])}async upsert(e,t,n,r){let i=V(e,t,n,r);return await this.#a([i])}async query(...e){return this.#a(e)}async getRows(...e){return this.#a(e).then(e=>e.rows)}async getRow(...e){return this.#a(e).then(e=>e.rows?.[0])}async getOne(...e){return this.#a(e).then(e=>Object.values(e.rows?.[0]??{})?.[0])}async getCount(...e){return this.#a(e).then(e=>e.rowCount)}async exec(...e){return this.#a(e).then(e=>e.rowCount)}async begin(e){this.#n===0&&await this.#i({text:`BEGIN`,values:[]}),this.#n+=1;try{let t=await e(this);return this.#n===1&&await this.#i({text:`COMMIT`,values:[]}),t}catch(e){if(this.#n===1)try{await this.#i({text:`ROLLBACK`,values:[]})}catch{throw Error(`Rollback error`,{cause:e})}throw e}finally{--this.#n}}static get prisma(){return async function({text:e,values:t}){if(`$queryRawUnsafe`in this&&typeof this.$queryRawUnsafe==`function`){let n=await this.$queryRawUnsafe(e,...t);return{rows:n,rowCount:n.length}}throw Error(`Prisma adapter requires a $queryRawUnsafe function.`)}}static get typeorm(){return async function({text:e,values:t}){if(`query`in this&&typeof this.query==`function`){let n=await this.query(e,t);return n.length===2&&Array.isArray(n[0])&&typeof n[1]==`number`?{rows:n[0],rowCount:n[1]}:{rows:n,rowCount:n.length}}throw Error(`TypeORM adapter requires a query function.`)}}static get sqlite(){return async function(e){if(`prepare`in this&&typeof this.prepare==`function`){let t=this.prepare(e.sql||e.text).all(...e.values);return{rows:t,rowCount:t.length}}throw Error(`SQLite adapter requires a prepare function.`)}}};function X(e,t){let n=new Y(e,t),r=new Proxy(e,{get(e,t,i){let a=t in n?n:t in e?e:void 0,o=a&&Reflect.get(a,t);return o&&o instanceof Function?function(...t){let n=this===i||this===r||this==null?a:this,s=o.apply(n,t);return s===e?r:s}:o===e?r:o}});return r}export{D as AND,M as LIMIT,N as OFFSET,E as OR,b as QueryFragments,Y as QueryHelper,j as UNION,A as UNION_ALL,O as WHERE,G as WHERE_AND,k as WHERE_OR,U as and,T as buildClauses,B as buildDelete,R as buildInsert,I as buildKeys,z as buildUpdate,V as buildUpsert,L as buildValues,S as ident,p as isQueryFragment,v as isQueryTemplateStyle,w as json,H as or,a as pgIdent,o as pgString,C as raw,x as sql,W as where,K as where_and,q as where_or,X as withQueryHelper};
1
+ function e(e,t,n){return Math.min(Math.max(e,t),n)}var t=class{#e;#t=0;#n;constructor(e){this.#e=e,this.#n=e.length}get position(){return this.#t}get size(){return this.#n}get remain(){return this.size-this.position}eof(){return this.remain<=0}seek(t){return this.#t=e(t,0,this.size),this}skip(e){return this.seek(this.#t+(e??1))}startsWith(e){if(this.eof())return null;let t=this.#e.slice(this.position);return(typeof e==`string`?t.startsWith(e)&&[e]:t.match(new RegExp(e,e.sticky?e.flags:e.flags+`y`)))||null}match(e,t){let n=this.startsWith(e);return n?(this.skip(n[0].length),t?t(n):n):null}#r(e,t){let n=this.#e.slice(this.position),r=typeof e==`string`?n.indexOf(e):n.search(e);return r<0?null:t(r)}search(e,t){return this.#r(e,n=>{let r=this.read(n),i=this.match(e);if(!i)return null;let a={skipped:r,matched:i};return t?t(a):a})}skipUntil(e){return this.#r(e,e=>this.skip(e))!==null}readUntil(e){return this.#r(e,e=>this.read(e))}read(e){if(this.eof())return``;if(e??=1,e<0)throw RangeError(`read(n): n must be >= 0`);let t=this.#e.slice(this.position,this.position+e);return this.skip(e),t}};const n=`AES128.AES256.ALL.ALLOWOVERWRITE.ANALYSE.ANALYZE.AND.ANY.ARRAY.AS.ASC.AUTHORIZATION.BACKUP.BETWEEN.BINARY.BLANKSASNULL.BOTH.BYTEDICT.CASE.CAST.CHECK.COLLATE.COLUMN.CONSTRAINT.CREATE.CREDENTIALS.CROSS.CURRENT_DATE.CURRENT_TIME.CURRENT_TIMESTAMP.CURRENT_USER.CURRENT_USER_ID.DEFAULT.DEFERRABLE.DEFLATE.DEFRAG.DELTA.DELTA32K.DESC.DISABLE.DISTINCT.DO.ELSE.EMPTYASNULL.ENABLE.ENCODE.ENCRYPT.ENCRYPTION.END.EXCEPT.EXPLICIT.FALSE.FOR.FOREIGN.FREEZE.FROM.FULL.GLOBALDICT256.GLOBALDICT64K.GRANT.GROUP.GZIP.HAVING.IDENTITY.IGNORE.ILIKE.IN.INITIALLY.INNER.INTERSECT.INTO.IS.ISNULL.JOIN.LEADING.LEFT.LIKE.LIMIT.LOCALTIME.LOCALTIMESTAMP.LUN.LUNS.LZO.LZOP.MINUS.MOSTLY13.MOSTLY32.MOSTLY8.NATURAL.NEW.NOT.NOTNULL.NULL.NULLS.OFF.OFFLINE.OFFSET.OLD.ON.ONLY.OPEN.OR.ORDER.OUTER.OVERLAPS.PARALLEL.PARTITION.PERCENT.PLACING.PRIMARY.RAW.READRATIO.RECOVER.REFERENCES.REJECTLOG.RESORT.RESTORE.RIGHT.SELECT.SESSION_USER.SIMILAR.SOME.SYSDATE.SYSTEM.TABLE.TAG.TDES.TEXT255.TEXT32K.THEN.TO.TOP.TRAILING.TRUE.TRUNCATECOLUMNS.UNION.UNIQUE.USER.USING.VERBOSE.WALLET.WHEN.WHERE.WITH.WITHOUT`.split(`.`);function r(e){return e.match(/^[a-zA-Z_][0-9a-zA-Z_$]*$/)&&!n.includes(e.toUpperCase())?e:`"${e.replace(/"/g,`""`)}"`}function i(e){return`${e.includes(`'`)?`E`:``}'${e.replace(/'/g,`''`).replace(/\\/g,`\\\\`)}'`}const a=`DELETE requires a non-empty WHERE condition.`,o=`UPDATE requires a non-empty WHERE condition.`;function s(e,t){return e.split(`.`).map(e=>r(e)).join(`.`)}function c(e,t){return e===null?`NULL`:typeof e==`boolean`?e?`true`:`false`:Array.isArray(e)?`ARRAY[`+e.map(e=>c(e)).join(`,`)+`]`:typeof e==`object`?`toJSON`in e&&typeof e.toJSON==`function`?i(String(e.toJSON())):i(e.toString()):i(String(e))}function l(e,n){let r=new t(n);for(;!r.eof();)if(e.dollarQuoted){if(!r.search(e.dollarQuoted))break;e.dollarQuoted=void 0}else if(e.inEscapedSingleQuote){if(!r.skipUntil(/[\\']/))break;if(r.match(`''`)||r.match(/\\./))continue;if(!r.match(`'`))break;e.inEscapedSingleQuote=!1}else if(e.inSingleQuote){if(!r.skipUntil(`'`))break;if(r.match(`''`))continue;if(!r.match(`'`))break;e.inSingleQuote=!1}else if(e.inBlockComment){if(!r.skipUntil(/\/\*|\*\//))break;if(r.match(`/*`,()=>++e.inBlockComment))continue;if(!r.match(`*/`))break;e.inBlockComment--}else if(e.inLineComment){if(!r.search(/\r\n|\r|\n/))break;e.inLineComment=!1}else{if(!r.skipUntil(/[-$E'/]/))break;if(r.match(/\$[a-zA-Z0-9_]*\$/,t=>e.dollarQuoted=t[0])||r.match(`E'`,()=>e.inEscapedSingleQuote=!0)||r.match(`'`,()=>e.inSingleQuote=!0)||r.match(`--`,()=>e.inLineComment=!0)||r.match(`/*`,()=>e.inBlockComment=1))continue;r.skip()}}function u(e){return e?!!(e.dollarQuoted||e.inLineComment||e.inBlockComment||e.inSingleQuote||e.inEscapedSingleQuote):!1}var d=class{text=``;values=[];sql=``;statement=``;embed=``;#e(e){return this.toString({valueFn:(t,n)=>u(n)?``:e(t),context:{},contextHandler:l})}constructor(){Object.defineProperties(this,{text:{enumerable:!0,get:()=>{let e=1;return this.#e(()=>`$`+ e++)}},values:{enumerable:!0,get:()=>{let e=[];return this.#e(t=>(e.push(t),``)),e}},sql:{enumerable:!1,get:()=>this.#e(()=>`?`)},statement:{enumerable:!1,get:()=>{let e=1;return this.#e(()=>`:`+ e++)}},embed:{enumerable:!0,get:()=>this.#e(e=>c(e))}})}},f=class extends d{#e;constructor(e){super(),this.#e=e}toString(e){return(e?.valueFn??c)(this.#e,e?.context)}},p=class extends d{#e;constructor(e){super(),this.#e=e}toString(e){return(e?.identFn??s)(this.#e,e?.context)}},m=class extends d{#e;constructor(e){super(),this.#e=String(e)}toString(e){return e?.context&&e?.contextHandler&&e.contextHandler(e.context,this.#e),this.#e}};function h(e){return e instanceof d}function g(e){return new p(e)}function _(e){return e===void 0||h(e)?e:new f(e)}function v(e){return e===void 0||h(e)?e:Array.isArray(e)?new S(e.map(v)):new m(e)}function y(e){return e===void 0||h(e)?e:v(JSON.stringify(e))}const b=e=>{if(!Array.isArray(e)||typeof e?.[0]!=`object`||e[0]===null||!(`raw`in e[0])||!Array.isArray(e[0]))return!1;let[t,...n]=e;return t.length-1===n.length};function x(e,t){if(e.length-1!==t.length)throw Error(`Template literal received a mismatched number of values.`);return e.flatMap((e,n)=>n?[t[n-1],e]:[e])}var S=class extends d{#e=[];#t;constructor(...e){if(super(),this.#t={prefix:``,glue:``,suffix:``,empty:``,wrapperFn:e=>e},Array.isArray(e[0])){let[t,n]=e;this.#t={...this.#t,...n},this.push(...t)}else{let[t]=e;this.#t={...this.#t,...t}}}setSewingPattern(e=``,t=``,n=``,r=``){return this.#t={...this.#t,prefix:e,glue:t,suffix:n,empty:r},this}push(...e){return this.#e.push(...e.map(v).filter(e=>e!==void 0)),this}append(...e){return this.push(...e)}join(e=`, `){return this.#t.glue=e,this}prefix(e=` `){return this.#t.prefix=e,this}suffix(e=` `){return this.#t.suffix=e,this}empty(e=``){return this.#t.empty=e,this}toString(e){let t=this.#e.map(t=>t.toString(e)).filter(e=>e).join(this.#t.glue);return t?this.#t.prefix+this.#t.wrapperFn(t,e)+this.#t.suffix:this.#t.empty}};function C(...e){let t;if(b(e)){let[n,...r]=e;t=[new S(x(n.map(v),r.map(_)))]}else t=e.map(_);return new S(t)}const w=g;function T(...e){return new S(e.map(v))}function E(...e){let t,n=(e,t)=>(t?.valueFn||c)(e,t?.context);if(b(e)){let[r,...i]=e;t=[new S(x(r.map(v),i.map(y)),{wrapperFn:n})]}else t=e.map(e=>new S([y(e)],{wrapperFn:n}));return new S(t)}function D(...e){let t=new S,n=e=>{if(e!=null){if(typeof e==`string`){t.push(v(e));return}if(h(e)){t.push(e);return}if(Array.isArray(e)){e.forEach(n);return}if(typeof e==`object`){for(let n in e)if(e[n]!==void 0){if(h(e[n])){t.push(C`${g(n)} ${e[n]}`);continue}if(e[n]===null){t.push(C`${g(n)} IS NULL`);continue}if(Array.isArray(e[n])){let r=e[n];r.length===0?t.push(C`FALSE`):t.push(C`${g(n)} = ANY (${r})`);continue}t.push(C`${g(n)} = ${e[n]}`)}return}}};return n(e),t}function O(...e){return D(e).setSewingPattern(`((`,`) OR (`,`))`,``)}function k(...e){return D(e).setSewingPattern(`((`,`) AND (`,`))`,``)}function A(...e){return D(e).setSewingPattern(`WHERE ((`,`) AND (`,`))`,``)}function j(...e){return D(e).text.length===0}function M(...e){return D(e).setSewingPattern(`WHERE ((`,`) OR (`,`))`,``)}function N(...e){return T(...e).join(` UNION ALL `)}function P(...e){return T(...e).join(` UNION `)}function F(e){return e==null?C``:(e=Number(e),e>=0?C`LIMIT ${e}`:C``)}function I(e){return e==null?C``:(e=Number(e),e>=0?C`OFFSET ${e}`:C``)}function L(e){let t=Array.isArray(e)?e:[e];if(t.length===0)throw Error(`At least one field value is required.`);let n=t[0],r=n&&Array.isArray(n);if(!n||!r&&typeof n!=`object`)throw Error(`Field values must be arrays or plain objects.`);let i=t.map(e=>{if(Array.isArray(e)!==r)throw Error(`All entries must share the same structure.`);return Object.fromEntries((Array.isArray(e)?e.map((e,t)=>[String(t),e]):Object.entries(e)).filter(([,e])=>e!==void 0))}),a=Object.keys(i[0]),o=i.map(e=>{if(Object.keys(e).length!==a.length)throw Error(`All entries must share the same structure.`);return a.map(t=>{if(!Object.prototype.hasOwnProperty.call(e,t))throw Error(`All entries must share the same structure.`);return e[t]})});return{keys:r?void 0:a,rows:o}}function R(e){let{keys:t,rows:n}=L(e);return{keys:t,fields:t?C(...t.map(g)).setSewingPattern(`(`,`, `,`)`):void 0,VALUES:C`VALUES ${C(...n.map(e=>C(...e).join(`, `))).setSewingPattern(`(`,`), (`,`)`)}`}}function z(e){let{fields:t}=R(e);if(!t)throw Error(`buildKeys requires FieldValues to be objects.`);return t}function B(e){return R(e).VALUES}function V(e,t,n){let{fields:r,VALUES:i}=R(t);if(!r)throw Error(`buildInsert requires FieldValues to be objects.`);return C`INSERT INTO ${g(e)} ${r} ${i}`.append(n).join(` `)}function H(e,t,n,r){let i=new S,a=!1;for(let e in t){let n=t[e];n!==void 0&&(i.push(C`${g(e)} = ${n}`),a=!0)}if(!a)throw Error(`buildUpdate requires at least one field to update.`);if(j(n))throw Error(o);return C`UPDATE ${g(e)} SET ${i.join(`, `)} ${A(n)}`.append(r).join(` `)}function U(e,t,n){if(j(t))throw Error(a);return C`DELETE FROM ${g(e)} ${A(t)}`.append(n).join(` `)}function W(e,t,n,r){if(!n.length)throw Error(`buildUpsert requires at least one conflict key.`);let{keys:i,fields:a,VALUES:o}=R(t);if(!i||!a)throw Error(`buildUpsert requires FieldValues to be objects.`);let s=C(...n.map(g)).setSewingPattern(`ON CONFLICT (`,`, `,`)`),c=i.filter(e=>!n.includes(e)),l=c.length===0?C`DO NOTHING`:C(...c.map(e=>C`${w(e)} = EXCLUDED.${w(e)}`)).setSewingPattern(`DO UPDATE SET `,`, `);return C`INSERT INTO ${g(e)} ${a} ${o} ${s} ${l}`.append(r).join(` `)}const G=O,K=k,q=A,J=A,Y=A,X=M;function Z(e,t){return Object.fromEntries(t.map(t=>[t,e[t]]))}var Q=class{#e;#t;#n=0;constructor(e,t={}){if(this.#e=e,this.#t={...t},!this.#t.query){if(!(`query`in e)||typeof e.query!=`function`)throw Error(`No valid query function provided.`);this.#t.query=e.query}}#r(e){if(b(e)){let[t,...n]=e;return C(t,...n)}let[t,n]=e;return typeof t==`object`&&t&&`text`in t?{text:t.text,values:t.values||[],embed:`embed`in t&&typeof t.embed==`string`?t.embed:void 0,sql:`sql`in t&&typeof t.sql==`string`?t.sql:void 0,statement:`statement`in t&&typeof t.statement==`string`?t.statement:void 0}:{text:t,values:n??[]}}#i(e){let t=this.#t.query;if(!t)throw Error(`Query function is not configured.`);return t.call(this.#e,e)}async#a(e){let t=this.#r(e);this.#t?.beforeQuery?.(t);let n=await this.#i(t).catch(e=>{throw this.#t?.onError?.(t,e),e});return typeof n.rowCount!=`number`&&(n.rowCount=n.rows?.length??0),this.#t?.afterQuery?.(t,Z(n,[`command`,`rowCount`,`rows`])),n}async insert(e,t,n){let r=V(e,t,n);return await this.#a([r])}async update(e,t,n,r){if(j(n))throw Error(o);let i=H(e,t,n,r);return await this.#a([i])}async delete(e,t,n){if(j(t))throw Error(a);let r=U(e,t,n);return await this.#a([r])}async upsert(e,t,n,r){let i=W(e,t,n,r);return await this.#a([i])}async query(...e){return this.#a(e)}async getRows(...e){return this.#a(e).then(e=>e.rows)}async getRow(...e){return this.#a(e).then(e=>e.rows?.[0])}async getOne(...e){return this.#a(e).then(e=>Object.values(e.rows?.[0]??{})?.[0])}async getCount(...e){return this.#a(e).then(e=>e.rowCount)}async exec(...e){return this.#a(e).then(e=>e.rowCount)}async begin(e){this.#n===0&&await this.#i({text:`BEGIN`,values:[]}),this.#n+=1;try{let t=await e(this);return this.#n===1&&await this.#i({text:`COMMIT`,values:[]}),t}catch(e){if(this.#n===1)try{await this.#i({text:`ROLLBACK`,values:[]})}catch{throw Error(`Rollback error`,{cause:e})}throw e}finally{--this.#n}}static get prisma(){return async function({text:e,values:t}){if(`$queryRawUnsafe`in this&&typeof this.$queryRawUnsafe==`function`){let n=await this.$queryRawUnsafe(e,...t);return{rows:n,rowCount:n.length}}throw Error(`Prisma adapter requires a $queryRawUnsafe function.`)}}static get typeorm(){return async function({text:e,values:t}){if(`query`in this&&typeof this.query==`function`){let n=await this.query(e,t);return n.length===2&&Array.isArray(n[0])&&typeof n[1]==`number`?{rows:n[0],rowCount:n[1]}:{rows:n,rowCount:n.length}}throw Error(`TypeORM adapter requires a query function.`)}}static get sqlite(){return async function(e){if(`prepare`in this&&typeof this.prepare==`function`){let t=this.prepare(e.sql||e.text).all(...e.values);return{rows:t,rowCount:t.length}}throw Error(`SQLite adapter requires a prepare function.`)}}};function $(e,t){let n=new Q(e,t),r=new Proxy(e,{get(e,t,i){let a=t in n?n:t in e?e:void 0,o=a&&Reflect.get(a,t);return o&&o instanceof Function?function(...t){let n=this===i||this===r||this==null?a:this,s=o.apply(n,t);return s===e?r:s}:o===e?r:o}});return r}export{k as AND,a as DELETE_ALL_WITHOUT_FORCE_ERROR,F as LIMIT,I as OFFSET,O as OR,S as QueryFragments,Q as QueryHelper,P as UNION,N as UNION_ALL,o as UPDATE_ALL_WITHOUT_FORCE_ERROR,A as WHERE,J as WHERE_AND,M as WHERE_OR,K as and,D as buildClauses,U as buildDelete,V as buildInsert,z as buildKeys,H as buildUpdate,W as buildUpsert,B as buildValues,w as ident,h as isQueryFragment,b as isQueryTemplateStyle,j as isWhereEmpty,E as json,G as or,s as pgIdent,c as pgString,T as raw,C as sql,q as where,Y as where_and,X as where_or,$ as withQueryHelper};
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "query-weaver",
3
- "version": "0.2.0-alpha.4",
3
+ "version": "0.2.0-alpha.5",
4
4
  "description": "SQL query builder using template string literal",
5
5
  "type": "module",
6
6
  "main": "./index.js",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "query-weaver",
3
- "version": "0.2.0-alpha.4",
3
+ "version": "0.2.0-alpha.5",
4
4
  "description": "SQL query builder using template string literal",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",