query-builder.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import { entityKind, is } from "../../entity.js";
  2. import { PgDialect } from "../dialect.js";
  3. import { SelectionProxyHandler } from "../../selection-proxy.js";
  4. import { WithSubquery } from "../../subquery.js";
  5. import { PgSelectBuilder } from "./select.js";
  6. class QueryBuilder {
  7. static [entityKind] = "PgQueryBuilder";
  8. dialect;
  9. dialectConfig;
  10. constructor(dialect) {
  11. this.dialect = is(dialect, PgDialect) ? dialect : void 0;
  12. this.dialectConfig = is(dialect, PgDialect) ? void 0 : dialect;
  13. }
  14. $with = (alias, selection) => {
  15. const queryBuilder = this;
  16. const as = (qb) => {
  17. if (typeof qb === "function") {
  18. qb = qb(queryBuilder);
  19. }
  20. return new Proxy(
  21. new WithSubquery(
  22. qb.getSQL(),
  23. selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}),
  24. alias,
  25. true
  26. ),
  27. new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
  28. );
  29. };
  30. return { as };
  31. };
  32. with(...queries) {
  33. const self = this;
  34. function select(fields) {
  35. return new PgSelectBuilder({
  36. fields: fields ?? void 0,
  37. session: void 0,
  38. dialect: self.getDialect(),
  39. withList: queries
  40. });
  41. }
  42. function selectDistinct(fields) {
  43. return new PgSelectBuilder({
  44. fields: fields ?? void 0,
  45. session: void 0,
  46. dialect: self.getDialect(),
  47. distinct: true
  48. });
  49. }
  50. function selectDistinctOn(on, fields) {
  51. return new PgSelectBuilder({
  52. fields: fields ?? void 0,
  53. session: void 0,
  54. dialect: self.getDialect(),
  55. distinct: { on }
  56. });
  57. }
  58. return { select, selectDistinct, selectDistinctOn };
  59. }
  60. select(fields) {
  61. return new PgSelectBuilder({
  62. fields: fields ?? void 0,
  63. session: void 0,
  64. dialect: this.getDialect()
  65. });
  66. }
  67. selectDistinct(fields) {
  68. return new PgSelectBuilder({
  69. fields: fields ?? void 0,
  70. session: void 0,
  71. dialect: this.getDialect(),
  72. distinct: true
  73. });
  74. }
  75. selectDistinctOn(on, fields) {
  76. return new PgSelectBuilder({
  77. fields: fields ?? void 0,
  78. session: void 0,
  79. dialect: this.getDialect(),
  80. distinct: { on }
  81. });
  82. }
  83. // Lazy load dialect to avoid circular dependency
  84. getDialect() {
  85. if (!this.dialect) {
  86. this.dialect = new PgDialect(this.dialectConfig);
  87. }
  88. return this.dialect;
  89. }
  90. }
  91. export {
  92. QueryBuilder
  93. };
  94. //# sourceMappingURL=query-builder.js.map