selection-proxy.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { ColumnAliasProxyHandler, TableAliasProxyHandler } from "./alias.js";
  2. import { Column } from "./column.js";
  3. import { entityKind, is } from "./entity.js";
  4. import { SQL, View } from "./sql/sql.js";
  5. import { Subquery } from "./subquery.js";
  6. import { ViewBaseConfig } from "./view-common.js";
  7. class SelectionProxyHandler {
  8. static [entityKind] = "SelectionProxyHandler";
  9. config;
  10. constructor(config) {
  11. this.config = { ...config };
  12. }
  13. get(subquery, prop) {
  14. if (prop === "_") {
  15. return {
  16. ...subquery["_"],
  17. selectedFields: new Proxy(
  18. subquery._.selectedFields,
  19. this
  20. )
  21. };
  22. }
  23. if (prop === ViewBaseConfig) {
  24. return {
  25. ...subquery[ViewBaseConfig],
  26. selectedFields: new Proxy(
  27. subquery[ViewBaseConfig].selectedFields,
  28. this
  29. )
  30. };
  31. }
  32. if (typeof prop === "symbol") {
  33. return subquery[prop];
  34. }
  35. const columns = is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery;
  36. const value = columns[prop];
  37. if (is(value, SQL.Aliased)) {
  38. if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) {
  39. return value.sql;
  40. }
  41. const newValue = value.clone();
  42. newValue.isSelectionField = true;
  43. return newValue;
  44. }
  45. if (is(value, SQL)) {
  46. if (this.config.sqlBehavior === "sql") {
  47. return value;
  48. }
  49. throw new Error(
  50. `You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`
  51. );
  52. }
  53. if (is(value, Column)) {
  54. if (this.config.alias) {
  55. return new Proxy(
  56. value,
  57. new ColumnAliasProxyHandler(
  58. new Proxy(
  59. value.table,
  60. new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false)
  61. )
  62. )
  63. );
  64. }
  65. return value;
  66. }
  67. if (typeof value !== "object" || value === null) {
  68. return value;
  69. }
  70. return new Proxy(value, new SelectionProxyHandler(this.config));
  71. }
  72. }
  73. export {
  74. SelectionProxyHandler
  75. };
  76. //# sourceMappingURL=selection-proxy.js.map