forked from TimelordUK/node-sqlserver-v8
-
Notifications
You must be signed in to change notification settings - Fork 0
/
table-builder.js
81 lines (71 loc) · 2.74 KB
/
table-builder.js
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
// const connectionString = 'Driver={ODBC Driver 17 for SQL Server}; Server=DESKTOP-VIUCH90;UID=linux; PWD=linux; Database=node'
const { TestEnv } = require('../../test/env/test-env')
const env = new TestEnv()
const connectionString = env.connectionString
builder().then(() => {
console.log('done')
})
async function builder () {
function makeOne (i) {
return {
id: i,
MatterColumn: `MatterColumn_${i}`,
SearchTerm: `SearchTerm_${i}`,
Comparator: `Comparator_${i}`
}
}
try {
const rows = 5
const connection = await env.sql.promises.open(connectionString)
const tableName = 'tmpTableBuilder'
const mgr = connection.tableMgr()
const builder = mgr.makeBuilder(tableName)
builder.addColumn('id').asInt().isPrimaryKey(1)
builder.addColumn('MatterColumn').asVarChar(100).notNull()
builder.addColumn('SearchTerm').asNVarCharMax().notNull()
builder.addColumn('Comparator').asNVarChar(20).notNull()
const vec = Array(rows).fill(0).map((_, i) => makeOne(i))
const t = builder.toTable()
const dropTypeSql = builder.dropTypeSql
const userTypeSql = builder.userTypeTableSql
const dropTvpInsert = builder.dropInsertTvpProcedure
const tvpInserterSql = builder.insertProcedureTvpSql
const typeName = `${tableName}Type`
const selectSql = `DECLARE @test AS ${typeName};
INSERT INTO @test SELECT * FROM ?;
SELECT * FROM @test`
console.log(dropTvpInsert)
await connection.promises.query(dropTvpInsert)
const create = builder.createTableSql
const dropTable = builder.dropTableSql
console.log(dropTable)
await builder.drop()
console.log(create)
await builder.create()
console.log(dropTypeSql)
await connection.promises.query(dropTypeSql)
console.log(userTypeSql)
await connection.promises.query(userTypeSql)
console.log(tvpInserterSql)
await connection.promises.query(tvpInserterSql)
const table = t.asTableType()
await connection.promises.getUserTypeTable('dbo.' + typeName)
// Works (only changing that line)
await connection.promises.getUserTypeTable('[dbo].[' + typeName + ']')
await connection.promises.getUserTypeTable('[' + typeName + ']')
console.log(JSON.stringify(table, null, 4))
// convert a set of objects to rows
table.addRowsFromObjects(vec)
// use a type the native driver can understand, using column based bulk binding.
const tp = env.sql.TvpFromTable(table)
// can now clear rows
table.rows = []
const res = await connection.promises.query(selectSql, [tp])
console.log(JSON.stringify(res.meta[0], null, 4))
console.log(JSON.stringify(res.first, null, 4))
await builder.drop()
await connection.promises.close()
} catch (e) {
console.log(e)
}
}