query-weaver 0.2.0-alpha.5 → 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 +17 -10
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +16 -8
- package/dist/index.d.ts +16 -8
- package/dist/index.js +1 -1
- package/dist/package.json +1 -1
- package/package.json +15 -17
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,10 +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
163
|
|
|
164
164
|
// Empty conditions throw for safety.
|
|
165
|
-
db.update(tableName, { name: 'updated' }, { id: undefined });
|
|
165
|
+
await db.update(tableName, { name: 'updated' }, { id: undefined });
|
|
166
166
|
```
|
|
167
167
|
|
|
168
168
|
### DELETE Builder and Helper
|
|
@@ -171,10 +171,10 @@ db.update(tableName, { name: 'updated' }, { id: undefined });
|
|
|
171
171
|
|
|
172
172
|
```js
|
|
173
173
|
sql.delete(tableName, { ...whereCondition }); // => sql`DELETE FROM ...`
|
|
174
|
-
db.delete(tableName, { ...whereCondition }); // => db.query`DELETE FROM ...`
|
|
174
|
+
await db.delete(tableName, { ...whereCondition }); // => db.query`DELETE FROM ...`
|
|
175
175
|
|
|
176
176
|
// Empty conditions throw for safety.
|
|
177
|
-
db.delete(tableName, { id: undefined });
|
|
177
|
+
await db.delete(tableName, { id: undefined });
|
|
178
178
|
```
|
|
179
179
|
|
|
180
180
|
### Transaction Helper
|
|
@@ -182,14 +182,21 @@ db.delete(tableName, { id: undefined });
|
|
|
182
182
|
`begin` helper
|
|
183
183
|
|
|
184
184
|
```js
|
|
185
|
-
db.begin(() => {
|
|
186
|
-
|
|
187
|
-
|
|
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(...);
|
|
188
195
|
});
|
|
189
196
|
```
|
|
190
197
|
|
|
191
198
|
If an error occurs, the transaction is safely rolled back.
|
|
192
|
-
**NOTE:**
|
|
199
|
+
**NOTE:** `begin` can be nested, but only the outermost transaction is effective.
|
|
193
200
|
|
|
194
201
|
## Low-level APIs
|
|
195
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,`\\\\`)}'`}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=$;
|
|
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
|
@@ -144,18 +144,24 @@ type pgQueryResult<X, T extends QueryResultRow> = (X extends {
|
|
|
144
144
|
} ? pg.QueryResult<T> : QueryResult<T>) & {
|
|
145
145
|
rowCount: number;
|
|
146
146
|
};
|
|
147
|
-
type QueryHelperOptions = {
|
|
147
|
+
type QueryHelperOptions<X extends object, Y extends object> = {
|
|
148
148
|
beforeQuery?: (ctx: Readonly<QueryConfig>) => void;
|
|
149
149
|
afterQuery?: <R extends QueryResultRow>(ctx: Readonly<QueryConfig>, r: QueryResult<R>) => void;
|
|
150
150
|
onError?: (ctx: Readonly<QueryConfig>, e: unknown) => void;
|
|
151
|
+
connect?: (obj: X) => Promise<Y>;
|
|
152
|
+
release?: (conn: Y) => Promise<void> | void;
|
|
151
153
|
};
|
|
152
154
|
type QueryTemplateOrSimpleQuery = QueryTemplateStyle | [query: string, values?: unknown[]] | [query: pg.QueryConfig<unknown[]>];
|
|
155
|
+
type QueryHelperBeginOption = {
|
|
156
|
+
transaction?: boolean;
|
|
157
|
+
role?: string;
|
|
158
|
+
};
|
|
153
159
|
/**
|
|
154
160
|
* Query Helper
|
|
155
161
|
*/
|
|
156
|
-
declare class QueryHelper<X extends object = object> {
|
|
162
|
+
declare class QueryHelper<X extends object = object, Y extends object = object> {
|
|
157
163
|
#private;
|
|
158
|
-
constructor(db: X, opts?: QueryHelperOptions & Partial<Queryable<X
|
|
164
|
+
constructor(db: X, opts?: QueryHelperOptions<X, Y> & Partial<Queryable<X>>, nested?: boolean);
|
|
159
165
|
/**
|
|
160
166
|
* INSERT builder
|
|
161
167
|
*
|
|
@@ -244,7 +250,8 @@ declare class QueryHelper<X extends object = object> {
|
|
|
244
250
|
* return true;
|
|
245
251
|
* });
|
|
246
252
|
*/
|
|
247
|
-
begin<R>(callback: (conn:
|
|
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>;
|
|
248
255
|
/**
|
|
249
256
|
* Prisma adapter: NB; It only supports a query that returns rows
|
|
250
257
|
*/
|
|
@@ -263,11 +270,12 @@ declare class QueryHelper<X extends object = object> {
|
|
|
263
270
|
rows: T[];
|
|
264
271
|
rowCount: number;
|
|
265
272
|
}>;
|
|
273
|
+
wrap(): WithQueryHelper<X, Y>;
|
|
266
274
|
}
|
|
267
275
|
type Overwrite<T, Q> = Omit<T, keyof Q> & Q;
|
|
268
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] };
|
|
269
277
|
type Override<T, Q> = Overwrite<MethodChainRewrite<T, Q>, Q>;
|
|
270
|
-
type WithQueryHelper<
|
|
278
|
+
type WithQueryHelper<X extends object = object, Y extends object = object> = Override<X, QueryHelper<X, Y>>;
|
|
271
279
|
/**
|
|
272
280
|
* Returns a proxy object that overrides the queryable instance `db` by Query Helper utilities
|
|
273
281
|
* @param db - Queryable object to be wrapped
|
|
@@ -275,7 +283,7 @@ type WithQueryHelper<T extends object = object> = Override<T, QueryHelper<T>>;
|
|
|
275
283
|
* @example
|
|
276
284
|
* const db = withQueryHelper(new pg.Client());
|
|
277
285
|
*/
|
|
278
|
-
declare function withQueryHelper<
|
|
279
|
-
declare function withQueryHelper<
|
|
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>;
|
|
280
288
|
//#endregion
|
|
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 };
|
|
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
|
@@ -144,18 +144,24 @@ type pgQueryResult<X, T extends QueryResultRow> = (X extends {
|
|
|
144
144
|
} ? pg.QueryResult<T> : QueryResult<T>) & {
|
|
145
145
|
rowCount: number;
|
|
146
146
|
};
|
|
147
|
-
type QueryHelperOptions = {
|
|
147
|
+
type QueryHelperOptions<X extends object, Y extends object> = {
|
|
148
148
|
beforeQuery?: (ctx: Readonly<QueryConfig>) => void;
|
|
149
149
|
afterQuery?: <R extends QueryResultRow>(ctx: Readonly<QueryConfig>, r: QueryResult<R>) => void;
|
|
150
150
|
onError?: (ctx: Readonly<QueryConfig>, e: unknown) => void;
|
|
151
|
+
connect?: (obj: X) => Promise<Y>;
|
|
152
|
+
release?: (conn: Y) => Promise<void> | void;
|
|
151
153
|
};
|
|
152
154
|
type QueryTemplateOrSimpleQuery = QueryTemplateStyle | [query: string, values?: unknown[]] | [query: pg.QueryConfig<unknown[]>];
|
|
155
|
+
type QueryHelperBeginOption = {
|
|
156
|
+
transaction?: boolean;
|
|
157
|
+
role?: string;
|
|
158
|
+
};
|
|
153
159
|
/**
|
|
154
160
|
* Query Helper
|
|
155
161
|
*/
|
|
156
|
-
declare class QueryHelper<X extends object = object> {
|
|
162
|
+
declare class QueryHelper<X extends object = object, Y extends object = object> {
|
|
157
163
|
#private;
|
|
158
|
-
constructor(db: X, opts?: QueryHelperOptions & Partial<Queryable<X
|
|
164
|
+
constructor(db: X, opts?: QueryHelperOptions<X, Y> & Partial<Queryable<X>>, nested?: boolean);
|
|
159
165
|
/**
|
|
160
166
|
* INSERT builder
|
|
161
167
|
*
|
|
@@ -244,7 +250,8 @@ declare class QueryHelper<X extends object = object> {
|
|
|
244
250
|
* return true;
|
|
245
251
|
* });
|
|
246
252
|
*/
|
|
247
|
-
begin<R>(callback: (conn:
|
|
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>;
|
|
248
255
|
/**
|
|
249
256
|
* Prisma adapter: NB; It only supports a query that returns rows
|
|
250
257
|
*/
|
|
@@ -263,11 +270,12 @@ declare class QueryHelper<X extends object = object> {
|
|
|
263
270
|
rows: T[];
|
|
264
271
|
rowCount: number;
|
|
265
272
|
}>;
|
|
273
|
+
wrap(): WithQueryHelper<X, Y>;
|
|
266
274
|
}
|
|
267
275
|
type Overwrite<T, Q> = Omit<T, keyof Q> & Q;
|
|
268
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] };
|
|
269
277
|
type Override<T, Q> = Overwrite<MethodChainRewrite<T, Q>, Q>;
|
|
270
|
-
type WithQueryHelper<
|
|
278
|
+
type WithQueryHelper<X extends object = object, Y extends object = object> = Override<X, QueryHelper<X, Y>>;
|
|
271
279
|
/**
|
|
272
280
|
* Returns a proxy object that overrides the queryable instance `db` by Query Helper utilities
|
|
273
281
|
* @param db - Queryable object to be wrapped
|
|
@@ -275,7 +283,7 @@ type WithQueryHelper<T extends object = object> = Override<T, QueryHelper<T>>;
|
|
|
275
283
|
* @example
|
|
276
284
|
* const db = withQueryHelper(new pg.Client());
|
|
277
285
|
*/
|
|
278
|
-
declare function withQueryHelper<
|
|
279
|
-
declare function withQueryHelper<
|
|
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>;
|
|
280
288
|
//#endregion
|
|
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 };
|
|
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,`\\\\`)}'`}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};
|
|
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
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "query-weaver",
|
|
3
|
-
"version": "0.2.0-alpha.
|
|
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
|
-
"
|
|
24
|
-
"lint": "
|
|
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
|
-
"@
|
|
36
|
-
"@
|
|
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.
|
|
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.
|
|
46
|
-
"
|
|
47
|
-
"
|
|
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.
|
|
49
|
+
"tsdown": "0.21.2",
|
|
51
50
|
"typescript": "^5.9.3",
|
|
52
|
-
"
|
|
53
|
-
"vitest": "^4.0.18"
|
|
51
|
+
"vitest": "^4.1.0"
|
|
54
52
|
},
|
|
55
|
-
"packageManager": "pnpm@10.
|
|
53
|
+
"packageManager": "pnpm@10.32.1",
|
|
56
54
|
"pnpm": {
|
|
57
55
|
"onlyBuiltDependencies": [
|
|
58
56
|
"@biomejs/biome",
|