workers-qb 1.2.1 → 1.2.3

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,7 +53,7 @@ export default {
53
53
  level: number
54
54
  }
55
55
 
56
- // Generated query: SELECT * FROM employees WHERE active = ?1 LIMIT 1
56
+ // Generated query: SELECT * FROM employees WHERE active = ?1
57
57
  const employeeList = await qb
58
58
  .fetchAll<Employee>({
59
59
  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}),"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()}`:` 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;
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}),"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()}`:` 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
+ 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, Where } from './interfaces';
1
+ import { ArrayResult, ConflictUpsert, DefaultObject, Delete, DeleteReturning, DeleteWithoutReturning, Insert, InsertMultiple, InsertOne, InsertWithoutReturning, Join, OneResult, RawQueryFetchAll, RawQueryFetchOne, RawQueryWithoutFetching, SelectAll, SelectOne, Update, UpdateReturning, UpdateWithoutReturning, Where } from './interfaces';
2
2
  import { ConflictTypes, OrderTypes } from './enums';
3
3
  import { Query, Raw } from './tools';
4
4
  export declare class QueryBuilder<GenericResultWrapper> {
@@ -17,10 +17,16 @@ export declare class QueryBuilder<GenericResultWrapper> {
17
17
  }): Query<ArrayResult<GenericResultWrapper, GenericResult>>;
18
18
  fetchOne<GenericResult = DefaultObject>(params: SelectOne): Query<OneResult<GenericResultWrapper, GenericResult>>;
19
19
  fetchAll<GenericResult = DefaultObject>(params: SelectAll): Query<ArrayResult<GenericResultWrapper, GenericResult>>;
20
- raw<GenericResult = DefaultObject>(params: RawQuery): Query<EitherResult<GenericResultWrapper, GenericResult>>;
21
- insert<GenericResult = DefaultObject>(params: Insert): Query<EitherResult<GenericResultWrapper, GenericResult>>;
22
- update<GenericResult = DefaultObject>(params: Update): Query<ArrayResult<GenericResultWrapper, GenericResult>>;
23
- delete<GenericResult = DefaultObject>(params: Delete): Query<ArrayResult<GenericResultWrapper, GenericResult>>;
20
+ raw<GenericResult = DefaultObject>(params: RawQueryFetchOne): Query<OneResult<GenericResultWrapper, GenericResult>>;
21
+ raw<GenericResult = DefaultObject>(params: RawQueryFetchAll): Query<ArrayResult<GenericResultWrapper, GenericResult>>;
22
+ raw<GenericResult = DefaultObject>(params: RawQueryWithoutFetching): Query<GenericResultWrapper>;
23
+ insert<GenericResult = DefaultObject>(params: InsertOne): Query<OneResult<GenericResultWrapper, GenericResult>>;
24
+ insert<GenericResult = DefaultObject>(params: InsertMultiple): Query<ArrayResult<GenericResultWrapper, GenericResult>>;
25
+ insert<GenericResult = DefaultObject>(params: InsertWithoutReturning): Query<GenericResultWrapper>;
26
+ update<GenericResult = DefaultObject>(params: UpdateReturning): Query<ArrayResult<GenericResultWrapper, GenericResult>>;
27
+ update<GenericResult = DefaultObject>(params: UpdateWithoutReturning): Query<GenericResultWrapper>;
28
+ delete<GenericResult = DefaultObject>(params: DeleteReturning): Query<ArrayResult<GenericResultWrapper, GenericResult>>;
29
+ delete<GenericResult = DefaultObject>(params: DeleteWithoutReturning): Query<GenericResultWrapper>;
24
30
  _parse_arguments(row: Record<string, string | boolean | number | null | Raw>): Array<any>;
25
31
  _onConflict(resolution?: string | ConflictTypes | ConflictUpsert): string;
26
32
  _insert(params: Insert): string;
@@ -27,6 +27,13 @@ export type RawQuery = {
27
27
  args?: (string | number | boolean | null | Raw)[];
28
28
  fetchType?: FetchTypes;
29
29
  };
30
+ export type RawQueryFetchOne = Omit<RawQuery, 'fetchType'> & {
31
+ fetchType: FetchTypes.ONE;
32
+ };
33
+ export type RawQueryFetchAll = Omit<RawQuery, 'fetchType'> & {
34
+ fetchType: FetchTypes.ALL;
35
+ };
36
+ export type RawQueryWithoutFetching = Omit<RawQuery, 'fetchType'>;
30
37
  export type SelectAll = SelectOne & {
31
38
  limit?: number;
32
39
  };
@@ -41,6 +48,16 @@ export type Insert = {
41
48
  returning?: string | Array<string>;
42
49
  onConflict?: string | ConflictTypes | ConflictUpsert;
43
50
  };
51
+ export type InsertOne = Omit<Insert, 'data' | 'returning'> & {
52
+ data: Record<string, string | boolean | number | null | Raw>;
53
+ returning: string | Array<string>;
54
+ };
55
+ export type InsertMultiple = Omit<Insert, 'data' | 'returning'> & {
56
+ data: Array<Record<string, string | boolean | number | null | Raw>>;
57
+ returning: string | Array<string>;
58
+ };
59
+ export type InsertWithoutReturning = Omit<Insert, 'returning'>;
60
+ export type test<I extends Insert = Insert> = I;
44
61
  export type Update = {
45
62
  tableName: string;
46
63
  data: Record<string, string | boolean | number | null | Raw>;
@@ -48,11 +65,19 @@ export type Update = {
48
65
  returning?: string | Array<string>;
49
66
  onConflict?: string | ConflictTypes;
50
67
  };
68
+ export type UpdateReturning = Omit<Update, 'returning'> & {
69
+ returning: string | Array<string>;
70
+ };
71
+ export type UpdateWithoutReturning = Omit<Update, 'returning'>;
51
72
  export type Delete = {
52
73
  tableName: string;
53
74
  where: Where;
54
75
  returning?: string | Array<string>;
55
76
  };
77
+ export type DeleteReturning = Omit<Delete, 'returning'> & {
78
+ returning: string | Array<string>;
79
+ };
80
+ export type DeleteWithoutReturning = Omit<Delete, 'returning'>;
56
81
  export type D1Result = {
57
82
  changes?: number;
58
83
  duration: number;
@@ -71,9 +96,6 @@ export type ArrayResult<ResultWrapper, Result> = Merge<ResultWrapper, {
71
96
  export type OneResult<ResultWrapper, Result> = Merge<ResultWrapper, {
72
97
  results?: Result;
73
98
  }>;
74
- export type EitherResult<ResultWrapper, Result> = Merge<ResultWrapper, {
75
- results?: Array<Result> | Result;
76
- }>;
77
99
  export type GetFetchValue<T> = T extends {
78
100
  fetchType?: infer U;
79
101
  } ? U : never;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "workers-qb",
3
- "version": "1.2.1",
3
+ "version": "1.2.3",
4
4
  "type": "module",
5
5
  "description": "Zero dependencies Query Builder for Cloudflare Workers",
6
6
  "main": "./dist/index.js",