CoolFace
Apppublic

AK-21/Graphite-Industrial-Intelligence

sourceHugging Faceupdated 3mo agoView on Hugging Face
0likes
session.js194 linesDownload Raw Back to d1
1import { NoopCache } from "../cache/core/index.js";2import { entityKind } from "../entity.js";3import { NoopLogger } from "../logger.js";4import { fillPlaceholders, sql } from "../sql/sql.js";5import { SQLiteTransaction } from "../sqlite-core/index.js";6import { SQLitePreparedQuery, SQLiteSession } from "../sqlite-core/session.js";7import { mapResultRow } from "../utils.js";8class SQLiteD1Session extends SQLiteSession {9  constructor(client, dialect, schema, options = {}) {10    super(dialect);11    this.client = client;12    this.schema = schema;13    this.options = options;14    this.logger = options.logger ?? new NoopLogger();15    this.cache = options.cache ?? new NoopCache();16  }17  static [entityKind] = "SQLiteD1Session";18  logger;19  cache;20  prepareQuery(query, fields, executeMethod, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig) {21    const stmt = this.client.prepare(query.sql);22    return new D1PreparedQuery(23      stmt,24      query,25      this.logger,26      this.cache,27      queryMetadata,28      cacheConfig,29      fields,30      executeMethod,31      isResponseInArrayMode,32      customResultMapper33    );34  }35  async batch(queries) {36    const preparedQueries = [];37    const builtQueries = [];38    for (const query of queries) {39      const preparedQuery = query._prepare();40      const builtQuery = preparedQuery.getQuery();41      preparedQueries.push(preparedQuery);42      if (builtQuery.params.length > 0) {43        builtQueries.push(preparedQuery.stmt.bind(...builtQuery.params));44      } else {45        const builtQuery2 = preparedQuery.getQuery();46        builtQueries.push(47          this.client.prepare(builtQuery2.sql).bind(...builtQuery2.params)48        );49      }50    }51    const batchResults = await this.client.batch(builtQueries);52    return batchResults.map((result, i) => preparedQueries[i].mapResult(result, true));53  }54  extractRawAllValueFromBatchResult(result) {55    return result.results;56  }57  extractRawGetValueFromBatchResult(result) {58    return result.results[0];59  }60  extractRawValuesValueFromBatchResult(result) {61    return d1ToRawMapping(result.results);62  }63  async transaction(transaction, config) {64    const tx = new D1Transaction("async", this.dialect, this, this.schema);65    await this.run(sql.raw(`begin${config?.behavior ? " " + config.behavior : ""}`));66    try {67      const result = await transaction(tx);68      await this.run(sql`commit`);69      return result;70    } catch (err) {71      await this.run(sql`rollback`);72      throw err;73    }74  }75}76class D1Transaction extends SQLiteTransaction {77  static [entityKind] = "D1Transaction";78  async transaction(transaction) {79    const savepointName = `sp${this.nestedIndex}`;80    const tx = new D1Transaction("async", this.dialect, this.session, this.schema, this.nestedIndex + 1);81    await this.session.run(sql.raw(`savepoint ${savepointName}`));82    try {83      const result = await transaction(tx);84      await this.session.run(sql.raw(`release savepoint ${savepointName}`));85      return result;86    } catch (err) {87      await this.session.run(sql.raw(`rollback to savepoint ${savepointName}`));88      throw err;89    }90  }91}92function d1ToRawMapping(results) {93  const rows = [];94  for (const row of results) {95    const entry = Object.keys(row).map((k) => row[k]);96    rows.push(entry);97  }98  return rows;99}100class D1PreparedQuery extends SQLitePreparedQuery {101  constructor(stmt, query, logger, cache, queryMetadata, cacheConfig, fields, executeMethod, _isResponseInArrayMode, customResultMapper) {102    super("async", executeMethod, query, cache, queryMetadata, cacheConfig);103    this.logger = logger;104    this._isResponseInArrayMode = _isResponseInArrayMode;105    this.customResultMapper = customResultMapper;106    this.fields = fields;107    this.stmt = stmt;108  }109  static [entityKind] = "D1PreparedQuery";110  /** @internal */111  customResultMapper;112  /** @internal */113  fields;114  /** @internal */115  stmt;116  async run(placeholderValues) {117    const params = fillPlaceholders(this.query.params, placeholderValues ?? {});118    this.logger.logQuery(this.query.sql, params);119    return await this.queryWithCache(this.query.sql, params, async () => {120      return this.stmt.bind(...params).run();121    });122  }123  async all(placeholderValues) {124    const { fields, query, logger, stmt, customResultMapper } = this;125    if (!fields && !customResultMapper) {126      const params = fillPlaceholders(query.params, placeholderValues ?? {});127      logger.logQuery(query.sql, params);128      return await this.queryWithCache(query.sql, params, async () => {129        return stmt.bind(...params).all().then(({ results }) => this.mapAllResult(results));130      });131    }132    const rows = await this.values(placeholderValues);133    return this.mapAllResult(rows);134  }135  mapAllResult(rows, isFromBatch) {136    if (isFromBatch) {137      rows = d1ToRawMapping(rows.results);138    }139    if (!this.fields && !this.customResultMapper) {140      return rows;141    }142    if (this.customResultMapper) {143      return this.customResultMapper(rows);144    }145    return rows.map((row) => mapResultRow(this.fields, row, this.joinsNotNullableMap));146  }147  async get(placeholderValues) {148    const { fields, joinsNotNullableMap, query, logger, stmt, customResultMapper } = this;149    if (!fields && !customResultMapper) {150      const params = fillPlaceholders(query.params, placeholderValues ?? {});151      logger.logQuery(query.sql, params);152      return await this.queryWithCache(query.sql, params, async () => {153        return stmt.bind(...params).all().then(({ results }) => results[0]);154      });155    }156    const rows = await this.values(placeholderValues);157    if (!rows[0]) {158      return void 0;159    }160    if (customResultMapper) {161      return customResultMapper(rows);162    }163    return mapResultRow(fields, rows[0], joinsNotNullableMap);164  }165  mapGetResult(result, isFromBatch) {166    if (isFromBatch) {167      result = d1ToRawMapping(result.results)[0];168    }169    if (!this.fields && !this.customResultMapper) {170      return result;171    }172    if (this.customResultMapper) {173      return this.customResultMapper([result]);174    }175    return mapResultRow(this.fields, result, this.joinsNotNullableMap);176  }177  async values(placeholderValues) {178    const params = fillPlaceholders(this.query.params, placeholderValues ?? {});179    this.logger.logQuery(this.query.sql, params);180    return await this.queryWithCache(this.query.sql, params, async () => {181      return this.stmt.bind(...params).raw();182    });183  }184  /** @internal */185  isResponseInArrayMode() {186    return this._isResponseInArrayMode;187  }188}189export {190  D1PreparedQuery,191  D1Transaction,192  SQLiteD1Session193};194//# sourceMappingURL=session.js.map