UNPKG

enhancer-data-bridge

Version:

A bridge between Enhancer Clould and user business datasource

116 lines (111 loc) 3.25 kB
var mysql = require('mysql'); var dbTypeMap = { '1': 'TINYINT', '2': 'SMALLINT', '3': 'INT', '4': 'FLOAT', '5': 'DOUBLE', '7': 'TIMESTAMP', '8': 'BIGINT', '9': 'MEDIUMINT', '10': 'DATE', '11': 'TIME', '12': 'DATETIME', '13': 'YEAR', '16': 'BIT', '252': 'BLOB', '253': 'VARCHAR', '254': 'CHAR', '246': 'DECIMAL' }; var varTypeMap = { '1': 'number', '2': 'number', '3': 'number', '4': 'number', '5': 'number', '7': 'number', '8': 'number', '9': 'string', '10': 'string', '11': 'string', '12': 'string', '13': 'string', '14': 'string', '15': 'string', '16': 'string', '252': 'string', '253': 'string', '254': 'string', '246': 'number' }; module.exports = { testConnection: function(dbConfig, cb) { var conn = mysql.createConnection(dbConfig); conn.query('SELECT 1', function(err, result) { err ? cb(null, err.message) : cb(null, true); conn.destroy(); }); }, testSql: function(dbConfig, sql, params, cb) { // mysql var conn = mysql.createConnection(dbConfig); // limit sql = sql.replace(/\sLIMIT\s+(\d+|\?)\s*(\,\s*(\d+|\?)\s*)?$/i, '').trim(); var isSelect = /^SELECT(\s|\()/i.test(sql); var isWithAs = /WITH(\s|\()/i.test(sql); if (isSelect || isWithAs) { sql = sql + ' LIMIT 0, 1'; } conn.query(sql, params, function(err, result, fields) { if (err) { cb(null, { success: false, message: err.message }); return conn.destroy(); } fields = ((isSelect || isWithAs) ? fields : (fields[fields.length - 2]) || fields[0]) || []; cb(null, { success: true, metaData: fields && fields.length ? fields.map(function(f) { f.dbType = dbTypeMap[f.type]; f.varType = varTypeMap[f.type] || 'string'; return f; }) : [] }); conn.destroy(); }); }, getTableNames: function(dbConfig, cb) { var conn = mysql.createConnection(dbConfig); conn.query('SHOW TABLES', [], function(err, results) { if ( err ) { cb(err); return conn.destroy(); } var tableNames = []; for (var i in results) { tableNames.push(results[i]['Tables_in_' + dbConfig.database]); } cb(null, tableNames); conn.destroy(); }); }, getTableColumns: function(dbConfig, tabName, cb) { var conn = mysql.createConnection(dbConfig); conn.query('SHOW COLUMNS FROM ' + tabName, [], function(err, columns) { if ( err ) { cb(err); return conn.destroy(); } columns = columns.map(function(col) { col.name = col.Field; col.dbType = col.Type; return col; }); cb(null, columns); conn.destroy(); }); } }