session.cjs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. LibSQLPreparedQuery: () => LibSQLPreparedQuery,
  22. LibSQLSession: () => LibSQLSession,
  23. LibSQLTransaction: () => LibSQLTransaction
  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 LibSQLSession extends import_session.SQLiteSession {
  34. constructor(client, dialect, schema, options, tx) {
  35. super(dialect);
  36. this.client = client;
  37. this.schema = schema;
  38. this.options = options;
  39. this.tx = tx;
  40. this.logger = options.logger ?? new import_logger.NoopLogger();
  41. this.cache = options.cache ?? new import_core.NoopCache();
  42. }
  43. static [import_entity.entityKind] = "LibSQLSession";
  44. logger;
  45. cache;
  46. prepareQuery(query, fields, executeMethod, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig) {
  47. return new LibSQLPreparedQuery(
  48. this.client,
  49. query,
  50. this.logger,
  51. this.cache,
  52. queryMetadata,
  53. cacheConfig,
  54. fields,
  55. this.tx,
  56. executeMethod,
  57. isResponseInArrayMode,
  58. customResultMapper
  59. );
  60. }
  61. async batch(queries) {
  62. const preparedQueries = [];
  63. const builtQueries = [];
  64. for (const query of queries) {
  65. const preparedQuery = query._prepare();
  66. const builtQuery = preparedQuery.getQuery();
  67. preparedQueries.push(preparedQuery);
  68. builtQueries.push({ sql: builtQuery.sql, args: builtQuery.params });
  69. }
  70. const batchResults = await this.client.batch(builtQueries);
  71. return batchResults.map((result, i) => preparedQueries[i].mapResult(result, true));
  72. }
  73. async migrate(queries) {
  74. const preparedQueries = [];
  75. const builtQueries = [];
  76. for (const query of queries) {
  77. const preparedQuery = query._prepare();
  78. const builtQuery = preparedQuery.getQuery();
  79. preparedQueries.push(preparedQuery);
  80. builtQueries.push({ sql: builtQuery.sql, args: builtQuery.params });
  81. }
  82. const batchResults = await this.client.migrate(builtQueries);
  83. return batchResults.map((result, i) => preparedQueries[i].mapResult(result, true));
  84. }
  85. async transaction(transaction, _config) {
  86. const libsqlTx = await this.client.transaction();
  87. const session = new LibSQLSession(
  88. this.client,
  89. this.dialect,
  90. this.schema,
  91. this.options,
  92. libsqlTx
  93. );
  94. const tx = new LibSQLTransaction("async", this.dialect, session, this.schema);
  95. try {
  96. const result = await transaction(tx);
  97. await libsqlTx.commit();
  98. return result;
  99. } catch (err) {
  100. await libsqlTx.rollback();
  101. throw err;
  102. }
  103. }
  104. extractRawAllValueFromBatchResult(result) {
  105. return result.rows;
  106. }
  107. extractRawGetValueFromBatchResult(result) {
  108. return result.rows[0];
  109. }
  110. extractRawValuesValueFromBatchResult(result) {
  111. return result.rows;
  112. }
  113. }
  114. class LibSQLTransaction extends import_sqlite_core.SQLiteTransaction {
  115. static [import_entity.entityKind] = "LibSQLTransaction";
  116. async transaction(transaction) {
  117. const savepointName = `sp${this.nestedIndex}`;
  118. const tx = new LibSQLTransaction("async", this.dialect, this.session, this.schema, this.nestedIndex + 1);
  119. await this.session.run(import_sql.sql.raw(`savepoint ${savepointName}`));
  120. try {
  121. const result = await transaction(tx);
  122. await this.session.run(import_sql.sql.raw(`release savepoint ${savepointName}`));
  123. return result;
  124. } catch (err) {
  125. await this.session.run(import_sql.sql.raw(`rollback to savepoint ${savepointName}`));
  126. throw err;
  127. }
  128. }
  129. }
  130. class LibSQLPreparedQuery extends import_session.SQLitePreparedQuery {
  131. constructor(client, query, logger, cache, queryMetadata, cacheConfig, fields, tx, executeMethod, _isResponseInArrayMode, customResultMapper) {
  132. super("async", executeMethod, query, cache, queryMetadata, cacheConfig);
  133. this.client = client;
  134. this.logger = logger;
  135. this.fields = fields;
  136. this.tx = tx;
  137. this._isResponseInArrayMode = _isResponseInArrayMode;
  138. this.customResultMapper = customResultMapper;
  139. this.customResultMapper = customResultMapper;
  140. this.fields = fields;
  141. }
  142. static [import_entity.entityKind] = "LibSQLPreparedQuery";
  143. async run(placeholderValues) {
  144. const params = (0, import_sql.fillPlaceholders)(this.query.params, placeholderValues ?? {});
  145. this.logger.logQuery(this.query.sql, params);
  146. return await this.queryWithCache(this.query.sql, params, async () => {
  147. const stmt = { sql: this.query.sql, args: params };
  148. return this.tx ? this.tx.execute(stmt) : this.client.execute(stmt);
  149. });
  150. }
  151. async all(placeholderValues) {
  152. const { fields, logger, query, tx, client, customResultMapper } = this;
  153. if (!fields && !customResultMapper) {
  154. const params = (0, import_sql.fillPlaceholders)(query.params, placeholderValues ?? {});
  155. logger.logQuery(query.sql, params);
  156. return await this.queryWithCache(query.sql, params, async () => {
  157. const stmt = { sql: query.sql, args: params };
  158. return (tx ? tx.execute(stmt) : client.execute(stmt)).then(({ rows: rows2 }) => this.mapAllResult(rows2));
  159. });
  160. }
  161. const rows = await this.values(placeholderValues);
  162. return this.mapAllResult(rows);
  163. }
  164. mapAllResult(rows, isFromBatch) {
  165. if (isFromBatch) {
  166. rows = rows.rows;
  167. }
  168. if (!this.fields && !this.customResultMapper) {
  169. return rows.map((row) => normalizeRow(row));
  170. }
  171. if (this.customResultMapper) {
  172. return this.customResultMapper(rows, normalizeFieldValue);
  173. }
  174. return rows.map((row) => {
  175. return (0, import_utils.mapResultRow)(
  176. this.fields,
  177. Array.prototype.slice.call(row).map((v) => normalizeFieldValue(v)),
  178. this.joinsNotNullableMap
  179. );
  180. });
  181. }
  182. async get(placeholderValues) {
  183. const { fields, logger, query, tx, client, customResultMapper } = this;
  184. if (!fields && !customResultMapper) {
  185. const params = (0, import_sql.fillPlaceholders)(query.params, placeholderValues ?? {});
  186. logger.logQuery(query.sql, params);
  187. return await this.queryWithCache(query.sql, params, async () => {
  188. const stmt = { sql: query.sql, args: params };
  189. return (tx ? tx.execute(stmt) : client.execute(stmt)).then(({ rows: rows2 }) => this.mapGetResult(rows2));
  190. });
  191. }
  192. const rows = await this.values(placeholderValues);
  193. return this.mapGetResult(rows);
  194. }
  195. mapGetResult(rows, isFromBatch) {
  196. if (isFromBatch) {
  197. rows = rows.rows;
  198. }
  199. const row = rows[0];
  200. if (!this.fields && !this.customResultMapper) {
  201. return normalizeRow(row);
  202. }
  203. if (!row) {
  204. return void 0;
  205. }
  206. if (this.customResultMapper) {
  207. return this.customResultMapper(rows, normalizeFieldValue);
  208. }
  209. return (0, import_utils.mapResultRow)(
  210. this.fields,
  211. Array.prototype.slice.call(row).map((v) => normalizeFieldValue(v)),
  212. this.joinsNotNullableMap
  213. );
  214. }
  215. async values(placeholderValues) {
  216. const params = (0, import_sql.fillPlaceholders)(this.query.params, placeholderValues ?? {});
  217. this.logger.logQuery(this.query.sql, params);
  218. return await this.queryWithCache(this.query.sql, params, async () => {
  219. const stmt = { sql: this.query.sql, args: params };
  220. return (this.tx ? this.tx.execute(stmt) : this.client.execute(stmt)).then(({ rows }) => rows);
  221. });
  222. }
  223. /** @internal */
  224. isResponseInArrayMode() {
  225. return this._isResponseInArrayMode;
  226. }
  227. }
  228. function normalizeRow(obj) {
  229. return Object.keys(obj).reduce((acc, key) => {
  230. if (Object.prototype.propertyIsEnumerable.call(obj, key)) {
  231. acc[key] = obj[key];
  232. }
  233. return acc;
  234. }, {});
  235. }
  236. function normalizeFieldValue(value) {
  237. if (typeof ArrayBuffer !== "undefined" && value instanceof ArrayBuffer) {
  238. if (typeof Buffer !== "undefined") {
  239. if (!(value instanceof Buffer)) {
  240. return Buffer.from(value);
  241. }
  242. return value;
  243. }
  244. if (typeof TextDecoder !== "undefined") {
  245. return new TextDecoder().decode(value);
  246. }
  247. throw new Error("TextDecoder is not available. Please provide either Buffer or TextDecoder polyfill.");
  248. }
  249. return value;
  250. }
  251. // Annotate the CommonJS export names for ESM import in node:
  252. 0 && (module.exports = {
  253. LibSQLPreparedQuery,
  254. LibSQLSession,
  255. LibSQLTransaction
  256. });
  257. //# sourceMappingURL=session.cjs.map