CoolFace
Apppublic

AK-21/Graphite-Industrial-Intelligence

sourceHugging Faceupdated 3mo agoView on Hugging Face
0likes
db.cjs361 linesDownload Raw Back to sqlite-core
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 db_exports = {};20__export(db_exports, {21  BaseSQLiteDatabase: () => BaseSQLiteDatabase,22  withReplicas: () => withReplicas23});24module.exports = __toCommonJS(db_exports);25var import_entity = require("../entity.cjs");26var import_selection_proxy = require("../selection-proxy.cjs");27var import_sql = require("../sql/sql.cjs");28var import_query_builders = require("./query-builders/index.cjs");29var import_subquery = require("../subquery.cjs");30var import_count = require("./query-builders/count.cjs");31var import_query = require("./query-builders/query.cjs");32var import_raw = require("./query-builders/raw.cjs");33class BaseSQLiteDatabase {34  constructor(resultKind, dialect, session, schema) {35    this.resultKind = resultKind;36    this.dialect = dialect;37    this.session = session;38    this._ = schema ? {39      schema: schema.schema,40      fullSchema: schema.fullSchema,41      tableNamesMap: schema.tableNamesMap42    } : {43      schema: void 0,44      fullSchema: {},45      tableNamesMap: {}46    };47    this.query = {};48    const query = this.query;49    if (this._.schema) {50      for (const [tableName, columns] of Object.entries(this._.schema)) {51        query[tableName] = new import_query.RelationalQueryBuilder(52          resultKind,53          schema.fullSchema,54          this._.schema,55          this._.tableNamesMap,56          schema.fullSchema[tableName],57          columns,58          dialect,59          session60        );61      }62    }63    this.$cache = { invalidate: async (_params) => {64    } };65  }66  static [import_entity.entityKind] = "BaseSQLiteDatabase";67  query;68  /**69   * Creates a subquery that defines a temporary named result set as a CTE.70   *71   * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.72   *73   * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}74   *75   * @param alias The alias for the subquery.76   *77   * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.78   *79   * @example80   *81   * ```ts82   * // Create a subquery with alias 'sq' and use it in the select query83   * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));84   *85   * const result = await db.with(sq).select().from(sq);86   * ```87   *88   * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:89   *90   * ```ts91   * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query92   * const sq = db.$with('sq').as(db.select({93   *   name: sql<string>`upper(${users.name})`.as('name'),94   * })95   * .from(users));96   *97   * const result = await db.with(sq).select({ name: sq.name }).from(sq);98   * ```99   */100  $with = (alias, selection) => {101    const self = this;102    const as = (qb) => {103      if (typeof qb === "function") {104        qb = qb(new import_query_builders.QueryBuilder(self.dialect));105      }106      return new Proxy(107        new import_subquery.WithSubquery(108          qb.getSQL(),109          selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}),110          alias,111          true112        ),113        new import_selection_proxy.SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })114      );115    };116    return { as };117  };118  $count(source, filters) {119    return new import_count.SQLiteCountBuilder({ source, filters, session: this.session });120  }121  /**122   * Incorporates a previously defined CTE (using `$with`) into the main query.123   *124   * This method allows the main query to reference a temporary named result set.125   *126   * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}127   *128   * @param queries The CTEs to incorporate into the main query.129   *130   * @example131   *132   * ```ts133   * // Define a subquery 'sq' as a CTE using $with134   * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));135   *136   * // Incorporate the CTE 'sq' into the main query and select from it137   * const result = await db.with(sq).select().from(sq);138   * ```139   */140  with(...queries) {141    const self = this;142    function select(fields) {143      return new import_query_builders.SQLiteSelectBuilder({144        fields: fields ?? void 0,145        session: self.session,146        dialect: self.dialect,147        withList: queries148      });149    }150    function selectDistinct(fields) {151      return new import_query_builders.SQLiteSelectBuilder({152        fields: fields ?? void 0,153        session: self.session,154        dialect: self.dialect,155        withList: queries,156        distinct: true157      });158    }159    function update(table) {160      return new import_query_builders.SQLiteUpdateBuilder(table, self.session, self.dialect, queries);161    }162    function insert(into) {163      return new import_query_builders.SQLiteInsertBuilder(into, self.session, self.dialect, queries);164    }165    function delete_(from) {166      return new import_query_builders.SQLiteDeleteBase(from, self.session, self.dialect, queries);167    }168    return { select, selectDistinct, update, insert, delete: delete_ };169  }170  select(fields) {171    return new import_query_builders.SQLiteSelectBuilder({ fields: fields ?? void 0, session: this.session, dialect: this.dialect });172  }173  selectDistinct(fields) {174    return new import_query_builders.SQLiteSelectBuilder({175      fields: fields ?? void 0,176      session: this.session,177      dialect: this.dialect,178      distinct: true179    });180  }181  /**182   * Creates an update query.183   *184   * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.185   *186   * Use `.set()` method to specify which values to update.187   *188   * See docs: {@link https://orm.drizzle.team/docs/update}189   *190   * @param table The table to update.191   *192   * @example193   *194   * ```ts195   * // Update all rows in the 'cars' table196   * await db.update(cars).set({ color: 'red' });197   *198   * // Update rows with filters and conditions199   * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));200   *201   * // Update with returning clause202   * const updatedCar: Car[] = await db.update(cars)203   *   .set({ color: 'red' })204   *   .where(eq(cars.id, 1))205   *   .returning();206   * ```207   */208  update(table) {209    return new import_query_builders.SQLiteUpdateBuilder(table, this.session, this.dialect);210  }211  $cache;212  /**213   * Creates an insert query.214   *215   * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.216   *217   * See docs: {@link https://orm.drizzle.team/docs/insert}218   *219   * @param table The table to insert into.220   *221   * @example222   *223   * ```ts224   * // Insert one row225   * await db.insert(cars).values({ brand: 'BMW' });226   *227   * // Insert multiple rows228   * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);229   *230   * // Insert with returning clause231   * const insertedCar: Car[] = await db.insert(cars)232   *   .values({ brand: 'BMW' })233   *   .returning();234   * ```235   */236  insert(into) {237    return new import_query_builders.SQLiteInsertBuilder(into, this.session, this.dialect);238  }239  /**240   * Creates a delete query.241   *242   * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.243   *244   * See docs: {@link https://orm.drizzle.team/docs/delete}245   *246   * @param table The table to delete from.247   *248   * @example249   *250   * ```ts251   * // Delete all rows in the 'cars' table252   * await db.delete(cars);253   *254   * // Delete rows with filters and conditions255   * await db.delete(cars).where(eq(cars.color, 'green'));256   *257   * // Delete with returning clause258   * const deletedCar: Car[] = await db.delete(cars)259   *   .where(eq(cars.id, 1))260   *   .returning();261   * ```262   */263  delete(from) {264    return new import_query_builders.SQLiteDeleteBase(from, this.session, this.dialect);265  }266  run(query) {267    const sequel = typeof query === "string" ? import_sql.sql.raw(query) : query.getSQL();268    if (this.resultKind === "async") {269      return new import_raw.SQLiteRaw(270        async () => this.session.run(sequel),271        () => sequel,272        "run",273        this.dialect,274        this.session.extractRawRunValueFromBatchResult.bind(this.session)275      );276    }277    return this.session.run(sequel);278  }279  all(query) {280    const sequel = typeof query === "string" ? import_sql.sql.raw(query) : query.getSQL();281    if (this.resultKind === "async") {282      return new import_raw.SQLiteRaw(283        async () => this.session.all(sequel),284        () => sequel,285        "all",286        this.dialect,287        this.session.extractRawAllValueFromBatchResult.bind(this.session)288      );289    }290    return this.session.all(sequel);291  }292  get(query) {293    const sequel = typeof query === "string" ? import_sql.sql.raw(query) : query.getSQL();294    if (this.resultKind === "async") {295      return new import_raw.SQLiteRaw(296        async () => this.session.get(sequel),297        () => sequel,298        "get",299        this.dialect,300        this.session.extractRawGetValueFromBatchResult.bind(this.session)301      );302    }303    return this.session.get(sequel);304  }305  values(query) {306    const sequel = typeof query === "string" ? import_sql.sql.raw(query) : query.getSQL();307    if (this.resultKind === "async") {308      return new import_raw.SQLiteRaw(309        async () => this.session.values(sequel),310        () => sequel,311        "values",312        this.dialect,313        this.session.extractRawValuesValueFromBatchResult.bind(this.session)314      );315    }316    return this.session.values(sequel);317  }318  transaction(transaction, config) {319    return this.session.transaction(transaction, config);320  }321}322const withReplicas = (primary, replicas, getReplica = () => replicas[Math.floor(Math.random() * replicas.length)]) => {323  const select = (...args) => getReplica(replicas).select(...args);324  const selectDistinct = (...args) => getReplica(replicas).selectDistinct(...args);325  const $count = (...args) => getReplica(replicas).$count(...args);326  const $with = (...args) => getReplica(replicas).with(...args);327  const update = (...args) => primary.update(...args);328  const insert = (...args) => primary.insert(...args);329  const $delete = (...args) => primary.delete(...args);330  const run = (...args) => primary.run(...args);331  const all = (...args) => primary.all(...args);332  const get = (...args) => primary.get(...args);333  const values = (...args) => primary.values(...args);334  const transaction = (...args) => primary.transaction(...args);335  return {336    ...primary,337    update,338    insert,339    delete: $delete,340    run,341    all,342    get,343    values,344    transaction,345    $primary: primary,346    $replicas: replicas,347    select,348    selectDistinct,349    $count,350    with: $with,351    get query() {352      return getReplica(replicas).query;353    }354  };355};356// Annotate the CommonJS export names for ESM import in node:3570 && (module.exports = {358  BaseSQLiteDatabase,359  withReplicas360});361//# sourceMappingURL=db.cjs.map