enhancer-data-bridge
Version:
A bridge between Enhancer Clould and user business datasource
107 lines (101 loc) • 3.02 kB
JavaScript
const { Pool, Client } = require('pg')
var dbTypeMap = {
'23': 'integer',
'1043': 'varchar',
'1042': 'char',
'1082': 'date',
'1114': 'timestamp',
'1700': 'numeric',
'701': 'float',
'790': 'money',
'25': 'text',
'1083': 'time'
};
var varTypeMap = {
'23': 'number',
'1043': 'string',
'1042': 'string',
'1082': 'date',
'1114': 'date',
'1700': 'number',
'701': 'number',
'790': 'number',
'25': 'string',
'1083': 'date'
};
module.exports = {
testConnection: function(dbConfig, cb) {
const client = new Client(dbConfig);
client.connect();
client.query('SELECT 1', function(err, result) {
err ? cb(null, err.message) : cb(null, true);
client.end();
});
},
testSql: function(dbConfig, sql, params, cb) {
// pgsql
const client = new Client(dbConfig);
client.connect();
// limit
sql = sql.replace(/\sLIMIT\s+(\d+|\?)\s*(\,\s*(\d+|\?)\s*)?$/i, '');
sql = sql + ' LIMIT 1';
// params placeholder
var i = 1;
sql = sql.replace(/\?/g, function(s) {
return '$' + i++
});
client.query(sql, params, function(err, result) {
if (err) {
cb(null, {
success: false,
message: err.message
});
return client.end();
}
cb(null, {
success: true,
metaData: result.fields.map(function(f) {
f.dbType = dbTypeMap[f.dataTypeID];
f.varType = varTypeMap[f.dataTypeID] || 'string';
return f;
})
});
client.end();
});
},
getTableNames: function(dbConfig, cb) {
const client = new Client(dbConfig);
client.connect();
client.query('SELECT table_name FROM information_schema.tables WHERE table_schema = \'public\''
, [], function(err, result) {
if ( err ) {
cb(err);
return client.end();
}
var tableNames = [];
for (var i in result.rows) {
tableNames.push(result.rows[i].table_name);
}
cb(null, tableNames);
client.end();
});
},
getTableColumns: function(dbConfig, tabName, cb) {
const client = new Client(dbConfig);
client.connect();
client.query('SELECT * FROM information_schema.columns WHERE table_name = $1'
, [tabName], function(err, result) {
if ( err ) {
cb(err);
return client.end();
}
var columns = result.rows.map(function(col) {
col.name = col.column_name;
col.dbType = col.data_type;
return col;
});
cb(null, columns);
client.end();
});
}
}