Selection.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. const ALIAS_REGEX = /\s+as\s+/i;
  2. class Selection {
  3. constructor(table, column, alias) {
  4. this.table = table || null;
  5. this.column = column || null;
  6. this.alias = alias || null;
  7. }
  8. static create(selection, table = null) {
  9. let dotIdx, column;
  10. let alias = null;
  11. if (typeof selection !== 'string') {
  12. return null;
  13. }
  14. if (ALIAS_REGEX.test(selection)) {
  15. const parts = selection.split(ALIAS_REGEX);
  16. selection = parts[0].trim();
  17. alias = parts[1].trim();
  18. }
  19. dotIdx = selection.lastIndexOf('.');
  20. if (dotIdx !== -1) {
  21. table = selection.substr(0, dotIdx);
  22. column = selection.substr(dotIdx + 1);
  23. } else {
  24. column = selection;
  25. }
  26. return new this(table, column, alias);
  27. }
  28. static get SelectAll() {
  29. return SELECT_ALL;
  30. }
  31. get name() {
  32. return this.alias || this.column;
  33. }
  34. // Test if this selection "includes" another selection.
  35. // For example `foo.*` includes `foo.bar`.
  36. includes(that) {
  37. const tablesMatch = that.table === this.table || this.table === null;
  38. const colsMatch = this.column === that.column || this.column === '*';
  39. return tablesMatch && colsMatch;
  40. }
  41. }
  42. const SELECT_ALL = new Selection(null, '*');
  43. module.exports = Selection;