All files / src factory.ts

63.73% Statements 181/284
58.12% Branches 68/117
46.88% Functions 45/96
62.91% Lines 173/275

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 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 8071x                                                                                                                       1x 8x   50x 50x   50x 50x     271x 226x           45x             50x 271x   271x 50x 271x   50x 50x   50x 271x   50x 50x     50x 2379x 2379x       50x 271x     45x           50x     271x       50x                                   8x 10197x 1104x     1104x     8x 404341x 38207x     38207x                       8x 111x 26x 26x 1104x   26x   26x     26x 111x 993x   18827x       993x 993x 993x 27484x   26688x   26688x 27484x 26812x   672x 673x     673x 646x     26x         993x 11737x 9876x   1861x 48580x   1861x 963x   898x   993x       993x 5858x     5858x 5526x   332x     332x   993x 538x 75x 75x             463x   463x       463x 61x 61x       857x 585x 272x   151x 151x 85x   66x 66x           121x   121x               736x       26x                                           8x     13x 13x 13x 111x     111x     111x 85x   26x   111x   13x     8x 111x 1104x 1104x     3703x 3703x                 3703x 3703x       1104x               8x 111x 3703x 3703x 3703x     3703x 3703x 3703x       8x 13x 13x 13x 13x 13x 26x 13x 13x     8x                           8x 4x     4x 4x   4x     4x     8x                 8x                 8x                 50x     50x                     1x         8x   8x                         8x                     8x                     8x                     8x                               8x                     8x                                   1x         8x                   8x                                                 8x                                                   8x                                                   8x                                                         8x                                   8x                         8x                     8x                       8x                 8x                 8x                   8x                   8x                       8x                   8x                                      
const camelCase = require('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;
}
export type IEntitiesInternal<T extends IModel> = Array<IEntityInternal<T>>;
 
export interface CreateOrmOptions {
  entities: IEntities<IModel>;
}
 
export const createOrm = ({ entities: externalEntities }: CreateOrmOptions) => {
  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'];
 
      // Returns unique identifier of model (the values of the primary keys)
      const getPkId = (model: IModel): string => {
        return primaryKeys
          .map((key: string) => model[key as keyof typeof model])
          .join('');
      };
 
      const references = columns
        .filter((x: IColumnInternal) => x.references)
        .reduce(
          (accum: any, item: IColumnInternal) =>
            Object.assign({}, accum, {
              [item.property]: item.references
            }),
          {}
        );
 
      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
      };
    }
  );
 
  const getEntityByTableName = (tableName: string): IEntityInternal<IModel> => {
    const entity = entities.find((data) => data.tableName == tableName);
    Iif (!entity) {
      throw new Error(`Could not find entity for table ${tableName}`);
    }
    return entity;
  };
 
  const getEntityByModel = (model: IModel): IEntityInternal<IModel> => {
    const entity = entities.find((data) => data.Model == model.constructor);
    Iif (!entity) {
      throw new Error(`Could not find entity for class ${model.constructor}`);
    }
    return entity;
  };
 
  /*
   * In:
   *  [
   *    [Article {id: 32}, ArticleTag {id: 54}]
   *    [Article {id: 32}, ArticleTag {id: 55}]
   *  ]
   * Out:
   *  Article {id: 32, ArticleTags articleTags: [ArticleTag {id: 54}, ArticleTag {id: 55}]
   */
  const nestClump = (clump: Array<Array<IModel>>): object => {
    clump = clump.map((x: Array<IModel>) => Object.values(x));
    const root = clump[0][0];
    clump = clump.map((row: Array<IModel>) =>
      row.filter((item: IModel, index: number) => index !== 0)
    );
    const built = { [getEntityByModel(root).displayName]: root };
 
    let nodes = [root];
 
    // Wowzer is this both CPU and Memory inefficient
    clump.forEach((array: Array<IModel>) => {
      array.forEach((_model: IModel) => {
        const nodeAlreadySeen = nodes.find(
          (x: IModel) =>
            x.constructor.name === _model.constructor.name &&
            getEntityByModel(x).getPkId(x) ===
              getEntityByModel(_model).getPkId(_model)
        );
        const model = nodeAlreadySeen || _model;
        const isNodeAlreadySeen = !!nodeAlreadySeen;
        const nodePointingToIt = nodes.find((node) => {
          const indexes = Object.values(getEntityByModel(node).references)
            .map((x: IModelClass, i: number) =>
              x === model.constructor ? i : null
            )
            .filter((x: number | null, i) => x != null) as Array<number>;
          if (!indexes.length) {
            return false;
          }
          for (const index of indexes) {
            const property = Object.keys(getEntityByModel(node).references)[
              index
            ];
            if (node[property] === model.id) {
              return true;
            }
          }
          return false;
        });
        // For first obj type which is has an instance in nodes array,
        // get its index in nodes array
        const indexOfOldestParent =
          array.reduce((answer: number | null, obj: IModel) => {
            if (answer != null) {
              return answer;
            }
            const index = nodes.findIndex(
              (n) => n.constructor === obj.constructor
            );
            if (index !== -1) {
              return index;
            }
            return null;
          }, null) || 0;
        const parentHeirarchy = [
          root,
          ...nodes.slice(0, indexOfOldestParent + 1).reverse()
        ];
        const nodeItPointsTo = parentHeirarchy.find((parent) => {
          const index = Object.values(
            getEntityByModel(model).references
          ).indexOf(parent.constructor);
          if (index === -1) {
            return false;
          }
          const property = Object.keys(getEntityByModel(model).references)[
            index
          ];
          return model[property as keyof typeof model] === parent.id;
        });
        if (isNodeAlreadySeen) {
          if (nodeItPointsTo && !nodePointingToIt) {
            nodes = [model, ...nodes];
            return;
          }
          // If the nodePointingToIt (eg, parcel_event) is part of an
          // existing collection on this node (eg, parcel) which is a
          // nodeAlreadySeen, early return so we don't create it (parcel) on
          // the nodePointingToIt (parcel_event), since it (parcel) has been
          // shown to be the parent (of parcel_events).
          Eif (nodePointingToIt) {
            const ec =
              model[
                getEntityByModel(nodePointingToIt)
                  .collectionDisplayName as keyof typeof model
              ];
            if (ec && ec.models.find((m: IModel) => m === nodePointingToIt)) {
              nodes = [model, ...nodes];
              return;
            }
          }
        }
        if (nodePointingToIt) {
          nodePointingToIt[getEntityByModel(model).displayName] = model;
        } else if (nodeItPointsTo) {
          let collection =
            nodeItPointsTo[getEntityByModel(model).collectionDisplayName];
          if (collection) {
            collection.models.push(model);
          } else {
            const Collection = getEntityByModel(model).Collection;
            nodeItPointsTo[getEntityByModel(model).collectionDisplayName] =
              new Collection({
                models: [model]
              });
          }
        } else {
          Eif (!getEntityByModel(model).getPkId(model)) {
            // If the join is fruitless; todo: add a test for this path
            return;
          }
          throw Error(
            `Could not find how this BO fits: ${JSON.stringify(model)} ${
              getEntityByModel(model).tableName
            }`
          );
        }
        nodes = [model, ...nodes];
      });
    });
 
    return built;
  };
 
  /*
   * Clump array of flat objects into groups based on id of root
   * In:
   *  [
   *    [Article {id: 32}, ArticleTag {id: 54}]
   *    [Article {id: 32}, ArticleTag {id: 55}]
   *    [Article {id: 33}, ArticleTag {id: 56}]
   *  ]
   * Out:
   *  [
   *    [
   *      [Article {id: 32}, ArticleTag {id: 54}]
   *      [Article {id: 32}, ArticleTag {id: 55}]
   *    ]
   *    [
   *      [Article {id: 33}, ArticleTag {id: 56}]
   *    ]
   *  ]
   */
  const clumpIntoGroups = (
    processed: Array<Array<IModel>>
  ): Array<Array<Array<IModel>>> => {
    const root = processed[0][0];
    const rootBo = root.constructor;
    const clumps = processed.reduce((accum: any, item: Array<IModel>) => {
      const id = getEntityByModel(root)
        .primaryKeys.map(
          (key: string) =>
            item.find((x: IModel) => x.constructor === rootBo)?.[key]
        )
        .join('@');
      if (accum.has(id)) {
        accum.set(id, [...accum.get(id), item]);
      } else {
        accum.set(id, [item]);
      }
      return accum;
    }, new Map());
    return [...clumps.values()];
  };
 
  const mapToBos = (objectified: any) => {
    return Object.keys(objectified).map((tableName) => {
      const entity = getEntityByTableName(tableName);
      const propified = Object.keys(objectified[tableName]).reduce(
        (obj: any, column) => {
          let propertyName =
            entity.propertyNames[entity.columnNames.indexOf(column)];
          Iif (!propertyName) {
            if (column.startsWith('meta_')) {
              propertyName = camelCase(column);
            } else {
              throw Error(
                `No property name for "${column}" in business object "${entity.displayName}". Non-spec'd columns must begin with "meta_".`
              );
            }
          }
          obj[propertyName] = objectified[tableName][column];
          return obj;
        },
        {}
      );
      return new entity.Model(propified);
    });
  };
 
  /*
   * Make objects (based on special table#column names) from flat database
   * return value.
   */
  const objectifyDatabaseResult = (result: object) => {
    return Object.keys(result).reduce((obj: any, text: string) => {
      const tableName = text.split('#')[0];
      const column = text.split('#')[1];
      Iif (!tableName || !column) {
        throw new Error('Column names must be namespaced to table');
      }
      obj[tableName] = obj[tableName] || {};
      obj[tableName][column] = result[text as keyof typeof result];
      return obj;
    }, {});
  };
 
  const createFromDatabase = <T extends ICollection<IModel>>(rows: any): T => {
    const result = Array.isArray(rows) ? rows : [rows];
    const objectified = result.map(objectifyDatabaseResult);
    const boified = objectified.map(mapToBos);
    const clumps = clumpIntoGroups(boified);
    const nested = clumps.map(nestClump);
    const models = nested.map((n) => Object.values(n)[0]);
    const Collection = getEntityByModel(models[0]).Collection;
    return <T>new Collection({ models });
  };
 
  const createAnyFromDatabase = <T extends ICollection<IModel>>(
    rows: any,
    rootKey: string | IModel
  ): T => {
    if (!rows || !rows.length) {
      const Collection =
        typeof rootKey === 'string'
          ? getEntityByTableName(rootKey).Collection
          : getEntityByModel(rootKey).Collection;
      return new Collection({ models: [] }) as T;
    }
    return <T>createFromDatabase<T>(rows);
  };
 
  const createOneFromDatabase = <T extends IModel>(rows: any): T => {
    Iif (!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 Iif (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,
    createFromDatabase,
    createAnyFromDatabase,
    createOneFromDatabase,
    createOneOrNoneFromDatabase,
    createManyFromDatabase,
    // tables property for access to select columns clause string
    tables: entities.reduce((accum: any, data: IEntityInternal<IModel>) => {
      accum[data.displayName] = {
        columns: data.selectColumnsClause
      };
      return accum;
    }, {})
  };
};
 
export interface CreateAbstractionLayerOptions {
  entities: IEntities<IModel>;
  db: any;
  logError?: (err: Error) => void;
}
 
export const createAbstractionLayer = ({
  entities: externalEntities,
  db,
  logError
}: CreateAbstractionLayerOptions) => {
  const orm = createOrm({ entities: externalEntities });
 
  const defaultErrorHandler = (err: Error) => {
    if (!(err.name === 'QueryResultError')) {
      if (logError) {
        logError(err);
      }
    }
    throw err;
  };
 
  /* ------------------------------------------------------------------------*/
  /* Query functions --------------------------------------------------------*/
  /* ------------------------------------------------------------------------*/
 
  const one = <T extends IModel>(
    query: string,
    values?: object,
    errorHandler = defaultErrorHandler
  ): T => {
    return db
      .many(query, values)
      .then((rows: any) => orm.createOneFromDatabase(rows))
      .catch(errorHandler);
  };
 
  const oneOrNone = <T extends IModel>(
    query: string,
    values?: object,
    errorHandler = defaultErrorHandler
  ): T | void => {
    return db
      .any(query, values)
      .then((rows: any) => orm.createOneOrNoneFromDatabase(rows))
      .catch(errorHandler);
  };
 
  const many = <T extends ICollection<IModel>>(
    query: string,
    values?: object,
    errorHandler = defaultErrorHandler
  ): T => {
    return db
      .any(query, values)
      .then((rows: any) => orm.createManyFromDatabase(rows))
      .catch(errorHandler);
  };
 
  const any = <T extends ICollection<IModel>>(
    query: string,
    values?: object,
    errorHandler = defaultErrorHandler
  ): T | void => {
    return db
      .result(query, values)
      .then((result: any) =>
        orm.createAnyFromDatabase(
          result.rows,
          result.fields[0].name.split('#')[0]
        )
      )
      .catch(errorHandler);
  };
 
  const none = (
    query: string,
    values?: object,
    errorHandler = defaultErrorHandler
  ): void => {
    return db
      .none(query, values)
      .then(() => null)
      .catch(errorHandler);
  };
 
  return Object.assign({}, orm, {
    // Query Functions
    one,
    oneOrNone,
    many,
    any,
    none,
    // provide direct access to db
    db
  });
};
 
export interface CreateOptions {
  entities: IEntities<IModel>;
  db: any;
  logError?: (err: Error) => void;
}
 
export const create = ({
  entities: externalEntities,
  db,
  logError
}: CreateOptions) => {
  const orm = createAbstractionLayer({
    entities: externalEntities,
    db,
    logError
  });
 
  /* ------------------------------------------------------------------------*/
  /* Helper Utilities for CRUD functions ------------------------------------*/
  /* ------------------------------------------------------------------------*/
 
  const getSqlInsertParts = (model: IModel) => {
    const columns = orm
      .getEntityByModel(model)
      .columnNames.filter(
        (column: string, index: number) =>
          model[
            orm.getEntityByModel(model).propertyNames[
              index
            ] as keyof typeof model
          ] !== void 0
      )
      .map((col: string) => `"${col}"`)
      .join(', ');
    const values = orm
      .getEntityByModel(model)
      .propertyNames.map(
        (property: string) => model[property as keyof typeof model]
      )
      .filter((value: any) => value !== void 0);
    const valuesVar = values.map(
      (value: any, index: number) => `$${index + 1}`
    );
    return { columns, values, valuesVar };
  };
 
  const getSqlUpdateParts = (model: IModel, on = 'id') => {
    const clauseArray = orm
      .getEntityByModel(model)
      .columnNames.filter(
        (sqlColumn: string, index: number) =>
          model[
            orm.getEntityByModel(model).propertyNames[
              index
            ] as keyof typeof model
          ] !== void 0
      )
      .map(
        (sqlColumn: string, index: number) => `"${sqlColumn}" = $${index + 1}`
      );
    const clause = clauseArray.join(', ');
    const idVar = `$${clauseArray.length + 1}`;
    const _values = orm
      .getEntityByModel(model)
      .propertyNames.map(
        (property: string) => model[property as keyof typeof model]
      )
      .filter((value: any) => value !== void 0);
    const values = [..._values, model[on as keyof typeof model]];
    return { clause, idVar, values };
  };
 
  const getMatchingParts = (model: IModel) => {
    const whereClause = orm
      .getEntityByModel(model)
      .propertyNames.map((property: string, index: number) =>
        model[property as keyof typeof model] != null
          ? `"${orm.getEntityByModel(model).tableName}"."${
              orm.getEntityByModel(model).columnNames[index]
            }"`
          : null
      )
      .filter((x: string | null) => x != null)
      .map((x: string | null, i: number) => `${x} = $${i + 1}`)
      .join(' AND ');
    const values = orm
      .getEntityByModel(model)
      .propertyNames.map((property: string) =>
        model[property as keyof typeof model] != null
          ? model[property as keyof typeof model]
          : null
      )
      .filter((x: any) => x != null);
    return { whereClause, values };
  };
 
  // This one returns an object, which allows it to be more versatile.
  // To-do: make this one even better and use it instead of the one above.
  const getMatchingPartsObject = (model: IModel) => {
    const whereClause = orm
      .getEntityByModel(model)
      .propertyNames.map((property: string, index: number) =>
        model[property as keyof typeof model] != null
          ? `"${orm.getEntityByModel(model).tableName}"."${
              orm.getEntityByModel(model).columnNames[index]
            }"`
          : null
      )
      .filter((x: string | null) => x != null)
      .map((x: string | null, i: number) => `${x} = $(${i + 1})`)
      .join(' AND ');
    const values = orm
      .getEntityByModel(model)
      .propertyNames.map((property: string) =>
        model[property as keyof typeof model] != null
          ? model[property as keyof typeof model]
          : null
      )
      .filter((x: any) => x != null)
      .reduce(
        (accum: any, val: any, index: number) =>
          Object.assign({}, accum, { [index + 1]: val }),
        {}
      );
    return { whereClause, values };
  };
 
  const getNewWith = (model: IModel, sqlColumns: any, values: any) => {
    const Constructor = model.constructor as any;
    const modelKeys = sqlColumns.map(
      (key: string) =>
        orm.getEntityByModel(model).propertyNames[
          orm.getEntityByModel(model).columnNames.indexOf(key)
        ]
    );
    const modelData = modelKeys.reduce(
      (data: any, key: string, index: number) => {
        data[key] = values[index];
        return data;
      },
      {}
    );
    return new Constructor(modelData);
  };
 
  const getValueBySqlColumn = (model: IModel, sqlColumn: string) => {
    return model[
      orm.getEntityByModel(model).propertyNames[
        orm.getEntityByModel(model).columnNames.indexOf(sqlColumn)
      ] as keyof typeof model
    ];
  };
 
  /* ------------------------------------------------------------------------*/
  /* Built-in basic CRUD functions ------------------------------------------*/
  /* ------------------------------------------------------------------------*/
 
  // Standard create
  const create = <T extends IModel>(model: T): T => {
    const { columns, values, valuesVar } = getSqlInsertParts(model);
    const query = `
      INSERT INTO "${orm.getEntityByModel(model).tableName}" ( ${columns} )
      VALUES ( ${valuesVar} )
      RETURNING ${orm.getEntityByModel(model).selectColumnsClause};
    `;
    return orm.one<T>(query, values);
  };
 
  // Standard update
  const update = <T extends IModel>(model: T, { on = 'id' } = {}): T => {
    const { clause, idVar, values } = getSqlUpdateParts(model, on);
    const query = `
      UPDATE "${orm.getEntityByModel(model).tableName}"
      SET ${clause}
      WHERE "${orm.getEntityByModel(model).tableName}".${on} = ${idVar}
      RETURNING ${orm.getEntityByModel(model).selectColumnsClause};
    `;
    return orm.one<T>(query, values);
  };
 
  // Standard delete
  const _delete = <T extends IModel>(model: T): void => {
    const id = (model as any).id;
    const query = `
      DELETE FROM "${orm.getEntityByModel(model).tableName}"
      WHERE "${orm.getEntityByModel(model).tableName}".id = $(id)
    `;
    return orm.none(query, { id });
  };
 
  const deleteMatching = <T extends IModel>(model: T) => {
    const { whereClause, values } = getMatchingParts(model);
    const query = `
      DELETE FROM "${orm.getEntityByModel(model).tableName}"
      WHERE ${whereClause};
    `;
    return orm.none(query, values);
  };
 
  const getMatching = <T extends IModel>(model: T): T => {
    const { whereClause, values } = getMatchingParts(model);
    const query = `
      SELECT ${orm.getEntityByModel(model).selectColumnsClause}
      FROM "${orm.getEntityByModel(model).tableName}"
      WHERE ${whereClause};
    `;
    return orm.one<T>(query, values);
  };
 
  const getOneOrNoneMatching = <T extends IModel>(model: T): T | void => {
    const { whereClause, values } = getMatchingParts(model);
    const query = `
      SELECT ${orm.getEntityByModel(model).selectColumnsClause}
      FROM "${orm.getEntityByModel(model).tableName}"
      WHERE ${whereClause};
    `;
    return orm.oneOrNone<T>(query, values);
  };
 
  const getAnyMatching = <T extends ICollection<IModel>>(
    model: IModel
  ): T | void => {
    const { whereClause, values } = getMatchingParts(model);
    const query = `
      SELECT ${orm.getEntityByModel(model).selectColumnsClause}
      FROM "${orm.getEntityByModel(model).tableName}"
      WHERE ${whereClause};
    `;
    return orm.any<T>(query, values);
  };
 
  const getAllMatching = <T extends ICollection<IModel>>(model: IModel): T => {
    const { whereClause, values } = getMatchingParts(model);
    const query = `
      SELECT ${orm.getEntityByModel(model).selectColumnsClause}
      FROM "${orm.getEntityByModel(model).tableName}"
      WHERE ${whereClause};
    `;
    return orm.many<T>(query, values);
  };
 
  return Object.assign({}, orm, {
    // Built-in basic CRUD functions
    create,
    update,
    delete: _delete,
    deleteMatching,
    getMatching,
    getOneOrNoneMatching,
    getAnyMatching,
    getAllMatching,
    // Helper Utility functions
    getSqlInsertParts,
    getSqlUpdateParts,
    getMatchingParts,
    getMatchingPartsObject,
    getNewWith,
    getValueBySqlColumn
  });
};