session.cjs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. MySql2PreparedQuery: () => MySql2PreparedQuery,
  22. MySql2Session: () => MySql2Session,
  23. MySql2Transaction: () => MySql2Transaction
  24. });
  25. module.exports = __toCommonJS(session_exports);
  26. var import_node_events = require("node:events");
  27. var import_core = require("../cache/core/index.cjs");
  28. var import_column = require("../column.cjs");
  29. var import_entity = require("../entity.cjs");
  30. var import_logger = require("../logger.cjs");
  31. var import_session = require("../mysql-core/session.cjs");
  32. var import_sql = require("../sql/sql.cjs");
  33. var import_utils = require("../utils.cjs");
  34. class MySql2PreparedQuery extends import_session.MySqlPreparedQuery {
  35. constructor(client, queryString, params, logger, cache, queryMetadata, cacheConfig, fields, customResultMapper, generatedIds, returningIds) {
  36. super(cache, queryMetadata, cacheConfig);
  37. this.client = client;
  38. this.params = params;
  39. this.logger = logger;
  40. this.fields = fields;
  41. this.customResultMapper = customResultMapper;
  42. this.generatedIds = generatedIds;
  43. this.returningIds = returningIds;
  44. this.rawQuery = {
  45. sql: queryString,
  46. // rowsAsArray: true,
  47. typeCast: function(field, next) {
  48. if (field.type === "TIMESTAMP" || field.type === "DATETIME" || field.type === "DATE") {
  49. return field.string();
  50. }
  51. return next();
  52. }
  53. };
  54. this.query = {
  55. sql: queryString,
  56. rowsAsArray: true,
  57. typeCast: function(field, next) {
  58. if (field.type === "TIMESTAMP" || field.type === "DATETIME" || field.type === "DATE") {
  59. return field.string();
  60. }
  61. return next();
  62. }
  63. };
  64. }
  65. static [import_entity.entityKind] = "MySql2PreparedQuery";
  66. rawQuery;
  67. query;
  68. async execute(placeholderValues = {}) {
  69. const params = (0, import_sql.fillPlaceholders)(this.params, placeholderValues);
  70. this.logger.logQuery(this.rawQuery.sql, params);
  71. const { fields, client, rawQuery, query, joinsNotNullableMap, customResultMapper, returningIds, generatedIds } = this;
  72. if (!fields && !customResultMapper) {
  73. const res = await this.queryWithCache(rawQuery.sql, params, async () => {
  74. return await client.query(rawQuery, params);
  75. });
  76. const insertId = res[0].insertId;
  77. const affectedRows = res[0].affectedRows;
  78. if (returningIds) {
  79. const returningResponse = [];
  80. let j = 0;
  81. for (let i = insertId; i < insertId + affectedRows; i++) {
  82. for (const column of returningIds) {
  83. const key = returningIds[0].path[0];
  84. if ((0, import_entity.is)(column.field, import_column.Column)) {
  85. if (column.field.primary && column.field.autoIncrement) {
  86. returningResponse.push({ [key]: i });
  87. }
  88. if (column.field.defaultFn && generatedIds) {
  89. returningResponse.push({ [key]: generatedIds[j][key] });
  90. }
  91. }
  92. }
  93. j++;
  94. }
  95. return returningResponse;
  96. }
  97. return res;
  98. }
  99. const result = await this.queryWithCache(query.sql, params, async () => {
  100. return await client.query(query, params);
  101. });
  102. const rows = result[0];
  103. if (customResultMapper) {
  104. return customResultMapper(rows);
  105. }
  106. return rows.map((row) => (0, import_utils.mapResultRow)(fields, row, joinsNotNullableMap));
  107. }
  108. async *iterator(placeholderValues = {}) {
  109. const params = (0, import_sql.fillPlaceholders)(this.params, placeholderValues);
  110. const conn = (isPool(this.client) ? await this.client.getConnection() : this.client).connection;
  111. const { fields, query, rawQuery, joinsNotNullableMap, client, customResultMapper } = this;
  112. const hasRowsMapper = Boolean(fields || customResultMapper);
  113. const driverQuery = hasRowsMapper ? conn.query(query, params) : conn.query(rawQuery, params);
  114. const stream = driverQuery.stream();
  115. function dataListener() {
  116. stream.pause();
  117. }
  118. stream.on("data", dataListener);
  119. try {
  120. const onEnd = (0, import_node_events.once)(stream, "end");
  121. const onError = (0, import_node_events.once)(stream, "error");
  122. while (true) {
  123. stream.resume();
  124. const row = await Promise.race([onEnd, onError, new Promise((resolve) => stream.once("data", resolve))]);
  125. if (row === void 0 || Array.isArray(row) && row.length === 0) {
  126. break;
  127. } else if (row instanceof Error) {
  128. throw row;
  129. } else {
  130. if (hasRowsMapper) {
  131. if (customResultMapper) {
  132. const mappedRow = customResultMapper([row]);
  133. yield Array.isArray(mappedRow) ? mappedRow[0] : mappedRow;
  134. } else {
  135. yield (0, import_utils.mapResultRow)(fields, row, joinsNotNullableMap);
  136. }
  137. } else {
  138. yield row;
  139. }
  140. }
  141. }
  142. } finally {
  143. stream.off("data", dataListener);
  144. if (isPool(client)) {
  145. conn.end();
  146. }
  147. }
  148. }
  149. }
  150. class MySql2Session extends import_session.MySqlSession {
  151. constructor(client, dialect, schema, options) {
  152. super(dialect);
  153. this.client = client;
  154. this.schema = schema;
  155. this.options = options;
  156. this.logger = options.logger ?? new import_logger.NoopLogger();
  157. this.cache = options.cache ?? new import_core.NoopCache();
  158. this.mode = options.mode;
  159. }
  160. static [import_entity.entityKind] = "MySql2Session";
  161. logger;
  162. mode;
  163. cache;
  164. prepareQuery(query, fields, customResultMapper, generatedIds, returningIds, queryMetadata, cacheConfig) {
  165. return new MySql2PreparedQuery(
  166. this.client,
  167. query.sql,
  168. query.params,
  169. this.logger,
  170. this.cache,
  171. queryMetadata,
  172. cacheConfig,
  173. fields,
  174. customResultMapper,
  175. generatedIds,
  176. returningIds
  177. );
  178. }
  179. /**
  180. * @internal
  181. * What is its purpose?
  182. */
  183. async query(query, params) {
  184. this.logger.logQuery(query, params);
  185. const result = await this.client.query({
  186. sql: query,
  187. values: params,
  188. rowsAsArray: true,
  189. typeCast: function(field, next) {
  190. if (field.type === "TIMESTAMP" || field.type === "DATETIME" || field.type === "DATE") {
  191. return field.string();
  192. }
  193. return next();
  194. }
  195. });
  196. return result;
  197. }
  198. all(query) {
  199. const querySql = this.dialect.sqlToQuery(query);
  200. this.logger.logQuery(querySql.sql, querySql.params);
  201. return this.client.execute(querySql.sql, querySql.params).then((result) => result[0]);
  202. }
  203. async transaction(transaction, config) {
  204. const session = isPool(this.client) ? new MySql2Session(
  205. await this.client.getConnection(),
  206. this.dialect,
  207. this.schema,
  208. this.options
  209. ) : this;
  210. const tx = new MySql2Transaction(
  211. this.dialect,
  212. session,
  213. this.schema,
  214. 0,
  215. this.mode
  216. );
  217. if (config) {
  218. const setTransactionConfigSql = this.getSetTransactionSQL(config);
  219. if (setTransactionConfigSql) {
  220. await tx.execute(setTransactionConfigSql);
  221. }
  222. const startTransactionSql = this.getStartTransactionSQL(config);
  223. await (startTransactionSql ? tx.execute(startTransactionSql) : tx.execute(import_sql.sql`begin`));
  224. } else {
  225. await tx.execute(import_sql.sql`begin`);
  226. }
  227. try {
  228. const result = await transaction(tx);
  229. await tx.execute(import_sql.sql`commit`);
  230. return result;
  231. } catch (err) {
  232. await tx.execute(import_sql.sql`rollback`);
  233. throw err;
  234. } finally {
  235. if (isPool(this.client)) {
  236. session.client.release();
  237. }
  238. }
  239. }
  240. }
  241. class MySql2Transaction extends import_session.MySqlTransaction {
  242. static [import_entity.entityKind] = "MySql2Transaction";
  243. async transaction(transaction) {
  244. const savepointName = `sp${this.nestedIndex + 1}`;
  245. const tx = new MySql2Transaction(
  246. this.dialect,
  247. this.session,
  248. this.schema,
  249. this.nestedIndex + 1,
  250. this.mode
  251. );
  252. await tx.execute(import_sql.sql.raw(`savepoint ${savepointName}`));
  253. try {
  254. const result = await transaction(tx);
  255. await tx.execute(import_sql.sql.raw(`release savepoint ${savepointName}`));
  256. return result;
  257. } catch (err) {
  258. await tx.execute(import_sql.sql.raw(`rollback to savepoint ${savepointName}`));
  259. throw err;
  260. }
  261. }
  262. }
  263. function isPool(client) {
  264. return "getConnection" in client;
  265. }
  266. // Annotate the CommonJS export names for ESM import in node:
  267. 0 && (module.exports = {
  268. MySql2PreparedQuery,
  269. MySql2Session,
  270. MySql2Transaction
  271. });
  272. //# sourceMappingURL=session.cjs.map