/* Microsoft SQL Server Integration Services JavaScript Task Copyright (c) 2006-2018 CozyRoc LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ component.parameters = { Connection: { description: "The ADO.NET Connection Manager.", category: "Command", type: { id: "connection", connectionTypes: "ADO.NET" }, order: 1, validate(value) { if (!value) return "Please specify ADO.NET connection." } }, Statement: { description: "The SQL statement to execute.", category: "Command", type: { id: "text-editor", title: "Enter SQL statement", format: "SQL" }, order: 2, validate(value) { if (!value) return "Please specify SQL statement." } }, Timeout: { description: "The number of seconds before a command times out. Set 0 for infinite time-out.", category: "Command", type: "integer", order: 3, value: 0 }, ErrorRowDisposition: { description: "How to handle error rows.", category: "Error", type: { id: "list", values: ["IgnoreFailure", "RedirectRow", "FailComponent"] }, value: "FailComponent" }, ParseExpression: { description: "Regular expression to parse statement parameters.", category: "Parameters", type: "regex", order: 1, value: "@(\\w+)", validate(value) { if (!value) return "Please specify ParseExpression." } }, InputColumns: { description: "Input columns for command parameters.", category: "Parameters", type: { id: "column", direction: "input", columnType: "all", multiple: true }, order: 2, validate(value) { if (!value) return "Please specify InputColumns." } } }; var columnSeparator = ",\n", inputName = "Input 0", outputName = "Output 0", errorOutputName = "Error Output"; var DTSUsageType = getClrType("Microsoft.SqlServer.Dts.Pipeline.Wrapper.DTSUsageType"), DbType = getClrType("System.Data.DbType"), DBNull = getClrType("System.DBNull"), DTSRowDisposition = getClrType("Microsoft.SqlServer.Dts.Pipeline.Wrapper.DTSRowDisposition"); function getMatches(string, regex, index) { index || (index = 1); // default to the first capturing group var matches = []; var match; while (match = regex.exec(string)) { matches.push(match[index]); } return matches; } // Parse specified statement with specified regular expression to retrieve parameters. function getParameters() { var result = [], regex = new RegExp(this.parameters.ParseExpression.value, "gim"), mc = getMatches(this.parameters.Statement.value, regex, 1), foundDuplicates = false; for (var paramIndex in mc) { var parameter = mc[paramIndex]; if (result.indexOf(parameter) > -1) { // Found duplicate parameter. Stop processing. foundDuplicates = true; result.length = 0; break; } result.push(parameter); } if (foundDuplicates) { // Setup uniquely named parameters. for (var paramIndex in mc) result.push("Param" + (Number(paramIndex) + 1)); } return result; }; // Return ADO.NET data type from SSIS data type. function getDbType(dt) { switch (dt) { case DataType.DT_BOOL: return DbType.Boolean; case DataType.DT_STR: case DataType.DT_WSTR: return DbType.String; case DataType.DT_I1: return DbType.SByte; case DataType.DT_UI1: return DbType.Byte; case DataType.DT_I2: return DbType.Int16; case DataType.DT_UI2: return DbType.UInt16; case DataType.DT_I4: return DbType.Int32; case DataType.DT_UI4: return DbType.UInt32; case DataType.DT_I8: return DbType.Int64; case DataType.DT_UI8: return DbType.UInt64; case DataType.DT_R4: return DbType.Single; case DataType.DT_R8: return DbType.Double; case DataType.DT_NUMERIC: case DataType.DT_DECIMAL: return DbType.Decimal; case DataType.DT_CY: return DbType.Currency; case DataType.DT_DBTIMESTAMP: return DbType.DateTime; case DataType.DT_DBDATE: return DbType.Date; case DataType.DT_DBTIME: return DbType.Time; } throw "Unhandled type: " + dt; } // Setup parameter data type. function setupParameter(inputCol, parameter) { parameter.DbType = getDbType(inputCol.dataType); parameter.Size = inputCol.length; // Get precision. var precision = inputCol.precision; if (inputCol.dataType == DataType.DT_DECIMAL && precision < 1) { // Decimal type has precision 29. // http://msdn.microsoft.com/en-us/library/ms141036.aspx precision = 29; } // Setup precision and scale. parameter.Precision = precision parameter.Scale = inputCol.scale; } component.validate = function () { if (!this.parameters.ParseExpression.value || !this.parameters.Statement.value || !this.parameters.InputColumns.value) return; var params = getParameters.call(this), selectedCols = this.parameters.InputColumns.value.split(columnSeparator); if (params.length > selectedCols.length) { // Selected input columns are not enough. return "Please specify input columns for these parameters: " + params.join(", "); } var input = this.inputCollection[inputName], virtInput = input.getVirtualInput(), virtCount = virtInput.virtualInputColumnCollection.count; for (var i = 0; i < virtCount; i++) { var virtColumn = virtInput.virtualInputColumnCollection[i]; var usageType = selectedCols.indexOf(virtColumn.name) > -1 ? DTSUsageType.UT_READONLY : DTSUsageType.UT_IGNORED; if (usageType !== virtColumn.usageType) { virtInput.setUsageType(virtColumn.lineageID, usageType); } } var useRedirection = this.parameters.ErrorRowDisposition.value === "RedirectRow"; if (useRedirection) { // As validate() is called also during runtime, need to check if errorRowDisposition is already set. // Otherwise an exception would be thrown. if (input.errorRowDisposition !== DTSRowDisposition.RD_RedirectRow) input.errorRowDisposition = DTSRowDisposition.RD_RedirectRow; var errorOutput, errDescColumn; try { errorOutput = this.outputCollection[errorOutputName]; } catch (ex) { errorOutput = this.outputCollection.new(errorOutputName); }; if (!errorOutput.isErrorOut) errorOutput.isErrorOut = true; if (errorOutput.synchronousInputID !== input.id) errorOutput.synchronousInputID = input.id; if (errorOutput.exclusionGroup != 1) errorOutput.exclusionGroup = 1; if (errorOutput.hasSideEffects) errorOutput.hasSideEffects = false; try { errDescColumn = errorOutput.outputColumnCollection["ErrorDescription"]; } catch (ex) { errDescColumn = errorOutput.outputColumnCollection.new("ErrorDescription"); }; if (errDescColumn.dataType !== DataType.DT_WSTR || errDescColumn.length !== 250) errDescColumn.setDataTypeProperties(DataType.DT_WSTR, 250, 0, 0, 0); } else { if (input.errorRowDisposition !== DTSRowDisposition.RD_NotUsed) input.errorRowDisposition = DTSRowDisposition.RD_NotUsed; } for (var i = this.inputCollection.count - 1; i > -1; i--) { var input = this.inputCollection[i]; if (input.name !== inputName) this.inputCollection.removeObjectByID(input.id); } for (var i = this.outputCollection.count - 1; i > -1; i--) { var output = this.outputCollection[i]; if (output.name !== outputName && (!useRedirection || output.name !== errorOutputName)) this.outputCollection.removeObjectByID(output.id); } }; component.reinitializeMetadata = function () { // As reinitializeMetadata() is called also during runtime, need to check if usesDispositions is already set. // Otherwise an exception would be thrown. if (!this.usesDispositions) this.usesDispositions = true; var input, output; try { input = this.inputCollection[inputName]; } catch (ex) { input = this.inputCollection.new(inputName); }; try { output = this.outputCollection[outputName]; } catch (ex) { output = this.outputCollection.new(outputName); }; if (output.synchronousInputID !== input.id) output.synchronousInputID = input.id; if (output.exclusionGroup != 1) output.exclusionGroup = 1; }; component.preExecute = function () { this.connection = this.connections[this.parameters.Connection.value].acquire(); // Initialize ADO.NET command. this.command = this.connection.dbConnection.CreateCommand(); this.command.CommandText = this.parameters.Statement.value; this.command.CommandTimeout = this.parameters.Timeout.value; // Get parameters. var params = getParameters.call(this); // Setup parameters. var input = this.inputCollection[inputName]; for (var paramIndex in params) { var parameter = this.command.CreateParameter(); parameter.ParameterName = params[paramIndex]; setupParameter(input.inputColumnCollection[paramIndex], parameter); this.command.Parameters.Add(parameter); } }; component.postExecute = function () { this.connection.close(); }; component.processData = function (inputBuffer, outputs) { if (inputBuffer.endOfRowset) return; var selectedCols = this.parameters.InputColumns.value.split(columnSeparator); if (this.parameters.ErrorRowDisposition.value === "RedirectRow") var errorOutputBuffer = outputs[errorOutputName]; while (inputBuffer.nextRow()) { // Setup parameters value. for (paramIndex in selectedCols) { var colValue = DBNull.Value, colName = selectedCols[paramIndex]; if (!inputBuffer.isNull(colName)) colValue = inputBuffer.get(colName) this.command.Parameters[colName].Value = colValue; } switch (this.parameters.ErrorRowDisposition.value) { case "IgnoreFailure": try { this.command.ExecuteNonQuery(); } catch (ex) { } inputBuffer.directRow(outputName); break; case "RedirectRow": try { this.command.ExecuteNonQuery(); inputBuffer.directRow(outputName); } catch (ex) { errorOutputBuffer.set("ErrorDescription", ex.message); inputBuffer.directRow(errorOutputName); } break; case "FailComponent": this.command.ExecuteNonQuery(); inputBuffer.directRow(outputName); break; } } };