session.js 7.9 KB

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