foreign-keys.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { entityKind } from "../entity.js";
  2. import { TableName } from "../table.utils.js";
  3. class ForeignKeyBuilder {
  4. static [entityKind] = "MySqlForeignKeyBuilder";
  5. /** @internal */
  6. reference;
  7. /** @internal */
  8. _onUpdate;
  9. /** @internal */
  10. _onDelete;
  11. constructor(config, actions) {
  12. this.reference = () => {
  13. const { name, columns, foreignColumns } = config();
  14. return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns };
  15. };
  16. if (actions) {
  17. this._onUpdate = actions.onUpdate;
  18. this._onDelete = actions.onDelete;
  19. }
  20. }
  21. onUpdate(action) {
  22. this._onUpdate = action;
  23. return this;
  24. }
  25. onDelete(action) {
  26. this._onDelete = action;
  27. return this;
  28. }
  29. /** @internal */
  30. build(table) {
  31. return new ForeignKey(table, this);
  32. }
  33. }
  34. class ForeignKey {
  35. constructor(table, builder) {
  36. this.table = table;
  37. this.reference = builder.reference;
  38. this.onUpdate = builder._onUpdate;
  39. this.onDelete = builder._onDelete;
  40. }
  41. static [entityKind] = "MySqlForeignKey";
  42. reference;
  43. onUpdate;
  44. onDelete;
  45. getName() {
  46. const { name, columns, foreignColumns } = this.reference();
  47. const columnNames = columns.map((column) => column.name);
  48. const foreignColumnNames = foreignColumns.map((column) => column.name);
  49. const chunks = [
  50. this.table[TableName],
  51. ...columnNames,
  52. foreignColumns[0].table[TableName],
  53. ...foreignColumnNames
  54. ];
  55. return name ?? `${chunks.join("_")}_fk`;
  56. }
  57. }
  58. function foreignKey(config) {
  59. function mappedConfig() {
  60. const { name, columns, foreignColumns } = config;
  61. return {
  62. name,
  63. columns,
  64. foreignColumns
  65. };
  66. }
  67. return new ForeignKeyBuilder(mappedConfig);
  68. }
  69. export {
  70. ForeignKey,
  71. ForeignKeyBuilder,
  72. foreignKey
  73. };
  74. //# sourceMappingURL=foreign-keys.js.map