session.cjs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. "use strict";
  2. var __defProp = Object.defineProperty;
  3. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  4. var __getOwnPropNames = Object.getOwnPropertyNames;
  5. var __hasOwnProp = Object.prototype.hasOwnProperty;
  6. var __export = (target, all) => {
  7. for (var name in all)
  8. __defProp(target, name, { get: all[name], enumerable: true });
  9. };
  10. var __copyProps = (to, from, except, desc) => {
  11. if (from && typeof from === "object" || typeof from === "function") {
  12. for (let key of __getOwnPropNames(from))
  13. if (!__hasOwnProp.call(to, key) && key !== except)
  14. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  15. }
  16. return to;
  17. };
  18. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  19. var session_exports = {};
  20. __export(session_exports, {
  21. D1PreparedQuery: () => D1PreparedQuery,
  22. D1Transaction: () => D1Transaction,
  23. SQLiteD1Session: () => SQLiteD1Session
  24. });
  25. module.exports = __toCommonJS(session_exports);
  26. var import_core = require("../cache/core/index.cjs");
  27. var import_entity = require("../entity.cjs");
  28. var import_logger = require("../logger.cjs");
  29. var import_sql = require("../sql/sql.cjs");
  30. var import_sqlite_core = require("../sqlite-core/index.cjs");
  31. var import_session = require("../sqlite-core/session.cjs");
  32. var import_utils = require("../utils.cjs");
  33. class SQLiteD1Session extends import_session.SQLiteSession {
  34. constructor(client, dialect, schema, options = {}) {
  35. super(dialect);
  36. this.client = client;
  37. this.schema = schema;
  38. this.options = options;
  39. this.logger = options.logger ?? new import_logger.NoopLogger();
  40. this.cache = options.cache ?? new import_core.NoopCache();
  41. }
  42. static [import_entity.entityKind] = "SQLiteD1Session";
  43. logger;
  44. cache;
  45. prepareQuery(query, fields, executeMethod, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig) {
  46. const stmt = this.client.prepare(query.sql);
  47. return new D1PreparedQuery(
  48. stmt,
  49. query,
  50. this.logger,
  51. this.cache,
  52. queryMetadata,
  53. cacheConfig,
  54. fields,
  55. executeMethod,
  56. isResponseInArrayMode,
  57. customResultMapper
  58. );
  59. }
  60. async batch(queries) {
  61. const preparedQueries = [];
  62. const builtQueries = [];
  63. for (const query of queries) {
  64. const preparedQuery = query._prepare();
  65. const builtQuery = preparedQuery.getQuery();
  66. preparedQueries.push(preparedQuery);
  67. if (builtQuery.params.length > 0) {
  68. builtQueries.push(preparedQuery.stmt.bind(...builtQuery.params));
  69. } else {
  70. const builtQuery2 = preparedQuery.getQuery();
  71. builtQueries.push(
  72. this.client.prepare(builtQuery2.sql).bind(...builtQuery2.params)
  73. );
  74. }
  75. }
  76. const batchResults = await this.client.batch(builtQueries);
  77. return batchResults.map((result, i) => preparedQueries[i].mapResult(result, true));
  78. }
  79. extractRawAllValueFromBatchResult(result) {
  80. return result.results;
  81. }
  82. extractRawGetValueFromBatchResult(result) {
  83. return result.results[0];
  84. }
  85. extractRawValuesValueFromBatchResult(result) {
  86. return d1ToRawMapping(result.results);
  87. }
  88. async transaction(transaction, config) {
  89. const tx = new D1Transaction("async", this.dialect, this, this.schema);
  90. await this.run(import_sql.sql.raw(`begin${config?.behavior ? " " + config.behavior : ""}`));
  91. try {
  92. const result = await transaction(tx);
  93. await this.run(import_sql.sql`commit`);
  94. return result;
  95. } catch (err) {
  96. await this.run(import_sql.sql`rollback`);
  97. throw err;
  98. }
  99. }
  100. }
  101. class D1Transaction extends import_sqlite_core.SQLiteTransaction {
  102. static [import_entity.entityKind] = "D1Transaction";
  103. async transaction(transaction) {
  104. const savepointName = `sp${this.nestedIndex}`;
  105. const tx = new D1Transaction("async", this.dialect, this.session, this.schema, this.nestedIndex + 1);
  106. await this.session.run(import_sql.sql.raw(`savepoint ${savepointName}`));
  107. try {
  108. const result = await transaction(tx);
  109. await this.session.run(import_sql.sql.raw(`release savepoint ${savepointName}`));
  110. return result;
  111. } catch (err) {
  112. await this.session.run(import_sql.sql.raw(`rollback to savepoint ${savepointName}`));
  113. throw err;
  114. }
  115. }
  116. }
  117. function d1ToRawMapping(results) {
  118. const rows = [];
  119. for (const row of results) {
  120. const entry = Object.keys(row).map((k) => row[k]);
  121. rows.push(entry);
  122. }
  123. return rows;
  124. }
  125. class D1PreparedQuery extends import_session.SQLitePreparedQuery {
  126. constructor(stmt, query, logger, cache, queryMetadata, cacheConfig, fields, executeMethod, _isResponseInArrayMode, customResultMapper) {
  127. super("async", executeMethod, query, cache, queryMetadata, cacheConfig);
  128. this.logger = logger;
  129. this._isResponseInArrayMode = _isResponseInArrayMode;
  130. this.customResultMapper = customResultMapper;
  131. this.fields = fields;
  132. this.stmt = stmt;
  133. }
  134. static [import_entity.entityKind] = "D1PreparedQuery";
  135. /** @internal */
  136. customResultMapper;
  137. /** @internal */
  138. fields;
  139. /** @internal */
  140. stmt;
  141. async run(placeholderValues) {
  142. const params = (0, import_sql.fillPlaceholders)(this.query.params, placeholderValues ?? {});
  143. this.logger.logQuery(this.query.sql, params);
  144. return await this.queryWithCache(this.query.sql, params, async () => {
  145. return this.stmt.bind(...params).run();
  146. });
  147. }
  148. async all(placeholderValues) {
  149. const { fields, query, logger, stmt, customResultMapper } = this;
  150. if (!fields && !customResultMapper) {
  151. const params = (0, import_sql.fillPlaceholders)(query.params, placeholderValues ?? {});
  152. logger.logQuery(query.sql, params);
  153. return await this.queryWithCache(query.sql, params, async () => {
  154. return stmt.bind(...params).all().then(({ results }) => this.mapAllResult(results));
  155. });
  156. }
  157. const rows = await this.values(placeholderValues);
  158. return this.mapAllResult(rows);
  159. }
  160. mapAllResult(rows, isFromBatch) {
  161. if (isFromBatch) {
  162. rows = d1ToRawMapping(rows.results);
  163. }
  164. if (!this.fields && !this.customResultMapper) {
  165. return rows;
  166. }
  167. if (this.customResultMapper) {
  168. return this.customResultMapper(rows);
  169. }
  170. return rows.map((row) => (0, import_utils.mapResultRow)(this.fields, row, this.joinsNotNullableMap));
  171. }
  172. async get(placeholderValues) {
  173. const { fields, joinsNotNullableMap, query, logger, stmt, customResultMapper } = this;
  174. if (!fields && !customResultMapper) {
  175. const params = (0, import_sql.fillPlaceholders)(query.params, placeholderValues ?? {});
  176. logger.logQuery(query.sql, params);
  177. return await this.queryWithCache(query.sql, params, async () => {
  178. return stmt.bind(...params).all().then(({ results }) => results[0]);
  179. });
  180. }
  181. const rows = await this.values(placeholderValues);
  182. if (!rows[0]) {
  183. return void 0;
  184. }
  185. if (customResultMapper) {
  186. return customResultMapper(rows);
  187. }
  188. return (0, import_utils.mapResultRow)(fields, rows[0], joinsNotNullableMap);
  189. }
  190. mapGetResult(result, isFromBatch) {
  191. if (isFromBatch) {
  192. result = d1ToRawMapping(result.results)[0];
  193. }
  194. if (!this.fields && !this.customResultMapper) {
  195. return result;
  196. }
  197. if (this.customResultMapper) {
  198. return this.customResultMapper([result]);
  199. }
  200. return (0, import_utils.mapResultRow)(this.fields, result, this.joinsNotNullableMap);
  201. }
  202. async values(placeholderValues) {
  203. const params = (0, import_sql.fillPlaceholders)(this.query.params, placeholderValues ?? {});
  204. this.logger.logQuery(this.query.sql, params);
  205. return await this.queryWithCache(this.query.sql, params, async () => {
  206. return this.stmt.bind(...params).raw();
  207. });
  208. }
  209. /** @internal */
  210. isResponseInArrayMode() {
  211. return this._isResponseInArrayMode;
  212. }
  213. }
  214. // Annotate the CommonJS export names for ESM import in node:
  215. 0 && (module.exports = {
  216. D1PreparedQuery,
  217. D1Transaction,
  218. SQLiteD1Session
  219. });
  220. //# sourceMappingURL=session.cjs.map