@demsr/n8n-nodes-db2
Version:
n8n Community node to query a DB2 instance for iSeries
339 lines • 14.8 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Db2 = void 0;
const n8n_workflow_1 = require("n8n-workflow");
const GenericFunctions_1 = require("./GenericFunctions");
const utilities_1 = require("n8n-nodes-base/dist/utils/utilities");
class Db2 {
constructor() {
this.description = {
displayName: 'DB2',
name: 'Db2',
icon: 'file:IbmiDb2.svg',
group: ['transform'],
version: 1,
description: 'Connect to IBM iSeries DB2 Instance',
defaults: {
name: 'DB2',
},
inputs: ["main"],
outputs: ["main"],
credentials: [
{
name: 'db2Api',
required: true,
},
],
properties: [
{
displayName: 'Operation',
name: 'operation',
type: 'options',
noDataExpression: true,
options: [
{
name: 'Execute Query',
value: 'executeQuery',
description: 'Execute a SQL query',
action: 'Execute a SQL query',
},
{
name: 'Insert',
value: 'insert',
description: 'Insert rows in database',
action: 'Insert rows in database',
},
{
name: 'Update',
value: 'update',
description: 'Update rows in database',
action: 'Update rows in database',
},
{
name: 'Delete',
value: 'delete',
description: 'Delete rows in database',
action: 'Delete rows in database',
},
],
default: 'executeQuery',
},
{
displayName: 'Query',
name: 'query',
type: 'string',
noDataExpression: true,
typeOptions: {
editor: 'sqlEditor',
rows: 5,
sqlDialect: 'StandardSQL',
},
displayOptions: {
show: {
operation: ['executeQuery'],
},
},
default: '',
placeholder: 'SELECT * FROM SCHEMA.TABLE LIMIT 10',
required: true,
description: 'The SQL query to execute',
},
{
displayName: 'Table',
name: 'table',
type: 'resourceLocator',
default: { mode: 'list', value: '' },
required: true,
modes: [
{
displayName: 'From List',
name: 'list',
type: 'list',
placeholder: 'Select a Table...',
typeOptions: {
searchListMethod: 'searchTables',
searchFilterRequired: false,
searchable: true,
},
},
{
displayName: 'Name',
name: 'name',
type: 'string',
placeholder: 'table_name',
},
],
displayOptions: {
show: {
operation: ['insert'],
},
},
description: 'Name of the table in which to insert data to',
},
{
displayName: 'Columns',
name: 'columns',
type: 'string',
displayOptions: {
show: {
operation: ['insert'],
},
},
requiresDataPath: 'multiple',
default: '',
placeholder: 'id,name,description',
description: 'Comma-separated list of the properties which should used as columns for the new rows',
},
{
displayName: 'Table',
name: 'table',
type: 'resourceLocator',
default: { mode: 'list', value: '' },
required: true,
modes: [
{
displayName: 'From List',
name: 'list',
type: 'list',
placeholder: 'Select a Table...',
typeOptions: {
searchListMethod: 'searchTables',
searchFilterRequired: false,
searchable: true,
},
},
{
displayName: 'Name',
name: 'name',
type: 'string',
placeholder: 'table_name',
},
],
displayOptions: {
show: {
operation: ['update'],
},
},
description: 'Name of the table in which to delete data',
},
{
displayName: 'Update Keys',
name: 'updateKey',
type: 'string',
requiresDataPath: 'single',
displayOptions: {
show: {
operation: ['update'],
},
},
default: 'id',
required: true,
description: 'Name of the property which decides which rows in the database should be updated. Normally that would be "id". Comma separated',
},
{
displayName: 'Columns',
name: 'columns',
type: 'string',
requiresDataPath: 'multiple',
displayOptions: {
show: {
operation: ['update'],
},
},
default: '',
placeholder: 'name,description',
description: 'Comma-separated list of the properties which should used as columns for rows to update',
},
{
displayName: 'Table',
name: 'table',
type: 'resourceLocator',
default: { mode: 'list', value: '' },
required: true,
modes: [
{
displayName: 'From List',
name: 'list',
type: 'list',
placeholder: 'Select a Table...',
typeOptions: {
searchListMethod: 'searchTables',
searchFilterRequired: false,
searchable: true,
},
},
{
displayName: 'Name',
name: 'name',
type: 'string',
placeholder: 'table_name',
},
],
displayOptions: {
show: {
operation: ['delete'],
},
},
description: 'Name of the table in which to delete data',
},
{
displayName: 'Delete Key',
name: 'deleteKey',
type: 'string',
requiresDataPath: 'single',
displayOptions: {
show: {
operation: ['delete'],
},
},
default: 'id',
required: true,
description: 'Name of the property which decides which rows in the database should be deleted. Normally that would be "id".',
},
],
};
this.methods = {
credentialTest: {
async dbConnectionTest(credential) {
const credentials = credential.data;
try {
(0, GenericFunctions_1.testConnection)(credentials);
}
catch (error) {
return {
status: 'Error',
message: error.message,
};
}
return {
status: 'OK',
message: 'Connection successful!',
};
},
},
listSearch: {
searchTables: GenericFunctions_1.searchTables,
},
};
}
async execute() {
const credentials = await this.getCredentials('db2Api');
if (credentials === undefined) {
throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'No credentials found for this node.');
}
const pool = (0, GenericFunctions_1.getConnectionPool)(credentials);
let returnItems = [];
const items = this.getInputData();
const operation = this.getNodeParameter('operation', 0);
try {
if (operation === 'executeQuery') {
const queryQueue = items.map(async (_, index) => {
let rawQuery = this.getNodeParameter('query', index).trim();
for (const resolvable of (0, utilities_1.getResolvables)(rawQuery)) {
rawQuery = rawQuery.replace(resolvable, this.evaluateExpression(resolvable, index));
}
return pool.query(rawQuery);
});
returnItems = (await Promise.all(queryQueue)).reduce((collection, results, index) => {
const executionData = this.helpers.constructExecutionMetaData(this.helpers.returnJsonArray(results), { itemData: { item: index } });
collection.push(...executionData);
return collection;
}, []);
}
else if (operation === 'insert') {
const table = this.getNodeParameter('table', 0, '', { extractValue: true });
const columnString = this.getNodeParameter('columns', 0);
const columns = columnString.split(',').map((column) => column.trim());
const insertItems = this.helpers.copyInputItems(items, columns);
const insertSQL = `INSERT INTO ${table} (${columnString}) VALUES (${columns.map((_column) => '?').join(',')})`;
const insertData = insertItems.reduce((collection, item) => collection.concat([Object.values(item)]), []);
const affectedRows = await pool.batchUpdate(insertSQL, insertData);
returnItems = this.helpers.returnJsonArray({
affectedRows: affectedRows.reduce((a, c) => a + c),
});
}
else if (operation === 'update') {
const table = this.getNodeParameter('table', 0, '', { extractValue: true });
const updateKeys = this.getNodeParameter('updateKey', 0).split(',');
const columns = this.getNodeParameter('columns', 0)
.split(',')
.map((column) => column.trim());
const updateItems = this.helpers.copyInputItems(this.getInputData(), columns.concat(updateKeys));
const updateSQL = `UPDATE ${table} SET ${columns.map((c) => `${c}=?`).join(',')} WHERE ${updateKeys.map((u) => `${u}=?`).join(' and ')}`;
const updateData = updateItems.reduce((collection, item) => collection.concat([Object.values(item)]), []);
const affectedRows = await pool.batchUpdate(updateSQL, updateData);
returnItems = this.helpers.returnJsonArray({
affectedRows: affectedRows.reduce((a, c) => a + c),
});
}
else if (operation === 'delete') {
const table = this.getNodeParameter('table', 0, '', { extractValue: true });
const deleteKey = this.getNodeParameter('deleteKey', 0);
const deleteItems = this.helpers.copyInputItems(this.getInputData(), [deleteKey]);
const deleteData = deleteItems.reduce((collection, item) => collection.concat([Object.values(item)]), []);
const deleteSQL = `DELETE FROM ${table} WHERE ${deleteKey}=?`;
const affectedRows = await pool.batchUpdate(deleteSQL, deleteData);
returnItems = this.helpers.returnJsonArray({
affectedRows: affectedRows.reduce((a, c) => a + c),
});
}
else {
pool.close();
throw new n8n_workflow_1.NodeOperationError(this.getNode(), `The operation "${operation}" is not supported!`);
}
}
catch (error) {
if (this.continueOnFail()) {
returnItems = items;
}
else {
pool.close();
throw new n8n_workflow_1.NodeOperationError(this.getNode(), error);
}
}
pool.close();
return this.prepareOutputData(returnItems);
}
}
exports.Db2 = Db2;
//# sourceMappingURL=Db2.node.js.map