driver.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import { createClient } from "gel";
  2. import { entityKind } from "../entity.js";
  3. import { GelDatabase } from "../gel-core/db.js";
  4. import { GelDialect } from "../gel-core/dialect.js";
  5. import { DefaultLogger } from "../logger.js";
  6. import {
  7. createTableRelationsHelpers,
  8. extractTablesRelationalConfig
  9. } from "../relations.js";
  10. import { isConfig } from "../utils.js";
  11. import { GelDbSession } from "./session.js";
  12. class GelDriver {
  13. constructor(client, dialect, options = {}) {
  14. this.client = client;
  15. this.dialect = dialect;
  16. this.options = options;
  17. }
  18. static [entityKind] = "GelDriver";
  19. createSession(schema) {
  20. return new GelDbSession(this.client, this.dialect, schema, {
  21. logger: this.options.logger,
  22. cache: this.options.cache
  23. });
  24. }
  25. }
  26. class GelJsDatabase extends GelDatabase {
  27. static [entityKind] = "GelJsDatabase";
  28. }
  29. function construct(client, config = {}) {
  30. const dialect = new GelDialect({ casing: config.casing });
  31. let logger;
  32. if (config.logger === true) {
  33. logger = new DefaultLogger();
  34. } else if (config.logger !== false) {
  35. logger = config.logger;
  36. }
  37. let schema;
  38. if (config.schema) {
  39. const tablesConfig = extractTablesRelationalConfig(config.schema, createTableRelationsHelpers);
  40. schema = {
  41. fullSchema: config.schema,
  42. schema: tablesConfig.tables,
  43. tableNamesMap: tablesConfig.tableNamesMap
  44. };
  45. }
  46. const driver = new GelDriver(client, dialect, { logger, cache: config.cache });
  47. const session = driver.createSession(schema);
  48. const db = new GelJsDatabase(dialect, session, schema);
  49. db.$client = client;
  50. db.$cache = config.cache;
  51. if (db.$cache) {
  52. db.$cache["invalidate"] = config.cache?.onMutate;
  53. }
  54. return db;
  55. }
  56. function drizzle(...params) {
  57. if (typeof params[0] === "string") {
  58. const instance = createClient({ dsn: params[0] });
  59. return construct(instance, params[1]);
  60. }
  61. if (isConfig(params[0])) {
  62. const { connection, client, ...drizzleConfig } = params[0];
  63. if (client) return construct(client, drizzleConfig);
  64. const instance = createClient(connection);
  65. return construct(instance, drizzleConfig);
  66. }
  67. return construct(params[0], params[1]);
  68. }
  69. ((drizzle2) => {
  70. function mock(config) {
  71. return construct({}, config);
  72. }
  73. drizzle2.mock = mock;
  74. })(drizzle || (drizzle = {}));
  75. export {
  76. GelDriver,
  77. GelJsDatabase,
  78. drizzle
  79. };
  80. //# sourceMappingURL=driver.js.map