All files / src/query-interface sync-planner.ts

100% Statements 30/30
95.83% Branches 23/24
100% Functions 16/16
100% Lines 28/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99                                439x 262x 439x                               433x 260x 433x       1794x 1794x   3x                     526x 87x   439x 439x 87x     439x                 439x 87x     87x         3619x 3449x   170x 170x 2x   168x 3619x       439x 1825x 1825x        
import type { AttributeDefinition, ModelDefinition } from '../model/model-definition.ts';
 
/**
 * Plans the order of `sync()` over several models: referenced tables first, and the foreign keys
 * of reference cycles deferred until every table exists.
 *
 * @internal
 */
export class SyncPlanner {
  /**
   * Orders definitions so that referenced tables come first.
   *
   * @param definitions - Model definitions.
   * @returns Definitions in dependency order.
   */
  dependencyOrder(definitions: readonly ModelDefinition[]): readonly ModelDefinition[] {
    const byTable = new Map(definitions.map((definition) => [definition.tableName, definition]));
    return definitions.reduce<readonly ModelDefinition[]>(
      (ordered, definition) => this.#visit(byTable, definition, new Set(), ordered),
      [],
    );
  }
 
  /**
   * Columns (by field) of each definition whose foreign key points to a table created later in
   * `ordered` — a reference cycle. Their tables are created without these constraints, which are
   * added once every table exists.
   *
   * @param ordered - Definitions in dependency order.
   * @returns Deferred fields per definition.
   */
  deferredReferences(
    ordered: readonly ModelDefinition[],
  ): ReadonlyMap<ModelDefinition, readonly string[]> {
    const position = new Map(ordered.map((definition, index) => [definition.tableName, index]));
    return new Map(
      ordered.map((definition, index) => [
        definition,
        [...definition.attributes.values()]
          .filter((attribute) => {
            const target = position.get(this.#referencedTable(attribute.references) ?? '');
            return target !== undefined && target > index;
          })
          .map((attribute) => attribute.field),
      ]),
    );
  }
 
  #visit(
    byTable: ReadonlyMap<string, ModelDefinition>,
    definition: ModelDefinition,
    seen: ReadonlySet<string>,
    ordered: readonly ModelDefinition[],
  ): readonly ModelDefinition[] {
    if (ordered.includes(definition) || seen.has(definition.tableName)) {
      return ordered;
    }
    const nextSeen = new Set([...seen, definition.tableName]);
    const withDependencies = this.#dependencies(byTable, definition).reduce(
      (acc, dependency) => this.#visit(byTable, dependency, nextSeen, acc),
      ordered,
    );
    return withDependencies.includes(definition)
      ? withDependencies
      : [...withDependencies, definition];
  }
 
  #dependencies(
    byTable: ReadonlyMap<string, ModelDefinition>,
    definition: ModelDefinition,
  ): readonly ModelDefinition[] {
    return this.#referencedTables(definition)
      .map((table) => byTable.get(table))
      .filter(
        (dependency): dependency is ModelDefinition =>
          dependency !== undefined && dependency !== definition,
      );
  }
 
  #referencedTable(references: AttributeDefinition['references']): string | undefined {
    if (references === undefined || typeof references === 'string') {
      return references;
    }
    const model = references.model;
    if (typeof model === 'string') {
      return model;
    }
    const table = 'getTableName' in model ? model.getTableName() : model;
    return typeof table === 'string' ? table : table.tableName;
  }
 
  #referencedTables(definition: ModelDefinition): readonly string[] {
    return [...definition.attributes.values()].flatMap((attribute) => {
      const table = this.#referencedTable(attribute.references);
      return table === undefined ? [] : [table];
    });
  }
}