/
sqlContextUtils.js
308 lines (260 loc) · 8.33 KB
/
sqlContextUtils.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
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
var lift = require( "when/node" ).lift;
var sql = require( "mssql" );
var util = require( "util" );
var _ = require( "lodash" );
var when = require( "when" );
var Readable = require( "stream" ).Readable;
var specialParamOptions = [
require( "./asTable" ),
require( "./asList" )
];
util.inherits( DataResultStream, Readable );
function DataResultStream( request, options ) {
var self = this;
Readable.call( this, _.extend( {}, options, { objectMode: true } ) );
request.on( "recordset", function( columns ) {
self.push( { recordset: columns } );
} );
request.on( "row", function( row ) {
self.push( { row: row } );
} );
request.on( "error", function( error ) {
self.emit( "error", error );
} );
request.on( "done", function() {
self.push( null );
} );
}
DataResultStream.prototype._read = _.noop;
function errorHandler( err ) {
this.err = err;
this.transition( "error" );
}
function instrument( state, name, op ) {
if ( !state.metrics ) {
return op();
}
return state.metrics.instrument(
{
key: [ "sql", name ],
namespace: state.metricsNamespace,
call: op,
success: _.identity,
failure: _.identity
}
);
}
function bulkLoadTable( state, name, options ) {
var table = new sql.Table( options.bulkLoadTable.name );
table.create = true;
_.forEach( options.bulkLoadTable.columns, function( column, columnName ) {
table.columns.add( columnName, column.type, { nullable: column.nullable === undefined ? true : column.nullable } );
} );
var columnNames = Object.keys( options.bulkLoadTable.columns );
options.bulkLoadTable.rows.forEach( function( row ) {
var values = columnNames.map( function( columnName ) {
return row[ columnName ];
} );
table.rows.add.apply( table.rows, values );
} );
var req = new sql.Request( state.transaction || state.connection );
return when.resolve()
.then( function() {
if ( !isTempTableName( options.bulkLoadTable.name ) ) {
return;
}
var dropSql = "IF OBJECT_ID('tempdb.." + options.bulkLoadTable.name + "') IS NOT NULL DROP TABLE " + options.bulkLoadTable.name + ";";
if ( !options.bulkLoadTable.useExisting ) {
// Make sure we're not adding to an existing temp table
nonPreparedSql( state, name + "-pre-drop", { query: dropSql } );
}
// Accumulate list of tables on state, which is the transaction object, to enforce appropriate scope
// Keep this list to avoid double-dropping tables when we bulk load the same temp table more than once using `useExisting`
state.droppedTempTables = state.droppedTempTables || {};
if ( state.droppedTempTables[ options.bulkLoadTable.name ] ) {
return;
}
state.droppedTempTables[ options.bulkLoadTable.name ] = true;
// Add to drop sql for each temp table, to be run in a single step at end of transaction
if ( state.tempTablesDropSql ) {
state.tempTablesDropSql += "\n" + dropSql;
} else {
state.tempTablesDropSql = dropSql;
// Add step at end to drop temp tables
addState( state, "__drop-temp-tables", function( execute ) {
return execute( { query: state.tempTablesDropSql } );
} );
}
} )
.then( function() {
return instrument( state, name, function() {
return lift( req.bulk ).bind( req )( table );
} );
} );
}
function createParameter( val, key ) {
if ( typeof val !== "object" ) {
return {
key: key,
value: val
};
}
var specialOption = _.find( specialParamOptions, function( option ) {
return option.matchesParam( val );
} );
return specialOption ? specialOption.createParameter( val, key ) : {
key: key,
type: val.type,
value: val.val
};
}
function createParameters( params ) {
return _( params )
.map( createParameter )
.flatten()
.value();
}
function transformQuery( params, query ) {
return specialParamOptions.reduce( function( acc, option ) {
return option.transformQuery( params, acc );
}, query );
}
function nonPreparedSql( state, name, options ) {
var req = new sql.Request( state.transaction || state.connection );
req.multiple = options.hasOwnProperty( "multiple" ) ? options.multiple : false;
var params = createParameters( options.params );
params.forEach( function( param ) {
if ( param.type ) {
req.input( param.key, param.type, param.value );
} else {
req.input( param.key, param.value );
}
} );
var operation = options.query ? "query" : "execute";
var sqlCmd = transformQuery( options.params, options.query || options.procedure );
return instrument( state, name, function() {
if ( !options.stream ) {
return lift( req[ operation ] ).bind( req )( sqlCmd );
}
var stream;
req.stream = true;
stream = new DataResultStream( req );
req[ operation ]( sqlCmd );
return when.resolve( stream );
} );
}
function preparedSql( state, name, options ) {
var cmd = new sql.PreparedStatement( state.transaction || state.connection );
cmd.multiple = options.hasOwnProperty( "multiple" ) ? options.multiple : false;
var params = createParameters( options.params );
var paramKeyValues = {};
params.forEach( function( param ) {
cmd.input( param.key, param.type );
paramKeyValues[ param.key ] = param.value;
} );
var prepare = lift( cmd.prepare ).bind( cmd );
var execute = lift( cmd.execute ).bind( cmd );
var unprepare = lift( cmd.unprepare ).bind( cmd );
var statement = transformQuery( options.params, options.preparedSql );
return instrument( state, name, function() {
return prepare( statement )
.then( function() {
if ( options.stream ) {
cmd.stream = true;
// Can't use the lifted execute here because we need the
// request returned by the original callback version, which the
// lift would replace with a promise.
var req = cmd.execute( paramKeyValues, _.noop );
var stream = new DataResultStream( req );
stream.on( "end", unprepare );
return when.resolve( stream );
}
return execute( paramKeyValues )
.then( function( result ) {
return unprepare()
.then( function() {
return result;
} );
}, function( err ) {
return unprepare()
.then( function() {
throw err;
} );
} );
} );
} );
}
function isTempTableName( name ) {
return name[ 0 ] === "#";
}
function executeSql( state, name, options ) {
if ( options.query || options.procedure ) {
return nonPreparedSql( state, name, options );
}
if ( options.preparedSql ) {
return preparedSql( state, name, options );
}
if ( options.bulkLoadTable ) {
if ( isTempTableName( options.bulkLoadTable.name ) && !state.transaction ) {
throw new Error( "You may not bulk load a temporary table on a plain context; use a transaction context." );
}
return bulkLoadTable( state, name, options );
}
throw new Error( "The options argument must have query, procedure, preparedSql, or bulkLoadTable." );
}
function addState( fsm, name, stepAction ) {
if ( fsm.states[ name ] ) {
throw new Error( "A step by that name already exists: " + fsm.instance );
}
if ( name === "__beforeHook__" ) {
fsm.pipeline.unshift( name );
} else {
fsm.pipeline.push( name );
}
fsm.states[ name ] = {
_onEnter: function() {
var promise;
var exec = function( options ) {
// Capture call stack for call to execute from within a step.
// This provides call context that would otherwise get lost when we
// pass around an execute function and call it multiple times.
var callStack = new Error().stack;
promise = executeSql( fsm, name, options )
.catch( function( error ) {
// Remove the "Error" top line of captured stack and replace it with error message from actual error.
var capturedStackParts = callStack.split( "\n" ).slice( 1 );
capturedStackParts.unshift( error.toString() );
error.stack = capturedStackParts.join( "\n" );
throw error;
} );
return promise;
};
try {
var stepReturnValue = stepAction.call(
fsm,
exec,
fsm.results
);
when( stepReturnValue )
.then( function( result ) {
return when( promise ) // We'll not force the caller to return the execute promise
.then( function( promiseResult ) {
return result || promiseResult;
} );
} )
.then( fsm.handle.bind( fsm, "success" ), fsm.handle.bind( fsm, "error" ) ) ;
} catch ( err ) {
fsm.handle( "error", err );
}
},
success: function( result ) {
fsm.results[ name ] = result;
fsm.emit( "data", result );
fsm.nextState();
},
error: errorHandler
};
}
module.exports = {
addState: addState
};