-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.ts
92 lines (79 loc) · 2.35 KB
/
helpers.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
import type { mssqlTypes } from '@cityssm/mssql-multi-pool'
/**
*
* @param columnMetadata - Column metadata from a source database.
* @returns Column lists for creating and inserting records.
*/
export function buildColumnLists(
columnMetadata: Array<
mssqlTypes.IColumnMetadata[keyof mssqlTypes.IColumnMetadata]
>
): { create: string; insert: string; parameters: string } {
const create: string[] = []
const insert: string[] = []
const parameters: string[] = []
for (const [columnIndex, column] of Object.entries(columnMetadata)) {
create.push(columnMetadataToCreateString(column))
insert.push(`[${column.name}]`)
parameters.push(`@${columnIndex}`)
}
return {
create: create.join(', '),
insert: insert.join(', '),
parameters: parameters.join(', ')
}
}
function columnMetadataToCreateString(
columnMetadata: mssqlTypes.IColumnMetadata[keyof mssqlTypes.IColumnMetadata]
): string {
console.log(columnMetadata)
const createStringPieces = [`[${columnMetadata.name}]`]
const columnType = (
typeof columnMetadata.type === 'function'
? columnMetadata.type()
: columnMetadata.type
) as mssqlTypes.ISqlType | undefined
const columnTypeName =
columnType === undefined
? 'VarChar'
: (columnType.type as { name: keyof typeof mssqlTypes.TYPES }).name
switch (columnTypeName) {
case 'Char':
case 'NChar':
case 'VarChar':
case 'NVarChar':
case 'VarBinary': {
createStringPieces.push(
`${columnTypeName} (${columnMetadata.length === 0 || columnMetadata.length > 8000 ? 'max' : columnMetadata.length})`
)
break
}
case 'Decimal':
case 'Numeric': {
if (
columnMetadata.precision !== undefined &&
columnMetadata.scale !== undefined
) {
createStringPieces.push(
`${columnTypeName} (${columnMetadata.precision}, ${columnMetadata.scale})`
)
} else {
createStringPieces.push(`VarChar (${columnMetadata.length + 1})`)
}
break
}
case 'Time':
case 'DateTime2':
case 'DateTimeOffset': {
createStringPieces.push(`${columnTypeName} (${columnMetadata.scale})`)
break
}
default: {
createStringPieces.push(columnTypeName)
}
}
if (!columnMetadata.nullable) {
createStringPieces.push('not null')
}
return createStringPieces.join(' ')
}