session.cjs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. "use strict";
  2. var __create = Object.create;
  3. var __defProp = Object.defineProperty;
  4. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  5. var __getOwnPropNames = Object.getOwnPropertyNames;
  6. var __getProtoOf = Object.getPrototypeOf;
  7. var __hasOwnProp = Object.prototype.hasOwnProperty;
  8. var __export = (target, all) => {
  9. for (var name in all)
  10. __defProp(target, name, { get: all[name], enumerable: true });
  11. };
  12. var __copyProps = (to, from, except, desc) => {
  13. if (from && typeof from === "object" || typeof from === "function") {
  14. for (let key of __getOwnPropNames(from))
  15. if (!__hasOwnProp.call(to, key) && key !== except)
  16. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  17. }
  18. return to;
  19. };
  20. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  21. // If the importer is in node compatibility mode or this is not an ESM
  22. // file that has been converted to a CommonJS file using a Babel-
  23. // compatible transform (i.e. "__esModule" has not been set), then set
  24. // "default" to the CommonJS "module.exports" for node compatibility.
  25. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  26. mod
  27. ));
  28. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  29. var session_exports = {};
  30. __export(session_exports, {
  31. NodePgPreparedQuery: () => NodePgPreparedQuery,
  32. NodePgSession: () => NodePgSession,
  33. NodePgTransaction: () => NodePgTransaction
  34. });
  35. module.exports = __toCommonJS(session_exports);
  36. var import_pg = __toESM(require("pg"), 1);
  37. var import_core = require("../cache/core/index.cjs");
  38. var import_entity = require("../entity.cjs");
  39. var import_logger = require("../logger.cjs");
  40. var import_pg_core = require("../pg-core/index.cjs");
  41. var import_session = require("../pg-core/session.cjs");
  42. var import_sql = require("../sql/sql.cjs");
  43. var import_tracing = require("../tracing.cjs");
  44. var import_utils = require("../utils.cjs");
  45. const { Pool, types } = import_pg.default;
  46. class NodePgPreparedQuery extends import_session.PgPreparedQuery {
  47. constructor(client, queryString, params, logger, cache, queryMetadata, cacheConfig, fields, name, _isResponseInArrayMode, customResultMapper) {
  48. super({ sql: queryString, params }, cache, queryMetadata, cacheConfig);
  49. this.client = client;
  50. this.queryString = queryString;
  51. this.params = params;
  52. this.logger = logger;
  53. this.fields = fields;
  54. this._isResponseInArrayMode = _isResponseInArrayMode;
  55. this.customResultMapper = customResultMapper;
  56. this.rawQueryConfig = {
  57. name,
  58. text: queryString,
  59. types: {
  60. // @ts-ignore
  61. getTypeParser: (typeId, format) => {
  62. if (typeId === types.builtins.TIMESTAMPTZ) {
  63. return (val) => val;
  64. }
  65. if (typeId === types.builtins.TIMESTAMP) {
  66. return (val) => val;
  67. }
  68. if (typeId === types.builtins.DATE) {
  69. return (val) => val;
  70. }
  71. if (typeId === types.builtins.INTERVAL) {
  72. return (val) => val;
  73. }
  74. if (typeId === 1231) {
  75. return (val) => val;
  76. }
  77. if (typeId === 1115) {
  78. return (val) => val;
  79. }
  80. if (typeId === 1185) {
  81. return (val) => val;
  82. }
  83. if (typeId === 1187) {
  84. return (val) => val;
  85. }
  86. if (typeId === 1182) {
  87. return (val) => val;
  88. }
  89. return types.getTypeParser(typeId, format);
  90. }
  91. }
  92. };
  93. this.queryConfig = {
  94. name,
  95. text: queryString,
  96. rowMode: "array",
  97. types: {
  98. // @ts-ignore
  99. getTypeParser: (typeId, format) => {
  100. if (typeId === types.builtins.TIMESTAMPTZ) {
  101. return (val) => val;
  102. }
  103. if (typeId === types.builtins.TIMESTAMP) {
  104. return (val) => val;
  105. }
  106. if (typeId === types.builtins.DATE) {
  107. return (val) => val;
  108. }
  109. if (typeId === types.builtins.INTERVAL) {
  110. return (val) => val;
  111. }
  112. if (typeId === 1231) {
  113. return (val) => val;
  114. }
  115. if (typeId === 1115) {
  116. return (val) => val;
  117. }
  118. if (typeId === 1185) {
  119. return (val) => val;
  120. }
  121. if (typeId === 1187) {
  122. return (val) => val;
  123. }
  124. if (typeId === 1182) {
  125. return (val) => val;
  126. }
  127. return types.getTypeParser(typeId, format);
  128. }
  129. }
  130. };
  131. }
  132. static [import_entity.entityKind] = "NodePgPreparedQuery";
  133. rawQueryConfig;
  134. queryConfig;
  135. async execute(placeholderValues = {}) {
  136. return import_tracing.tracer.startActiveSpan("drizzle.execute", async () => {
  137. const params = (0, import_sql.fillPlaceholders)(this.params, placeholderValues);
  138. this.logger.logQuery(this.rawQueryConfig.text, params);
  139. const { fields, rawQueryConfig: rawQuery, client, queryConfig: query, joinsNotNullableMap, customResultMapper } = this;
  140. if (!fields && !customResultMapper) {
  141. return import_tracing.tracer.startActiveSpan("drizzle.driver.execute", async (span) => {
  142. span?.setAttributes({
  143. "drizzle.query.name": rawQuery.name,
  144. "drizzle.query.text": rawQuery.text,
  145. "drizzle.query.params": JSON.stringify(params)
  146. });
  147. return this.queryWithCache(rawQuery.text, params, async () => {
  148. return await client.query(rawQuery, params);
  149. });
  150. });
  151. }
  152. const result = await import_tracing.tracer.startActiveSpan("drizzle.driver.execute", (span) => {
  153. span?.setAttributes({
  154. "drizzle.query.name": query.name,
  155. "drizzle.query.text": query.text,
  156. "drizzle.query.params": JSON.stringify(params)
  157. });
  158. return this.queryWithCache(query.text, params, async () => {
  159. return await client.query(query, params);
  160. });
  161. });
  162. return import_tracing.tracer.startActiveSpan("drizzle.mapResponse", () => {
  163. return customResultMapper ? customResultMapper(result.rows) : result.rows.map((row) => (0, import_utils.mapResultRow)(fields, row, joinsNotNullableMap));
  164. });
  165. });
  166. }
  167. all(placeholderValues = {}) {
  168. return import_tracing.tracer.startActiveSpan("drizzle.execute", () => {
  169. const params = (0, import_sql.fillPlaceholders)(this.params, placeholderValues);
  170. this.logger.logQuery(this.rawQueryConfig.text, params);
  171. return import_tracing.tracer.startActiveSpan("drizzle.driver.execute", (span) => {
  172. span?.setAttributes({
  173. "drizzle.query.name": this.rawQueryConfig.name,
  174. "drizzle.query.text": this.rawQueryConfig.text,
  175. "drizzle.query.params": JSON.stringify(params)
  176. });
  177. return this.queryWithCache(this.rawQueryConfig.text, params, async () => {
  178. return this.client.query(this.rawQueryConfig, params);
  179. }).then((result) => result.rows);
  180. });
  181. });
  182. }
  183. /** @internal */
  184. isResponseInArrayMode() {
  185. return this._isResponseInArrayMode;
  186. }
  187. }
  188. class NodePgSession extends import_session.PgSession {
  189. constructor(client, dialect, schema, options = {}) {
  190. super(dialect);
  191. this.client = client;
  192. this.schema = schema;
  193. this.options = options;
  194. this.logger = options.logger ?? new import_logger.NoopLogger();
  195. this.cache = options.cache ?? new import_core.NoopCache();
  196. }
  197. static [import_entity.entityKind] = "NodePgSession";
  198. logger;
  199. cache;
  200. prepareQuery(query, fields, name, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig) {
  201. return new NodePgPreparedQuery(
  202. this.client,
  203. query.sql,
  204. query.params,
  205. this.logger,
  206. this.cache,
  207. queryMetadata,
  208. cacheConfig,
  209. fields,
  210. name,
  211. isResponseInArrayMode,
  212. customResultMapper
  213. );
  214. }
  215. async transaction(transaction, config) {
  216. const isPool = this.client instanceof Pool || Object.getPrototypeOf(this.client).constructor.name.includes("Pool");
  217. const session = isPool ? new NodePgSession(await this.client.connect(), this.dialect, this.schema, this.options) : this;
  218. const tx = new NodePgTransaction(this.dialect, session, this.schema);
  219. await tx.execute(import_sql.sql`begin${config ? import_sql.sql` ${tx.getTransactionConfigSQL(config)}` : void 0}`);
  220. try {
  221. const result = await transaction(tx);
  222. await tx.execute(import_sql.sql`commit`);
  223. return result;
  224. } catch (error) {
  225. await tx.execute(import_sql.sql`rollback`);
  226. throw error;
  227. } finally {
  228. if (isPool) session.client.release();
  229. }
  230. }
  231. async count(sql2) {
  232. const res = await this.execute(sql2);
  233. return Number(
  234. res["rows"][0]["count"]
  235. );
  236. }
  237. }
  238. class NodePgTransaction extends import_pg_core.PgTransaction {
  239. static [import_entity.entityKind] = "NodePgTransaction";
  240. async transaction(transaction) {
  241. const savepointName = `sp${this.nestedIndex + 1}`;
  242. const tx = new NodePgTransaction(
  243. this.dialect,
  244. this.session,
  245. this.schema,
  246. this.nestedIndex + 1
  247. );
  248. await tx.execute(import_sql.sql.raw(`savepoint ${savepointName}`));
  249. try {
  250. const result = await transaction(tx);
  251. await tx.execute(import_sql.sql.raw(`release savepoint ${savepointName}`));
  252. return result;
  253. } catch (err) {
  254. await tx.execute(import_sql.sql.raw(`rollback to savepoint ${savepointName}`));
  255. throw err;
  256. }
  257. }
  258. }
  259. // Annotate the CommonJS export names for ESM import in node:
  260. 0 && (module.exports = {
  261. NodePgPreparedQuery,
  262. NodePgSession,
  263. NodePgTransaction
  264. });
  265. //# sourceMappingURL=session.cjs.map