Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import mysql from 'mysql'
- import util from 'util'
- const MySQL = 'MySQL'
- const sqlQueryExecutor = {
- /**
- * Asynchronous function that handles queries for MySQL datasources and returns data from the database.
- *
- * @param {object} query This query is created by the user upon creation of the original dataset.
- * @param {string} includedFields The projection fields used by the current visualization. Only these fields are pulled from the database. Maps to 'SELECT' in MySQL
- * @param {int} limit Limits number of responses.
- * @param {string} match Matches values. Maps to 'WHERE' in MySQL
- */
- async executeQuery(query, {includedFields, limit, match}) {
- const primaryKey = query.key
- const connection = mysql.createConnection({
- host: `${query.dataSource.host}`,
- user: `${query.dataSource.user}`,
- password: `${query.dataSource.password}`,
- database: `${query.dataSource.db}`
- })
- //Map projection fields into a MySQL SELECT function
- if (includedFields !== undefined) {
- if (includedFields.length > 1 && query.query !== '') {
- includedFields.concat('_id')
- _.uniq(includedFields)
- const fieldIndex = includedFields.indexOf('_id')
- if (fieldIndex !== -1)
- includedFields[fieldIndex] = primaryKey
- const projection = 'SELECT ' + includedFields + ' FROM (' + query.query + ') as RESULT'
- query.query = projection
- }
- }
- //map match to MySQL WHERE function
- if (match !== undefined) {
- for (const matchKey in match) {
- query.query = query.query + ' WHERE ' + primaryKey + ' IN (' + match[matchKey] + ')'
- }
- }
- //Map limit to MySQL LIMIT function
- if (limit !== undefined) {
- query.query = query.query + ' LIMIT ' + limit
- }
- //connection.query needs to be promisified in order to work with async/await
- connection.query = util.promisify(connection.query)
- if (query.query !== '' && query.key !== 'Primary Key') {
- try {
- const queryResult = await connection.query(query.query)
- for (let i=0; i<queryResult.length; i++) {
- //Match user-defined primary key to _id
- queryResult[i]._id = queryResult[i][primaryKey]
- }
- return queryResult
- } catch (err) {
- throw `An error occurred while connecting to MySQL database: "${err.name}: ${err.message}"\n`
- }
- } else {
- return []
- }
- },
- queryType: MySQL
- }
- export default sqlQueryExecutor
Add Comment
Please, Sign In to add comment