All files / src core.ts

98.88% Statements 266/269
91.89% Branches 102/111
100% Functions 30/30
98.81% Lines 249/252

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 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668                                                                                                                                                                                                        3x     126x   514x 514x   514x 514x     4858x 4396x           462x             514x 4858x   4858x 514x 4858x   514x 514x   514x 4858x   514x 514x   514x 1x 1x 2x 2x 2x     1x     514x       514x 514x 4858x 396x 396x             514x 514x 514x 4858x 4858x     514x     4858x       514x                                         126x         514x 514x         126x 169x 169x 1x   168x     126x         514x 514x         126x     500x 500x 1x   499x     126x 103x     126x       126x 514x 514x       514x 396x 396x         514x                         126x       1489x 1489x 1489x 1489x 1321x     1489x     126x 45x 45x 45x 988x     988x 988x 1x   987x 987x   987x 987x 153x 153x 153x   153x         153x 153x     987x 987x 2x 1x   1x         986x           43x 43x 152x   43x     126x               219x 219x 1489x 1489x 1489x 1489x 1321x 1321x 281x 281x   1040x 1040x 739x 739x     168x     168x 168x   582x 582x 2973x 2973x   582x 582x   582x       582x   582x   219x                         126x         219x 219x 219x     219x 219x   219x     126x       65x 65x 65x     65x   65x     126x     559x 38x         559x     126x                                   559x       559x 559x 559x 366x 366x   366x           366x     559x 559x 332x 332x   559x 559x 366x 366x   559x 557x 557x                       126x 45x 45x 45x 43x 43x 152x   43x       43x 152x 152x 152x 125x   152x   43x 43x 43x 43x 43x 43x 43x 43x 43x 43x     43x 219x 219x 219x 219x 65x       65x 65x   219x               219x 65x 65x     219x 582x 582x 582x 582x   582x 582x 262x     320x 581x 581x 581x 11x   570x 570x     570x 559x                         43x 43x 65x   43x 43x     126x       10x   5x     5x   5x     126x 17x 2x   15x 15x   15x 4x   11x     126x     8x 3x   5x     126x     9x 3x   6x     126x                 514x     514x        
import camelCase from 'camelcase';
 
export interface IColumnData {
  column: string;
  property?: string;
  references?: IModelClass;
  primaryKey?: boolean;
}
export type IColumn = IColumnData | string;
export type IColumns = Array<IColumn> | (() => Array<IColumn>);
 
export interface IColumnInternalData {
  column: string;
  property: string;
  references?: IModelClass;
  primaryKey: boolean;
}
export type IColumnInternal = IColumnInternalData;
export type IColumnsInternal = Array<IColumnInternal>;
 
export interface IModel {
  [key: string]: any;
}
// IModel used as a type refers to an instance of IModel;
// IModelClass used as a type refers to the class itself
export type IModelClass = new (props: any) => IModel;
export interface ICollection<T extends IModel> {
  models: Array<T>;
}
export interface IEntity<T extends IModel> {
  tableName: string;
  displayName?: string;
  collectionDisplayName?: string;
  columns: IColumns;
  Model: new (props: any) => T;
  Collection: new ({ models }: any) => ICollection<T>;
}
export type IEntities<T extends IModel> = Array<IEntity<T>>;
 
export interface IEntityInternal<T extends IModel> {
  tableName: string;
  displayName: string;
  collectionDisplayName: string;
  columns: IColumnsInternal;
  propertyNames: Array<string>;
  Model: new (props: any) => T;
  Collection: new ({ models }: any) => ICollection<T>;
  columnNames: Array<string>;
  prefixedColumnNames: Array<string>;
  primaryKeys: Array<string>;
  references: object;
  selectColumnsClause: string;
  getPkId: (model: IModel) => string;
  columnToPropertyMap: Map<string, string>;
  propertyToColumnMap: Map<string, string>;
  referencesEntries: Array<{ property: string; ModelClass: IModelClass }>;
}
export type IEntitiesInternal<T extends IModel> = Array<IEntityInternal<T>>;
 
export interface ICreateCoreOptions {
  entities: IEntities<IModel>;
}
 
export interface ICore {
  /* ------------------------------------------------------------------------*/
  /* Object Relational Mapping methods --------------------------------------*/
  /* ------------------------------------------------------------------------*/
 
  /* Note these construction methods ensure their count against the number of
   * generated top level business objects - independent of the number of
   * relational rows passed in as a result from a database driver query.
   * Thus, for example, `one` understands that there may be multiple result
   * rows (which a database driver's `one` query method would throw at) but
   * which correctly nest into one Model.)
   */
 
  createFromDatabase: <T extends ICollection<IModel>>(rows: any) => T;
  createAnyFromDatabase: <T extends ICollection<IModel>>(
    rows: any,
    rootKey: string | IModelClass
  ) => T;
  createOneFromDatabase: <T extends IModel>(rows: any) => T;
  createOneOrNoneFromDatabase: <T extends IModel>(rows: any) => T | void;
  createManyFromDatabase: <T extends ICollection<IModel>>(rows: any) => T;
 
  /* ------------------------------------------------------------------------*/
  /* Helpful Properties -----------------------------------------------------*/
  /* ------------------------------------------------------------------------*/
 
  /* The tables property gives access to the sql select clause string for
   * each entity based on it's `displayName`. This property can be used when
   * writing raw SQL as the select clause, which handles quoting column names
   * and namespacing them to the table to avoid collisions and as required
   * for PureORM mapping.
   */
  tables: { [key: string]: { columns: string } };
  getEntityByModel: (model: IModel) => IEntityInternal<IModel>;
  getEntityByTableName: (tableName: string) => IEntityInternal<IModel>;
}
 
export const createCore = ({
  entities: externalEntities
}: ICreateCoreOptions): ICore => {
  const entities: IEntitiesInternal<IModel> = externalEntities.map(
    (d: IEntity<IModel>) => {
      const tableName = d.tableName;
      const displayName = d.displayName || camelCase(d.tableName);
      const collectionDisplayName =
        d.collectionDisplayName || `${displayName}s`;
      const columns = (
        typeof d.columns === 'function' ? d.columns() : d.columns
      ).map((d: IColumn) => {
        if (typeof d === 'string') {
          return {
            column: d,
            property: camelCase(d),
            primaryKey: false
          };
        }
        return {
          column: d.column,
          property: d.property || camelCase(d.column),
          primaryKey: d.primaryKey || false,
          ...(d.references ? { references: d.references } : {})
        };
      });
      const propertyNames = columns.map(
        (x: IColumnInternal): string => x.property
      );
      const columnNames = columns.map((x: IColumnInternal): string => x.column);
      const prefixedColumnNames = columnNames.map(
        (col: string) => `${tableName}#${col}`
      );
      const Model = d.Model;
      const Collection = d.Collection;
 
      const pkColumnsData = columns.filter(
        (x: IColumnInternal) => x.primaryKey
      );
      const _primaryKeys = pkColumnsData.map((x: IColumnInternal) => x.column);
      const primaryKeys = _primaryKeys.length > 0 ? _primaryKeys : ['id'];
 
      const getPkId = (model: IModel): string => {
        let id = '';
        for (let i = 0; i < primaryKeys.length; i++) {
          const part = model[primaryKeys[i] as keyof typeof model];
          Eif (part !== void 0 && part !== null) {
            id += String(part);
          }
        }
        return id;
      };
 
      const references: any = {};
      const referencesEntries: Array<{
        property: string;
        ModelClass: IModelClass;
      }> = [];
      for (const col of columns) {
        if (col.references) {
          references[col.property] = col.references;
          referencesEntries.push({
            property: col.property,
            ModelClass: col.references
          });
        }
      }
 
      const columnToPropertyMap = new Map<string, string>();
      const propertyToColumnMap = new Map<string, string>();
      for (let i = 0; i < columnNames.length; i++) {
        columnToPropertyMap.set(columnNames[i], propertyNames[i]);
        propertyToColumnMap.set(propertyNames[i], columnNames[i]);
      }
 
      const selectColumnsClause = prefixedColumnNames
        .map(
          (prefixed: string, index: number) =>
            `"${tableName}".${columnNames[index]} as "${prefixed}"`
        )
        .join(', ');
 
      return {
        tableName,
        displayName,
        collectionDisplayName,
        columns,
        propertyNames,
        Model,
        Collection,
        columnNames,
        prefixedColumnNames,
        primaryKeys,
        references,
        selectColumnsClause,
        getPkId,
        columnToPropertyMap,
        propertyToColumnMap,
        referencesEntries
      };
    }
  );
 
  const tableNameToEntityMap = entities.reduce(
    (
      map: Map<string, IEntityInternal<IModel>>,
      entity: IEntityInternal<IModel>
    ) => {
      map.set(entity.tableName, entity);
      return map;
    },
    new Map()
  );
 
  const getEntityByTableName = (tableName: string): IEntityInternal<IModel> => {
    const entity = tableNameToEntityMap.get(tableName);
    if (!entity) {
      throw new Error(`Could not find entity for table ${tableName}`);
    }
    return entity;
  };
 
  const modelToEntityMap = entities.reduce(
    (
      map: Map<IModel, IEntityInternal<IModel>>,
      entity: IEntityInternal<IModel>
    ) => {
      map.set(entity.Model, entity);
      return map;
    },
    new Map()
  );
 
  const getEntityByModelClass = (
    Model: IModelClass
  ): IEntityInternal<IModel> => {
    const entity = modelToEntityMap.get(Model);
    if (!entity) {
      throw new Error(`Could not find entity for class ${Model}`);
    }
    return entity;
  };
 
  const getEntityByModel = (model: IModel): IEntityInternal<IModel> => {
    return getEntityByModelClass(model.constructor as IModelClass);
  };
 
  const entityReferencePlans = new Map<
    IEntityInternal<IModel>,
    Array<{ property: string; targetEntity: IEntityInternal<IModel> }>
  >();
  for (let i = 0; i < entities.length; i++) {
    const entity = entities[i];
    const plans = new Array<{
      property: string;
      targetEntity: IEntityInternal<IModel>;
    }>(entity.referencesEntries.length);
    for (let j = 0; j < entity.referencesEntries.length; j++) {
      const ref = entity.referencesEntries[j];
      plans[j] = {
        property: ref.property,
        targetEntity: getEntityByModelClass(ref.ModelClass)
      };
    }
    entityReferencePlans.set(entity, plans);
  }
 
  interface IRowColumnPlan {
    rowKey: string;
    propertyName: string;
  }
  interface IEntityRowPlan {
    entity: IEntityInternal<IModel>;
    columnPlans: Array<IRowColumnPlan>;
    primaryKeyRowKeys: Array<string>;
  }
 
  const getPkIdFromRow = (
    row: any,
    primaryKeyRowKeys: Array<string>
  ): string => {
    let id = '';
    for (let i = 0; i < primaryKeyRowKeys.length; i++) {
      const part = row[primaryKeyRowKeys[i]];
      if (part !== void 0 && part !== null) {
        id += String(part);
      }
    }
    return id;
  };
 
  const buildEntityRowPlans = (sampleRow: any): Array<IEntityRowPlan> => {
    const plansByTable = new Map<string, IEntityRowPlan>();
    const tableOrder: Array<string> = [];
    for (const text in sampleRow) {
      Iif (!Object.prototype.hasOwnProperty.call(sampleRow, text)) {
        continue;
      }
      const hashIndex = text.indexOf('#');
      if (hashIndex === -1) {
        throw new Error('Column names must be namespaced to table');
      }
      const tableName = text.substring(0, hashIndex);
      const column = text.substring(hashIndex + 1);
 
      let plan = plansByTable.get(tableName);
      if (!plan) {
        const entity = getEntityByTableName(tableName);
        const primaryKeyRowKeys = entity.primaryKeys.map(
          (pk: string) => `${tableName}#${pk}`
        );
        plan = {
          entity,
          columnPlans: [],
          primaryKeyRowKeys
        };
        plansByTable.set(tableName, plan);
        tableOrder.push(tableName);
      }
 
      let propertyName = plan.entity.columnToPropertyMap.get(column);
      if (!propertyName) {
        if (column.startsWith('meta_')) {
          propertyName = camelCase(column);
        } else {
          throw Error(
            `No property name for "${column}" in business object "${plan.entity.displayName}". Non-spec'd columns must begin with "meta_".`
          );
        }
      }
      plan.columnPlans.push({
        rowKey: text,
        propertyName
      });
    }
 
    const orderedPlans = new Array<IEntityRowPlan>(tableOrder.length);
    for (let i = 0; i < tableOrder.length; i++) {
      orderedPlans[i] = plansByTable.get(tableOrder[i]) as IEntityRowPlan;
    }
    return orderedPlans;
  };
 
  const materializeModelsFromRow = (
    row: any,
    entityRowPlans: Array<IEntityRowPlan>,
    rootScopedModelsByEntity: IModelsByEntity,
    rowModels: Array<IModel | void>,
    rowModelPkIds: Array<string>,
    rowCreatedWithPkIndexes: Array<number>
  ): IModel => {
    rowCreatedWithPkIndexes.length = 0;
    for (let i = 0; i < entityRowPlans.length; i++) {
      const plan = entityRowPlans[i];
      const pkId = getPkIdFromRow(row, plan.primaryKeyRowKeys);
      rowModelPkIds[i] = pkId;
      if (pkId) {
        let modelsForEntity = rootScopedModelsByEntity.get(plan.entity);
        if (!modelsForEntity) {
          modelsForEntity = new Map<string, IModel>();
          rootScopedModelsByEntity.set(plan.entity, modelsForEntity);
        } else {
          const existing = modelsForEntity.get(pkId);
          if (existing) {
            rowModels[i] = existing;
            continue;
          }
        }
      } else Eif (i !== 0) {
        // No primary key means this is typically an outer-joined null row.
        // Skip model construction for non-root entities since it cannot link.
        rowModels[i] = void 0;
        continue;
      }
      const props: any = {};
      for (let j = 0; j < plan.columnPlans.length; j++) {
        const columnPlan = plan.columnPlans[j];
        props[columnPlan.propertyName] = row[columnPlan.rowKey];
      }
      const model = new plan.entity.Model(props);
      Eif (pkId) {
        // modelsForEntity is guaranteed to be initialized above for pk rows.
        (rootScopedModelsByEntity.get(plan.entity) as Map<string, IModel>).set(
          pkId,
          model
        );
        rowCreatedWithPkIndexes.push(i);
      }
      rowModels[i] = model;
    }
    return rowModels[0] as IModel;
  };
 
  type IModelsByEntity = Map<IEntityInternal<IModel>, Map<string, IModel>>;
  interface IRootScopeState {
    modelsByEntity: IModelsByEntity;
    collectionMembership?: WeakMap<
      IModel,
      Map<IEntityInternal<IModel>, Set<string>>
    >;
  }
  type IRootScopeStateByKey = Map<string, IRootScopeState>;
 
  const getRootScopeKey = (
    row: any,
    rootEntity: IEntityInternal<IModel>,
    rootPrimaryKeys: Array<string>
  ): string => {
    let rootScopeKey = '';
    for (let i = 0; i < rootPrimaryKeys.length; i++) {
      Iif (i > 0) {
        rootScopeKey += '@';
      }
      const value = row[`${rootEntity.tableName}#${rootPrimaryKeys[i]}`];
      rootScopeKey += value === void 0 || value === null ? '' : String(value);
    }
    return rootScopeKey;
  };
 
  const ensureRootScopeState = (
    rootScopeKey: string,
    rootScopeStateByKey: IRootScopeStateByKey
  ): IRootScopeState => {
    let state = rootScopeStateByKey.get(rootScopeKey);
    Eif (!state) {
      state = {
        modelsByEntity: new Map<IEntityInternal<IModel>, Map<string, IModel>>()
      };
      rootScopeStateByKey.set(rootScopeKey, state);
    }
    return state;
  };
 
  const ensureCollectionMembership = (
    rootScopeState: IRootScopeState
  ): WeakMap<IModel, Map<IEntityInternal<IModel>, Set<string>>> => {
    if (!rootScopeState.collectionMembership) {
      rootScopeState.collectionMembership = new WeakMap<
        IModel,
        Map<IEntityInternal<IModel>, Set<string>>
      >();
    }
    return rootScopeState.collectionMembership;
  };
 
  const linkSourceToTarget = ({
    sourceEntity,
    sourceModel,
    sourceModelPkId,
    targetEntity,
    targetModel,
    collectionMembership
  }: {
    sourceEntity: IEntityInternal<IModel>;
    sourceModel: IModel;
    sourceModelPkId: string;
    targetEntity: IEntityInternal<IModel>;
    targetModel: IModel;
    collectionMembership: WeakMap<
      IModel,
      Map<IEntityInternal<IModel>, Set<string>>
    >;
  }) => {
    sourceModel[targetEntity.displayName as keyof typeof sourceModel] =
      targetModel;
 
    const collectionKey =
      sourceEntity.collectionDisplayName as keyof typeof targetModel;
    let collection = targetModel[collectionKey];
    if (!collection) {
      const Collection = sourceEntity.Collection;
      const createdCollection = new Collection({ models: [] });
      // Keep ORM back-reference collections out of default JSON serialization.
      Object.defineProperty(targetModel, collectionKey, {
        value: createdCollection,
        writable: true,
        configurable: true,
        enumerable: false
      });
      collection = createdCollection;
    }
 
    let byCollection = collectionMembership.get(targetModel);
    if (!byCollection) {
      byCollection = new Map<IEntityInternal<IModel>, Set<string>>();
      collectionMembership.set(targetModel, byCollection);
    }
    let memberIds = byCollection.get(sourceEntity);
    if (!memberIds) {
      memberIds = new Set<string>();
      byCollection.set(sourceEntity, memberIds);
    }
    if (!memberIds.has(sourceModelPkId)) {
      collection.models.push(sourceModel);
      memberIds.add(sourceModelPkId);
    }
  };
 
  /*
   * createFromDatabase architecture:
   * 1) Compile row plans once (column -> property mapping per entity/table).
   * 2) Materialize models per row with scoped de-duplication by root scope key.
   * 3) Index models by root scope + entity + entity primary key.
   * 4) Link refs incrementally as new models appear.
   * 5) Return root models in first-seen root scope order.
   */
  const createFromDatabase = <T extends ICollection<IModel>>(rows: any): T => {
    const result = Array.isArray(rows) ? rows : [rows];
    const len = result.length;
    const entityRowPlans = buildEntityRowPlans(result[0]);
    const selectedEntities = new Set<IEntityInternal<IModel>>();
    for (let i = 0; i < entityRowPlans.length; i++) {
      selectedEntities.add(entityRowPlans[i].entity);
    }
    const applicableRefPlans = new Map<
      IEntityInternal<IModel>,
      Array<{ property: string; targetEntity: IEntityInternal<IModel> }>
    >();
    for (let i = 0; i < entityRowPlans.length; i++) {
      const entity = entityRowPlans[i].entity;
      const refs = entityReferencePlans.get(entity) || [];
      const filteredRefs = refs.filter((ref) =>
        selectedEntities.has(ref.targetEntity)
      );
      applicableRefPlans.set(entity, filteredRefs);
    }
    const rootEntity = entityRowPlans[0].entity;
    const rootPrimaryKeys = rootEntity.primaryKeys;
    const rootScopeOrder: Array<string> = [];
    const rootModelsByScopeKey = new Map<string, IModel>();
    const rootScopeStateByKey: IRootScopeStateByKey = new Map();
    let currentRootScopeKey: string | void = void 0;
    let currentRootScopeState: IRootScopeState | void = void 0;
    const rowModels = new Array<IModel | void>(entityRowPlans.length);
    const rowModelPkIds = new Array<string>(entityRowPlans.length);
    const rowCreatedWithPkIndexes: Array<number> = [];
 
    // Phase 1: materialize and index model instances by root scope + entity.
    for (let i = 0; i < len; i++) {
      const row = result[i];
      const rootScopeKey = getRootScopeKey(row, rootEntity, rootPrimaryKeys);
      let rootScopeState: IRootScopeState | void = currentRootScopeState;
      if (!rootScopeState || rootScopeKey !== currentRootScopeKey) {
        rootScopeState = ensureRootScopeState(
          rootScopeKey,
          rootScopeStateByKey
        );
        currentRootScopeKey = rootScopeKey;
        currentRootScopeState = rootScopeState;
      }
      const rootModel = materializeModelsFromRow(
        row,
        entityRowPlans,
        rootScopeState.modelsByEntity,
        rowModels,
        rowModelPkIds,
        rowCreatedWithPkIndexes
      );
      if (!rootModelsByScopeKey.has(rootScopeKey)) {
        rootScopeOrder.push(rootScopeKey);
        rootModelsByScopeKey.set(rootScopeKey, rootModel);
      }
 
      for (let c = 0; c < rowCreatedWithPkIndexes.length; c++) {
        const j = rowCreatedWithPkIndexes[c];
        const sourceModel = rowModels[j] as IModel;
        const sourceModelPkId = rowModelPkIds[j];
        const sourceEntity = entityRowPlans[j].entity;
 
        const refs = applicableRefPlans.get(sourceEntity);
        if (!refs || refs.length === 0) {
          continue;
        }
 
        for (let r = 0; r < refs.length; r++) {
          const ref = refs[r];
          const refId = sourceModel[ref.property as keyof typeof sourceModel];
          if (refId == null) {
            continue;
          }
          const targetPkId = String(refId);
          const target = rootScopeState.modelsByEntity
            .get(ref.targetEntity)
            ?.get(targetPkId);
          if (target) {
            linkSourceToTarget({
              sourceEntity,
              sourceModel,
              sourceModelPkId,
              targetEntity: ref.targetEntity,
              targetModel: target,
              collectionMembership: ensureCollectionMembership(rootScopeState)
            });
          }
        }
      }
    }
 
    const models = new Array<IModel>(rootScopeOrder.length);
    for (let i = 0; i < rootScopeOrder.length; i++) {
      models[i] = rootModelsByScopeKey.get(rootScopeOrder[i]) as IModel;
    }
    const Collection = getEntityByModel(models[0]).Collection;
    return <T>new Collection({ models });
  };
 
  const createAnyFromDatabase = <T extends ICollection<IModel>>(
    rows: any,
    rootKey: string | IModelClass
  ): T => {
    if (!rows || !rows.length) {
      const Collection =
        typeof rootKey === 'string'
          ? getEntityByTableName(rootKey).Collection
          : getEntityByModelClass(rootKey).Collection;
      return new Collection({ models: [] }) as T;
    }
    return <T>createFromDatabase<T>(rows);
  };
 
  const createOneFromDatabase = <T extends IModel>(rows: any): T => {
    if (!rows || !rows.length) {
      throw Error('Did not get one.');
    }
    const collection = createFromDatabase<ICollection<IModel>>(rows);
    Iif (!collection || !collection.models || collection.models.length === 0) {
      throw Error('Did not get one.');
    } else if (collection.models.length > 1) {
      throw Error('Got more than one.');
    }
    return <T>collection.models[0];
  };
 
  const createOneOrNoneFromDatabase = <T extends IModel>(
    rows: any
  ): T | void => {
    if (!rows || !rows.length) {
      return void 0;
    }
    return <T>createOneFromDatabase(rows);
  };
 
  const createManyFromDatabase = <T extends ICollection<IModel>>(
    rows: any
  ): T => {
    if (!rows || !rows.length) {
      throw Error('Did not get at least one.');
    }
    return <T>createFromDatabase(rows);
  };
 
  return {
    getEntityByModel,
    getEntityByTableName,
    createFromDatabase,
    createAnyFromDatabase,
    createOneFromDatabase,
    createOneOrNoneFromDatabase,
    createManyFromDatabase,
    tables: entities.reduce((accum: any, data: IEntityInternal<IModel>) => {
      accum[data.displayName] = {
        columns: data.selectColumnsClause
      };
      return accum;
    }, {})
  };
};