workers-qb 1.2.0 → 1.2.2

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
@@ -19,8 +19,8 @@ Currently, 2 databases are supported:
19
19
 
20
20
  - [x] Zero dependencies.
21
21
  - [x] Fully typed/TypeScript support
22
- - [x] SQL Type checking with compatible IDE's
23
- - [x] Create/drop tables
22
+ - [x] [Type Checks for data read](https://workers-qb.massadas.com/type-check/)
23
+ - [x] [Create/drop tables](https://workers-qb.massadas.com/basic-queries/#dropping-and-creating-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
26
  - [x] [Upsert](https://workers-qb.massadas.com/advanced-queries/upsert/)
@@ -53,10 +53,10 @@ export default {
53
53
  level: number
54
54
  }
55
55
 
56
+ // Generated query: SELECT * FROM employees WHERE active = ?1
56
57
  const employeeList = await qb
57
- .fetchOne<Employee>({
58
+ .fetchAll<Employee>({
58
59
  tableName: 'employees',
59
- fields: '*',
60
60
  where: {
61
61
  conditions: 'active = ?1',
62
62
  params: [true],
@@ -101,6 +101,7 @@ export default {
101
101
  const qb = new PGQB(new Client(env.DB_URL))
102
102
  await qb.connect()
103
103
 
104
+ // Generated query: SELECT count(*) as count FROM employees WHERE active = ?1 LIMIT 1
104
105
  const fetched = await qb
105
106
  .fetchOne({
106
107
  tableName: 'employees',
package/dist/index.js CHANGED
@@ -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 ( ${e.schema})`)}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)}raw(e){return new o((e=>this.execute(e)),e.query,e.args,e.fetchType)}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}\n SET ${r.join(", ")}`+this._where(e.where?.conditions)+this._returning(e.returning)}_delete(e){return`DELETE\n FROM ${e.tableName}`+this._where(e.where?.conditions)+this._returning(e.returning)}_select(e){return`SELECT ${this._fields(e.fields)}\n 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{db;constructor(e){super(),this.db=e}async connect(){await this.db.connect()}async close(){await this.db.end()}async execute(e){const t=e.query.replaceAll("?","$");let r;return this._debugger&&console.log({"workers-qb":e}),r=e.arguments?await this.db.query({values:e.arguments,text:t}):await this.db.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 ( ${e.schema})`)}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}),"object"==typeof e.where&&!Array.isArray(e.where)&&e.where?.params?e.where?.params:void 0,exports.FetchTypes.ONE)}fetchAll(e){return new o((e=>this.execute(e)),this._select(e),"object"==typeof e.where&&!Array.isArray(e.where)&&e.where?.params?e.where?.params:void 0,exports.FetchTypes.ALL)}raw(e){return new o((e=>this.execute(e)),e.query,e.args,e.fetchType)}insert(e){let t=[];if("object"==typeof e.onConflict&&("object"==typeof e.onConflict?.where&&!Array.isArray(e.onConflict?.where)&&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"object"==typeof e.where&&!Array.isArray(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),"object"==typeof e.where&&!Array.isArray(e.where)&&e.where?.params?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),"object"==typeof e.onConflict?.where&&!Array.isArray(e.onConflict?.where)&&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="object"==typeof e.where&&!Array.isArray(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}\n SET ${r.join(", ")}`+this._where(e.where)+this._returning(e.returning)}_delete(e){return`DELETE\n FROM ${e.tableName}`+this._where(e.where)+this._returning(e.returning)}_select(e){return`SELECT ${this._fields(e.fields)}\n FROM ${e.tableName}`+this._join(e.join)+this._where(e.where)+this._groupBy(e.groupBy)+this._having(e.having)+this._orderBy(e.orderBy)+this._limit(e.limit)+this._offset(e.offset)}_fields(e){return e?"string"==typeof e?e:e.join(", "):"*"}_where(e){if(!e)return"";let t=e;return"object"!=typeof e||Array.isArray(e)||(t=e.conditions),"string"==typeof t?` WHERE ${t.toString()}`:t.length>0?` WHERE ${t.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{db;constructor(e){super(),this.db=e}async connect(){await this.db.connect()}async close(){await this.db.end()}async execute(e){const t=e.query.replaceAll("?","$");let r;return this._debugger&&console.log({"workers-qb":e}),r=e.arguments?await this.db.query({values:e.arguments,text:t}):await this.db.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;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
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 ( ${e.schema})`)}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)}raw(e){return new a((e=>this.execute(e)),e.query,e.args,e.fetchType)}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}\n SET ${r.join(", ")}`+this._where(e.where?.conditions)+this._returning(e.returning)}_delete(e){return`DELETE\n FROM ${e.tableName}`+this._where(e.where?.conditions)+this._returning(e.returning)}_select(e){return`SELECT ${this._fields(e.fields)}\n 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{db;constructor(e){super(),this.db=e}async connect(){await this.db.connect()}async close(){await this.db.end()}async execute(e){const r=e.query.replaceAll("?","$");let n;return this._debugger&&console.log({"workers-qb":e}),n=e.arguments?await this.db.query({values:e.arguments,text:r}):await this.db.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};
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 ( ${e.schema})`)}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}),"object"==typeof e.where&&!Array.isArray(e.where)&&e.where?.params?e.where?.params:void 0,t.ONE)}fetchAll(e){return new a((e=>this.execute(e)),this._select(e),"object"==typeof e.where&&!Array.isArray(e.where)&&e.where?.params?e.where?.params:void 0,t.ALL)}raw(e){return new a((e=>this.execute(e)),e.query,e.args,e.fetchType)}insert(e){let r=[];if("object"==typeof e.onConflict&&("object"==typeof e.onConflict?.where&&!Array.isArray(e.onConflict?.where)&&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"object"==typeof e.where&&!Array.isArray(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),"object"==typeof e.where&&!Array.isArray(e.where)&&e.where?.params?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),"object"==typeof e.onConflict?.where&&!Array.isArray(e.onConflict?.where)&&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="object"==typeof e.where&&!Array.isArray(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}\n SET ${r.join(", ")}`+this._where(e.where)+this._returning(e.returning)}_delete(e){return`DELETE\n FROM ${e.tableName}`+this._where(e.where)+this._returning(e.returning)}_select(e){return`SELECT ${this._fields(e.fields)}\n FROM ${e.tableName}`+this._join(e.join)+this._where(e.where)+this._groupBy(e.groupBy)+this._having(e.having)+this._orderBy(e.orderBy)+this._limit(e.limit)+this._offset(e.offset)}_fields(e){return e?"string"==typeof e?e:e.join(", "):"*"}_where(e){if(!e)return"";let t=e;return"object"!=typeof e||Array.isArray(e)||(t=e.conditions),"string"==typeof t?` WHERE ${t.toString()}`:t.length>0?` WHERE ${t.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{db;constructor(e){super(),this.db=e}async connect(){await this.db.connect()}async close(){await this.db.end()}async execute(e){const r=e.query.replaceAll("?","$");let n;return this._debugger&&console.log({"workers-qb":e}),n=e.arguments?await this.db.query({values:e.arguments,text:r}):await this.db.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};
@@ -1,4 +1,4 @@
1
- import { ArrayResult, ConflictUpsert, DefaultObject, Delete, EitherResult, Insert, Join, OneResult, RawQuery, SelectAll, SelectOne, Update } from './interfaces';
1
+ import { ArrayResult, ConflictUpsert, DefaultObject, Delete, EitherResult, Insert, Join, OneResult, RawQuery, SelectAll, SelectOne, Update, Where } from './interfaces';
2
2
  import { ConflictTypes, OrderTypes } from './enums';
3
3
  import { Query, Raw } from './tools';
4
4
  export declare class QueryBuilder<GenericResultWrapper> {
@@ -27,8 +27,8 @@ export declare class QueryBuilder<GenericResultWrapper> {
27
27
  _update(params: Update): string;
28
28
  _delete(params: Delete): string;
29
29
  _select(params: SelectAll): string;
30
- _fields(value: string | Array<string>): string;
31
- _where(value?: string | Array<string>): string;
30
+ _fields(value?: string | Array<string>): string;
31
+ _where(value?: Where): string;
32
32
  _join(value?: Join | Array<Join>): string;
33
33
  _groupBy(value?: string | Array<string>): string;
34
34
  _having(value?: string): string;
@@ -5,7 +5,7 @@ export type DefaultObject = Record<string, Primitive>;
5
5
  export type Where = {
6
6
  conditions: string | Array<string>;
7
7
  params?: (string | boolean | number | null | Raw)[];
8
- };
8
+ } | string | Array<string>;
9
9
  export type Join = {
10
10
  type?: string | JoinTypes;
11
11
  table: string | SelectAll;
@@ -14,7 +14,7 @@ export type Join = {
14
14
  };
15
15
  export type SelectOne = {
16
16
  tableName: string;
17
- fields: string | Array<string>;
17
+ fields?: string | Array<string>;
18
18
  where?: Where;
19
19
  join?: Join | Array<Join>;
20
20
  groupBy?: string | Array<string>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "workers-qb",
3
- "version": "1.2.0",
3
+ "version": "1.2.2",
4
4
  "type": "module",
5
5
  "description": "Zero dependencies Query Builder for Cloudflare Workers",
6
6
  "main": "./dist/index.js",