parse-native-query-error.test.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. var assert = require('assert');
  2. var _ = require('@sailshq/lodash');
  3. var Pack = require('../../');
  4. describe('Queryable ::', function() {
  5. describe('Parse Native Query Error', function() {
  6. var manager;
  7. var connection;
  8. // Create a manager and connection
  9. before(function(done) {
  10. // Needed to dynamically get the host using the docker container
  11. var host = process.env.MYSQL_PORT_3306_TCP_ADDR || 'localhost';
  12. Pack.createManager({
  13. connectionString: 'mysql://mp:mp@' + host + ':3306/mppg'
  14. })
  15. .exec(function(err, report) {
  16. if (err) {
  17. return done(err);
  18. }
  19. // Store the manager
  20. manager = report.manager;
  21. Pack.getConnection({
  22. manager: manager
  23. })
  24. .exec(function(err, report) {
  25. if (err) {
  26. return done(err);
  27. }
  28. // Store the connection
  29. connection = report.connection;
  30. // Create a table to use for testing
  31. Pack.sendNativeQuery({
  32. connection: connection,
  33. nativeQuery: 'CREATE TABLE IF NOT EXISTS people(name varchar(255) UNIQUE);'
  34. })
  35. .exec(function(err) {
  36. if (err) {
  37. return done(err);
  38. }
  39. return done();
  40. });
  41. });
  42. });
  43. });
  44. // Afterwards destroy the test table and release the connection
  45. after(function(done) {
  46. Pack.sendNativeQuery({
  47. connection: connection,
  48. nativeQuery: 'DROP TABLE people;'
  49. })
  50. .exec(function(err) {
  51. if (err) {
  52. return done(err);
  53. }
  54. Pack.releaseConnection({
  55. connection: connection
  56. }).exec(done);
  57. });
  58. });
  59. it('should normalize UNIQUE constraint errors', function(done) {
  60. // Insert two records with identical names
  61. Pack.sendNativeQuery({
  62. connection: connection,
  63. nativeQuery: 'INSERT INTO people VALUES (\'Batman\'), (\'Batman\');'
  64. })
  65. .exec(function(err) {
  66. assert(err);
  67. assert.equal(err.exit, 'queryFailed');
  68. Pack.parseNativeQueryError({
  69. nativeQueryError: err.raw.error
  70. })
  71. .exec(function(err, report) {
  72. if (err) {
  73. return done(err);
  74. }
  75. assert(report.footprint);
  76. assert(report.footprint.identity);
  77. assert.equal(report.footprint.identity, 'notUnique');
  78. assert(_.isArray(report.footprint.keys));
  79. assert.equal(report.footprint.keys.length, 1);
  80. assert.equal(_.first(report.footprint.keys), 'name');
  81. return done();
  82. });
  83. });
  84. });
  85. });
  86. });