session.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. import { hashQuery, NoopCache } from "../cache/core/cache.js";
  2. import { entityKind, is } from "../entity.js";
  3. import { DrizzleQueryError, TransactionRollbackError } from "../errors.js";
  4. import { sql } from "../sql/index.js";
  5. import { tracer } from "../tracing.js";
  6. import { PgDatabase } from "./db.js";
  7. class PgPreparedQuery {
  8. constructor(query, cache, queryMetadata, cacheConfig) {
  9. this.query = query;
  10. this.cache = cache;
  11. this.queryMetadata = queryMetadata;
  12. this.cacheConfig = cacheConfig;
  13. if (cache && cache.strategy() === "all" && cacheConfig === void 0) {
  14. this.cacheConfig = { enable: true, autoInvalidate: true };
  15. }
  16. if (!this.cacheConfig?.enable) {
  17. this.cacheConfig = void 0;
  18. }
  19. }
  20. authToken;
  21. getQuery() {
  22. return this.query;
  23. }
  24. mapResult(response, _isFromBatch) {
  25. return response;
  26. }
  27. /** @internal */
  28. setToken(token) {
  29. this.authToken = token;
  30. return this;
  31. }
  32. static [entityKind] = "PgPreparedQuery";
  33. /** @internal */
  34. joinsNotNullableMap;
  35. /** @internal */
  36. async queryWithCache(queryString, params, query) {
  37. if (this.cache === void 0 || is(this.cache, NoopCache) || this.queryMetadata === void 0) {
  38. try {
  39. return await query();
  40. } catch (e) {
  41. throw new DrizzleQueryError(queryString, params, e);
  42. }
  43. }
  44. if (this.cacheConfig && !this.cacheConfig.enable) {
  45. try {
  46. return await query();
  47. } catch (e) {
  48. throw new DrizzleQueryError(queryString, params, e);
  49. }
  50. }
  51. if ((this.queryMetadata.type === "insert" || this.queryMetadata.type === "update" || this.queryMetadata.type === "delete") && this.queryMetadata.tables.length > 0) {
  52. try {
  53. const [res] = await Promise.all([
  54. query(),
  55. this.cache.onMutate({ tables: this.queryMetadata.tables })
  56. ]);
  57. return res;
  58. } catch (e) {
  59. throw new DrizzleQueryError(queryString, params, e);
  60. }
  61. }
  62. if (!this.cacheConfig) {
  63. try {
  64. return await query();
  65. } catch (e) {
  66. throw new DrizzleQueryError(queryString, params, e);
  67. }
  68. }
  69. if (this.queryMetadata.type === "select") {
  70. const fromCache = await this.cache.get(
  71. this.cacheConfig.tag ?? (await hashQuery(queryString, params)),
  72. this.queryMetadata.tables,
  73. this.cacheConfig.tag !== void 0,
  74. this.cacheConfig.autoInvalidate
  75. );
  76. if (fromCache === void 0) {
  77. let result;
  78. try {
  79. result = await query();
  80. } catch (e) {
  81. throw new DrizzleQueryError(queryString, params, e);
  82. }
  83. await this.cache.put(
  84. this.cacheConfig.tag ?? (await hashQuery(queryString, params)),
  85. result,
  86. // make sure we send tables that were used in a query only if user wants to invalidate it on each write
  87. this.cacheConfig.autoInvalidate ? this.queryMetadata.tables : [],
  88. this.cacheConfig.tag !== void 0,
  89. this.cacheConfig.config
  90. );
  91. return result;
  92. }
  93. return fromCache;
  94. }
  95. try {
  96. return await query();
  97. } catch (e) {
  98. throw new DrizzleQueryError(queryString, params, e);
  99. }
  100. }
  101. }
  102. class PgSession {
  103. constructor(dialect) {
  104. this.dialect = dialect;
  105. }
  106. static [entityKind] = "PgSession";
  107. /** @internal */
  108. execute(query, token) {
  109. return tracer.startActiveSpan("drizzle.operation", () => {
  110. const prepared = tracer.startActiveSpan("drizzle.prepareQuery", () => {
  111. return this.prepareQuery(
  112. this.dialect.sqlToQuery(query),
  113. void 0,
  114. void 0,
  115. false
  116. );
  117. });
  118. return prepared.setToken(token).execute(void 0, token);
  119. });
  120. }
  121. all(query) {
  122. return this.prepareQuery(
  123. this.dialect.sqlToQuery(query),
  124. void 0,
  125. void 0,
  126. false
  127. ).all();
  128. }
  129. /** @internal */
  130. async count(sql2, token) {
  131. const res = await this.execute(sql2, token);
  132. return Number(
  133. res[0]["count"]
  134. );
  135. }
  136. }
  137. class PgTransaction extends PgDatabase {
  138. constructor(dialect, session, schema, nestedIndex = 0) {
  139. super(dialect, session, schema);
  140. this.schema = schema;
  141. this.nestedIndex = nestedIndex;
  142. }
  143. static [entityKind] = "PgTransaction";
  144. rollback() {
  145. throw new TransactionRollbackError();
  146. }
  147. /** @internal */
  148. getTransactionConfigSQL(config) {
  149. const chunks = [];
  150. if (config.isolationLevel) {
  151. chunks.push(`isolation level ${config.isolationLevel}`);
  152. }
  153. if (config.accessMode) {
  154. chunks.push(config.accessMode);
  155. }
  156. if (typeof config.deferrable === "boolean") {
  157. chunks.push(config.deferrable ? "deferrable" : "not deferrable");
  158. }
  159. return sql.raw(chunks.join(" "));
  160. }
  161. setTransaction(config) {
  162. return this.session.execute(sql`set transaction ${this.getTransactionConfigSQL(config)}`);
  163. }
  164. }
  165. export {
  166. PgPreparedQuery,
  167. PgSession,
  168. PgTransaction
  169. };
  170. //# sourceMappingURL=session.js.map