-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathknex.ts
314 lines (299 loc) · 9.28 KB
/
knex.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
import { pipeFromFilter } from '@wholebuzz/fs/lib/stream'
import byline from 'byline'
import { getClientType } from 'db-json-column/lib/knex'
import {
defaultSplitterOptions,
mssqlSplitterOptions,
mysqlSplitterOptions,
postgreSplitterOptions,
sqliteSplitterOptions,
} from 'dbgate-query-splitter/lib/options'
import { SplitQueryStream } from 'dbgate-query-splitter/lib/splitQueryStream'
import { Knex } from 'knex'
import schemaInspector from 'knex-schema-inspector'
import { Column } from 'knex-schema-inspector/dist/types/column'
import { Transform } from 'stream'
import StreamTree, { pumpWritable, ReadableStreamTree, WritableStreamTree } from 'tree-stream'
import { streamToKnexCompoundInsert } from './compound'
import { DatabaseCopyShardFunction, DatabaseCopyTransformFactory } from './format'
export const batch2 = require('batch2')
export async function dumpToKnex(
input: ReadableStreamTree,
db: Knex,
table: string,
options?: { compoundInsert?: boolean; batchSize?: number; returning?: string }
) {
if (!table && !options?.compoundInsert) input.node.stream.setEncoding('utf8')
await db.transaction(async (transaction) => {
const output = options?.compoundInsert
? streamToKnexCompoundInsert({ transaction }, { ...options })
: table
? streamToKnex({ transaction }, { table, ...options })
: streamToKnexRaw({ transaction })
await pumpWritable(output, undefined, input)
return transaction.commit().catch(transaction.rollback)
})
}
export function queryKnex(
db: Knex,
table: string,
options: {
limit?: number
orderBy?: string[]
query?: string
inputShardBy?: string
inputShardFunction?: DatabaseCopyShardFunction
inputShardIndex?: number
inputShards?: number
transformObject?: (x: unknown) => unknown
transformObjectStream?: DatabaseCopyTransformFactory
where?: Array<string | any[]>
}
) {
let input
if (options.query) {
input = StreamTree.readable(db.raw(options.query).stream())
} else {
let query = db(table)
for (const where of options.where ?? []) {
query = Array.isArray(where)
? query.where(where[0], where[1], where[2])
: query.where(db.raw(where))
}
if (options.inputShardBy && options.inputShards && options.inputShardIndex !== undefined) {
const clientType = getClientType(db)
query = query.where(
db.raw(
`${(options.inputShardFunction === DatabaseCopyShardFunction.number
? shardNumberSQL
: shardMd5LswSQL)(clientType, options.inputShardBy, options.inputShards)} = ${
options.inputShardIndex
}`
)
)
}
for (const orderBy of options.orderBy ?? []) {
query = query.orderByRaw(orderBy)
}
if (options.limit) query.limit(options.limit)
input = streamFromKnex(query)
}
return input
}
export function streamFromKnex(query: Knex.QueryBuilder): ReadableStreamTree {
return StreamTree.readable(query.stream())
}
export function streamToKnex(
source: {
knex?: Knex
transaction?: Knex.Transaction
},
options: {
table: string
batchSize?: number
returning?: string
}
) {
const stream = StreamTree.writable(
new Transform({
objectMode: true,
transform(data: any[], _: string, callback: () => void) {
let query = source.transaction
? source.transaction.batchInsert(options.table, data)
: source.knex!.batchInsert(options.table, data)
if (options.returning) query = query.returning(options.returning)
if (source.transaction) query = query.transacting(source.transaction)
query
.then((result) => {
if (options.returning) this.push(result)
callback()
})
.catch((err) => {
throw err
})
},
})
)
return stream.pipeFrom(batch2.obj({ size: options.batchSize ?? 4000 }))
}
export function streamToKnexRaw(
source: {
knex?: Knex
transaction?: Knex.Transaction
},
options?: { returning?: boolean }
) {
let stream = StreamTree.writable(
new Transform({
objectMode: true,
transform(data: string, _: string, callback: () => void) {
const text = data.replace(/\?/g, '\\?')
const query = source.transaction ? source.transaction.raw(text) : source.knex!.raw(text)
query
.then((result) => {
if (options?.returning) this.push(result)
callback()
})
.catch((err) => {
throw err
})
},
})
)
stream = stream.pipeFrom(
newDBGateQuerySplitterStream(
((source.transaction || source.knex) as any).context.client.config.client
)
)
stream = stream.pipeFrom(byline.createStream())
return stream
}
export function pipeKnexInsertTextTransform(
output: WritableStreamTree,
knex?: Knex,
tableName?: string
) {
return pipeFromFilter(output, (x) => {
const insert = { ...x }
for (const key of Object.keys(insert)) {
const val = insert[key]
if (val === null || val === undefined) {
continue
} else if (val instanceof Date) {
insert[key] = val.toISOString()
} else if (typeof val === 'object') {
insert[key] = JSON.stringify(val)
}
}
const ret =
knex
?.table(tableName ?? '')
.insert(insert)
.toString() + ';\n'
return ret
})
}
export async function knexInspectCreateTableSchema(
inputKnex: Knex,
outputKnex: Knex,
tableName: string
) {
const columnsInfo = await knexInspectTableSchema(inputKnex, tableName)
return knexFormatCreateTableSchema(outputKnex, tableName, columnsInfo)
}
export async function knexInspectTableSchema(inputKnex: Knex, tableName: string) {
return schemaInspector(inputKnex).columnInfo(tableName)
}
export function knexFormatCreateTableSchema(
outputKnex: Knex,
tableName: string,
columnsInfo: Column[],
columnType?: Record<string, string>
) {
const clientType = getClientType(outputKnex)
return (
outputKnex.schema
.createTableIfNotExists(tableName ?? '', (t) => {
for (const columnInfo of columnsInfo) {
const type = columnType?.[columnInfo.name] || columnInfo.data_type
let column
switch (type) {
case 'boolean':
column = t.boolean(columnInfo.name)
break
case 'int':
case 'integer':
column = t.integer(columnInfo.name)
break
case 'double precision':
case 'float':
column = t.float(columnInfo.name)
break
case 'datetime':
case 'datetime2':
case 'timestamp with time zone':
column = t.dateTime(columnInfo.name, { precision: 6 })
break
case 'json':
column = clientType === 'mssql' ? t.text(columnInfo.name) : t.json(columnInfo.name)
break
case 'jsonb':
column = clientType === 'mssql' ? t.text(columnInfo.name) : t.jsonb(columnInfo.name)
break
case 'character varying':
case 'nvarchar':
case 'text':
column = t.text(columnInfo.name)
break
}
if (!column) continue
if (columnInfo.is_primary_key) column = column.primary()
if (columnInfo.is_unique) column = column.unique()
// if (columnInfo.is_nullable) column = column.nullable()
if (columnInfo.is_nullable === false) column = column.notNullable()
}
})
.toString() + ';\n'
)
}
export function newDBGateQuerySplitterStream(type?: any) {
switch (type) {
case 'postgresql':
return new SplitQueryStream(postgreSplitterOptions)
case 'mysql':
return new SplitQueryStream(mysqlSplitterOptions)
case 'mssql':
return new SplitQueryStream(mssqlSplitterOptions)
case 'sqlite':
return new SplitQueryStream(sqliteSplitterOptions)
default:
return new SplitQueryStream(defaultSplitterOptions)
}
}
export function shardNumberSQL(client: string, column: string, modulus: string | number) {
switch (client) {
case 'mssql':
return `(${column} % ${modulus})`
case 'mysql':
case 'postgres':
return `mod(${column}, ${modulus})`
default:
throw new Error(`shardIntegerSQL unsupported ${client}`)
}
}
export function shardMd5LswSQL(client: string, column: string, modulus: string | number) {
switch (client) {
case 'mssql':
return `((CAST(HASHBYTES('MD5', ${column}) AS int) & 0xffff) % ${column})`
case 'mysql':
return `mod(conv(right(md5(${column}), 4), 16, 10), ${column})`
case 'postgresql':
return `mod(('x' || right(md5(${column}), 4))::bit(16)::int, ${modulus})`
default:
throw new Error(`shardTextSQL unsupported ${client}`)
}
}
export const knexLogConfig = {
warn(_message: any) {
/* */
},
error(_message: any) {
/* */
},
deprecate(_message: any) {
/* */
},
debug(_message: any) {
/* */
},
}
export const knexPoolConfig = {
// https://github.com/Vincit/tarn.js/blob/master/src/Pool.ts
// https://github.com/GoogleCloudPlatform/nodejs-docs-samples/blob/master/cloud-sql/postgres/knex/server.js
acquireTimeoutMillis: 60000,
createRetryIntervalMillis: 200,
createTimeoutMillis: 30000,
idleTimeoutMillis: 600000,
min: 1,
max: 1,
}