workers-qb 1.1.1 → 1.2.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/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2022 Gabriel Massadas
3
+ Copyright (c) 2024 Gabriel Massadas
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -47,10 +47,16 @@ export default {
47
47
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
48
48
  const qb = new D1QB(env.DB)
49
49
 
50
- const fetched = await qb
51
- .fetchOne({
50
+ type Employee = {
51
+ name: string
52
+ role: string
53
+ level: number
54
+ }
55
+
56
+ const employeeList = await qb
57
+ .fetchOne<Employee>({
52
58
  tableName: 'employees',
53
- fields: 'count(*) as count',
59
+ fields: '*',
54
60
  where: {
55
61
  conditions: 'active = ?1',
56
62
  params: [true],
@@ -58,8 +64,11 @@ export default {
58
64
  })
59
65
  .execute()
60
66
 
67
+ // You get IDE type hints on each employee data, like:
68
+ // employeeList.results[0].name
69
+
61
70
  return Response.json({
62
- activeEmployees: fetched.results?.count || 0,
71
+ activeEmployees: employeeList.results?.length || 0,
63
72
  })
64
73
  },
65
74
  }
package/dist/index.js ADDED
@@ -0,0 +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;
package/dist/index.mjs ADDED
@@ -0,0 +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,26 +1,26 @@
1
- import { ConflictUpsert, Delete, Insert, Join, RawQuery, SelectAll, SelectOne, Update } from './interfaces';
1
+ import { ArrayResult, ConflictUpsert, DefaultObject, Delete, EitherResult, Insert, Join, OneResult, RawQuery, SelectAll, SelectOne, Update } from './interfaces';
2
2
  import { ConflictTypes, OrderTypes } from './enums';
3
3
  import { Query, Raw } from './tools';
4
- export declare class QueryBuilder<GenericResult, GenericResultOne> {
4
+ export declare class QueryBuilder<GenericResultWrapper> {
5
5
  _debugger: boolean;
6
6
  setDebugger(state: boolean): void;
7
- execute(query: Query): Promise<GenericResultOne | GenericResult>;
8
- batchExecute(queryArray: Query[]): Promise<(GenericResultOne | GenericResult)[]>;
9
- createTable(params: {
7
+ execute(query: Query): Promise<any>;
8
+ batchExecute(queryArray: Query[]): Promise<any[]>;
9
+ createTable<GenericResult = undefined>(params: {
10
10
  tableName: string;
11
11
  schema: string;
12
12
  ifNotExists?: boolean;
13
- }): Query;
14
- dropTable(params: {
13
+ }): Query<ArrayResult<GenericResultWrapper, GenericResult>>;
14
+ dropTable<GenericResult = undefined>(params: {
15
15
  tableName: string;
16
16
  ifExists?: boolean;
17
- }): Query;
18
- fetchOne(params: SelectOne): Query;
19
- fetchAll(params: SelectAll): Query;
20
- raw(params: RawQuery): Query;
21
- insert(params: Insert): Query;
22
- update(params: Update): Query;
23
- delete(params: Delete): Query;
17
+ }): Query<ArrayResult<GenericResultWrapper, GenericResult>>;
18
+ fetchOne<GenericResult = DefaultObject>(params: SelectOne): Query<OneResult<GenericResultWrapper, GenericResult>>;
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>>;
24
24
  _parse_arguments(row: Record<string, string | boolean | number | null | Raw>): Array<any>;
25
25
  _onConflict(resolution?: string | ConflictTypes | ConflictUpsert): string;
26
26
  _insert(params: Insert): string;
@@ -1,9 +1,9 @@
1
1
  import { QueryBuilder } from '../Builder';
2
2
  import { Query } from '../tools';
3
- import { D1Result, D1ResultOne } from '../interfaces';
4
- export declare class D1QB extends QueryBuilder<D1Result, D1ResultOne> {
3
+ import { D1Result } from '../interfaces';
4
+ export declare class D1QB extends QueryBuilder<D1Result> {
5
5
  db: any;
6
6
  constructor(db: any);
7
- execute(query: Query): Promise<D1ResultOne | D1Result>;
8
- batchExecute(queryArray: Query[]): Promise<(D1ResultOne | D1Result)[]>;
7
+ execute(query: Query): Promise<any>;
8
+ batchExecute(queryArray: Query[]): Promise<any>;
9
9
  }
@@ -1,10 +1,20 @@
1
1
  import { QueryBuilder } from '../Builder';
2
2
  import { Query } from '../tools';
3
- import { PGResult, PGResultOne } from '../interfaces';
4
- export declare class PGQB extends QueryBuilder<PGResult, PGResultOne> {
3
+ import { PGResult } from '../interfaces';
4
+ export declare class PGQB extends QueryBuilder<PGResult> {
5
5
  db: any;
6
6
  constructor(db: any);
7
7
  connect(): Promise<void>;
8
8
  close(): Promise<void>;
9
- execute(query: Query): Promise<PGResultOne | PGResult>;
9
+ execute(query: Query): Promise<{
10
+ command: any;
11
+ lastRowId: any;
12
+ rowCount: any;
13
+ results: any;
14
+ } | {
15
+ command: any;
16
+ lastRowId: any;
17
+ rowCount: any;
18
+ results?: undefined;
19
+ }>;
10
20
  }
@@ -1,16 +1,18 @@
1
1
  import { ConflictTypes, FetchTypes, JoinTypes, OrderTypes } from './enums';
2
2
  import { Raw } from './tools';
3
- export interface Where {
3
+ import { IsEqual, Merge, Primitive, Simplify } from './typefest';
4
+ export type DefaultObject = Record<string, Primitive>;
5
+ export type Where = {
4
6
  conditions: string | Array<string>;
5
- params?: (string | boolean | number | null)[];
6
- }
7
- export interface Join {
7
+ params?: (string | boolean | number | null | Raw)[];
8
+ };
9
+ export type Join = {
8
10
  type?: string | JoinTypes;
9
11
  table: string | SelectAll;
10
12
  on: string;
11
13
  alias?: string;
12
- }
13
- export interface SelectOne {
14
+ };
15
+ export type SelectOne = {
14
16
  tableName: string;
15
17
  fields: string | Array<string>;
16
18
  where?: Where;
@@ -19,63 +21,61 @@ export interface SelectOne {
19
21
  having?: string;
20
22
  orderBy?: string | Array<string> | Record<string, string | OrderTypes>;
21
23
  offset?: number;
22
- }
23
- export interface RawQuery {
24
+ };
25
+ export type RawQuery = {
24
26
  query: string;
25
27
  args?: (string | number | boolean | null | Raw)[];
26
28
  fetchType?: FetchTypes;
27
- }
28
- export interface SelectAll extends SelectOne {
29
+ };
30
+ export type SelectAll = SelectOne & {
29
31
  limit?: number;
30
- }
31
- export interface ConflictUpsert {
32
+ };
33
+ export type ConflictUpsert = {
32
34
  column: string | Array<string>;
33
35
  data: Record<string, string | boolean | number | null | Raw>;
34
36
  where?: Where;
35
- }
36
- export interface Insert {
37
+ };
38
+ export type Insert = {
37
39
  tableName: string;
38
40
  data: Record<string, string | boolean | number | null | Raw> | Array<Record<string, string | boolean | number | null | Raw>>;
39
41
  returning?: string | Array<string>;
40
42
  onConflict?: string | ConflictTypes | ConflictUpsert;
41
- }
42
- export interface Update {
43
+ };
44
+ export type Update = {
43
45
  tableName: string;
44
46
  data: Record<string, string | boolean | number | null | Raw>;
45
47
  where?: Where;
46
48
  returning?: string | Array<string>;
47
49
  onConflict?: string | ConflictTypes;
48
- }
49
- export interface Delete {
50
+ };
51
+ export type Delete = {
50
52
  tableName: string;
51
53
  where: Where;
52
54
  returning?: string | Array<string>;
53
- }
54
- export interface D1Result {
55
+ };
56
+ export type D1Result = {
55
57
  changes?: number;
56
58
  duration: number;
57
59
  last_row_id?: string | number;
58
- results?: Array<Record<string, string | boolean | number | null>>;
59
60
  served_by: string;
60
61
  success: boolean;
61
- }
62
- export interface D1ResultOne {
63
- changes?: number;
64
- duration: number;
65
- last_row_id?: string | number;
66
- results?: Record<string, string | boolean | number | null>;
67
- served_by: string;
68
- success: boolean;
69
- }
70
- export interface PGResult {
71
- command: string;
72
- lastRowId?: string | number;
73
- rowCount: number;
74
- results?: Array<Record<string, string | boolean | number | null>>;
75
- }
76
- export interface PGResultOne {
62
+ };
63
+ export type PGResult = {
77
64
  command: string;
78
65
  lastRowId?: string | number;
79
66
  rowCount: number;
80
- results?: Record<string, string | boolean | number | null>;
81
- }
67
+ };
68
+ export type ArrayResult<ResultWrapper, Result> = Merge<ResultWrapper, {
69
+ results?: Array<Result>;
70
+ }>;
71
+ export type OneResult<ResultWrapper, Result> = Merge<ResultWrapper, {
72
+ results?: Result;
73
+ }>;
74
+ export type EitherResult<ResultWrapper, Result> = Merge<ResultWrapper, {
75
+ results?: Array<Result> | Result;
76
+ }>;
77
+ export type GetFetchValue<T> = T extends {
78
+ fetchType?: infer U;
79
+ } ? U : never;
80
+ export type SwitchFetch<P, A, B> = IsEqual<P, FetchTypes.ALL> extends true ? ArrayResult<A, B> : IsEqual<P, FetchTypes.ONE> extends true ? OneResult<A, B> : A;
81
+ export type FindResult<P, A, B> = Simplify<SwitchFetch<GetFetchValue<P>, A, B>>;
@@ -1,14 +1,14 @@
1
- import { FetchTypes } from 'enums';
1
+ import { FetchTypes } from './enums';
2
2
  export declare class Raw {
3
3
  isRaw: boolean;
4
4
  content: any;
5
5
  constructor(content: any);
6
6
  }
7
- export declare class Query {
8
- executeMethod: (query: Query) => Promise<any>;
7
+ export declare class Query<Result = any> {
8
+ executeMethod: (query: Query<Result>) => Promise<Result>;
9
9
  query: string;
10
10
  arguments?: (string | number | boolean | null | Raw)[];
11
11
  fetchType?: FetchTypes;
12
- constructor(executeMethod: (query: Query) => Promise<any>, query: string, args?: (string | number | boolean | null | Raw)[], fetchType?: FetchTypes);
13
- execute(): Promise<any>;
12
+ constructor(executeMethod: (query: Query<Result>) => Promise<Result>, query: string, args?: (string | number | boolean | null | Raw)[], fetchType?: FetchTypes);
13
+ execute(): Promise<Result>;
14
14
  }
@@ -0,0 +1,16 @@
1
+ export type Primitive = null | undefined | string | number | boolean | symbol | bigint;
2
+ export type OmitIndexSignature<ObjectType> = {
3
+ [KeyType in keyof ObjectType as {} extends Record<KeyType, unknown> ? never : KeyType]: ObjectType[KeyType];
4
+ };
5
+ export type PickIndexSignature<ObjectType> = {
6
+ [KeyType in keyof ObjectType as {} extends Record<KeyType, unknown> ? KeyType : never]: ObjectType[KeyType];
7
+ };
8
+ export type Simplify<T> = {
9
+ [KeyType in keyof T]: T[KeyType];
10
+ } & {};
11
+ type SimpleMerge<Destination, Source> = {
12
+ [Key in keyof Destination as Key extends keyof Source ? never : Key]: Destination[Key];
13
+ } & Source;
14
+ export type Merge<Destination, Source> = Simplify<SimpleMerge<PickIndexSignature<Destination>, PickIndexSignature<Source>> & SimpleMerge<OmitIndexSignature<Destination>, OmitIndexSignature<Source>>>;
15
+ export type IsEqual<A, B> = (<G>() => G extends A ? 1 : 2) extends <G>() => G extends B ? 1 : 2 ? true : false;
16
+ export {};
package/package.json CHANGED
@@ -1,14 +1,15 @@
1
1
  {
2
2
  "name": "workers-qb",
3
- "version": "1.1.1",
3
+ "version": "1.2.0",
4
+ "type": "module",
4
5
  "description": "Zero dependencies Query Builder for Cloudflare Workers",
5
- "main": "./dist/workers-qb.js",
6
- "types": "./dist/src/workers-qb.d.ts",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/src/index.d.ts",
7
8
  "exports": {
8
9
  ".": {
9
- "types": "./dist/src/workers-qb.d.ts",
10
- "import": "./dist/workers-qb.mjs",
11
- "require": "./dist/workers-qb.js"
10
+ "types": "./dist/src/index.d.ts",
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.js"
12
13
  }
13
14
  },
14
15
  "files": [
@@ -21,8 +22,8 @@
21
22
  "postpublish": "pinst --enable",
22
23
  "build": "rollup -c",
23
24
  "package": "npm run build && npm pack",
24
- "test": "jest --no-cache --runInBand",
25
- "test:cov": "jest --coverage --no-cache --runInBand",
25
+ "test": "jest --config jest.config.cjs --no-cache --runInBand",
26
+ "test:cov": "jest --config jest.config.cjs --coverage --no-cache --runInBand",
26
27
  "addscope": "node tools/packagejson name @g4brym/workers-qb",
27
28
  "prettify": "prettier --check . || (prettier -w .; exit 1)",
28
29
  "prepare": "husky install"
@@ -83,5 +84,29 @@
83
84
  "rollup-plugin-bundle-size": "^1.0.3",
84
85
  "ts-jest": "^28.0.5",
85
86
  "typescript": "^4.8.4"
87
+ },
88
+ "prettier": {
89
+ "semi": false,
90
+ "singleQuote": true,
91
+ "trailingComma": "es5",
92
+ "arrowParens": "always",
93
+ "printWidth": 120
94
+ },
95
+ "eslintConfig": {
96
+ "parser": "@typescript-eslint/parser",
97
+ "extends": [
98
+ "plugin:@typescript-eslint/recommended",
99
+ "prettier"
100
+ ],
101
+ "parserOptions": {
102
+ "sourceType": "module"
103
+ },
104
+ "rules": {
105
+ "prettier/prettier": "error"
106
+ },
107
+ "plugins": [
108
+ "@typescript-eslint",
109
+ "prettier"
110
+ ]
86
111
  }
87
112
  }
@@ -1 +0,0 @@
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)}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} 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{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 +0,0 @@
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)}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} 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{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};
File without changes