Guest User

Untitled

a guest
Jan 17th, 2018
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. import mysql from 'mysql'
  2. import util from 'util'
  3.  
  4. const MySQL = 'MySQL'
  5.  
  6. const sqlQueryExecutor = {
  7. /**
  8. * Asynchronous function that handles queries for MySQL datasources and returns data from the database.
  9. *
  10. * @param {object} query This query is created by the user upon creation of the original dataset.
  11. * @param {string} includedFields The projection fields used by the current visualization. Only these fields are pulled from the database. Maps to 'SELECT' in MySQL
  12. * @param {int} limit Limits number of responses.
  13. * @param {string} match Matches values. Maps to 'WHERE' in MySQL
  14. */
  15. async executeQuery(query, {includedFields, limit, match}) {
  16. const primaryKey = query.key
  17. const connection = mysql.createConnection({
  18. host: `${query.dataSource.host}`,
  19. user: `${query.dataSource.user}`,
  20. password: `${query.dataSource.password}`,
  21. database: `${query.dataSource.db}`
  22. })
  23. //Map projection fields into a MySQL SELECT function
  24. if (includedFields !== undefined) {
  25. if (includedFields.length > 1 && query.query !== '') {
  26. includedFields.concat('_id')
  27. _.uniq(includedFields)
  28. const fieldIndex = includedFields.indexOf('_id')
  29. if (fieldIndex !== -1)
  30. includedFields[fieldIndex] = primaryKey
  31. const projection = 'SELECT ' + includedFields + ' FROM (' + query.query + ') as RESULT'
  32. query.query = projection
  33. }
  34. }
  35. //map match to MySQL WHERE function
  36. if (match !== undefined) {
  37. for (const matchKey in match) {
  38. query.query = query.query + ' WHERE ' + primaryKey + ' IN (' + match[matchKey] + ')'
  39. }
  40.  
  41. }
  42. //Map limit to MySQL LIMIT function
  43. if (limit !== undefined) {
  44. query.query = query.query + ' LIMIT ' + limit
  45. }
  46. //connection.query needs to be promisified in order to work with async/await
  47. connection.query = util.promisify(connection.query)
  48. if (query.query !== '' && query.key !== 'Primary Key') {
  49. try {
  50. const queryResult = await connection.query(query.query)
  51. for (let i=0; i<queryResult.length; i++) {
  52.  
  53. //Match user-defined primary key to _id
  54. queryResult[i]._id = queryResult[i][primaryKey]
  55. }
  56. return queryResult
  57. } catch (err) {
  58. throw `An error occurred while connecting to MySQL database: "${err.name}: ${err.message}"\n`
  59. }
  60. } else {
  61. return []
  62. }
  63. },
  64. queryType: MySQL
  65. }
  66.  
  67. export default sqlQueryExecutor
Add Comment
Please, Sign In to add comment