run-native-query.js 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // ██████╗ ██╗ ██╗███╗ ██╗ ███╗ ██╗ █████╗ ████████╗██╗██╗ ██╗███████╗
  2. // ██╔══██╗██║ ██║████╗ ██║ ████╗ ██║██╔══██╗╚══██╔══╝██║██║ ██║██╔════╝
  3. // ██████╔╝██║ ██║██╔██╗ ██║ ██╔██╗ ██║███████║ ██║ ██║██║ ██║█████╗
  4. // ██╔══██╗██║ ██║██║╚██╗██║ ██║╚██╗██║██╔══██║ ██║ ██║╚██╗ ██╔╝██╔══╝
  5. // ██║ ██║╚██████╔╝██║ ╚████║ ██║ ╚████║██║ ██║ ██║ ██║ ╚████╔╝ ███████╗
  6. // ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚═══╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═══╝ ╚══════╝
  7. //
  8. // ██████╗ ██╗ ██╗███████╗██████╗ ██╗ ██╗
  9. // ██╔═══██╗██║ ██║██╔════╝██╔══██╗╚██╗ ██╔╝
  10. // ██║ ██║██║ ██║█████╗ ██████╔╝ ╚████╔╝
  11. // ██║▄▄ ██║██║ ██║██╔══╝ ██╔══██╗ ╚██╔╝
  12. // ╚██████╔╝╚██████╔╝███████╗██║ ██║ ██║
  13. // ╚══▀▀═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═╝
  14. //
  15. // Run a native SQL query on an open connection and return the raw results.
  16. var _ = require('@sailshq/lodash');
  17. var MySQL = require('machinepack-mysql');
  18. module.exports = function runNativeQuery(connection, query, valuesToEscape, meta, cb) {
  19. MySQL.sendNativeQuery({
  20. connection: connection,
  21. nativeQuery: query,
  22. valuesToEscape: valuesToEscape,
  23. meta: meta
  24. })
  25. .switch({
  26. error: function error(err) {
  27. return cb(err);
  28. },
  29. // If the query failed, try and parse it into a normalized format.
  30. queryFailed: function queryFailed(report) {
  31. // Parse the native query error into a normalized format
  32. var parsedError;
  33. try {
  34. parsedError = MySQL.parseNativeQueryError({
  35. nativeQueryError: report.error
  36. }).execSync();
  37. } catch (e) {
  38. return cb(e);
  39. }
  40. // If the catch all error was used, return an error instance instead of
  41. // the footprint.
  42. var catchAllError = false;
  43. if (parsedError.footprint.identity === 'catchall') {
  44. catchAllError = true;
  45. }
  46. if (catchAllError) {
  47. return cb(report.error);
  48. }
  49. // Attach parsed error as footprint on the native query error
  50. if (!_.has(report.error, 'footprint')) {
  51. report.error.footprint = parsedError;
  52. }
  53. return cb(report.error);
  54. },
  55. success: function success(report) {
  56. return cb(null, report.result.rows);
  57. }
  58. });
  59. };