(tableName, attrValueHashes, options, attributes)
| 296 | } |
| 297 | |
| 298 | bulkInsertQuery(tableName, attrValueHashes, options, attributes) { |
| 299 | options = options || {}; |
| 300 | attributes = attributes || {}; |
| 301 | let query = 'INSERT INTO <%= table %> (<%= attributes %>)<%= output %> VALUES <%= tuples %>;'; |
| 302 | if (options.returning) { |
| 303 | query = 'SELECT * FROM FINAL TABLE( INSERT INTO <%= table %> (<%= attributes %>)<%= output %> VALUES <%= tuples %>);'; |
| 304 | } |
| 305 | const emptyQuery = 'INSERT INTO <%= table %>', |
| 306 | tuples = [], |
| 307 | allAttributes = [], |
| 308 | allQueries = []; |
| 309 | |
| 310 | let outputFragment; |
| 311 | const valuesForEmptyQuery = []; |
| 312 | |
| 313 | if (options.returning) { |
| 314 | outputFragment = ''; |
| 315 | } |
| 316 | _.forEach(attrValueHashes, attrValueHash => { |
| 317 | // special case for empty objects with primary keys |
| 318 | const fields = Object.keys(attrValueHash); |
| 319 | const firstAttr = attributes[fields[0]]; |
| 320 | if (fields.length === 1 && firstAttr && firstAttr.autoIncrement && attrValueHash[fields[0]] === null) { |
| 321 | valuesForEmptyQuery.push(`(${ this.autoGenValue++ })`); |
| 322 | return; |
| 323 | } |
| 324 | |
| 325 | // normal case |
| 326 | _.forOwn(attrValueHash, (value, key) => { |
| 327 | if (allAttributes.indexOf(key) === -1) { |
| 328 | if (value === null && attributes[key] && attributes[key].autoIncrement) |
| 329 | return; |
| 330 | |
| 331 | allAttributes.push(key); |
| 332 | } |
| 333 | }); |
| 334 | }); |
| 335 | if (valuesForEmptyQuery.length > 0) { |
| 336 | allQueries.push(`${emptyQuery } VALUES ${ valuesForEmptyQuery.join(',')}`); |
| 337 | } |
| 338 | |
| 339 | if (allAttributes.length > 0) { |
| 340 | _.forEach(attrValueHashes, attrValueHash => { |
| 341 | tuples.push(`(${ |
| 342 | allAttributes.map(key => |
| 343 | this.escape(attrValueHash[key]), undefined, { context: 'INSERT' }).join(',')})`); |
| 344 | }); |
| 345 | allQueries.push(query); |
| 346 | } |
| 347 | const replacements = { |
| 348 | table: this.quoteTable(tableName), |
| 349 | attributes: allAttributes.map(attr => |
| 350 | this.quoteIdentifier(attr)).join(','), |
| 351 | tuples, |
| 352 | output: outputFragment |
| 353 | }; |
| 354 | |
| 355 | const generatedQuery = _.template(allQueries.join(';'), this._templateSettings)(replacements); |
no test coverage detected