index.js 4.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // ██╗ ██╗ █████╗ ████████╗███████╗██████╗ ██╗ ██╗███╗ ██╗███████╗
  2. // ██║ ██║██╔══██╗╚══██╔══╝██╔════╝██╔══██╗██║ ██║████╗ ██║██╔════╝
  3. // ██║ █╗ ██║███████║ ██║ █████╗ ██████╔╝██║ ██║██╔██╗ ██║█████╗
  4. // ██║███╗██║██╔══██║ ██║ ██╔══╝ ██╔══██╗██║ ██║██║╚██╗██║██╔══╝
  5. // ╚███╔███╔╝██║ ██║ ██║ ███████╗██║ ██║███████╗██║██║ ╚████║███████╗
  6. // ╚══╝╚══╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝╚══════╝╚═╝╚═╝ ╚═══╝╚══════╝
  7. //
  8. // ███████╗ ██████╗ ██╗ ██████╗ ██╗ ██╗██╗██╗ ██████╗ ███████╗██████╗
  9. // ██╔════╝██╔═══██╗██║ ██╔══██╗██║ ██║██║██║ ██╔══██╗██╔════╝██╔══██╗
  10. // ███████╗██║ ██║██║ ██████╔╝██║ ██║██║██║ ██║ ██║█████╗ ██████╔╝
  11. // ╚════██║██║▄▄ ██║██║ ██╔══██╗██║ ██║██║██║ ██║ ██║██╔══╝ ██╔══██╗
  12. // ███████║╚██████╔╝███████╗ ██████╔╝╚██████╔╝██║███████╗██████╔╝███████╗██║ ██║
  13. // ╚══════╝ ╚══▀▀═╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═╝╚══════╝╚═════╝ ╚══════╝╚═╝ ╚═╝
  14. //
  15. // Use Waterline Statements to generate a SQL query that can be used in one of
  16. // the many supported drivers or run independently.
  17. var Knex = require('knex');
  18. var Utils = require('waterline-utils');
  19. var Sequelizer = require('./lib/sequelizer');
  20. module.exports = function sqlBuilder(options) {
  21. if (!options.dialect) {
  22. throw new Error('Missing Dialect!');
  23. }
  24. // Build up a Knex instance to use in the query builder
  25. var knexInstance = Knex({
  26. dialect: options.dialect,
  27. useNullAsDefault: true
  28. });
  29. return {
  30. // ╔═╗╔═╗╔╗╔╔═╗╦═╗╔═╗╔╦╗╔═╗╦═╗
  31. // ║ ╦║╣ ║║║║╣ ╠╦╝╠═╣ ║ ║ ║╠╦╝
  32. // ╚═╝╚═╝╝╚╝╚═╝╩╚═╩ ╩ ╩ ╚═╝╩╚═
  33. // This the main function used by the adapters. Given a Statement, use the
  34. // query parser to generate a token tree and then build up a SQL string.
  35. generate: function generate(query) {
  36. // Tokenize the values
  37. var tokens = Utils.query.tokenizer(query);
  38. // Analyze the tokens
  39. var tree = Utils.query.analyzer(tokens);
  40. // Generate the SQL
  41. var sql = Sequelizer({
  42. knex: knexInstance,
  43. tree: tree
  44. });
  45. return sql;
  46. },
  47. // ╔═╗╔═╗╔═╗ ╦ ╦╔═╗╦ ╦╔═╗╔═╗╦═╗
  48. // ╚═╗║╣ ║═╬╗║ ║║╣ ║ ║╔═╝║╣ ╠╦╝
  49. // ╚═╝╚═╝╚═╝╚╚═╝╚═╝╩═╝╩╚═╝╚═╝╩╚═
  50. // Given a token tree from the query parser, build up a SQL string.
  51. sequelizer: function sequelizer(tree) {
  52. return Sequelizer({
  53. knex: knexInstance,
  54. tree: tree
  55. });
  56. }
  57. };
  58. };