workers-qb 1.0.2 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -23,6 +23,7 @@ Currently, 2 databases are supported:
23
23
  - [x] Create/drop tables
24
24
  - [x] [Insert/Bulk Inserts/Update/Select/Delete/Join queries](https://workers-qb.massadas.com/basic-queries/)
25
25
  - [x] [On Conflict for Inserts and Updates](https://workers-qb.massadas.com/advanced-queries/onConflict/)
26
+ - [x] [Upsert](https://workers-qb.massadas.com/advanced-queries/upsert/)
26
27
  - [x] [Support for Cloudflare Workers D1](https://workers-qb.massadas.com/databases/cloudflare-d1/)
27
28
  - [x] [Support for Cloudflare Workers PostgreSQL (using node-postgres)](https://workers-qb.massadas.com/databases/postgresql/)
28
29
  - [ ] Named parameters (waiting for full support in D1)
@@ -1,4 +1,4 @@
1
- import { Delete, Insert, Join, SelectAll, SelectOne, Update } from './interfaces';
1
+ import { ConflictUpsert, Delete, Insert, Join, SelectAll, SelectOne, Update } from './interfaces';
2
2
  import { ConflictTypes, OrderTypes } from './enums';
3
3
  import { Query, Raw } from './tools';
4
4
  export declare class QueryBuilder<GenericResult, GenericResultOne> {
@@ -21,7 +21,7 @@ export declare class QueryBuilder<GenericResult, GenericResultOne> {
21
21
  update(params: Update): Query;
22
22
  delete(params: Delete): Query;
23
23
  _parse_arguments(row: Record<string, string | boolean | number | null | Raw>): Array<any>;
24
- _onConflict(resolution?: string | ConflictTypes): string;
24
+ _onConflict(resolution?: string | ConflictTypes | ConflictUpsert): string;
25
25
  _insert(params: Insert): string;
26
26
  _update(params: Update): string;
27
27
  _delete(params: Delete): string;
@@ -23,16 +23,21 @@ export interface SelectOne {
23
23
  export interface SelectAll extends SelectOne {
24
24
  limit?: number;
25
25
  }
26
+ export interface ConflictUpsert {
27
+ column: string | Array<string>;
28
+ data: Record<string, string | boolean | number | null | Raw>;
29
+ where?: Where;
30
+ }
26
31
  export interface Insert {
27
32
  tableName: string;
28
33
  data: Record<string, string | boolean | number | null | Raw> | Array<Record<string, string | boolean | number | null | Raw>>;
29
34
  returning?: string | Array<string>;
30
- onConflict?: string | ConflictTypes;
35
+ onConflict?: string | ConflictTypes | ConflictUpsert;
31
36
  }
32
37
  export interface Update {
33
38
  tableName: string;
34
39
  data: Record<string, string | boolean | number | null | Raw>;
35
- where: Where;
40
+ where?: Where;
36
41
  returning?: string | Array<string>;
37
42
  onConflict?: string | ConflictTypes;
38
43
  }
@@ -1 +1 @@
1
- "use strict";var e,t,r,s;exports.OrderTypes=void 0,(e=exports.OrderTypes||(exports.OrderTypes={})).ASC="ASC",e.DESC="DESC",exports.FetchTypes=void 0,(t=exports.FetchTypes||(exports.FetchTypes={})).ONE="ONE",t.ALL="ALL",exports.ConflictTypes=void 0,(r=exports.ConflictTypes||(exports.ConflictTypes={})).ROLLBACK="ROLLBACK",r.ABORT="ABORT",r.FAIL="FAIL",r.IGNORE="IGNORE",r.REPLACE="REPLACE",exports.JoinTypes=void 0,(s=exports.JoinTypes||(exports.JoinTypes={})).INNER="INNER",s.LEFT="LEFT",s.CROSS="CROSS";class n{isRaw=!0;content;constructor(e){this.content=e}}class o{executeMethod;query;arguments;fetchType;constructor(e,t,r,s){this.executeMethod=e,this.query=t,this.arguments=r,this.fetchType=s}async execute(){return this.executeMethod(this)}}class a{_debugger=!1;setDebugger(e){this._debugger=e}async execute(e){throw new Error("Execute method not implemented")}async batchExecute(e){throw new Error("Batch execute method not implemented")}createTable(e){return new o((e=>this.execute(e)),`CREATE TABLE ${e.ifNotExists?"IF NOT EXISTS":""} ${e.tableName}\n (\n ${e.schema}\n )`)}dropTable(e){return new o((e=>this.execute(e)),`DROP TABLE ${e.ifExists?"IF EXISTS":""} ${e.tableName}`)}fetchOne(e){return new o((e=>this.execute(e)),this._select({...e,limit:1}),e.where?e.where.params:void 0,exports.FetchTypes.ONE)}fetchAll(e){return new o((e=>this.execute(e)),this._select(e),e.where?e.where.params:void 0,exports.FetchTypes.ALL)}insert(e){let t=[];if(Array.isArray(e.data))for(const r of e.data)t=t.concat(this._parse_arguments(r));else t=t.concat(this._parse_arguments(e.data));const r=Array.isArray(e.data)?exports.FetchTypes.ALL:exports.FetchTypes.ONE;return new o((e=>this.execute(e)),this._insert(e),t,r)}update(e){let t=this._parse_arguments(e.data);return e.where&&e.where.params&&(t=e.where.params.concat(t)),new o((e=>this.execute(e)),this._update(e),t,exports.FetchTypes.ALL)}delete(e){return new o((e=>this.execute(e)),this._delete(e),e.where?e.where.params:void 0,exports.FetchTypes.ALL)}_parse_arguments(e){return Object.values(e).filter((e=>!(e instanceof n)))}_onConflict(e){return e?`OR ${e} `:""}_insert(e){const t=[];Array.isArray(e.data)||(e.data=[e.data]);const r=Object.keys(e.data[0]).join(", ");let s=1;for(const r of e.data){const e=[];Object.values(r).forEach((t=>{t instanceof n?e.push(t.content):(e.push(`?${s}`),s+=1)})),t.push(`(${e.join(", ")})`)}return`INSERT ${this._onConflict(e.onConflict)}INTO ${e.tableName} (${r}) VALUES ${t.join(", ")}`+this._returning(e.returning)}_update(e){const t=e.where&&e.where.params?Object.keys(e.where.params).length:0,r=[];let s=1;for(const[o,a]of Object.entries(e.data))a instanceof n?r.push(`${o} = ${a.content}`):(r.push(`${o} = ?${t+s}`),s+=1);return`UPDATE ${this._onConflict(e.onConflict)}${e.tableName} SET ${r.join(", ")}`+this._where(e.where?.conditions)+this._returning(e.returning)}_delete(e){return`DELETE FROM ${e.tableName}`+this._where(e.where?.conditions)+this._returning(e.returning)}_select(e){return`SELECT ${this._fields(e.fields)} FROM ${e.tableName}`+this._join(e.join)+this._where(e.where?.conditions)+this._groupBy(e.groupBy)+this._having(e.having)+this._orderBy(e.orderBy)+this._limit(e.limit)+this._offset(e.offset)}_fields(e){return"string"==typeof e?e:e.join(", ")}_where(e){return e?"string"==typeof e?` WHERE ${e}`:` WHERE ${e.join(" AND ")}`:""}_join(e){if(!e)return"";Array.isArray(e)||(e=[e]);const t=[];return e.forEach((e=>{const r=e.type?`${e.type} `:"";t.push(`${r}JOIN ${"string"==typeof e.table?e.table:`(${this._select(e.table)})`}${e.alias?` AS ${e.alias}`:""} ON ${e.on}`)}))," "+t.join(" ")}_groupBy(e){return e?"string"==typeof e?` GROUP BY ${e}`:` GROUP BY ${e.join(", ")}`:""}_having(e){return e?` HAVING ${e}`:""}_orderBy(e){if(!e)return"";if("string"==typeof e)return` ORDER BY ${e}`;if(Array.isArray(e))return` ORDER BY ${e.join(", ")}`;const t=[];return Object.entries(e).forEach((([e,r])=>{t.push(`${e} ${r}`)})),` ORDER BY ${t.join(", ")}`}_limit(e){return e?` LIMIT ${e}`:""}_offset(e){return e?` OFFSET ${e}`:""}_returning(e){return e?"string"==typeof e?` RETURNING ${e}`:` RETURNING ${e.join(", ")}`:""}}exports.D1QB=class extends a{db;constructor(e){super(),this.db=e}async execute(e){let t=this.db.prepare(e.query);if(this._debugger&&console.log({"workers-qb":{query:e.query,arguments:e.arguments,fetchType:e.fetchType}}),e.arguments&&(t=t.bind(...e.arguments)),e.fetchType===exports.FetchTypes.ONE||e.fetchType===exports.FetchTypes.ALL){const r=await t.all();return{changes:r.meta?.changes,duration:r.meta?.duration,last_row_id:r.meta?.last_row_id,served_by:r.meta?.served_by,success:r.success,results:e.fetchType===exports.FetchTypes.ONE?r.results[0]:r.results}}return t.run()}async batchExecute(e){this._debugger&&console.log({"workers-qb":e});const t=e.map((e=>{let t=this.db.prepare(e.query);return e.arguments&&(t=t.bind(...e.arguments)),t}));return(await this.db.batch(t)).map(((t,r)=>e[r]?{changes:t.meta?.changes,duration:t.meta?.duration,last_row_id:t.meta?.last_row_id,served_by:t.meta?.served_by,success:t.success,results:e[r].fetchType===exports.FetchTypes.ONE?t.results?.[0]:t.results}:{changes:t.meta?.changes,duration:t.meta?.duration,last_row_id:t.meta?.last_row_id,served_by:t.meta?.served_by,success:t.success}))}},exports.PGQB=class extends a{client;constructor(e){super(),this.client=e}async connect(){await this.client.connect()}async close(){await this.client.end()}async execute(e){const t=e.query.replaceAll("?","$");let r;return this._debugger&&console.log({"workers-qb":e}),r=e.arguments?await this.client.query({values:e.arguments,text:t}):await this.client.query({text:t}),e.fetchType===exports.FetchTypes.ONE||e.fetchType===exports.FetchTypes.ALL?{command:r.command,lastRowId:r.oid,rowCount:r.rowCount,results:e.fetchType===exports.FetchTypes.ONE?r.rows[0]:r.rows}:{command:r.command,lastRowId:r.oid,rowCount:r.rowCount}}},exports.Query=o,exports.QueryBuilder=a,exports.Raw=n;
1
+ "use strict";var e,t,r,s;exports.OrderTypes=void 0,(e=exports.OrderTypes||(exports.OrderTypes={})).ASC="ASC",e.DESC="DESC",exports.FetchTypes=void 0,(t=exports.FetchTypes||(exports.FetchTypes={})).ONE="ONE",t.ALL="ALL",exports.ConflictTypes=void 0,(r=exports.ConflictTypes||(exports.ConflictTypes={})).ROLLBACK="ROLLBACK",r.ABORT="ABORT",r.FAIL="FAIL",r.IGNORE="IGNORE",r.REPLACE="REPLACE",exports.JoinTypes=void 0,(s=exports.JoinTypes||(exports.JoinTypes={})).INNER="INNER",s.LEFT="LEFT",s.CROSS="CROSS";class n{isRaw=!0;content;constructor(e){this.content=e}}class o{executeMethod;query;arguments;fetchType;constructor(e,t,r,s){this.executeMethod=e,this.query=t,this.arguments=r,this.fetchType=s}async execute(){return this.executeMethod(this)}}class a{_debugger=!1;setDebugger(e){this._debugger=e}async execute(e){throw new Error("Execute method not implemented")}async batchExecute(e){throw new Error("Batch execute method not implemented")}createTable(e){return new o((e=>this.execute(e)),`CREATE TABLE ${e.ifNotExists?"IF NOT EXISTS":""} ${e.tableName}\n (\n ${e.schema}\n )`)}dropTable(e){return new o((e=>this.execute(e)),`DROP TABLE ${e.ifExists?"IF EXISTS":""} ${e.tableName}`)}fetchOne(e){return new o((e=>this.execute(e)),this._select({...e,limit:1}),e.where?e.where.params:void 0,exports.FetchTypes.ONE)}fetchAll(e){return new o((e=>this.execute(e)),this._select(e),e.where?e.where.params:void 0,exports.FetchTypes.ALL)}insert(e){let t=[];if("object"==typeof e.onConflict&&(e.onConflict.where?.params&&(t=t.concat(e.onConflict.where.params)),e.onConflict.data&&(t=t.concat(this._parse_arguments(e.onConflict.data)))),Array.isArray(e.data))for(const r of e.data)t=t.concat(this._parse_arguments(r));else t=t.concat(this._parse_arguments(e.data));const r=Array.isArray(e.data)?exports.FetchTypes.ALL:exports.FetchTypes.ONE;return new o((e=>this.execute(e)),this._insert(e),t,r)}update(e){let t=this._parse_arguments(e.data);return e.where&&e.where.params&&(t=e.where.params.concat(t)),new o((e=>this.execute(e)),this._update(e),t,exports.FetchTypes.ALL)}delete(e){return new o((e=>this.execute(e)),this._delete(e),e.where?e.where.params:void 0,exports.FetchTypes.ALL)}_parse_arguments(e){return Object.values(e).filter((e=>!(e instanceof n)))}_onConflict(e){if(e){if("object"==typeof e){Array.isArray(e.column)||(e.column=[e.column]);const t=this.update({tableName:"_REPLACE_",data:e.data,where:e.where}).query.replace(" _REPLACE_","");return` ON CONFLICT (${e.column.join(", ")}) DO ${t}`}return`OR ${e} `}return""}_insert(e){const t=[];Array.isArray(e.data)||(e.data=[e.data]);const r=Object.keys(e.data[0]).join(", ");let s=1,o="",a="";e.onConflict&&"object"==typeof e.onConflict?(a=this._onConflict(e.onConflict),e.onConflict.where?.params&&(s+=e.onConflict.where?.params.length),e.onConflict.data&&(s+=this._parse_arguments(e.onConflict.data).length)):o=this._onConflict(e.onConflict);for(const r of e.data){const e=[];Object.values(r).forEach((t=>{t instanceof n?e.push(t.content):(e.push(`?${s}`),s+=1)})),t.push(`(${e.join(", ")})`)}return`INSERT ${o}INTO ${e.tableName} (${r}) VALUES ${t.join(", ")}`+a+this._returning(e.returning)}_update(e){const t=e.where&&e.where.params?Object.keys(e.where.params).length:0,r=[];let s=1;for(const[o,a]of Object.entries(e.data))a instanceof n?r.push(`${o} = ${a.content}`):(r.push(`${o} = ?${t+s}`),s+=1);return`UPDATE ${this._onConflict(e.onConflict)}${e.tableName} SET ${r.join(", ")}`+this._where(e.where?.conditions)+this._returning(e.returning)}_delete(e){return`DELETE FROM ${e.tableName}`+this._where(e.where?.conditions)+this._returning(e.returning)}_select(e){return`SELECT ${this._fields(e.fields)} FROM ${e.tableName}`+this._join(e.join)+this._where(e.where?.conditions)+this._groupBy(e.groupBy)+this._having(e.having)+this._orderBy(e.orderBy)+this._limit(e.limit)+this._offset(e.offset)}_fields(e){return"string"==typeof e?e:e.join(", ")}_where(e){return e?"string"==typeof e?` WHERE ${e}`:` WHERE ${e.join(" AND ")}`:""}_join(e){if(!e)return"";Array.isArray(e)||(e=[e]);const t=[];return e.forEach((e=>{const r=e.type?`${e.type} `:"";t.push(`${r}JOIN ${"string"==typeof e.table?e.table:`(${this._select(e.table)})`}${e.alias?` AS ${e.alias}`:""} ON ${e.on}`)}))," "+t.join(" ")}_groupBy(e){return e?"string"==typeof e?` GROUP BY ${e}`:` GROUP BY ${e.join(", ")}`:""}_having(e){return e?` HAVING ${e}`:""}_orderBy(e){if(!e)return"";if("string"==typeof e)return` ORDER BY ${e}`;if(Array.isArray(e))return` ORDER BY ${e.join(", ")}`;const t=[];return Object.entries(e).forEach((([e,r])=>{t.push(`${e} ${r}`)})),` ORDER BY ${t.join(", ")}`}_limit(e){return e?` LIMIT ${e}`:""}_offset(e){return e?` OFFSET ${e}`:""}_returning(e){return e?"string"==typeof e?` RETURNING ${e}`:` RETURNING ${e.join(", ")}`:""}}exports.D1QB=class extends a{db;constructor(e){super(),this.db=e}async execute(e){let t=this.db.prepare(e.query);if(this._debugger&&console.log({"workers-qb":{query:e.query,arguments:e.arguments,fetchType:e.fetchType}}),e.arguments&&(t=t.bind(...e.arguments)),e.fetchType===exports.FetchTypes.ONE||e.fetchType===exports.FetchTypes.ALL){const r=await t.all();return{changes:r.meta?.changes,duration:r.meta?.duration,last_row_id:r.meta?.last_row_id,served_by:r.meta?.served_by,success:r.success,results:e.fetchType===exports.FetchTypes.ONE?r.results[0]:r.results}}return t.run()}async batchExecute(e){this._debugger&&console.log({"workers-qb":e});const t=e.map((e=>{let t=this.db.prepare(e.query);return e.arguments&&(t=t.bind(...e.arguments)),t}));return(await this.db.batch(t)).map(((t,r)=>e[r]?{changes:t.meta?.changes,duration:t.meta?.duration,last_row_id:t.meta?.last_row_id,served_by:t.meta?.served_by,success:t.success,results:e[r].fetchType===exports.FetchTypes.ONE?t.results?.[0]:t.results}:{changes:t.meta?.changes,duration:t.meta?.duration,last_row_id:t.meta?.last_row_id,served_by:t.meta?.served_by,success:t.success}))}},exports.PGQB=class extends a{client;constructor(e){super(),this.client=e}async connect(){await this.client.connect()}async close(){await this.client.end()}async execute(e){const t=e.query.replaceAll("?","$");let r;return this._debugger&&console.log({"workers-qb":e}),r=e.arguments?await this.client.query({values:e.arguments,text:t}):await this.client.query({text:t}),e.fetchType===exports.FetchTypes.ONE||e.fetchType===exports.FetchTypes.ALL?{command:r.command,lastRowId:r.oid,rowCount:r.rowCount,results:e.fetchType===exports.FetchTypes.ONE?r.rows[0]:r.rows}:{command:r.command,lastRowId:r.oid,rowCount:r.rowCount}}},exports.Query=o,exports.QueryBuilder=a,exports.Raw=n;
@@ -1 +1 @@
1
- var e,t,r,s;!function(e){e.ASC="ASC",e.DESC="DESC"}(e||(e={})),function(e){e.ONE="ONE",e.ALL="ALL"}(t||(t={})),function(e){e.ROLLBACK="ROLLBACK",e.ABORT="ABORT",e.FAIL="FAIL",e.IGNORE="IGNORE",e.REPLACE="REPLACE"}(r||(r={})),function(e){e.INNER="INNER",e.LEFT="LEFT",e.CROSS="CROSS"}(s||(s={}));class n{isRaw=!0;content;constructor(e){this.content=e}}class a{executeMethod;query;arguments;fetchType;constructor(e,t,r,s){this.executeMethod=e,this.query=t,this.arguments=r,this.fetchType=s}async execute(){return this.executeMethod(this)}}class i{_debugger=!1;setDebugger(e){this._debugger=e}async execute(e){throw new Error("Execute method not implemented")}async batchExecute(e){throw new Error("Batch execute method not implemented")}createTable(e){return new a((e=>this.execute(e)),`CREATE TABLE ${e.ifNotExists?"IF NOT EXISTS":""} ${e.tableName}\n (\n ${e.schema}\n )`)}dropTable(e){return new a((e=>this.execute(e)),`DROP TABLE ${e.ifExists?"IF EXISTS":""} ${e.tableName}`)}fetchOne(e){return new a((e=>this.execute(e)),this._select({...e,limit:1}),e.where?e.where.params:void 0,t.ONE)}fetchAll(e){return new a((e=>this.execute(e)),this._select(e),e.where?e.where.params:void 0,t.ALL)}insert(e){let r=[];if(Array.isArray(e.data))for(const t of e.data)r=r.concat(this._parse_arguments(t));else r=r.concat(this._parse_arguments(e.data));const s=Array.isArray(e.data)?t.ALL:t.ONE;return new a((e=>this.execute(e)),this._insert(e),r,s)}update(e){let r=this._parse_arguments(e.data);return e.where&&e.where.params&&(r=e.where.params.concat(r)),new a((e=>this.execute(e)),this._update(e),r,t.ALL)}delete(e){return new a((e=>this.execute(e)),this._delete(e),e.where?e.where.params:void 0,t.ALL)}_parse_arguments(e){return Object.values(e).filter((e=>!(e instanceof n)))}_onConflict(e){return e?`OR ${e} `:""}_insert(e){const t=[];Array.isArray(e.data)||(e.data=[e.data]);const r=Object.keys(e.data[0]).join(", ");let s=1;for(const r of e.data){const e=[];Object.values(r).forEach((t=>{t instanceof n?e.push(t.content):(e.push(`?${s}`),s+=1)})),t.push(`(${e.join(", ")})`)}return`INSERT ${this._onConflict(e.onConflict)}INTO ${e.tableName} (${r}) VALUES ${t.join(", ")}`+this._returning(e.returning)}_update(e){const t=e.where&&e.where.params?Object.keys(e.where.params).length:0,r=[];let s=1;for(const[a,i]of Object.entries(e.data))i instanceof n?r.push(`${a} = ${i.content}`):(r.push(`${a} = ?${t+s}`),s+=1);return`UPDATE ${this._onConflict(e.onConflict)}${e.tableName} SET ${r.join(", ")}`+this._where(e.where?.conditions)+this._returning(e.returning)}_delete(e){return`DELETE FROM ${e.tableName}`+this._where(e.where?.conditions)+this._returning(e.returning)}_select(e){return`SELECT ${this._fields(e.fields)} FROM ${e.tableName}`+this._join(e.join)+this._where(e.where?.conditions)+this._groupBy(e.groupBy)+this._having(e.having)+this._orderBy(e.orderBy)+this._limit(e.limit)+this._offset(e.offset)}_fields(e){return"string"==typeof e?e:e.join(", ")}_where(e){return e?"string"==typeof e?` WHERE ${e}`:` WHERE ${e.join(" AND ")}`:""}_join(e){if(!e)return"";Array.isArray(e)||(e=[e]);const t=[];return e.forEach((e=>{const r=e.type?`${e.type} `:"";t.push(`${r}JOIN ${"string"==typeof e.table?e.table:`(${this._select(e.table)})`}${e.alias?` AS ${e.alias}`:""} ON ${e.on}`)}))," "+t.join(" ")}_groupBy(e){return e?"string"==typeof e?` GROUP BY ${e}`:` GROUP BY ${e.join(", ")}`:""}_having(e){return e?` HAVING ${e}`:""}_orderBy(e){if(!e)return"";if("string"==typeof e)return` ORDER BY ${e}`;if(Array.isArray(e))return` ORDER BY ${e.join(", ")}`;const t=[];return Object.entries(e).forEach((([e,r])=>{t.push(`${e} ${r}`)})),` ORDER BY ${t.join(", ")}`}_limit(e){return e?` LIMIT ${e}`:""}_offset(e){return e?` OFFSET ${e}`:""}_returning(e){return e?"string"==typeof e?` RETURNING ${e}`:` RETURNING ${e.join(", ")}`:""}}class o extends i{db;constructor(e){super(),this.db=e}async execute(e){let r=this.db.prepare(e.query);if(this._debugger&&console.log({"workers-qb":{query:e.query,arguments:e.arguments,fetchType:e.fetchType}}),e.arguments&&(r=r.bind(...e.arguments)),e.fetchType===t.ONE||e.fetchType===t.ALL){const s=await r.all();return{changes:s.meta?.changes,duration:s.meta?.duration,last_row_id:s.meta?.last_row_id,served_by:s.meta?.served_by,success:s.success,results:e.fetchType===t.ONE?s.results[0]:s.results}}return r.run()}async batchExecute(e){this._debugger&&console.log({"workers-qb":e});const r=e.map((e=>{let t=this.db.prepare(e.query);return e.arguments&&(t=t.bind(...e.arguments)),t}));return(await this.db.batch(r)).map(((r,s)=>e[s]?{changes:r.meta?.changes,duration:r.meta?.duration,last_row_id:r.meta?.last_row_id,served_by:r.meta?.served_by,success:r.success,results:e[s].fetchType===t.ONE?r.results?.[0]:r.results}:{changes:r.meta?.changes,duration:r.meta?.duration,last_row_id:r.meta?.last_row_id,served_by:r.meta?.served_by,success:r.success}))}}class c extends i{client;constructor(e){super(),this.client=e}async connect(){await this.client.connect()}async close(){await this.client.end()}async execute(e){const r=e.query.replaceAll("?","$");let s;return this._debugger&&console.log({"workers-qb":e}),s=e.arguments?await this.client.query({values:e.arguments,text:r}):await this.client.query({text:r}),e.fetchType===t.ONE||e.fetchType===t.ALL?{command:s.command,lastRowId:s.oid,rowCount:s.rowCount,results:e.fetchType===t.ONE?s.rows[0]:s.rows}:{command:s.command,lastRowId:s.oid,rowCount:s.rowCount}}}export{r as ConflictTypes,o as D1QB,t as FetchTypes,s as JoinTypes,e as OrderTypes,c as PGQB,a as Query,i as QueryBuilder,n as Raw};
1
+ var e,t,r,n;!function(e){e.ASC="ASC",e.DESC="DESC"}(e||(e={})),function(e){e.ONE="ONE",e.ALL="ALL"}(t||(t={})),function(e){e.ROLLBACK="ROLLBACK",e.ABORT="ABORT",e.FAIL="FAIL",e.IGNORE="IGNORE",e.REPLACE="REPLACE"}(r||(r={})),function(e){e.INNER="INNER",e.LEFT="LEFT",e.CROSS="CROSS"}(n||(n={}));class s{isRaw=!0;content;constructor(e){this.content=e}}class a{executeMethod;query;arguments;fetchType;constructor(e,t,r,n){this.executeMethod=e,this.query=t,this.arguments=r,this.fetchType=n}async execute(){return this.executeMethod(this)}}class o{_debugger=!1;setDebugger(e){this._debugger=e}async execute(e){throw new Error("Execute method not implemented")}async batchExecute(e){throw new Error("Batch execute method not implemented")}createTable(e){return new a((e=>this.execute(e)),`CREATE TABLE ${e.ifNotExists?"IF NOT EXISTS":""} ${e.tableName}\n (\n ${e.schema}\n )`)}dropTable(e){return new a((e=>this.execute(e)),`DROP TABLE ${e.ifExists?"IF EXISTS":""} ${e.tableName}`)}fetchOne(e){return new a((e=>this.execute(e)),this._select({...e,limit:1}),e.where?e.where.params:void 0,t.ONE)}fetchAll(e){return new a((e=>this.execute(e)),this._select(e),e.where?e.where.params:void 0,t.ALL)}insert(e){let r=[];if("object"==typeof e.onConflict&&(e.onConflict.where?.params&&(r=r.concat(e.onConflict.where.params)),e.onConflict.data&&(r=r.concat(this._parse_arguments(e.onConflict.data)))),Array.isArray(e.data))for(const t of e.data)r=r.concat(this._parse_arguments(t));else r=r.concat(this._parse_arguments(e.data));const n=Array.isArray(e.data)?t.ALL:t.ONE;return new a((e=>this.execute(e)),this._insert(e),r,n)}update(e){let r=this._parse_arguments(e.data);return e.where&&e.where.params&&(r=e.where.params.concat(r)),new a((e=>this.execute(e)),this._update(e),r,t.ALL)}delete(e){return new a((e=>this.execute(e)),this._delete(e),e.where?e.where.params:void 0,t.ALL)}_parse_arguments(e){return Object.values(e).filter((e=>!(e instanceof s)))}_onConflict(e){if(e){if("object"==typeof e){Array.isArray(e.column)||(e.column=[e.column]);const t=this.update({tableName:"_REPLACE_",data:e.data,where:e.where}).query.replace(" _REPLACE_","");return` ON CONFLICT (${e.column.join(", ")}) DO ${t}`}return`OR ${e} `}return""}_insert(e){const t=[];Array.isArray(e.data)||(e.data=[e.data]);const r=Object.keys(e.data[0]).join(", ");let n=1,a="",o="";e.onConflict&&"object"==typeof e.onConflict?(o=this._onConflict(e.onConflict),e.onConflict.where?.params&&(n+=e.onConflict.where?.params.length),e.onConflict.data&&(n+=this._parse_arguments(e.onConflict.data).length)):a=this._onConflict(e.onConflict);for(const r of e.data){const e=[];Object.values(r).forEach((t=>{t instanceof s?e.push(t.content):(e.push(`?${n}`),n+=1)})),t.push(`(${e.join(", ")})`)}return`INSERT ${a}INTO ${e.tableName} (${r}) VALUES ${t.join(", ")}`+o+this._returning(e.returning)}_update(e){const t=e.where&&e.where.params?Object.keys(e.where.params).length:0,r=[];let n=1;for(const[a,o]of Object.entries(e.data))o instanceof s?r.push(`${a} = ${o.content}`):(r.push(`${a} = ?${t+n}`),n+=1);return`UPDATE ${this._onConflict(e.onConflict)}${e.tableName} SET ${r.join(", ")}`+this._where(e.where?.conditions)+this._returning(e.returning)}_delete(e){return`DELETE FROM ${e.tableName}`+this._where(e.where?.conditions)+this._returning(e.returning)}_select(e){return`SELECT ${this._fields(e.fields)} FROM ${e.tableName}`+this._join(e.join)+this._where(e.where?.conditions)+this._groupBy(e.groupBy)+this._having(e.having)+this._orderBy(e.orderBy)+this._limit(e.limit)+this._offset(e.offset)}_fields(e){return"string"==typeof e?e:e.join(", ")}_where(e){return e?"string"==typeof e?` WHERE ${e}`:` WHERE ${e.join(" AND ")}`:""}_join(e){if(!e)return"";Array.isArray(e)||(e=[e]);const t=[];return e.forEach((e=>{const r=e.type?`${e.type} `:"";t.push(`${r}JOIN ${"string"==typeof e.table?e.table:`(${this._select(e.table)})`}${e.alias?` AS ${e.alias}`:""} ON ${e.on}`)}))," "+t.join(" ")}_groupBy(e){return e?"string"==typeof e?` GROUP BY ${e}`:` GROUP BY ${e.join(", ")}`:""}_having(e){return e?` HAVING ${e}`:""}_orderBy(e){if(!e)return"";if("string"==typeof e)return` ORDER BY ${e}`;if(Array.isArray(e))return` ORDER BY ${e.join(", ")}`;const t=[];return Object.entries(e).forEach((([e,r])=>{t.push(`${e} ${r}`)})),` ORDER BY ${t.join(", ")}`}_limit(e){return e?` LIMIT ${e}`:""}_offset(e){return e?` OFFSET ${e}`:""}_returning(e){return e?"string"==typeof e?` RETURNING ${e}`:` RETURNING ${e.join(", ")}`:""}}class i extends o{db;constructor(e){super(),this.db=e}async execute(e){let r=this.db.prepare(e.query);if(this._debugger&&console.log({"workers-qb":{query:e.query,arguments:e.arguments,fetchType:e.fetchType}}),e.arguments&&(r=r.bind(...e.arguments)),e.fetchType===t.ONE||e.fetchType===t.ALL){const n=await r.all();return{changes:n.meta?.changes,duration:n.meta?.duration,last_row_id:n.meta?.last_row_id,served_by:n.meta?.served_by,success:n.success,results:e.fetchType===t.ONE?n.results[0]:n.results}}return r.run()}async batchExecute(e){this._debugger&&console.log({"workers-qb":e});const r=e.map((e=>{let t=this.db.prepare(e.query);return e.arguments&&(t=t.bind(...e.arguments)),t}));return(await this.db.batch(r)).map(((r,n)=>e[n]?{changes:r.meta?.changes,duration:r.meta?.duration,last_row_id:r.meta?.last_row_id,served_by:r.meta?.served_by,success:r.success,results:e[n].fetchType===t.ONE?r.results?.[0]:r.results}:{changes:r.meta?.changes,duration:r.meta?.duration,last_row_id:r.meta?.last_row_id,served_by:r.meta?.served_by,success:r.success}))}}class c extends o{client;constructor(e){super(),this.client=e}async connect(){await this.client.connect()}async close(){await this.client.end()}async execute(e){const r=e.query.replaceAll("?","$");let n;return this._debugger&&console.log({"workers-qb":e}),n=e.arguments?await this.client.query({values:e.arguments,text:r}):await this.client.query({text:r}),e.fetchType===t.ONE||e.fetchType===t.ALL?{command:n.command,lastRowId:n.oid,rowCount:n.rowCount,results:e.fetchType===t.ONE?n.rows[0]:n.rows}:{command:n.command,lastRowId:n.oid,rowCount:n.rowCount}}}export{r as ConflictTypes,i as D1QB,t as FetchTypes,n as JoinTypes,e as OrderTypes,c as PGQB,a as Query,o as QueryBuilder,s as Raw};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "workers-qb",
3
- "version": "1.0.2",
3
+ "version": "1.1.0",
4
4
  "description": "Zero dependencies Query Builder for Cloudflare Workers",
5
5
  "main": "./dist/workers-qb.js",
6
6
  "types": "./dist/src/workers-qb.d.ts",