CoolFace
Apppublic

AK-21/Graphite-Industrial-Intelligence

sourceHugging Faceupdated 3mo agoView on Hugging Face
0likes
session.cjs179 linesDownload Raw Back to tidb-serverless
1"use strict";2var __defProp = Object.defineProperty;3var __getOwnPropDesc = Object.getOwnPropertyDescriptor;4var __getOwnPropNames = Object.getOwnPropertyNames;5var __hasOwnProp = Object.prototype.hasOwnProperty;6var __export = (target, all) => {7  for (var name in all)8    __defProp(target, name, { get: all[name], enumerable: true });9};10var __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};18var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);19var session_exports = {};20__export(session_exports, {21  TiDBServerlessPreparedQuery: () => TiDBServerlessPreparedQuery,22  TiDBServerlessSession: () => TiDBServerlessSession,23  TiDBServerlessTransaction: () => TiDBServerlessTransaction24});25module.exports = __toCommonJS(session_exports);26var import_core = require("../cache/core/index.cjs");27var import_column = require("../column.cjs");28var import_entity = require("../entity.cjs");29var import_logger = require("../logger.cjs");30var import_session = require("../mysql-core/session.cjs");31var import_sql = require("../sql/sql.cjs");32var import_utils = require("../utils.cjs");33const executeRawConfig = { fullResult: true };34const queryConfig = { arrayMode: true };35class TiDBServerlessPreparedQuery extends import_session.MySqlPreparedQuery {36  constructor(client, queryString, params, logger, cache, queryMetadata, cacheConfig, fields, customResultMapper, generatedIds, returningIds) {37    super(cache, queryMetadata, cacheConfig);38    this.client = client;39    this.queryString = queryString;40    this.params = params;41    this.logger = logger;42    this.fields = fields;43    this.customResultMapper = customResultMapper;44    this.generatedIds = generatedIds;45    this.returningIds = returningIds;46  }47  static [import_entity.entityKind] = "TiDBPreparedQuery";48  async execute(placeholderValues = {}) {49    const params = (0, import_sql.fillPlaceholders)(this.params, placeholderValues);50    this.logger.logQuery(this.queryString, params);51    const { fields, client, queryString, joinsNotNullableMap, customResultMapper, returningIds, generatedIds } = this;52    if (!fields && !customResultMapper) {53      const res = await this.queryWithCache(queryString, params, async () => {54        return await client.execute(queryString, params, executeRawConfig);55      });56      const insertId = res.lastInsertId ?? 0;57      const affectedRows = res.rowsAffected ?? 0;58      if (returningIds) {59        const returningResponse = [];60        let j = 0;61        for (let i = insertId; i < insertId + affectedRows; i++) {62          for (const column of returningIds) {63            const key = returningIds[0].path[0];64            if ((0, import_entity.is)(column.field, import_column.Column)) {65              if (column.field.primary && column.field.autoIncrement) {66                returningResponse.push({ [key]: i });67              }68              if (column.field.defaultFn && generatedIds) {69                returningResponse.push({ [key]: generatedIds[j][key] });70              }71            }72          }73          j++;74        }75        return returningResponse;76      }77      return res;78    }79    const rows = await this.queryWithCache(queryString, params, async () => {80      return await client.execute(queryString, params, queryConfig);81    });82    if (customResultMapper) {83      return customResultMapper(rows);84    }85    return rows.map((row) => (0, import_utils.mapResultRow)(fields, row, joinsNotNullableMap));86  }87  iterator(_placeholderValues) {88    throw new Error("Streaming is not supported by the TiDB Cloud Serverless driver");89  }90}91class TiDBServerlessSession extends import_session.MySqlSession {92  constructor(baseClient, dialect, tx, schema, options = {}) {93    super(dialect);94    this.baseClient = baseClient;95    this.schema = schema;96    this.options = options;97    this.client = tx ?? baseClient;98    this.logger = options.logger ?? new import_logger.NoopLogger();99    this.cache = options.cache ?? new import_core.NoopCache();100  }101  static [import_entity.entityKind] = "TiDBServerlessSession";102  logger;103  client;104  cache;105  prepareQuery(query, fields, customResultMapper, generatedIds, returningIds, queryMetadata, cacheConfig) {106    return new TiDBServerlessPreparedQuery(107      this.client,108      query.sql,109      query.params,110      this.logger,111      this.cache,112      queryMetadata,113      cacheConfig,114      fields,115      customResultMapper,116      generatedIds,117      returningIds118    );119  }120  all(query) {121    const querySql = this.dialect.sqlToQuery(query);122    this.logger.logQuery(querySql.sql, querySql.params);123    return this.client.execute(querySql.sql, querySql.params);124  }125  async count(sql2) {126    const res = await this.execute(sql2);127    return Number(128      res["rows"][0]["count"]129    );130  }131  async transaction(transaction) {132    const nativeTx = await this.baseClient.begin();133    try {134      const session = new TiDBServerlessSession(this.baseClient, this.dialect, nativeTx, this.schema, this.options);135      const tx = new TiDBServerlessTransaction(136        this.dialect,137        session,138        this.schema139      );140      const result = await transaction(tx);141      await nativeTx.commit();142      return result;143    } catch (err) {144      await nativeTx.rollback();145      throw err;146    }147  }148}149class TiDBServerlessTransaction extends import_session.MySqlTransaction {150  static [import_entity.entityKind] = "TiDBServerlessTransaction";151  constructor(dialect, session, schema, nestedIndex = 0) {152    super(dialect, session, schema, nestedIndex, "default");153  }154  async transaction(transaction) {155    const savepointName = `sp${this.nestedIndex + 1}`;156    const tx = new TiDBServerlessTransaction(157      this.dialect,158      this.session,159      this.schema,160      this.nestedIndex + 1161    );162    await tx.execute(import_sql.sql.raw(`savepoint ${savepointName}`));163    try {164      const result = await transaction(tx);165      await tx.execute(import_sql.sql.raw(`release savepoint ${savepointName}`));166      return result;167    } catch (err) {168      await tx.execute(import_sql.sql.raw(`rollback to savepoint ${savepointName}`));169      throw err;170    }171  }172}173// Annotate the CommonJS export names for ESM import in node:1740 && (module.exports = {175  TiDBServerlessPreparedQuery,176  TiDBServerlessSession,177  TiDBServerlessTransaction178});179//# sourceMappingURL=session.cjs.map