-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcanned-sql2.js
282 lines (225 loc) · 8.42 KB
/
canned-sql2.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
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
/*
*
* Copyright Daniel Hutmacher under Creative Commons 4.0 license with attribution.
* http://creativecommons.org/licenses/by/4.0/
*
* Source: https://github.com/sqlsunday/sp_ctrl3
*
* DISCLAIMER: This script may not be suitable to run in a production
* environment. I cannot assume any responsibility regarding
* the accuracy of the output information, performance
* impacts on your server, or any other consequence. If
* your juristiction does not allow for this kind of
* waiver/disclaimer, or if you do not accept these terms,
* you are NOT allowed to store, distribute or use this
* code in any way.
*
* This is a rework of my original "canned SQL" abstraction layer that I
* made some time ago because I got so tired or juggling the asynchronous
* nightmare that was querying SQL Server with Tedious, not to mention
* getting the error handling to do what I wanted.
*
* This module depends on the "tedious" Node.js module.
*
* A significant part of the code in this module was written with AI
* assistance, although I've reviewed, tested, commented, and cleaned the
* result manually.
*
*/
const Connection = require('tedious').Connection;
const Request = require('tedious').Request;
const TYPES = require('tedious').TYPES;
const ISOLATION_LEVEL = require('tedious').ISOLATION_LEVEL;
// Create the database connection:
async function connect(config) {
const connection = new Connection(config);
await new Promise((resolve, reject) => {
connection.connect((err) => {
if (err) reject(err);
resolve();
});
});
return connection;
}
// Run the SQL batch:
async function query(connection, statement, parameters) {
return new Promise((resolve, reject) => {
const resultSets = [];
let currentResultSet = [];
const request = new Request(statement, (err) => {
if (err) {
resolve({
success: false,
error: {
message: err.message,
code: err.code,
state: err.state,
class: err.class,
lineNumber: err.lineNumber,
serverName: err.serverName
}
});
}
});
// If the user provided parameters, we'll add those now:
if (parameters) {
parameters.forEach(function(parameter) {
request.addParameter(parameter.name, parameter.type, parameter.value);
});
}
// When a row arrives, add all the column values to a row object, add that row object to currentResultSet:
request.on('row', (columns) => {
const row = {};
for (const column of columns) {
row[column.metadata.colName] = column.value;
}
currentResultSet.push(row);
});
// At the end of a resultset, add it to resultSets, and start over:
request.on('doneInProc', (rowCount, more) => {
if (currentResultSet.length > 0) {
resultSets.push([...currentResultSet]);
currentResultSet = [];
}
});
// When the request completes, add the last result set to resultSets:
request.on('requestCompleted', () => {
// Handle any remaining rows in the current set
if (currentResultSet.length > 0) {
resultSets.push([...currentResultSet]);
}
// Resolve: return success and the resultSets array:
resolve({
success: true,
results: resultSets /* resultSets.length === 1 ? resultSets[0] : resultSets */
});
});
// If something went wrong:
request.on('error', (error) => {
// We'll still resolve the Promise, in order to not trigger any errors,
// but we'll set success:false, and include a description of the error.
resolve({
success: false,
error: {
message: error.message,
code: error.code,
state: error.state,
class: error.class,
lineNumber: error.lineNumber,
serverName: error.serverName
}
});
});
// With all that set up, we're ready to fire off the request:
connection.execSql(request);
});
};
// BEGIN TRANSACTION:
const beginTransaction = (connection, isolationLevel) => {
return new Promise((resolve, reject) => {
connection.beginTransaction((err) => {
if (err) {
resolve({
success: false,
error: {
message: err.message,
code: err.code,
state: err.state,
class: err.class,
lineNumber: err.lineNumber,
serverName: err.serverName
}
});
} else {
resolve({ success: true });
}
}, '', isolationLevel || 0);
});
};
// COMMIT TRANSACTION:
const commitTransaction = (connection) => {
return new Promise((resolve, reject) => {
connection.commitTransaction((err) => {
if (err) {
resolve({
success: false,
error: {
message: err.message,
code: err.code,
state: err.state,
class: err.class,
lineNumber: err.lineNumber,
serverName: err.serverName
}
});
} else {
resolve({ success: true });
}
});
});
};
// ROLLBACK TRANSACTION:
const rollbackTransaction = (connection) => {
return new Promise((resolve, reject) => {
connection.rollbackTransaction((err) => {
if (err) {
resolve({
success: false,
error: {
message: err.message,
code: err.code,
state: err.state,
class: err.class,
lineNumber: err.lineNumber,
serverName: err.serverName
}
});
} else {
resolve({ success: true });
}
});
});
};
// Export the functions
exports.query = query;
exports.connect = connect;
exports.begin = beginTransaction;
exports.commit = commitTransaction;
exports.rollback = rollbackTransaction;
// Isolation levels
exports.READ_UNCOMMITTED = ISOLATION_LEVEL.READ_UNCOMMITTED;
exports.READ_COMMITTED = ISOLATION_LEVEL.READ_COMMITTED;
exports.REPEATABLE_READ = ISOLATION_LEVEL.REPEATABLE_READ;
exports.SERIALIZABLE = ISOLATION_LEVEL.SERIALIZABLE;
exports.SNAPSHOT = ISOLATION_LEVEL.SNAPSHOT;
// Translating SQL Server datatypes to their respective types in Tedious.
// This is how the user defines the data types in parameterized queries.
exports.bit = TYPES.Bit;
exports.tinyint = TYPES.TinyInt;
exports.smallint = TYPES.SmallInt;
exports.int = TYPES.Int;
exports.bigint = TYPES.BigInt; // Warning: values are returned as a string because bigint can exceed 53 bits in length
exports.numeric = TYPES.Numeric; // Max precision supported for input paramters is currently 19
exports.decimal = TYPES.Decimal; // Max precision supported for input paramters is currently 19
exports.smallmoney = TYPES.SmallMoney;
exports.money = TYPES.Money;
exports.float = TYPES.Float;
exports.real = TYPES.Real;
exports.smalldatetime = TYPES.SmallDateTime;
exports.datetime = TYPES.DateTime;
exports.datetime2 = TYPES.DateTime2;
exports.datetimeoffset = TYPES.DateTimeOffset;
exports.time = TYPES.Time;
exports.date = TYPES.Date;
exports.char = TYPES.Char;
exports.varchar = TYPES.VarChar;
exports.text = TYPES.Text;
exports.nchar = TYPES.NChar;
exports.nvarchar = TYPES.NVarChar;
exports.ntext = TYPES.NText;
exports.binary = TYPES.Binary;
exports.varbinary = TYPES.VarBinary;
exports.image = TYPES.Image;
exports.uniqueidentifier = TYPES.UniqueIdentifier; // Returned as hexadecimal string
exports.sql_variant = TYPES.Variant;
exports.xml = TYPES.Xml;