LiteralBuilder.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. const { asArray, isObject } = require('../utils/objectUtils');
  2. const { buildArg } = require('../utils/buildUtils');
  3. class LiteralBuilder {
  4. constructor(value) {
  5. this._value = value;
  6. this._cast = null;
  7. // Cast objects and arrays to json by default.
  8. this._toJson = isObject(value);
  9. this._toArray = false;
  10. }
  11. get cast() {
  12. return this._cast;
  13. }
  14. castText() {
  15. return this.castTo('text');
  16. }
  17. castInt() {
  18. return this.castTo('integer');
  19. }
  20. castBigInt() {
  21. return this.castTo('bigint');
  22. }
  23. castFloat() {
  24. return this.castTo('float');
  25. }
  26. castDecimal() {
  27. return this.castTo('decimal');
  28. }
  29. castReal() {
  30. return this.castTo('real');
  31. }
  32. castBool() {
  33. return this.castTo('boolean');
  34. }
  35. castJson() {
  36. this._toArray = false;
  37. this._toJson = true;
  38. this._cast = 'jsonb';
  39. return this;
  40. }
  41. castArray() {
  42. console.log(
  43. 'castArray() is deprecated. Use asArray() instead. castArray() will be removed in 2.0'
  44. );
  45. return this.asArray();
  46. }
  47. castType(sqlType) {
  48. console.log(
  49. 'castType(type) is deprecated. Use castTo(type) instead. castType(type) will be removed in 2.0'
  50. );
  51. return this.castTo(sqlType);
  52. }
  53. castTo(sqlType) {
  54. this._cast = sqlType;
  55. return this;
  56. }
  57. asArray() {
  58. this._toJson = false;
  59. this._toArray = true;
  60. return this;
  61. }
  62. toKnexRaw(knex) {
  63. let sql = null;
  64. let bindings = null;
  65. if (this._toJson) {
  66. bindings = JSON.stringify(this._value);
  67. sql = '?';
  68. } else if (this._toArray) {
  69. bindings = asArray(this._value).map(it => buildArg(it, knex));
  70. sql = `ARRAY[${bindings.map(() => '?').join(', ')}]`;
  71. } else {
  72. bindings = this._value;
  73. sql = '?';
  74. }
  75. if (this._cast) {
  76. sql = `CAST(${sql} AS ${this._cast})`;
  77. }
  78. return knex.raw(sql, bindings);
  79. }
  80. }
  81. function lit(val) {
  82. return new LiteralBuilder(val);
  83. }
  84. module.exports = {
  85. LiteralBuilder,
  86. lit
  87. };