CoolFace
Apppublic

AK-21/Graphite-Industrial-Intelligence

sourceHugging Faceupdated 3mo agoView on Hugging Face
0likes
session.cjs268 linesDownload Raw Back to singlestore
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  SingleStoreDriverPreparedQuery: () => SingleStoreDriverPreparedQuery,22  SingleStoreDriverSession: () => SingleStoreDriverSession,23  SingleStoreDriverTransaction: () => SingleStoreDriverTransaction24});25module.exports = __toCommonJS(session_exports);26var import_node_events = require("node:events");27var import_core = require("../cache/core/index.cjs");28var import_column = require("../column.cjs");29var import_entity = require("../entity.cjs");30var import_logger = require("../logger.cjs");31var import_session = require("../singlestore-core/session.cjs");32var import_sql = require("../sql/sql.cjs");33var import_utils = require("../utils.cjs");34class SingleStoreDriverPreparedQuery extends import_session.SingleStorePreparedQuery {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] = "SingleStoreDriverPreparedQuery";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}150class SingleStoreDriverSession extends import_session.SingleStoreSession {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  }159  static [import_entity.entityKind] = "SingleStoreDriverSession";160  logger;161  cache;162  prepareQuery(query, fields, customResultMapper, generatedIds, returningIds, queryMetadata, cacheConfig) {163    return new SingleStoreDriverPreparedQuery(164      this.client,165      query.sql,166      query.params,167      this.logger,168      this.cache,169      queryMetadata,170      cacheConfig,171      fields,172      customResultMapper,173      generatedIds,174      returningIds175    );176  }177  /**178   * @internal179   * What is its purpose?180   */181  async query(query, params) {182    this.logger.logQuery(query, params);183    const result = await this.client.query({184      sql: query,185      values: params,186      rowsAsArray: true,187      typeCast: function(field, next) {188        if (field.type === "TIMESTAMP" || field.type === "DATETIME" || field.type === "DATE") {189          return field.string();190        }191        return next();192      }193    });194    return result;195  }196  all(query) {197    const querySql = this.dialect.sqlToQuery(query);198    this.logger.logQuery(querySql.sql, querySql.params);199    return this.client.execute(querySql.sql, querySql.params).then((result) => result[0]);200  }201  async transaction(transaction, config) {202    const session = isPool(this.client) ? new SingleStoreDriverSession(203      await this.client.getConnection(),204      this.dialect,205      this.schema,206      this.options207    ) : this;208    const tx = new SingleStoreDriverTransaction(209      this.dialect,210      session,211      this.schema,212      0213    );214    if (config) {215      const setTransactionConfigSql = this.getSetTransactionSQL(config);216      if (setTransactionConfigSql) {217        await tx.execute(setTransactionConfigSql);218      }219      const startTransactionSql = this.getStartTransactionSQL(config);220      await (startTransactionSql ? tx.execute(startTransactionSql) : tx.execute(import_sql.sql`begin`));221    } else {222      await tx.execute(import_sql.sql`begin`);223    }224    try {225      const result = await transaction(tx);226      await tx.execute(import_sql.sql`commit`);227      return result;228    } catch (err) {229      await tx.execute(import_sql.sql`rollback`);230      throw err;231    } finally {232      if (isPool(this.client)) {233        session.client.release();234      }235    }236  }237}238class SingleStoreDriverTransaction extends import_session.SingleStoreTransaction {239  static [import_entity.entityKind] = "SingleStoreDriverTransaction";240  async transaction(transaction) {241    const savepointName = `sp${this.nestedIndex + 1}`;242    const tx = new SingleStoreDriverTransaction(243      this.dialect,244      this.session,245      this.schema,246      this.nestedIndex + 1247    );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}259function isPool(client) {260  return "getConnection" in client;261}262// Annotate the CommonJS export names for ESM import in node:2630 && (module.exports = {264  SingleStoreDriverPreparedQuery,265  SingleStoreDriverSession,266  SingleStoreDriverTransaction267});268//# sourceMappingURL=session.cjs.map