CoolFace
Apppublic

AK-21/Graphite-Industrial-Intelligence

sourceHugging Faceupdated 3mo agoView on Hugging Face
0likes
relations.cjs328 linesDownload Raw Back to drizzle-orm
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, desc2) => {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: !(desc2 = __getOwnPropDesc(from, key)) || desc2.enumerable });15  }16  return to;17};18var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);19var relations_exports = {};20__export(relations_exports, {21  Many: () => Many,22  One: () => One,23  Relation: () => Relation,24  Relations: () => Relations,25  createMany: () => createMany,26  createOne: () => createOne,27  createTableRelationsHelpers: () => createTableRelationsHelpers,28  extractTablesRelationalConfig: () => extractTablesRelationalConfig,29  getOperators: () => getOperators,30  getOrderByOperators: () => getOrderByOperators,31  mapRelationalRow: () => mapRelationalRow,32  normalizeRelation: () => normalizeRelation,33  relations: () => relations34});35module.exports = __toCommonJS(relations_exports);36var import_table = require("./table.cjs");37var import_column = require("./column.cjs");38var import_entity = require("./entity.cjs");39var import_primary_keys = require("./pg-core/primary-keys.cjs");40var import_expressions = require("./sql/expressions/index.cjs");41var import_sql = require("./sql/sql.cjs");42class Relation {43  constructor(sourceTable, referencedTable, relationName) {44    this.sourceTable = sourceTable;45    this.referencedTable = referencedTable;46    this.relationName = relationName;47    this.referencedTableName = referencedTable[import_table.Table.Symbol.Name];48  }49  static [import_entity.entityKind] = "Relation";50  referencedTableName;51  fieldName;52}53class Relations {54  constructor(table, config) {55    this.table = table;56    this.config = config;57  }58  static [import_entity.entityKind] = "Relations";59}60class One extends Relation {61  constructor(sourceTable, referencedTable, config, isNullable) {62    super(sourceTable, referencedTable, config?.relationName);63    this.config = config;64    this.isNullable = isNullable;65  }66  static [import_entity.entityKind] = "One";67  withFieldName(fieldName) {68    const relation = new One(69      this.sourceTable,70      this.referencedTable,71      this.config,72      this.isNullable73    );74    relation.fieldName = fieldName;75    return relation;76  }77}78class Many extends Relation {79  constructor(sourceTable, referencedTable, config) {80    super(sourceTable, referencedTable, config?.relationName);81    this.config = config;82  }83  static [import_entity.entityKind] = "Many";84  withFieldName(fieldName) {85    const relation = new Many(86      this.sourceTable,87      this.referencedTable,88      this.config89    );90    relation.fieldName = fieldName;91    return relation;92  }93}94function getOperators() {95  return {96    and: import_expressions.and,97    between: import_expressions.between,98    eq: import_expressions.eq,99    exists: import_expressions.exists,100    gt: import_expressions.gt,101    gte: import_expressions.gte,102    ilike: import_expressions.ilike,103    inArray: import_expressions.inArray,104    isNull: import_expressions.isNull,105    isNotNull: import_expressions.isNotNull,106    like: import_expressions.like,107    lt: import_expressions.lt,108    lte: import_expressions.lte,109    ne: import_expressions.ne,110    not: import_expressions.not,111    notBetween: import_expressions.notBetween,112    notExists: import_expressions.notExists,113    notLike: import_expressions.notLike,114    notIlike: import_expressions.notIlike,115    notInArray: import_expressions.notInArray,116    or: import_expressions.or,117    sql: import_sql.sql118  };119}120function getOrderByOperators() {121  return {122    sql: import_sql.sql,123    asc: import_expressions.asc,124    desc: import_expressions.desc125  };126}127function extractTablesRelationalConfig(schema, configHelpers) {128  if (Object.keys(schema).length === 1 && "default" in schema && !(0, import_entity.is)(schema["default"], import_table.Table)) {129    schema = schema["default"];130  }131  const tableNamesMap = {};132  const relationsBuffer = {};133  const tablesConfig = {};134  for (const [key, value] of Object.entries(schema)) {135    if ((0, import_entity.is)(value, import_table.Table)) {136      const dbName = (0, import_table.getTableUniqueName)(value);137      const bufferedRelations = relationsBuffer[dbName];138      tableNamesMap[dbName] = key;139      tablesConfig[key] = {140        tsName: key,141        dbName: value[import_table.Table.Symbol.Name],142        schema: value[import_table.Table.Symbol.Schema],143        columns: value[import_table.Table.Symbol.Columns],144        relations: bufferedRelations?.relations ?? {},145        primaryKey: bufferedRelations?.primaryKey ?? []146      };147      for (const column of Object.values(148        value[import_table.Table.Symbol.Columns]149      )) {150        if (column.primary) {151          tablesConfig[key].primaryKey.push(column);152        }153      }154      const extraConfig = value[import_table.Table.Symbol.ExtraConfigBuilder]?.(value[import_table.Table.Symbol.ExtraConfigColumns]);155      if (extraConfig) {156        for (const configEntry of Object.values(extraConfig)) {157          if ((0, import_entity.is)(configEntry, import_primary_keys.PrimaryKeyBuilder)) {158            tablesConfig[key].primaryKey.push(...configEntry.columns);159          }160        }161      }162    } else if ((0, import_entity.is)(value, Relations)) {163      const dbName = (0, import_table.getTableUniqueName)(value.table);164      const tableName = tableNamesMap[dbName];165      const relations2 = value.config(166        configHelpers(value.table)167      );168      let primaryKey;169      for (const [relationName, relation] of Object.entries(relations2)) {170        if (tableName) {171          const tableConfig = tablesConfig[tableName];172          tableConfig.relations[relationName] = relation;173          if (primaryKey) {174            tableConfig.primaryKey.push(...primaryKey);175          }176        } else {177          if (!(dbName in relationsBuffer)) {178            relationsBuffer[dbName] = {179              relations: {},180              primaryKey181            };182          }183          relationsBuffer[dbName].relations[relationName] = relation;184        }185      }186    }187  }188  return { tables: tablesConfig, tableNamesMap };189}190function relations(table, relations2) {191  return new Relations(192    table,193    (helpers) => Object.fromEntries(194      Object.entries(relations2(helpers)).map(([key, value]) => [195        key,196        value.withFieldName(key)197      ])198    )199  );200}201function createOne(sourceTable) {202  return function one(table, config) {203    return new One(204      sourceTable,205      table,206      config,207      config?.fields.reduce((res, f) => res && f.notNull, true) ?? false208    );209  };210}211function createMany(sourceTable) {212  return function many(referencedTable, config) {213    return new Many(sourceTable, referencedTable, config);214  };215}216function normalizeRelation(schema, tableNamesMap, relation) {217  if ((0, import_entity.is)(relation, One) && relation.config) {218    return {219      fields: relation.config.fields,220      references: relation.config.references221    };222  }223  const referencedTableTsName = tableNamesMap[(0, import_table.getTableUniqueName)(relation.referencedTable)];224  if (!referencedTableTsName) {225    throw new Error(226      `Table "${relation.referencedTable[import_table.Table.Symbol.Name]}" not found in schema`227    );228  }229  const referencedTableConfig = schema[referencedTableTsName];230  if (!referencedTableConfig) {231    throw new Error(`Table "${referencedTableTsName}" not found in schema`);232  }233  const sourceTable = relation.sourceTable;234  const sourceTableTsName = tableNamesMap[(0, import_table.getTableUniqueName)(sourceTable)];235  if (!sourceTableTsName) {236    throw new Error(237      `Table "${sourceTable[import_table.Table.Symbol.Name]}" not found in schema`238    );239  }240  const reverseRelations = [];241  for (const referencedTableRelation of Object.values(242    referencedTableConfig.relations243  )) {244    if (relation.relationName && relation !== referencedTableRelation && referencedTableRelation.relationName === relation.relationName || !relation.relationName && referencedTableRelation.referencedTable === relation.sourceTable) {245      reverseRelations.push(referencedTableRelation);246    }247  }248  if (reverseRelations.length > 1) {249    throw relation.relationName ? new Error(250      `There are multiple relations with name "${relation.relationName}" in table "${referencedTableTsName}"`251    ) : new Error(252      `There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[import_table.Table.Symbol.Name]}". Please specify relation name`253    );254  }255  if (reverseRelations[0] && (0, import_entity.is)(reverseRelations[0], One) && reverseRelations[0].config) {256    return {257      fields: reverseRelations[0].config.references,258      references: reverseRelations[0].config.fields259    };260  }261  throw new Error(262    `There is not enough information to infer relation "${sourceTableTsName}.${relation.fieldName}"`263  );264}265function createTableRelationsHelpers(sourceTable) {266  return {267    one: createOne(sourceTable),268    many: createMany(sourceTable)269  };270}271function mapRelationalRow(tablesConfig, tableConfig, row, buildQueryResultSelection, mapColumnValue = (value) => value) {272  const result = {};273  for (const [274    selectionItemIndex,275    selectionItem276  ] of buildQueryResultSelection.entries()) {277    if (selectionItem.isJson) {278      const relation = tableConfig.relations[selectionItem.tsKey];279      const rawSubRows = row[selectionItemIndex];280      const subRows = typeof rawSubRows === "string" ? JSON.parse(rawSubRows) : rawSubRows;281      result[selectionItem.tsKey] = (0, import_entity.is)(relation, One) ? subRows && mapRelationalRow(282        tablesConfig,283        tablesConfig[selectionItem.relationTableTsKey],284        subRows,285        selectionItem.selection,286        mapColumnValue287      ) : subRows.map(288        (subRow) => mapRelationalRow(289          tablesConfig,290          tablesConfig[selectionItem.relationTableTsKey],291          subRow,292          selectionItem.selection,293          mapColumnValue294        )295      );296    } else {297      const value = mapColumnValue(row[selectionItemIndex]);298      const field = selectionItem.field;299      let decoder;300      if ((0, import_entity.is)(field, import_column.Column)) {301        decoder = field;302      } else if ((0, import_entity.is)(field, import_sql.SQL)) {303        decoder = field.decoder;304      } else {305        decoder = field.sql.decoder;306      }307      result[selectionItem.tsKey] = value === null ? null : decoder.mapFromDriverValue(value);308    }309  }310  return result;311}312// Annotate the CommonJS export names for ESM import in node:3130 && (module.exports = {314  Many,315  One,316  Relation,317  Relations,318  createMany,319  createOne,320  createTableRelationsHelpers,321  extractTablesRelationalConfig,322  getOperators,323  getOrderByOperators,324  mapRelationalRow,325  normalizeRelation,326  relations327});328//# sourceMappingURL=relations.cjs.map