Skip to content

Commit

Permalink
Add .all() and .one() to modular selects (#56)
Browse files Browse the repository at this point in the history
  • Loading branch information
G4brym authored Sep 5, 2024
1 parent 172d8aa commit 26bf427
Show file tree
Hide file tree
Showing 7 changed files with 104 additions and 36 deletions.
42 changes: 41 additions & 1 deletion docs/pages/modular-selects.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,13 @@ const result = await qb
.fields(['id', 'name'])
.where('field = ?1', 'test')
.join({ type: JoinTypes.LEFT, table: 'employees', on: 'testTable.employee_id = employees.id' })
.execute()
.all()
```

### Execution Methods

#### .count()

Count method is also available for the modular selects

```ts
Expand All @@ -50,3 +54,39 @@ const result = await qb

console.log(`Total results: ${result.results.total}`)
```

#### .all()

This is the same as calling `qb.fetchAll()` or calling `qb.select().execute()`

```ts
const qb = new D1QB(env.DB)

const result = await qb.select('testTable').fields(['id', 'name']).where('field = ?1', 'test').all()

console.log(`Total results: ${result.results.length}`)
```

#### .execute()

This is the same as calling `qb.fetchAll()` or calling `qb.select().all()`

```ts
const qb = new D1QB(env.DB)

const result = await qb.select('testTable').fields(['id', 'name']).where('field = ?1', 'test').execute()

console.log(`Total results: ${result.results.length}`)
```

#### .one()

This is the same as calling `qb.fetchOne()`

```ts
const qb = new D1QB(env.DB)

const result = await qb.select('testTable').fields(['id', 'name']).where('field = ?1', 'test').one()

console.log(`Result: ${result.results}`)
```
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "workers-qb",
"version": "1.5.0",
"version": "1.5.1",
"description": "Zero dependencies Query Builder for Cloudflare Workers",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
Expand Down
3 changes: 3 additions & 0 deletions src/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,9 @@ export class QueryBuilder<GenericResultWrapper> {
},
(params: SelectAll) => {
return this.fetchAll<GenericResult>(params)
},
(params: SelectOne) => {
return this.fetchOne<GenericResult>(params)
}
)
}
Expand Down
51 changes: 37 additions & 14 deletions src/modularBuilder.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
import { ArrayResult, CountResult, DefaultReturnObject, Primitive, SelectAll } from './interfaces'
import { ArrayResult, CountResult, DefaultReturnObject, OneResult, Primitive, SelectAll, SelectOne } from './interfaces'
import { Query, QueryWithExtra } from './tools'

export class SelectBuilder<GenericResultWrapper, GenericResult = DefaultReturnObject> {
_debugger = false
private _options: Partial<SelectAll> = {}
private _queryBuilder: (params: SelectAll) => QueryWithExtra<GenericResultWrapper>

constructor(options: Partial<SelectAll>, queryBuilder: (params: SelectAll) => QueryWithExtra<GenericResultWrapper>) {
private _fetchAll: (params: SelectAll) => QueryWithExtra<GenericResultWrapper>
private _fetchOne: (params: SelectOne) => QueryWithExtra<GenericResultWrapper>

constructor(
options: Partial<SelectAll>,
fetchAll: (params: SelectAll) => QueryWithExtra<GenericResultWrapper>,
fetchOne: (params: SelectOne) => QueryWithExtra<GenericResultWrapper>
) {
this._options = options
this._queryBuilder = queryBuilder
this._fetchAll = fetchAll
this._fetchOne = fetchOne
}

setDebugger(state: boolean): void {
Expand All @@ -21,7 +27,8 @@ export class SelectBuilder<GenericResultWrapper, GenericResult = DefaultReturnOb
...this._options,
tableName: tableName,
},
this._queryBuilder
this._fetchAll,
this._fetchOne
)
}

Expand Down Expand Up @@ -57,7 +64,8 @@ export class SelectBuilder<GenericResultWrapper, GenericResult = DefaultReturnOb
params: params,
},
},
this._queryBuilder
this._fetchAll,
this._fetchOne
)
}

Expand All @@ -83,7 +91,8 @@ export class SelectBuilder<GenericResultWrapper, GenericResult = DefaultReturnOb
...this._options,
offset: offset,
},
this._queryBuilder
this._fetchAll,
this._fetchOne
)
}

Expand All @@ -93,7 +102,8 @@ export class SelectBuilder<GenericResultWrapper, GenericResult = DefaultReturnOb
...this._options,
limit: limit,
},
this._queryBuilder
this._fetchAll,
this._fetchOne
)
}

Expand All @@ -114,19 +124,32 @@ export class SelectBuilder<GenericResultWrapper, GenericResult = DefaultReturnOb
...this._options,
[fieldName]: val as Array<string>,
},
this._queryBuilder
this._fetchAll,
this._fetchOne
)
}

getQuery(): Query<ArrayResult<GenericResultWrapper, GenericResult>> {
return this._queryBuilder(this._options as SelectAll)
getQueryAll(): Query<ArrayResult<GenericResultWrapper, GenericResult>> {
return this._fetchAll(this._options as SelectAll)
}

getQueryOne(): Query<OneResult<GenericResultWrapper, GenericResult>> {
return this._fetchOne(this._options as SelectAll)
}

async execute(): Promise<ArrayResult<GenericResultWrapper, GenericResult>> {
return this._queryBuilder(this._options as SelectAll).execute()
return this._fetchAll(this._options as SelectAll).execute()
}

async all(): Promise<ArrayResult<GenericResultWrapper, GenericResult>> {
return this._fetchAll(this._options as SelectAll).execute()
}

async one(): Promise<OneResult<GenericResultWrapper, GenericResult>> {
return this._fetchOne(this._options as SelectOne).execute()
}

async count(): Promise<CountResult<GenericResultWrapper>> {
return this._queryBuilder(this._options as SelectAll).count()
return this._fetchOne(this._options as SelectOne).count()
}
}
36 changes: 19 additions & 17 deletions tests/builder/select.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ describe('Select Builder', () => {
tableName: 'testTable',
fields: '*',
}),
new QuerybuilderTest().select('testTable').fields('*').getQuery(),
new QuerybuilderTest().select('testTable').fields('*').getQueryAll(),
]) {
expect(result.query).toEqual('SELECT * FROM testTable')
expect(result.arguments).toBeUndefined()
Expand All @@ -21,7 +21,7 @@ describe('Select Builder', () => {
new QuerybuilderTest().fetchAll({
tableName: 'testTable',
}),
new QuerybuilderTest().select('testTable').getQuery(),
new QuerybuilderTest().select('testTable').getQueryAll(),
]) {
expect(result.query).toEqual('SELECT * FROM testTable')
expect(result.arguments).toBeUndefined()
Expand All @@ -34,6 +34,7 @@ describe('Select Builder', () => {
new QuerybuilderTest().fetchOne({
tableName: 'testTable',
}),
new QuerybuilderTest().select('testTable').getQueryOne(),
]) {
expect(result.query).toEqual('SELECT * FROM testTable LIMIT 1')
expect(result.arguments).toBeUndefined()
Expand All @@ -47,12 +48,13 @@ describe('Select Builder', () => {
tableName: 'testTable',
fields: '*',
where: {
conditions: 'field = ?1',
conditions: 'field = ?',
params: ['test'],
},
}),
new QuerybuilderTest().select('testTable').where('field = ?', 'test').getQueryOne(),
]) {
expect(result.query).toEqual('SELECT * FROM testTable WHERE field = ?1 LIMIT 1')
expect(result.query).toEqual('SELECT * FROM testTable WHERE field = ? LIMIT 1')
expect(result.arguments).toEqual(['test'])
expect(result.fetchType).toEqual('ONE')
}
Expand Down Expand Up @@ -156,7 +158,7 @@ describe('Select Builder', () => {
.fields('*')
.where('field = ?1', 'test')
.join({ table: 'employees', on: 'testTable.employee_id = employees.id' })
.getQuery(),
.getQueryAll(),
]) {
expect(result.query).toEqual(
'SELECT * FROM testTable JOIN employees ON testTable.employee_id = employees.id ' + 'WHERE field = ?1'
Expand Down Expand Up @@ -268,7 +270,7 @@ describe('Select Builder', () => {
.fields(['id', 'name'])
.where('field = ?1', 'test')
.join({ type: JoinTypes.LEFT, table: 'employees', on: 'testTable.employee_id = employees.id' })
.getQuery(),
.getQueryAll(),
]) {
expect(result.query).toEqual(
'SELECT id, name FROM testTable LEFT JOIN employees ON testTable.employee_id = employees.id WHERE field = ?1'
Expand Down Expand Up @@ -310,7 +312,7 @@ describe('Select Builder', () => {
on: 'testTable.id = otherTableGrouped.test_table_id',
alias: 'otherTableGrouped',
})
.getQuery(),
.getQueryAll(),
]) {
expect(result.query).toEqual(
'SELECT * FROM testTable JOIN (SELECT test_table_id, GROUP_CONCAT(attribute) ' +
Expand Down Expand Up @@ -426,7 +428,7 @@ describe('Select Builder', () => {
on: 'testTable.id = otherTableGrouped.test_table_id',
alias: 'otherTableGrouped',
})
.getQuery(),
.getQueryAll(),
]) {
expect(result.query).toEqual(
'SELECT * FROM testTable JOIN (SELECT test_table_id, GROUP_CONCAT(attribute) ' +
Expand Down Expand Up @@ -471,7 +473,7 @@ describe('Select Builder', () => {
.fields('*')
.where('field = ?', 'test')
.where('test = ?', 123)
.getQuery(),
.getQueryAll(),
]) {
expect(result.query).toEqual('SELECT * FROM testTable WHERE field = ? AND test = ?')
expect(result.arguments).toEqual(['test', 123])
Expand All @@ -496,7 +498,7 @@ describe('Select Builder', () => {
.where('field = ?1', 'test')
.where('test = ?2', 123)
.groupBy('type')
.getQuery(),
.getQueryAll(),
]) {
expect(result.query).toEqual('SELECT * FROM testTable WHERE field = ?1 AND test = ?2 GROUP BY type')
expect(result.arguments).toEqual(['test', 123])
Expand All @@ -522,7 +524,7 @@ describe('Select Builder', () => {
.where('test = ?2', 123)
.groupBy('type')
.groupBy('day')
.getQuery(),
.getQueryAll(),
]) {
expect(result.query).toEqual('SELECT * FROM testTable WHERE field = ?1 AND test = ?2 GROUP BY type, day')
expect(result.arguments).toEqual(['test', 123])
Expand All @@ -549,7 +551,7 @@ describe('Select Builder', () => {
.where('test = ?2', 123)
.groupBy('type')
.having('COUNT(trackid) > 15')
.getQuery(),
.getQueryAll(),
]) {
expect(result.query).toEqual(
'SELECT * FROM testTable WHERE field = ?1 AND test = ?2 GROUP BY type HAVING COUNT(trackid) > 15'
Expand Down Expand Up @@ -579,7 +581,7 @@ describe('Select Builder', () => {
.groupBy('type')
.having('COUNT(trackid) > 15')
.having('COUNT(trackid) < 30')
.getQuery(),
.getQueryAll(),
]) {
expect(result.query).toEqual(
'SELECT * FROM testTable WHERE field = ?1 AND test = ?2 GROUP BY type HAVING COUNT(trackid) > 15 AND COUNT(trackid) < 30'
Expand Down Expand Up @@ -608,7 +610,7 @@ describe('Select Builder', () => {
.where('test = ?2', 123)
.groupBy('type')
.orderBy('id')
.getQuery(),
.getQueryAll(),
]) {
expect(result.query).toEqual('SELECT * FROM testTable WHERE field = ?1 AND test = ?2 GROUP BY type ORDER BY id')
expect(result.arguments).toEqual(['test', 123])
Expand Down Expand Up @@ -636,7 +638,7 @@ describe('Select Builder', () => {
.groupBy('type')
.orderBy('id')
.orderBy('timestamp')
.getQuery(),
.getQueryAll(),
]) {
expect(result.query).toEqual(
'SELECT * FROM testTable WHERE field = ?1 AND test = ?2 GROUP BY type ORDER BY id, timestamp'
Expand Down Expand Up @@ -669,7 +671,7 @@ describe('Select Builder', () => {
.groupBy('type')
.orderBy({ id: 'ASC' })
.orderBy({ timestamp: OrderTypes.DESC })
.getQuery(),
.getQueryAll(),
]) {
expect(result.query).toEqual(
'SELECT * FROM testTable WHERE field = ?1 AND test = ?2 GROUP BY type ORDER BY id ASC, timestamp DESC'
Expand Down Expand Up @@ -700,7 +702,7 @@ describe('Select Builder', () => {
.groupBy('type')
.limit(10)
.offset(15)
.getQuery(),
.getQueryAll(),
]) {
expect(result.query).toEqual(
'SELECT * FROM testTable WHERE field = ?1 AND test = ?2 GROUP BY type LIMIT 10 OFFSET 15'
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@
"noUncheckedIndexedAccess": true,
"noEmit": true
},
"include": ["src/*.ts", "src/databases/*.ts"]
"include": ["src/*.ts", "src/databases/*.ts", "tests/*.ts", "tests/builder/*.ts"]
}

0 comments on commit 26bf427

Please sign in to comment.