@contember/database 0.12.0-alpha.9 → 1.0.0-alpha.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/dist/src/Literal.d.ts +2 -2
- package/dist/src/Literal.d.ts.map +1 -1
- package/dist/src/Literal.js.map +1 -1
- package/dist/src/builders/CaseStatement.js +3 -3
- package/dist/src/builders/CaseStatement.js.map +1 -1
- package/dist/src/builders/ColumnExpressionFactory.d.ts +2 -2
- package/dist/src/builders/ColumnExpressionFactory.d.ts.map +1 -1
- package/dist/src/builders/ColumnExpressionFactory.js +2 -2
- package/dist/src/builders/ColumnExpressionFactory.js.map +1 -1
- package/dist/src/builders/Compiler.d.ts.map +1 -1
- package/dist/src/builders/Compiler.js +15 -11
- package/dist/src/builders/Compiler.js.map +1 -1
- package/dist/src/builders/ConditionBuilder.d.ts +14 -9
- package/dist/src/builders/ConditionBuilder.d.ts.map +1 -1
- package/dist/src/builders/ConditionBuilder.js +62 -45
- package/dist/src/builders/ConditionBuilder.js.map +1 -1
- package/dist/src/builders/DeleteBuilder.js +1 -1
- package/dist/src/builders/DeleteBuilder.js.map +1 -1
- package/dist/src/builders/InsertBuilder.d.ts +22 -11
- package/dist/src/builders/InsertBuilder.d.ts.map +1 -1
- package/dist/src/builders/InsertBuilder.js +25 -6
- package/dist/src/builders/InsertBuilder.js.map +1 -1
- package/dist/src/builders/SelectBuilder.d.ts +2 -2
- package/dist/src/builders/SelectBuilder.d.ts.map +1 -1
- package/dist/src/builders/SelectBuilder.js +9 -9
- package/dist/src/builders/SelectBuilder.js.map +1 -1
- package/dist/src/builders/UpdateBuilder.js +2 -2
- package/dist/src/builders/UpdateBuilder.js.map +1 -1
- package/dist/src/builders/WindowFunction.js +2 -2
- package/dist/src/builders/WindowFunction.js.map +1 -1
- package/dist/src/builders/formatUtils.js +3 -3
- package/dist/src/builders/formatUtils.js.map +1 -1
- package/dist/src/builders/internal/Returning.js +1 -1
- package/dist/src/builders/internal/Returning.js.map +1 -1
- package/dist/src/builders/internal/Subqueries.d.ts +3 -3
- package/dist/src/builders/internal/Subqueries.d.ts.map +1 -1
- package/dist/src/builders/internal/Subqueries.js +3 -2
- package/dist/src/builders/internal/Subqueries.js.map +1 -1
- package/dist/src/builders/internal/Where.d.ts +2 -2
- package/dist/src/builders/internal/Where.d.ts.map +1 -1
- package/dist/src/builders/internal/Where.js +11 -9
- package/dist/src/builders/internal/Where.js.map +1 -1
- package/dist/src/builders/internal/With.js +1 -1
- package/dist/src/builders/internal/With.js.map +1 -1
- package/dist/src/builders/utils.js +1 -1
- package/dist/src/builders/utils.js.map +1 -1
- package/dist/src/client/Client.d.ts +1 -1
- package/dist/src/client/Client.d.ts.map +1 -1
- package/dist/src/client/Client.js.map +1 -1
- package/dist/src/client/Connection.d.ts +1 -1
- package/dist/src/client/Connection.d.ts.map +1 -1
- package/dist/src/client/Connection.js +10 -5
- package/dist/src/client/Connection.js.map +1 -1
- package/dist/src/client/EventManager.d.ts +4 -1
- package/dist/src/client/EventManager.d.ts.map +1 -1
- package/dist/src/client/EventManager.js +2 -0
- package/dist/src/client/EventManager.js.map +1 -1
- package/dist/src/client/SingleConnection.js +2 -2
- package/dist/src/client/SingleConnection.js.map +1 -1
- package/dist/src/client/Transaction.js +4 -4
- package/dist/src/client/Transaction.js.map +1 -1
- package/dist/src/client/execution.d.ts.map +1 -1
- package/dist/src/client/execution.js +3 -0
- package/dist/src/client/execution.js.map +1 -1
- package/dist/src/tsconfig.tsbuildinfo +1 -1
- package/dist/src/utils/ConstraintHelper.d.ts +2 -1
- package/dist/src/utils/ConstraintHelper.d.ts.map +1 -1
- package/dist/src/utils/ConstraintHelper.js +16 -8
- package/dist/src/utils/ConstraintHelper.js.map +1 -1
- package/dist/src/utils/sql.js +3 -3
- package/dist/src/utils/sql.js.map +1 -1
- package/dist/tests/cases/unit/queryBuilderTest.js +39 -38
- package/dist/tests/cases/unit/queryBuilderTest.js.map +1 -1
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/package.json +4 -4
- package/src/Literal.ts +1 -1
- package/src/builders/ColumnExpressionFactory.ts +3 -3
- package/src/builders/Compiler.ts +11 -5
- package/src/builders/ConditionBuilder.ts +69 -58
- package/src/builders/InsertBuilder.ts +49 -10
- package/src/builders/SelectBuilder.ts +3 -3
- package/src/builders/internal/Subqueries.ts +7 -5
- package/src/builders/internal/Where.ts +12 -10
- package/src/client/Client.ts +1 -1
- package/src/client/Connection.ts +8 -3
- package/src/client/EventManager.ts +5 -1
- package/src/client/execution.ts +4 -1
- package/src/utils/ConstraintHelper.ts +16 -8
- package/tests/cases/unit/queryBuilderTest.ts +7 -9
package/src/builders/Compiler.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { aliasLiteral, assertNever, prependSchema, wrapIdentifier } from '../utils'
|
|
2
2
|
import { SelectBuilder } from './SelectBuilder'
|
|
3
3
|
import { Literal } from '../Literal'
|
|
4
4
|
import { DeleteBuilder } from './DeleteBuilder'
|
|
@@ -227,16 +227,22 @@ class Compiler {
|
|
|
227
227
|
}
|
|
228
228
|
}
|
|
229
229
|
|
|
230
|
-
private compileOnConflictTarget(target?: InsertBuilder.
|
|
230
|
+
private compileOnConflictTarget(target?: InsertBuilder.ConflictTargetOptions) {
|
|
231
231
|
if (!target) {
|
|
232
232
|
return Literal.empty
|
|
233
233
|
}
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
234
|
+
const createColumnList = (columns: string[]) =>
|
|
235
|
+
Literal.empty.appendAll(
|
|
236
|
+
columns.map(it => new Literal(wrapIdentifier(it))),
|
|
237
237
|
', ',
|
|
238
238
|
['(', ')'],
|
|
239
239
|
)
|
|
240
|
+
|
|
241
|
+
if (Array.isArray(target)) {
|
|
242
|
+
return createColumnList(target)
|
|
243
|
+
}
|
|
244
|
+
if ('columns' in target) {
|
|
245
|
+
return createColumnList(target.columns).append(target.where.compile())
|
|
240
246
|
}
|
|
241
247
|
return new Literal('on constraint ' + wrapIdentifier(target.constraint))
|
|
242
248
|
}
|
|
@@ -4,8 +4,10 @@ import { QueryBuilder } from './QueryBuilder'
|
|
|
4
4
|
import { SelectBuilder } from './SelectBuilder'
|
|
5
5
|
import { toFqnWrap } from './formatUtils'
|
|
6
6
|
import { Compiler } from './Compiler'
|
|
7
|
+
import { createSubQueryLiteralFactory, SubQueryExpression } from './internal/Subqueries'
|
|
7
8
|
|
|
8
9
|
export type ConditionCallback = (builder: ConditionBuilder) => ConditionBuilder
|
|
10
|
+
export type ConditionExpression = ConditionBuilder | ConditionCallback
|
|
9
11
|
|
|
10
12
|
interface Raw {
|
|
11
13
|
sql: string
|
|
@@ -37,6 +39,8 @@ const likeOperators = [
|
|
|
37
39
|
Operator.endsWithCI,
|
|
38
40
|
]
|
|
39
41
|
|
|
42
|
+
const isReadonlyArray = (arr: any): arr is readonly any[] => Array.isArray(arr)
|
|
43
|
+
|
|
40
44
|
export class ConditionBuilder {
|
|
41
45
|
private constructor(public readonly expressions: Literal[]) {}
|
|
42
46
|
|
|
@@ -44,29 +48,24 @@ export class ConditionBuilder {
|
|
|
44
48
|
return new ConditionBuilder([])
|
|
45
49
|
}
|
|
46
50
|
|
|
47
|
-
public static
|
|
48
|
-
return
|
|
51
|
+
public static process(condition: ConditionExpression): ConditionBuilder {
|
|
52
|
+
return typeof condition === 'function' ? condition(ConditionBuilder.create()) : condition
|
|
49
53
|
}
|
|
50
54
|
|
|
51
|
-
|
|
52
|
-
return
|
|
55
|
+
public static not(condition: ConditionExpression): ConditionBuilder {
|
|
56
|
+
return ConditionBuilder.create().not(condition)
|
|
53
57
|
}
|
|
54
58
|
|
|
55
|
-
|
|
56
|
-
return this.
|
|
59
|
+
and(condition: ConditionExpression): ConditionBuilder {
|
|
60
|
+
return this.processConditionExpression(ConditionBuilder.process(condition), ['and', false])
|
|
57
61
|
}
|
|
58
62
|
|
|
59
|
-
|
|
60
|
-
return this.
|
|
63
|
+
or(condition: ConditionExpression): ConditionBuilder {
|
|
64
|
+
return this.processConditionExpression(ConditionBuilder.process(condition), ['or', false])
|
|
61
65
|
}
|
|
62
66
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
const sql = ConditionBuilder.createLiteral(builder.expressions, ...parameters)
|
|
66
|
-
if (sql) {
|
|
67
|
-
return new ConditionBuilder([...this.expressions, sql])
|
|
68
|
-
}
|
|
69
|
-
return this
|
|
67
|
+
not(condition: ConditionExpression): ConditionBuilder {
|
|
68
|
+
return this.processConditionExpression(ConditionBuilder.process(condition), ['and', true])
|
|
70
69
|
}
|
|
71
70
|
|
|
72
71
|
compare(columnName: QueryBuilder.ColumnIdentifier, operator: Operator, value: Value): ConditionBuilder {
|
|
@@ -80,47 +79,19 @@ export class ConditionBuilder {
|
|
|
80
79
|
}
|
|
81
80
|
value = value.replace(/([\\%_])/g, v => '\\' + v)
|
|
82
81
|
}
|
|
83
|
-
return this.with(new Literal(
|
|
82
|
+
return this.with(new Literal(ConditionBuilder.createOperatorSql(toFqnWrap(columnName), '?', operator), [value]))
|
|
84
83
|
}
|
|
85
84
|
|
|
86
85
|
columnsEq(columnName1: QueryBuilder.ColumnIdentifier, columnName2: QueryBuilder.ColumnIdentifier): ConditionBuilder {
|
|
87
86
|
return this.compareColumns(columnName1, Operator.eq, columnName2)
|
|
88
87
|
}
|
|
89
88
|
|
|
90
|
-
compareColumns(
|
|
91
|
-
|
|
92
|
-
operator: Operator,
|
|
93
|
-
columnName2: QueryBuilder.ColumnIdentifier,
|
|
94
|
-
) {
|
|
95
|
-
return this.with(new Literal(this.createOperatorSql(toFqnWrap(columnName1), toFqnWrap(columnName2), operator)))
|
|
89
|
+
compareColumns(columnName1: QueryBuilder.ColumnIdentifier, operator: Operator, columnName2: QueryBuilder.ColumnIdentifier) {
|
|
90
|
+
return this.with(new Literal(ConditionBuilder.createOperatorSql(toFqnWrap(columnName1), toFqnWrap(columnName2), operator)))
|
|
96
91
|
}
|
|
97
92
|
|
|
98
|
-
|
|
99
|
-
if (!
|
|
100
|
-
throw new Error(`Operator ${operator} is not supported`)
|
|
101
|
-
}
|
|
102
|
-
switch (operator) {
|
|
103
|
-
case Operator.contains:
|
|
104
|
-
return `${left} LIKE '%' || ${right} || '%'`
|
|
105
|
-
case Operator.containsCI:
|
|
106
|
-
return `${left} ILIKE '%' || ${right} || '%'`
|
|
107
|
-
case Operator.startsWith:
|
|
108
|
-
return `${left} LIKE ${right} || '%'`
|
|
109
|
-
case Operator.startsWithCI:
|
|
110
|
-
return `${left} ILIKE ${right} || '%'`
|
|
111
|
-
case Operator.endsWith:
|
|
112
|
-
return `${left} LIKE '%' || ${right}`
|
|
113
|
-
case Operator.endsWithCI:
|
|
114
|
-
return `${left} ILIKE '%' || ${right}`
|
|
115
|
-
}
|
|
116
|
-
return `${left} ${operator} ${right}`
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
in(
|
|
120
|
-
columnName: QueryBuilder.ColumnIdentifier,
|
|
121
|
-
values: Value[] | SelectBuilder<SelectBuilder.Result>,
|
|
122
|
-
): ConditionBuilder {
|
|
123
|
-
if (!Array.isArray(values)) {
|
|
93
|
+
in(columnName: QueryBuilder.ColumnIdentifier, values: ReadonlyArray<Value> | SelectBuilder<SelectBuilder.Result>): ConditionBuilder {
|
|
94
|
+
if (!isReadonlyArray(values)) {
|
|
124
95
|
// todo: replace placeholder with some kind of callback
|
|
125
96
|
const query = values.createQuery(new Compiler.Context(Compiler.SCHEMA_PLACEHOLDER, new Set()))
|
|
126
97
|
return this.with(new Literal(`${toFqnWrap(columnName)} in (${query.sql})`, query.parameters))
|
|
@@ -133,10 +104,25 @@ export class ConditionBuilder {
|
|
|
133
104
|
return this.raw('false')
|
|
134
105
|
}
|
|
135
106
|
|
|
136
|
-
|
|
107
|
+
exists(subQuery: SubQueryExpression<SelectBuilder>): ConditionBuilder {
|
|
108
|
+
const context = new Compiler.Context(Compiler.SCHEMA_PLACEHOLDER, new Set())
|
|
109
|
+
const query = createSubQueryLiteralFactory<SelectBuilder>(subQuery)(context, subQuery => {
|
|
110
|
+
if (subQuery.options.select.length === 0) {
|
|
111
|
+
return subQuery.select(expr => expr.raw('?::int', 1))
|
|
112
|
+
}
|
|
113
|
+
return subQuery
|
|
114
|
+
})
|
|
115
|
+
return this.with(new Literal(`exists (${query.sql})`, query.parameters))
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
isNull(columnName: QueryBuilder.ColumnIdentifier): ConditionBuilder {
|
|
137
119
|
return this.with(new Literal(`${toFqnWrap(columnName)} is null`))
|
|
138
120
|
}
|
|
139
121
|
|
|
122
|
+
isNotNull(columnName: QueryBuilder.ColumnIdentifier): ConditionBuilder {
|
|
123
|
+
return this.with(new Literal(`${toFqnWrap(columnName)} is not null`))
|
|
124
|
+
}
|
|
125
|
+
|
|
140
126
|
raw(sql: string, ...bindings: Value[]): ConditionBuilder {
|
|
141
127
|
return this.with(new Literal(sql, bindings))
|
|
142
128
|
}
|
|
@@ -152,11 +138,40 @@ export class ConditionBuilder {
|
|
|
152
138
|
return ConditionBuilder.createLiteral(this.expressions)
|
|
153
139
|
}
|
|
154
140
|
|
|
155
|
-
|
|
156
|
-
expressions
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
141
|
+
isEmpty(): boolean {
|
|
142
|
+
return this.expressions.length === 0
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
private processConditionExpression(builder: ConditionBuilder, parameters: ['and' | 'or', boolean]): ConditionBuilder {
|
|
146
|
+
const sql = ConditionBuilder.createLiteral(builder.expressions, ...parameters)
|
|
147
|
+
if (sql) {
|
|
148
|
+
return new ConditionBuilder([...this.expressions, sql])
|
|
149
|
+
}
|
|
150
|
+
return this
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
private static createOperatorSql(left: string, right: string, operator: Operator): string {
|
|
154
|
+
if (!Object.values(Operator).includes(operator)) {
|
|
155
|
+
throw new Error(`Operator ${operator} is not supported`)
|
|
156
|
+
}
|
|
157
|
+
switch (operator) {
|
|
158
|
+
case Operator.contains:
|
|
159
|
+
return `${left} LIKE '%' || ${right} || '%'`
|
|
160
|
+
case Operator.containsCI:
|
|
161
|
+
return `${left} ILIKE '%' || ${right} || '%'`
|
|
162
|
+
case Operator.startsWith:
|
|
163
|
+
return `${left} LIKE ${right} || '%'`
|
|
164
|
+
case Operator.startsWithCI:
|
|
165
|
+
return `${left} ILIKE ${right} || '%'`
|
|
166
|
+
case Operator.endsWith:
|
|
167
|
+
return `${left} LIKE '%' || ${right}`
|
|
168
|
+
case Operator.endsWithCI:
|
|
169
|
+
return `${left} ILIKE '%' || ${right}`
|
|
170
|
+
}
|
|
171
|
+
return `${left} ${operator} ${right}`
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
private static createLiteral(expressions: Literal[], operator: 'or' | 'and' = 'and', not: boolean = false): Literal | null {
|
|
160
175
|
if (expressions.length === 0) {
|
|
161
176
|
return null
|
|
162
177
|
}
|
|
@@ -167,8 +182,4 @@ export class ConditionBuilder {
|
|
|
167
182
|
|
|
168
183
|
return new Literal(not ? `not(${sql})` : operator === 'or' ? `(${sql})` : sql, bindings)
|
|
169
184
|
}
|
|
170
|
-
|
|
171
|
-
isEmpty(): boolean {
|
|
172
|
-
return this.expressions.length === 0
|
|
173
|
-
}
|
|
174
185
|
}
|
|
@@ -42,7 +42,10 @@ class InsertBuilder<Result extends InsertBuilder.InsertResult> implements With.A
|
|
|
42
42
|
values: QueryBuilder.Values,
|
|
43
43
|
where?: Where.Expression,
|
|
44
44
|
): InsertBuilder<Result>
|
|
45
|
-
public onConflict(
|
|
45
|
+
public onConflict(
|
|
46
|
+
action: ConflictActionType.doNothing,
|
|
47
|
+
target?: InsertBuilder.ConflictTarget,
|
|
48
|
+
): InsertBuilder<Result>
|
|
46
49
|
public onConflict(
|
|
47
50
|
action: ConflictActionType,
|
|
48
51
|
target?: InsertBuilder.ConflictTarget,
|
|
@@ -50,16 +53,36 @@ class InsertBuilder<Result extends InsertBuilder.InsertResult> implements With.A
|
|
|
50
53
|
where?: Where.Expression,
|
|
51
54
|
): InsertBuilder<Result> {
|
|
52
55
|
let conflictAction: InsertBuilder.ConflictAction
|
|
53
|
-
|
|
56
|
+
const conflictTarget: InsertBuilder.ConflictTargetOptions | undefined = (() => {
|
|
57
|
+
if (!target) {
|
|
58
|
+
return undefined
|
|
59
|
+
}
|
|
60
|
+
if (Array.isArray(target)) {
|
|
61
|
+
return {
|
|
62
|
+
columns: target,
|
|
63
|
+
where: new Where.Statement([]),
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if ('constraint' in target) {
|
|
67
|
+
return target
|
|
68
|
+
}
|
|
69
|
+
const whereStm = new Where.Statement([])
|
|
70
|
+
return {
|
|
71
|
+
columns: target.columns,
|
|
72
|
+
where: target.where ? whereStm.withWhere(target.where) : whereStm,
|
|
73
|
+
}
|
|
74
|
+
})()
|
|
75
|
+
|
|
76
|
+
if (action === ConflictActionType.update && values && conflictTarget) {
|
|
54
77
|
const whereStm = new Where.Statement([])
|
|
55
78
|
conflictAction = {
|
|
56
79
|
type: action,
|
|
57
80
|
values: resolveValues(values),
|
|
58
|
-
target,
|
|
81
|
+
target: conflictTarget,
|
|
59
82
|
where: where ? whereStm.withWhere(where) : whereStm,
|
|
60
83
|
}
|
|
61
84
|
} else if (action === ConflictActionType.doNothing) {
|
|
62
|
-
conflictAction = { type: action, target }
|
|
85
|
+
conflictAction = { type: action, target: conflictTarget }
|
|
63
86
|
} else {
|
|
64
87
|
throw Error()
|
|
65
88
|
}
|
|
@@ -128,16 +151,32 @@ namespace InsertBuilder {
|
|
|
128
151
|
values: Exclude<Options['values'], undefined>
|
|
129
152
|
}
|
|
130
153
|
|
|
131
|
-
export type
|
|
132
|
-
| {
|
|
133
|
-
|
|
|
154
|
+
export type ConflictTargetOptions =
|
|
155
|
+
| ({ columns: IndexColumns} & Where.Options)
|
|
156
|
+
| { constraint: string }
|
|
157
|
+
|
|
158
|
+
type DoNothingConflictAction = {
|
|
159
|
+
type: ConflictActionType.doNothing
|
|
160
|
+
target?: ConflictTargetOptions
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
type DoUpdateConflictAction =
|
|
164
|
+
& Where.Options
|
|
165
|
+
& {
|
|
134
166
|
type: ConflictActionType.update
|
|
135
167
|
values: QueryBuilder.ResolvedValues
|
|
136
|
-
target:
|
|
137
|
-
|
|
168
|
+
target: ConflictTargetOptions
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export type ConflictAction =
|
|
172
|
+
| DoNothingConflictAction
|
|
173
|
+
| DoUpdateConflictAction
|
|
138
174
|
|
|
139
175
|
export type IndexColumns = string[]
|
|
140
|
-
export type ConflictTarget =
|
|
176
|
+
export type ConflictTarget =
|
|
177
|
+
| IndexColumns
|
|
178
|
+
| { columns: IndexColumns; where?: Where.Expression }
|
|
179
|
+
| { constraint: string }
|
|
141
180
|
}
|
|
142
181
|
|
|
143
182
|
export { InsertBuilder }
|
|
@@ -5,7 +5,7 @@ import { Compiler } from './Compiler'
|
|
|
5
5
|
import { QueryBuilder } from './QueryBuilder'
|
|
6
6
|
import { Client, Connection } from '../client'
|
|
7
7
|
import { Literal } from '../Literal'
|
|
8
|
-
import { ConditionBuilder, ConditionCallback } from './ConditionBuilder'
|
|
8
|
+
import { ConditionBuilder, ConditionCallback, ConditionExpression } from './ConditionBuilder'
|
|
9
9
|
import { LockType } from './LockType'
|
|
10
10
|
import { columnExpressionToLiteral, toFqnWrap } from './utils'
|
|
11
11
|
import { createSubQueryLiteralFactory, SubQueryExpression, SubQueryLiteralFactory } from './internal/Subqueries'
|
|
@@ -113,7 +113,7 @@ class SelectBuilder<Result = SelectBuilder.Result> implements With.Aware, Where.
|
|
|
113
113
|
if (joinCondition === undefined) {
|
|
114
114
|
return undefined
|
|
115
115
|
}
|
|
116
|
-
const builder = ConditionBuilder.
|
|
116
|
+
const builder = ConditionBuilder.process(joinCondition)
|
|
117
117
|
|
|
118
118
|
return builder.getSql() || undefined
|
|
119
119
|
}
|
|
@@ -202,7 +202,7 @@ namespace SelectBuilder {
|
|
|
202
202
|
}
|
|
203
203
|
>
|
|
204
204
|
|
|
205
|
-
export type JoinCondition =
|
|
205
|
+
export type JoinCondition = ConditionExpression
|
|
206
206
|
}
|
|
207
207
|
|
|
208
208
|
export { SelectBuilder }
|
|
@@ -3,14 +3,16 @@ import { Literal } from '../../Literal'
|
|
|
3
3
|
import { SelectBuilder } from '../SelectBuilder'
|
|
4
4
|
import { QueryBuilder } from '../QueryBuilder'
|
|
5
5
|
|
|
6
|
-
export type SubQueryLiteralFactory = (context: Compiler.Context) => Literal
|
|
7
|
-
export type SubQueryExpression = SelectBuilder.Callback | Literal |
|
|
6
|
+
export type SubQueryLiteralFactory<Builder extends QueryBuilder = QueryBuilder> = (context: Compiler.Context, preprocessor?: (query: SelectBuilder | Builder) => QueryBuilder) => Literal
|
|
7
|
+
export type SubQueryExpression<Builder extends QueryBuilder = QueryBuilder> = SelectBuilder.Callback | Literal | Builder
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
const noop = <T>(value: T): T => value
|
|
10
|
+
|
|
11
|
+
export function createSubQueryLiteralFactory<Builder extends QueryBuilder = QueryBuilder>(expr: SubQueryExpression<Builder>): SubQueryLiteralFactory<Builder> {
|
|
10
12
|
if (typeof expr === 'function') {
|
|
11
|
-
return ctx => expr(SelectBuilder.create()).createQuery(ctx)
|
|
13
|
+
return (ctx, preprocessor) => (preprocessor ?? noop)(expr(SelectBuilder.create())).createQuery(ctx)
|
|
12
14
|
} else if (((expr: any): expr is QueryBuilder => 'createQuery' in expr)(expr)) {
|
|
13
|
-
return ctx => expr.createQuery(ctx)
|
|
15
|
+
return (ctx, preprocessor) => ((preprocessor ?? noop)(expr)).createQuery(ctx)
|
|
14
16
|
} else {
|
|
15
17
|
return () => expr
|
|
16
18
|
}
|
|
@@ -12,15 +12,11 @@ namespace Where {
|
|
|
12
12
|
constructor(public readonly values: (Literal | ValueWhere)[]) {}
|
|
13
13
|
|
|
14
14
|
public withWhere(expression: Expression): Statement {
|
|
15
|
-
if (typeof expression
|
|
16
|
-
|
|
15
|
+
if (typeof expression === 'function' || expression instanceof ConditionBuilder) {
|
|
16
|
+
const sql = ConditionBuilder.process(expression).getSql()
|
|
17
|
+
return sql ? this.withWhere(sql) : this
|
|
17
18
|
}
|
|
18
|
-
|
|
19
|
-
const sql = builder.getSql()
|
|
20
|
-
if (!sql) {
|
|
21
|
-
return this
|
|
22
|
-
}
|
|
23
|
-
return new Statement([...this.values, sql])
|
|
19
|
+
return new Statement([...this.values, expression])
|
|
24
20
|
}
|
|
25
21
|
|
|
26
22
|
public compile(): Literal {
|
|
@@ -30,7 +26,13 @@ namespace Where {
|
|
|
30
26
|
|
|
31
27
|
const valueWhereToLiteral = (where: Where.ValueWhere): Literal =>
|
|
32
28
|
new Literal('').appendAll(
|
|
33
|
-
Object.keys(where).map(it =>
|
|
29
|
+
Object.keys(where).map(it => {
|
|
30
|
+
const identifier = wrapIdentifier(it)
|
|
31
|
+
if (where[it] === null) {
|
|
32
|
+
return new Literal(`${identifier} is null`)
|
|
33
|
+
}
|
|
34
|
+
return new Literal(`${identifier} = ?`, [where[it]])
|
|
35
|
+
}),
|
|
34
36
|
' and ',
|
|
35
37
|
)
|
|
36
38
|
|
|
@@ -50,7 +52,7 @@ namespace Where {
|
|
|
50
52
|
}
|
|
51
53
|
|
|
52
54
|
export type ValueWhere = { [columnName: string]: Value }
|
|
53
|
-
export type Expression = ValueWhere | ConditionCallback | Literal
|
|
55
|
+
export type Expression = ValueWhere | ConditionCallback | ConditionBuilder | Literal
|
|
54
56
|
}
|
|
55
57
|
|
|
56
58
|
export { Where }
|
package/src/client/Client.ts
CHANGED
|
@@ -43,7 +43,7 @@ class Client<ConnectionType extends Connection.ConnectionLike = Connection.Conne
|
|
|
43
43
|
|
|
44
44
|
async query<Row extends Record<string, any>>(
|
|
45
45
|
sql: string,
|
|
46
|
-
parameters: any[] = [],
|
|
46
|
+
parameters: readonly any[] = [],
|
|
47
47
|
meta: Record<string, any> = {},
|
|
48
48
|
config: Connection.QueryConfig = {},
|
|
49
49
|
): Promise<Connection.Result<Row>> {
|
package/src/client/Connection.ts
CHANGED
|
@@ -13,6 +13,11 @@ class Connection implements Connection.ConnectionLike, Connection.ClientFactory,
|
|
|
13
13
|
public readonly eventManager: EventManager = new EventManagerImpl(),
|
|
14
14
|
) {
|
|
15
15
|
this.pool = new Pool(config)
|
|
16
|
+
this.pool.on('error', err => {
|
|
17
|
+
// eslint-disable-next-line no-console
|
|
18
|
+
console.error(err)
|
|
19
|
+
this.eventManager.fire(EventManager.Event.clientError, err)
|
|
20
|
+
})
|
|
16
21
|
}
|
|
17
22
|
|
|
18
23
|
public createClient(schema: string, queryMeta: Record<string, any>): Client {
|
|
@@ -38,7 +43,7 @@ class Connection implements Connection.ConnectionLike, Connection.ClientFactory,
|
|
|
38
43
|
return result
|
|
39
44
|
} catch (e) {
|
|
40
45
|
await transaction.rollbackUnclosed()
|
|
41
|
-
client.release(e)
|
|
46
|
+
client.release(e as Error)
|
|
42
47
|
throw e
|
|
43
48
|
}
|
|
44
49
|
}
|
|
@@ -60,7 +65,7 @@ class Connection implements Connection.ConnectionLike, Connection.ClientFactory,
|
|
|
60
65
|
client.release()
|
|
61
66
|
return result
|
|
62
67
|
} catch (e) {
|
|
63
|
-
client.release(e)
|
|
68
|
+
client.release(e as Error)
|
|
64
69
|
throw e
|
|
65
70
|
}
|
|
66
71
|
}
|
|
@@ -85,7 +90,7 @@ namespace Connection {
|
|
|
85
90
|
|
|
86
91
|
query<Row extends Record<string, any>>(
|
|
87
92
|
sql: string,
|
|
88
|
-
parameters?: any[],
|
|
93
|
+
parameters?: readonly any[],
|
|
89
94
|
meta?: Record<string, any>,
|
|
90
95
|
config?: Connection.QueryConfig,
|
|
91
96
|
): Promise<Connection.Result<Row>>
|
|
@@ -5,6 +5,7 @@ export class EventManagerImpl {
|
|
|
5
5
|
[EventManager.Event.queryStart]: [] as EventManager.QueryStartCallback[],
|
|
6
6
|
[EventManager.Event.queryEnd]: [] as EventManager.QueryEndCallback[],
|
|
7
7
|
[EventManager.Event.queryError]: [] as EventManager.QueryStartCallback[],
|
|
8
|
+
[EventManager.Event.clientError]: [] as EventManager.ClientErrorCallback[],
|
|
8
9
|
}
|
|
9
10
|
|
|
10
11
|
constructor(private readonly parent: EventManager | null = null) {}
|
|
@@ -26,7 +27,7 @@ export class EventManagerImpl {
|
|
|
26
27
|
event: EventManager.Event,
|
|
27
28
|
cb: EventManager.ListenerTypes[Event],
|
|
28
29
|
): void {
|
|
29
|
-
this.listeners[event] = this.listeners[event].filter(it => it !== cb) as any[]
|
|
30
|
+
this.listeners[event] = (this.listeners[event] as EventManager.ListenerTypes[Event][]).filter(it => it !== cb) as any[]
|
|
30
31
|
}
|
|
31
32
|
}
|
|
32
33
|
|
|
@@ -37,16 +38,19 @@ namespace EventManager {
|
|
|
37
38
|
queryStart = 'queryStart',
|
|
38
39
|
queryEnd = 'queryEnd',
|
|
39
40
|
queryError = 'queryError',
|
|
41
|
+
clientError = 'clientError',
|
|
40
42
|
}
|
|
41
43
|
|
|
42
44
|
export type QueryStartCallback = (query: Connection.Query) => void
|
|
43
45
|
export type QueryEndCallback = (query: Connection.Query, result: Connection.Result) => void
|
|
44
46
|
export type QueryErrorCallback = (query: Connection.Query, error: Error) => void
|
|
47
|
+
export type ClientErrorCallback = (error: Error) => void
|
|
45
48
|
|
|
46
49
|
export interface ListenerTypes {
|
|
47
50
|
[EventManager.Event.queryStart]: QueryStartCallback
|
|
48
51
|
[EventManager.Event.queryEnd]: QueryEndCallback
|
|
49
52
|
[EventManager.Event.queryError]: QueryErrorCallback
|
|
53
|
+
[EventManager.Event.clientError]: ClientErrorCallback
|
|
50
54
|
}
|
|
51
55
|
|
|
52
56
|
export type ListenersList = { [T in keyof ListenerTypes]: ListenerTypes[T][] }
|
package/src/client/execution.ts
CHANGED
|
@@ -58,9 +58,12 @@ export async function executeQuery<Row extends Record<string, any>>(
|
|
|
58
58
|
|
|
59
59
|
return result
|
|
60
60
|
} catch (error) {
|
|
61
|
+
if (!(error instanceof Error)) {
|
|
62
|
+
throw error
|
|
63
|
+
}
|
|
61
64
|
eventManager.fire(EventManager.Event.queryError, { sql, parameters, meta }, error)
|
|
62
65
|
|
|
63
|
-
switch (error.code) {
|
|
66
|
+
switch ((error as any).code) {
|
|
64
67
|
case '23502':
|
|
65
68
|
throw new NotNullViolationError(sql, parameters, error)
|
|
66
69
|
case '23503':
|
|
@@ -2,15 +2,24 @@ import { Client } from '../client'
|
|
|
2
2
|
import { wrapIdentifier } from './sql'
|
|
3
3
|
|
|
4
4
|
export class ConstraintHelper {
|
|
5
|
-
private
|
|
5
|
+
private fkConstraintNames: string[] | null = null
|
|
6
|
+
private fkConstraintsLevel = 0
|
|
6
7
|
|
|
7
8
|
constructor(private readonly client: Client) {}
|
|
8
9
|
|
|
9
10
|
public async setFkConstraintsDeferred(): Promise<void> {
|
|
11
|
+
this.fkConstraintsLevel++
|
|
12
|
+
if (this.fkConstraintsLevel > 1) {
|
|
13
|
+
return
|
|
14
|
+
}
|
|
10
15
|
return await this.setFkConstraintsPolicy('DEFERRED')
|
|
11
16
|
}
|
|
12
17
|
|
|
13
18
|
public async setFkConstraintsImmediate(): Promise<void> {
|
|
19
|
+
this.fkConstraintsLevel--
|
|
20
|
+
if (this.fkConstraintsLevel > 0) {
|
|
21
|
+
return
|
|
22
|
+
}
|
|
14
23
|
return await this.setFkConstraintsPolicy('IMMEDIATE')
|
|
15
24
|
}
|
|
16
25
|
|
|
@@ -20,18 +29,17 @@ export class ConstraintHelper {
|
|
|
20
29
|
}
|
|
21
30
|
|
|
22
31
|
private async formatConstraints(): Promise<string> {
|
|
23
|
-
if (this.
|
|
24
|
-
this.
|
|
32
|
+
if (this.fkConstraintNames === null) {
|
|
33
|
+
this.fkConstraintNames = (
|
|
25
34
|
await this.client.query<{ name: string }>(
|
|
26
35
|
`SELECT con.conname AS name
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
WHERE nsp.nspname = ? and con.condeferrable = true and contype = ?`,
|
|
36
|
+
FROM pg_catalog.pg_constraint con
|
|
37
|
+
INNER JOIN pg_catalog.pg_namespace nsp ON nsp.oid = connamespace
|
|
38
|
+
WHERE nsp.nspname = ? and con.condeferrable = true and contype = ?`,
|
|
31
39
|
[this.client.schema, 'f'],
|
|
32
40
|
)
|
|
33
41
|
).rows.map(it => it.name)
|
|
34
42
|
}
|
|
35
|
-
return this.
|
|
43
|
+
return this.fkConstraintNames.map(it => `${wrapIdentifier(this.client.schema)}.${wrapIdentifier(it)}`).join(', ')
|
|
36
44
|
}
|
|
37
45
|
}
|
|
@@ -44,11 +44,9 @@ test('query builder: constructs condition', async () => {
|
|
|
44
44
|
.compare('l', Operator.endsWithCI, 'Z')
|
|
45
45
|
.compareColumns('z', Operator.eq, ['foo', 'x'])
|
|
46
46
|
.in('o', [1, 2, 3])
|
|
47
|
-
.in(
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
)
|
|
51
|
-
.null('n')
|
|
47
|
+
.in('m', wrapper.selectBuilder().select(expr => expr.selectValue(1)))
|
|
48
|
+
.exists(it => it)
|
|
49
|
+
.isNull('n')
|
|
52
50
|
.raw('false'),
|
|
53
51
|
)
|
|
54
52
|
|
|
@@ -59,8 +57,8 @@ test('query builder: constructs condition', async () => {
|
|
|
59
57
|
where "a" = ? and "b" != ? and "c" < ? and "d" <= ? and "e" > ? and "f" >= ?
|
|
60
58
|
and "g" like '%' || ? || '%' and "h" like ? || '%' and "i" like '%' || ?
|
|
61
59
|
and "j" ilike '%' || ? || '%' and "k" ilike ? || '%' and "l" ilike '%' || ?
|
|
62
|
-
and "z" = "foo"."x" and "o" in (?, ?, ?) and "m" in (select ?) and "n" is null and false`,
|
|
63
|
-
parameters: [1, 2, 3, 4, 5, 6, 'foo\\\\\\%bar', 'lorem\\_ipsum', 'dolor\\%sit', 'X', 'Y', 'Z', 1, 2, 3, 1],
|
|
60
|
+
and "z" = "foo"."x" and "o" in (?, ?, ?) and "m" in (select ?) and exists (select ?::int) and "n" is null and false`,
|
|
61
|
+
parameters: [1, 2, 3, 4, 5, 6, 'foo\\\\\\%bar', 'lorem\\_ipsum', 'dolor\\%sit', 'X', 'Y', 'Z', 1, 2, 3, 1, 1],
|
|
64
62
|
})
|
|
65
63
|
})
|
|
66
64
|
|
|
@@ -82,8 +80,8 @@ test('query builder: construct "on"', async () => {
|
|
|
82
80
|
.and(clause =>
|
|
83
81
|
clause
|
|
84
82
|
.in(['bar', 'c'], [1, 2, 3])
|
|
85
|
-
.
|
|
86
|
-
.not(clause => clause.
|
|
83
|
+
.isNull(['bar', 'd'])
|
|
84
|
+
.not(clause => clause.isNull(['bar', 'd']))
|
|
87
85
|
.compareColumns(['bar', 'e'], Operator.lte, ['bar', 'f']),
|
|
88
86
|
),
|
|
89
87
|
)
|