Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(select): support custom function in select #45

Merged
merged 4 commits into from
Aug 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions doc/sql.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
- [QueryBuilder.prototype.buildParams](#querybuilderprototypebuildparams)
- [QueryBuilder.prototype.makeKeyOrExpr](#querybuilderprototypemakekeyorexprvalue-wrap--false)
- [QueryBuilder.prototype.makeParamValue](#querybuilderprototypemakeparamvaluevalue)
- [QueryBuilder.prototype.raw](#querybuilderprototyperawsqltemplate)
- [QueryConditionsBuilder](#class-queryconditionsbuilder-extends-querybuilder)
- [QueryConditionsBuilder.prototype.constructor](#queryconditionsbuilderprototypeconstructorparams-options)
- [QueryConditionsBuilder.prototype.\_whereValueMapper](#queryconditionsbuilderprototype_wherevaluemappervalue)
Expand Down Expand Up @@ -69,6 +70,8 @@
- [SelectBuilder.prototype.orderBy](#selectbuilderprototypeorderbyfield-dir--asc)
- [SelectBuilder.prototype.select](#selectbuilderprototypeselectfields)
- [SelectBuilder.prototype.selectAs](#selectbuilderprototypeselectasfield-alias)
- [SelectBuilder.prototype.selectFn](#selectbuilderprototypeselectfnfn-field-alias)
- [SelectBuilder.prototype.selectRaw](#selectbuilderprototypeselectrawsqlorbuilder)
- [SelectBuilder.prototype.sum](#selectbuilderprototypesumfield-alias)
- [RawBuilder](#class-rawbuilder-extends-querybuilder)
- [RawBuilder.prototype.constructor](#rawbuilderprototypeconstructorsqltemplate)
Expand Down Expand Up @@ -187,6 +190,8 @@ Build params for this query

#### QueryBuilder.prototype.makeParamValue(value)

#### QueryBuilder.prototype.raw(sqlTemplate)

### class QueryConditionsBuilder extends [QueryBuilder][sql-querybuilder]

#### QueryConditionsBuilder.prototype.constructor(params, options)
Expand Down Expand Up @@ -311,6 +316,10 @@ Build params for this query

#### SelectBuilder.prototype.selectAs(field, alias)

#### SelectBuilder.prototype.selectFn(fn, field, alias)

#### SelectBuilder.prototype.selectRaw(sqlOrBuilder)

#### SelectBuilder.prototype.sum(field, alias)

### class RawBuilder extends [QueryBuilder][sql-querybuilder]
Expand Down
7 changes: 5 additions & 2 deletions lib/conditions-builder.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
'use strict';

const { makeParamValue, QueryBuilder } = require('./query-builder.js');
const {
makeParamValue,
QueryBuilder,
RawBuilder,
} = require('./query-builder.js');
const { mapJoinIterable } = require('./utils.js');
const { RawBuilder } = require('./raw-builder.js');

const allowedConditions = new Set([
'=',
Expand Down
22 changes: 22 additions & 0 deletions lib/query-builder.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ class QueryBuilder {
return this.escapeKey(value);
}

raw(sqlTemplate) {
// eslint-disable-next-line no-use-before-define
return new RawBuilder(sqlTemplate, this.params, this.options);
}

// Build and return the SQL query
// Returns: <string>
build() {
Expand All @@ -42,6 +47,22 @@ class QueryBuilder {
}
}

class RawBuilder extends QueryBuilder {
// sqlTemplate <Function> function or sql string
// params <ParamsBuilder>
// Returns: <string> query
constructor(sqlTemplate, params, options) {
super(params, options);
this.sqlTemplate = sqlTemplate;
}

build() {
return typeof this.sqlTemplate === 'function'
? this.sqlTemplate(this.params)
: this.sqlTemplate;
}
}

function makeParamValue(value, params) {
if (value instanceof QueryBuilder) {
return '(' + value.build() + ')';
Expand Down Expand Up @@ -70,6 +91,7 @@ function checkTypeOrQuery(value, name, type) {

module.exports = {
QueryBuilder,
RawBuilder,
makeParamValue,
makeKeyWithAlias,
checkTypeOrQuery,
Expand Down
21 changes: 0 additions & 21 deletions lib/raw-builder.js

This file was deleted.

32 changes: 22 additions & 10 deletions lib/select-builder.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@

const { iter } = require('@metarhia/iterator');

const { checkTypeOrQuery, makeKeyWithAlias } = require('./query-builder.js');
const {
QueryBuilder,
checkTypeOrQuery,
makeKeyWithAlias,
} = require('./query-builder.js');
const { QueryConditionsBuilder } = require('./query-conditions-builder.js');
const { mapJoinIterable } = require('./utils.js');

const functionHandlers = {
count: (op) => `count(${op.field})`,
avg: (op) => `avg(${op.field})`,
min: (op) => `min(${op.field})`,
max: (op) => `max(${op.field})`,
sum: (op) => `sum(${op.field})`,
default: (op) => `${op.type}(${op.field})`,
};

class SelectBuilder extends QueryConditionsBuilder {
Expand Down Expand Up @@ -49,6 +49,15 @@ class SelectBuilder extends QueryConditionsBuilder {
return this._addSelectClause(undefined, field, alias);
}

selectFn(fn, field, alias) {
return this._addSelectClause(fn, field, alias);
}

selectRaw(sqlOrBuilder) {
this.operations.select.add({ sql: sqlOrBuilder });
return this;
}

innerJoin(tableName, leftKey, rightKey) {
this.operations.innerJoin.push({
table: this.escapeIdentifier(tableName),
Expand Down Expand Up @@ -141,10 +150,13 @@ class SelectBuilder extends QueryConditionsBuilder {
select,
(op) => {
if (typeof op === 'string') return op;
let clause =
op.type === undefined ? op.field : functionHandlers[op.type](op);
if (op.alias) clause += ` AS ${op.alias}`;
return clause;
if (typeof op.sql === 'string') return op.sql;
if (op.sql instanceof QueryBuilder) return op.sql.build();
if (op.type) {
const handler = functionHandlers[op.type] ?? functionHandlers.default;
return handler(op) + (op.alias ? ` AS ${op.alias}` : '');
}
return op.field + (op.alias ? ` AS ${op.alias}` : '');
},
', '
);
Expand Down
3 changes: 1 addition & 2 deletions sql.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
'use strict';

const { QueryBuilder } = require('./lib/query-builder.js');
const { QueryBuilder, RawBuilder } = require('./lib/query-builder.js');
const { QueryConditionsBuilder } = require('./lib/query-conditions-builder.js');
const { SelectBuilder } = require('./lib/select-builder.js');
const { UpdateBuilder } = require('./lib/update-builder.js');
const { DeleteBuilder } = require('./lib/delete-builder.js');
const { InsertBuilder } = require('./lib/insert-builder.js');
const { PgInsertBuilder } = require('./lib/pg-insert-builder.js');
const { PgSelectBuilder } = require('./lib/pg-select-builder.js');
const { RawBuilder } = require('./lib/raw-builder.js');
const { ConditionsBuilder } = require('./lib/conditions-builder.js');
const { ParamsBuilder } = require('./lib/params-builder.js');
const { PostgresParamsBuilder } = require('./lib/pg-params-builder.js');
Expand Down
2 changes: 1 addition & 1 deletion test/conditions-builder.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

const { SelectBuilder } = require('../lib/select-builder');
const { testSync } = require('metatests');
const { RawBuilder } = require('../lib/raw-builder');
const { RawBuilder } = require('../lib/query-builder.js');
const { ConditionsBuilder } = require('../lib/conditions-builder');
const { PostgresParamsBuilder } = require('../lib/pg-params-builder');

Expand Down
58 changes: 57 additions & 1 deletion test/sqlgen.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

const { testSync } = require('metatests');
const { SelectBuilder } = require('../lib/select-builder');
const { RawBuilder } = require('../lib/raw-builder');
const { RawBuilder } = require('../lib/query-builder.js');
const { PostgresParamsBuilder } = require('../lib/pg-params-builder');

const allowedConditions = new Set([
Expand Down Expand Up @@ -573,6 +573,62 @@ test.testSync('Select multiple operations', (test, { builder, params }) => {
test.strictSame(params.build(), []);
});

test.testSync('Select fn operation', (test, { builder, params }) => {
builder.from('table').selectFn('my_function', 'f1').whereEq('f2', 42);
const query = builder.build();
test.strictSame(
query,
'SELECT my_function("f1") FROM "table" WHERE "f2" = $1'
);
test.strictSame(params.build(), [42]);
});

test.testSync('Select fn operation', (test, { builder, params }) => {
builder.from('table').selectFn('array_agg', 'f1').whereEq('f2', 42);
const query = builder.build();
test.strictSame(query, 'SELECT array_agg("f1") FROM "table" WHERE "f2" = $1');
test.strictSame(params.build(), [42]);
});

test.testSync('Select custom operation', (test, { builder, params }) => {
builder.from('table').selectRaw('array_agg("f1")').whereEq('f2', 42);
const query = builder.build();
test.strictSame(query, 'SELECT array_agg("f1") FROM "table" WHERE "f2" = $1');
test.strictSame(params.build(), [42]);
});

test.testSync(
'Select custom operation with QueryBuilder',
(test, { builder, params }) => {
builder
.from('table')
.selectRaw(new RawBuilder('array_agg("f1")'))
.whereEq('f2', 42);
const query = builder.build();
test.strictSame(
query,
'SELECT array_agg("f1") FROM "table" WHERE "f2" = $1'
);
test.strictSame(params.build(), [42]);
}
);

test.testSync(
'Select custom operation with QueryBuilder',
(test, { builder, params }) => {
builder
.from('table')
.selectRaw(builder.raw('array_agg("f1")'))
.whereEq('f2', 42);
const query = builder.build();
test.strictSame(
query,
'SELECT array_agg("f1") FROM "table" WHERE "f2" = $1'
);
test.strictSame(params.build(), [42]);
}
);

test.testSync(
'Select multiple operations order',
(test, { builder, params }) => {
Expand Down
7 changes: 5 additions & 2 deletions types/lib/conditions-builder.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { ParamsBuilder } from './params-builder';
import { QueryBuilder, QueryBuilderOptions } from './query-builder';
import { SqlTemplate } from './raw-builder';
import {
QueryBuilder,
QueryBuilderOptions,
SqlTemplate,
} from './query-builder';

export interface ConditionsBuilderOptions extends QueryBuilderOptions {}

Expand Down
11 changes: 11 additions & 0 deletions types/lib/query-builder.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,19 @@ export class QueryBuilder<O extends QueryBuilderOptions = QueryBuilderOptions> {

makeKeyOrExpr(value: string | QueryBuilder): string;

raw(sqlTemplate: SqlTemplate): RawBuilder;
// Build and return the SQL query.
build(): string;

buildParams(): unknown[];
}

export type SqlTemplate = string | ((p: ParamsBuilder) => string);

export class RawBuilder extends QueryBuilder {
constructor(
sqlTemplate: SqlTemplate,
params: ParamsBuilder,
options?: QueryBuilderOptions
);
}
7 changes: 5 additions & 2 deletions types/lib/query-conditions-builder.d.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { ParamsBuilder } from './params-builder';
import { SelectQueryValue } from './select-builder';
import { QueryBuilder, QueryBuilderOptions } from './query-builder';
import { SqlTemplate } from './raw-builder';
import {
QueryBuilder,
QueryBuilderOptions,
SqlTemplate,
} from './query-builder';

// Utility class for all proxy Conditions methods.
export class QueryConditionsBuilder<
Expand Down
12 changes: 0 additions & 12 deletions types/lib/raw-builder.d.ts

This file was deleted.

2 changes: 2 additions & 0 deletions types/lib/select-builder.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ export class SelectBuilder extends QueryConditionsBuilder<

selectAs(field: string, alias: string): this;

selectFn(fn: string, field: string, alias: string): this;

innerJoin(tableName: string, leftKey: string, rightKey: string): this;

distinct(): this;
Expand Down
1 change: 0 additions & 1 deletion types/sql.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
export * from './lib/query-builder';
export * from './lib/query-conditions-builder';
export * from './lib/raw-builder';
export { SelectBuilder, SelectBuilderOptions } from './lib/select-builder';
export {
ConditionsBuilder,
Expand Down
Loading