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

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
@@ -146,11 +146,11 @@ console.log(JSON.stringify(sql`SELECT * FROM foobar WHERE ${raw("bar LIKE '%some
146
146
 
147
147
  ```js
148
148
  sql.insert(tableName, { ...fieldValuePairs }); // => sql`INSERT INTO ...`
149
- db.insert(tableName, { ...fieldValuePairs }); // => db.query`INSERT INTO ...`
149
+ await db.insert(tableName, { ...fieldValuePairs }); // => db.query`INSERT INTO ...`
150
150
 
151
151
  // Bulk insert
152
152
  sql.insert(tableName, [{ ...fieldValuePairs }, ...]); // => sql`INSERT INTO ... VALUES (...), (...), ...`
153
- db.insert(tableName, [{ ...fieldValuePairs }, ...]); // => db.query`INSERT INTO ... VALUES (...), (...), ...`
153
+ await db.insert(tableName, [{ ...fieldValuePairs }, ...]); // => db.query`INSERT INTO ... VALUES (...), (...), ...`
154
154
  ```
155
155
 
156
156
  ### UPDATE Builder and Helper
@@ -159,7 +159,10 @@ db.insert(tableName, [{ ...fieldValuePairs }, ...]); // => db.query`INSERT INTO
159
159
 
160
160
  ```js
161
161
  sql.update(tableName, { ...fieldValuePairs }, { ...whereCondition }); // => sql`UPDATE ...`
162
- db.update(tableName, { ...fieldValuePairs }, { ...whereCondition }); // => db.query`UPDATE ...`
162
+ await db.update(tableName, { ...fieldValuePairs }, { ...whereCondition }); // => db.query`UPDATE ...`
163
+
164
+ // Empty conditions throw for safety.
165
+ await db.update(tableName, { name: 'updated' }, { id: undefined });
163
166
  ```
164
167
 
165
168
  ### DELETE Builder and Helper
@@ -168,7 +171,10 @@ db.update(tableName, { ...fieldValuePairs }, { ...whereCondition }); // => db.q
168
171
 
169
172
  ```js
170
173
  sql.delete(tableName, { ...whereCondition }); // => sql`DELETE FROM ...`
171
- db.delete(tableName, { ...whereCondition }); // => db.query`DELETE FROM ...`
174
+ await db.delete(tableName, { ...whereCondition }); // => db.query`DELETE FROM ...`
175
+
176
+ // Empty conditions throw for safety.
177
+ await db.delete(tableName, { id: undefined });
172
178
  ```
173
179
 
174
180
  ### Transaction Helper
@@ -176,14 +182,21 @@ db.delete(tableName, { ...whereCondition }); // => db.query`DELETE FROM ...`
176
182
  `begin` helper
177
183
 
178
184
  ```js
179
- db.begin(() => {
180
- db.delete(...);
181
- db.insert(...);
185
+ await db.begin(async (c) => {
186
+ await c.delete(...);
187
+ await c.insert(...);
188
+ });
189
+
190
+ await db.begin({
191
+ role: 'guest',
192
+ }, async (c) => {
193
+ await c.delete(...);
194
+ await c.insert(...);
182
195
  });
183
196
  ```
184
197
 
185
198
  If an error occurs, the transaction is safely rolled back.
186
- **NOTE:** Transactions can be nested, but only the outermost transaction is effective.
199
+ **NOTE:** `begin` can be nested, but only the outermost transaction is effective.
187
200
 
188
201
  ## Low-level APIs
189
202
 
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{#e;#t;#n;constructor(e,t={},n=!1){this.#e=e,this.#t={...t},this.#n=n,!this.#t.connect&&!this.#t.release&&`connect`in this.#e&&typeof this.#e.connect==`function`&&`totalCount`in this.#e&&`idleCount`in this.#e&&(this.#t.connect=()=>this.#e.connect(),this.#t.release=e=>e.release())}#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??[]}}async#i(e){let t=this.#t.query??(`query`in this.#e&&typeof this.#e.query==`function`&&this.#e.query);if(!t)throw Error(`Query function is not configured on the object.`);return await 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#o(t){if(this.#n)return this;let n=new e(await this.#t.connect?.(this.#e)??this.#e,this.#t,!0);return t.role&&await n.#i(this.#r([C`SET ROLE ${w(t.role)}`])),t.transaction!==!1&&await n.#i({text:`BEGIN`,values:[]}),n}async#s(e,t,n=!0){if(!this.#n)try{t.transaction!==!1&&await e.#i({text:n?`COMMIT`:`ROLLBACK`,values:[]}),t.role&&await e.#i({text:`SET ROLE NONE`,values:[]})}finally{await this.#t.release?.(e.#e)}}async#c(e,t){return this.#s(e,t,!1)}async begin(e,t){typeof e==`function`&&(t=e,e={});let n=await this.#o(e),r;try{r=await t(n.wrap())}catch(t){throw await this.#c(n,e),t}return await this.#s(n,e),r}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.`)}}wrap(){let e=new Proxy(this.#e,{get:(t,n,r)=>{let i=n in this?this:n in t?t:void 0,a=i&&Reflect.get(i,n);return a&&a instanceof Function?function(...n){let o=this===r||this===e||this==null?i:this,s=a.apply(o,n);return s===t?e:s}:a===t?e:a}});return e}};function $(e,t){return new Q(e,t).wrap()}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;
@@ -141,18 +144,24 @@ type pgQueryResult<X, T extends QueryResultRow> = (X extends {
141
144
  } ? pg.QueryResult<T> : QueryResult<T>) & {
142
145
  rowCount: number;
143
146
  };
144
- type QueryHelperOptions = {
147
+ type QueryHelperOptions<X extends object, Y extends object> = {
145
148
  beforeQuery?: (ctx: Readonly<QueryConfig>) => void;
146
149
  afterQuery?: <R extends QueryResultRow>(ctx: Readonly<QueryConfig>, r: QueryResult<R>) => void;
147
150
  onError?: (ctx: Readonly<QueryConfig>, e: unknown) => void;
151
+ connect?: (obj: X) => Promise<Y>;
152
+ release?: (conn: Y) => Promise<void> | void;
148
153
  };
149
154
  type QueryTemplateOrSimpleQuery = QueryTemplateStyle | [query: string, values?: unknown[]] | [query: pg.QueryConfig<unknown[]>];
155
+ type QueryHelperBeginOption = {
156
+ transaction?: boolean;
157
+ role?: string;
158
+ };
150
159
  /**
151
160
  * Query Helper
152
161
  */
153
- declare class QueryHelper<X extends object = object> {
162
+ declare class QueryHelper<X extends object = object, Y extends object = object> {
154
163
  #private;
155
- constructor(db: X, opts?: QueryHelperOptions & Partial<Queryable<X>>);
164
+ constructor(db: X, opts?: QueryHelperOptions<X, Y> & Partial<Queryable<X>>, nested?: boolean);
156
165
  /**
157
166
  * INSERT builder
158
167
  *
@@ -173,7 +182,7 @@ declare class QueryHelper<X extends object = object> {
173
182
  * @example
174
183
  * await db.delete('table', { id: 'root' }, 'RETURNING *');
175
184
  */
176
- delete<T extends QueryResultRow>(table: string, where: WhereArg, appendix?: string | QueryFragment): Promise<pgQueryResult<X, T>>;
185
+ delete<T extends QueryResultRow>(table: string, where: WhereArg, appendix?: string | QueryFragment): Promise<QueryResult<T>>;
177
186
  /**
178
187
  * Upsert (INSERT ... ON CONFLICT) builder
179
188
  *
@@ -241,7 +250,8 @@ declare class QueryHelper<X extends object = object> {
241
250
  * return true;
242
251
  * });
243
252
  */
244
- begin<R>(callback: (conn: this) => Promise<R>): Promise<R>;
253
+ begin<R>(callback: (conn: WithQueryHelper<Y, Y>) => Promise<R>): Promise<R>;
254
+ begin<R>(opts: QueryHelperBeginOption, callback: (conn: WithQueryHelper<Y, Y>) => Promise<R>): Promise<R>;
245
255
  /**
246
256
  * Prisma adapter: NB; It only supports a query that returns rows
247
257
  */
@@ -260,11 +270,12 @@ declare class QueryHelper<X extends object = object> {
260
270
  rows: T[];
261
271
  rowCount: number;
262
272
  }>;
273
+ wrap(): WithQueryHelper<X, Y>;
263
274
  }
264
275
  type Overwrite<T, Q> = Omit<T, keyof Q> & Q;
265
276
  type MethodChainRewrite<T, Q> = { [K in keyof T]: T[K] extends ((...args: infer R) => T) ? (...args: R) => Override<T, Q> : T[K] extends T ? Override<T, Q> : T[K] };
266
277
  type Override<T, Q> = Overwrite<MethodChainRewrite<T, Q>, Q>;
267
- type WithQueryHelper<T extends object = object> = Override<T, QueryHelper<T>>;
278
+ type WithQueryHelper<X extends object = object, Y extends object = object> = Override<X, QueryHelper<X, Y>>;
268
279
  /**
269
280
  * Returns a proxy object that overrides the queryable instance `db` by Query Helper utilities
270
281
  * @param db - Queryable object to be wrapped
@@ -272,7 +283,7 @@ type WithQueryHelper<T extends object = object> = Override<T, QueryHelper<T>>;
272
283
  * @example
273
284
  * const db = withQueryHelper(new pg.Client());
274
285
  */
275
- declare function withQueryHelper<T extends Queryable<object>>(db: T, opts?: QueryHelperOptions & Partial<QueryableWithThis<T>>): WithQueryHelper<T>;
276
- declare function withQueryHelper<T extends object>(db: T, opts: QueryHelperOptions & QueryableWithThis<T>): WithQueryHelper<T>;
286
+ declare function withQueryHelper<X extends Queryable<object>, Y extends object>(db: X, opts?: QueryHelperOptions<X, Y> & Partial<QueryableWithThis<X>>): WithQueryHelper<X, Y>;
287
+ declare function withQueryHelper<X extends object, Y extends object>(db: X, opts: QueryHelperOptions<X, Y> & QueryableWithThis<X>): WithQueryHelper<X, Y>;
277
288
  //#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 };
289
+ export { AND, DELETE_ALL_WITHOUT_FORCE_ERROR, FieldValues, LIMIT, OFFSET, OR, QueryConfig, QueryFragment, QueryFragments, QueryHelper, QueryHelperBeginOption, 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;
@@ -141,18 +144,24 @@ type pgQueryResult<X, T extends QueryResultRow> = (X extends {
141
144
  } ? pg.QueryResult<T> : QueryResult<T>) & {
142
145
  rowCount: number;
143
146
  };
144
- type QueryHelperOptions = {
147
+ type QueryHelperOptions<X extends object, Y extends object> = {
145
148
  beforeQuery?: (ctx: Readonly<QueryConfig>) => void;
146
149
  afterQuery?: <R extends QueryResultRow>(ctx: Readonly<QueryConfig>, r: QueryResult<R>) => void;
147
150
  onError?: (ctx: Readonly<QueryConfig>, e: unknown) => void;
151
+ connect?: (obj: X) => Promise<Y>;
152
+ release?: (conn: Y) => Promise<void> | void;
148
153
  };
149
154
  type QueryTemplateOrSimpleQuery = QueryTemplateStyle | [query: string, values?: unknown[]] | [query: pg.QueryConfig<unknown[]>];
155
+ type QueryHelperBeginOption = {
156
+ transaction?: boolean;
157
+ role?: string;
158
+ };
150
159
  /**
151
160
  * Query Helper
152
161
  */
153
- declare class QueryHelper<X extends object = object> {
162
+ declare class QueryHelper<X extends object = object, Y extends object = object> {
154
163
  #private;
155
- constructor(db: X, opts?: QueryHelperOptions & Partial<Queryable<X>>);
164
+ constructor(db: X, opts?: QueryHelperOptions<X, Y> & Partial<Queryable<X>>, nested?: boolean);
156
165
  /**
157
166
  * INSERT builder
158
167
  *
@@ -173,7 +182,7 @@ declare class QueryHelper<X extends object = object> {
173
182
  * @example
174
183
  * await db.delete('table', { id: 'root' }, 'RETURNING *');
175
184
  */
176
- delete<T extends QueryResultRow>(table: string, where: WhereArg, appendix?: string | QueryFragment): Promise<pgQueryResult<X, T>>;
185
+ delete<T extends QueryResultRow>(table: string, where: WhereArg, appendix?: string | QueryFragment): Promise<QueryResult<T>>;
177
186
  /**
178
187
  * Upsert (INSERT ... ON CONFLICT) builder
179
188
  *
@@ -241,7 +250,8 @@ declare class QueryHelper<X extends object = object> {
241
250
  * return true;
242
251
  * });
243
252
  */
244
- begin<R>(callback: (conn: this) => Promise<R>): Promise<R>;
253
+ begin<R>(callback: (conn: WithQueryHelper<Y, Y>) => Promise<R>): Promise<R>;
254
+ begin<R>(opts: QueryHelperBeginOption, callback: (conn: WithQueryHelper<Y, Y>) => Promise<R>): Promise<R>;
245
255
  /**
246
256
  * Prisma adapter: NB; It only supports a query that returns rows
247
257
  */
@@ -260,11 +270,12 @@ declare class QueryHelper<X extends object = object> {
260
270
  rows: T[];
261
271
  rowCount: number;
262
272
  }>;
273
+ wrap(): WithQueryHelper<X, Y>;
263
274
  }
264
275
  type Overwrite<T, Q> = Omit<T, keyof Q> & Q;
265
276
  type MethodChainRewrite<T, Q> = { [K in keyof T]: T[K] extends ((...args: infer R) => T) ? (...args: R) => Override<T, Q> : T[K] extends T ? Override<T, Q> : T[K] };
266
277
  type Override<T, Q> = Overwrite<MethodChainRewrite<T, Q>, Q>;
267
- type WithQueryHelper<T extends object = object> = Override<T, QueryHelper<T>>;
278
+ type WithQueryHelper<X extends object = object, Y extends object = object> = Override<X, QueryHelper<X, Y>>;
268
279
  /**
269
280
  * Returns a proxy object that overrides the queryable instance `db` by Query Helper utilities
270
281
  * @param db - Queryable object to be wrapped
@@ -272,7 +283,7 @@ type WithQueryHelper<T extends object = object> = Override<T, QueryHelper<T>>;
272
283
  * @example
273
284
  * const db = withQueryHelper(new pg.Client());
274
285
  */
275
- declare function withQueryHelper<T extends Queryable<object>>(db: T, opts?: QueryHelperOptions & Partial<QueryableWithThis<T>>): WithQueryHelper<T>;
276
- declare function withQueryHelper<T extends object>(db: T, opts: QueryHelperOptions & QueryableWithThis<T>): WithQueryHelper<T>;
286
+ declare function withQueryHelper<X extends Queryable<object>, Y extends object>(db: X, opts?: QueryHelperOptions<X, Y> & Partial<QueryableWithThis<X>>): WithQueryHelper<X, Y>;
287
+ declare function withQueryHelper<X extends object, Y extends object>(db: X, opts: QueryHelperOptions<X, Y> & QueryableWithThis<X>): WithQueryHelper<X, Y>;
277
288
  //#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 };
289
+ export { AND, DELETE_ALL_WITHOUT_FORCE_ERROR, FieldValues, LIMIT, OFFSET, OR, QueryConfig, QueryFragment, QueryFragments, QueryHelper, QueryHelperBeginOption, 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{#e;#t;#n;constructor(e,t={},n=!1){this.#e=e,this.#t={...t},this.#n=n,!this.#t.connect&&!this.#t.release&&`connect`in this.#e&&typeof this.#e.connect==`function`&&`totalCount`in this.#e&&`idleCount`in this.#e&&(this.#t.connect=()=>this.#e.connect(),this.#t.release=e=>e.release())}#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??[]}}async#i(e){let t=this.#t.query??(`query`in this.#e&&typeof this.#e.query==`function`&&this.#e.query);if(!t)throw Error(`Query function is not configured on the object.`);return await 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#o(t){if(this.#n)return this;let n=new e(await this.#t.connect?.(this.#e)??this.#e,this.#t,!0);return t.role&&await n.#i(this.#r([C`SET ROLE ${w(t.role)}`])),t.transaction!==!1&&await n.#i({text:`BEGIN`,values:[]}),n}async#s(e,t,n=!0){if(!this.#n)try{t.transaction!==!1&&await e.#i({text:n?`COMMIT`:`ROLLBACK`,values:[]}),t.role&&await e.#i({text:`SET ROLE NONE`,values:[]})}finally{await this.#t.release?.(e.#e)}}async#c(e,t){return this.#s(e,t,!1)}async begin(e,t){typeof e==`function`&&(t=e,e={});let n=await this.#o(e),r;try{r=await t(n.wrap())}catch(t){throw await this.#c(n,e),t}return await this.#s(n,e),r}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.`)}}wrap(){let e=new Proxy(this.#e,{get:(t,n,r)=>{let i=n in this?this:n in t?t:void 0,a=i&&Reflect.get(i,n);return a&&a instanceof Function?function(...n){let o=this===r||this===e||this==null?i:this,s=a.apply(o,n);return s===t?e:s}:a===t?e:a}});return e}};function $(e,t){return new Q(e,t).wrap()}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.6",
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.6",
4
4
  "description": "SQL query builder using template string literal",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -20,8 +20,10 @@
20
20
  "test:watch": "vitest",
21
21
  "build": "tsdown",
22
22
  "prepack": "pnpm run build && pnpm run test",
23
- "format": "prettier",
24
- "lint": "eslint --fix",
23
+ "lint": "oxlint",
24
+ "lint:fix": "oxlint --fix",
25
+ "format": "oxfmt .",
26
+ "format:check": "oxfmt --check .",
25
27
  "type:check": "tsc --noEmit",
26
28
  "prepare": "husky"
27
29
  },
@@ -32,27 +34,23 @@
32
34
  },
33
35
  "license": "MIT",
34
36
  "devDependencies": {
35
- "@eslint/compat": "^2.0.2",
36
- "@eslint/js": "^10.0.1",
37
- "@kikuchan/string-reader": "0.1.0-alpha.7",
38
- "@types/node": "^25.3.3",
37
+ "@kikuchan/string-reader": "0.1.0-alpha.8",
38
+ "@types/node": "^25.5.0",
39
39
  "@types/pg": "^8.18.0",
40
- "esbuild": "^0.27.3",
41
- "eslint": "^10.0.2",
42
- "eslint-config-prettier": "^10.1.8",
40
+ "esbuild": "^0.27.4",
43
41
  "eslint-plugin-prettier": "^5.5.5",
44
42
  "husky": "^9.1.7",
45
- "lint-staged": "^16.3.1",
46
- "pg": "^8.19.0",
47
- "prettier": "^3.8.1",
43
+ "lint-staged": "^16.4.0",
44
+ "oxfmt": "^0.40.0",
45
+ "oxlint": "^1.55.0",
46
+ "pg": "^8.20.0",
48
47
  "prettier-plugin-organize-imports": "^4.3.0",
49
48
  "rimraf": "^6.1.3",
50
- "tsdown": "0.21.0-beta.2",
49
+ "tsdown": "0.21.2",
51
50
  "typescript": "^5.9.3",
52
- "typescript-eslint": "^8.56.1",
53
- "vitest": "^4.0.18"
51
+ "vitest": "^4.1.0"
54
52
  },
55
- "packageManager": "pnpm@10.30.3",
53
+ "packageManager": "pnpm@10.32.1",
56
54
  "pnpm": {
57
55
  "onlyBuiltDependencies": [
58
56
  "@biomejs/biome",