All files / dist/src orm.js

100% Statements 159/159
88.89% Branches 24/27
100% Functions 17/17
100% Lines 153/153

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  1x 1x 1x 1x 1x 41x   41x 40x     1x   40x 40x 23x 23x 23x 23x 23x 23x 23x 552x 552x 552x 552x 552x   23x           23x   23x   40x 5x 5x 5x 5x 5x 5x 5x 5x 120x 120x 12x 7x   12x 12x 12x 12x     5x   40x 6x 6x 6x 6x 6x 6x 6x 144x 144x 13x 7x   13x 13x 13x     6x 6x 6x   40x 10x 10x 10x 10x 10x 10x 10x 240x 240x 14x 4x   14x 14x 14x     10x       40x 2x 2x 2x 2x 2x 2x 2x 48x 48x 5x 3x   5x 5x 5x     2x   40x 3x 3x 3x 3x 6x 6x 6x     3x   40x 5x 5x 5x       40x 6x 6x 6x           40x 2x 2x 2x         2x     40x 2x 2x 2x           2x     40x 1x 1x 1x       1x   40x 1x 1x 1x       1x   40x 1x 1x 1x         1x   40x 2x 2x 2x         2x   40x 2x 2x 2x         2x   40x 2x 2x 2x         2x   40x                                       1x  
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.create = void 0;
const core_1 = require("./core");
const pgp_1 = require("./driver-integrations/pgp");
const create = ({ entities: externalEntities, db, logError }) => {
    const core = (0, core_1.createCore)({ entities: externalEntities });
    let orm;
    if (db.$config.pgp) {
        orm = (0, pgp_1.createForPGP)({ core, db, logError });
    }
    else {
        throw new Error(`You're database driver is not yet supported. You can make a PR to add it, or use the \`createCore\` export which doesn't try to abstract over the database driver, and instead you pass the results of the database driver queries to it.`);
    }
    const helperPlanByEntity = new Map();
    const getHelperPlan = (entity) => {
        let plan = helperPlanByEntity.get(entity);
        Eif (!plan) {
            const quotedColumns = new Array(entity.columnNames.length);
            const updateClausePrefixes = new Array(entity.columnNames.length);
            const wherePositionalPrefixes = new Array(entity.columnNames.length);
            const whereNamedPrefixes = new Array(entity.columnNames.length);
            for (let i = 0; i < entity.columnNames.length; i++) {
                const column = entity.columnNames[i];
                quotedColumns[i] = `"${column}"`;
                updateClausePrefixes[i] = `"${column}" = $`;
                wherePositionalPrefixes[i] = `"${entity.tableName}"."${column}" = $`;
                whereNamedPrefixes[i] = `"${entity.tableName}"."${column}" = $(`;
            }
            plan = {
                quotedColumns,
                updateClausePrefixes,
                wherePositionalPrefixes,
                whereNamedPrefixes
            };
            helperPlanByEntity.set(entity, plan);
        }
        return plan;
    };
    const getSqlInsertParts = (model) => {
        const entity = orm.getEntityByModel(model);
        const { columnNames, propertyNames } = entity;
        const helperPlan = getHelperPlan(entity);
        let columns = '';
        const values = [];
        const valuesVar = [];
        let paramIndex = 1;
        for (let i = 0; i < columnNames.length; i++) {
            const val = model[propertyNames[i]];
            if (val !== void 0) {
                if (columns) {
                    columns += ', ';
                }
                columns += helperPlan.quotedColumns[i];
                values.push(val);
                valuesVar.push(`$${paramIndex}`);
                paramIndex++;
            }
        }
        return { columns, values, valuesVar };
    };
    const getSqlUpdateParts = (model, on = 'id') => {
        const entity = orm.getEntityByModel(model);
        const { columnNames, propertyNames } = entity;
        const helperPlan = getHelperPlan(entity);
        let clause = '';
        const values = [];
        let paramIndex = 1;
        for (let i = 0; i < columnNames.length; i++) {
            const val = model[propertyNames[i]];
            if (val !== void 0) {
                if (clause) {
                    clause += ', ';
                }
                clause += helperPlan.updateClausePrefixes[i] + paramIndex;
                values.push(val);
                paramIndex++;
            }
        }
        const idVar = `$${paramIndex}`;
        values.push(model[on]);
        return { clause, idVar, values };
    };
    const getMatchingParts = (model) => {
        const entity = orm.getEntityByModel(model);
        const { propertyNames, columnNames } = entity;
        const helperPlan = getHelperPlan(entity);
        const values = [];
        let paramIndex = 1;
        let whereClause = '';
        for (let i = 0; i < propertyNames.length; i++) {
            const val = model[propertyNames[i]];
            if (val != null) {
                if (whereClause) {
                    whereClause += ' AND ';
                }
                whereClause += helperPlan.wherePositionalPrefixes[i] + paramIndex;
                values.push(val);
                paramIndex++;
            }
        }
        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) => {
        const entity = orm.getEntityByModel(model);
        const { propertyNames, columnNames } = entity;
        const helperPlan = getHelperPlan(entity);
        const values = {};
        let paramIndex = 1;
        let whereClause = '';
        for (let i = 0; i < propertyNames.length; i++) {
            const val = model[propertyNames[i]];
            if (val != null) {
                if (whereClause) {
                    whereClause += ' AND ';
                }
                whereClause += helperPlan.whereNamedPrefixes[i] + paramIndex + ')';
                values[paramIndex] = val;
                paramIndex++;
            }
        }
        return { whereClause, values };
    };
    const getNewWith = (model, sqlColumns, values) => {
        const Constructor = model.constructor;
        const entity = orm.getEntityByModel(model);
        const modelData = {};
        for (let i = 0; i < sqlColumns.length; i++) {
            const propertyName = entity.columnToPropertyMap.get(sqlColumns[i]);
            Eif (propertyName) {
                modelData[propertyName] = values[i];
            }
        }
        return new Constructor(modelData);
    };
    const getValueBySqlColumn = (model, sqlColumn) => {
        const entity = orm.getEntityByModel(model);
        const propertyName = entity.columnToPropertyMap.get(sqlColumn);
        return propertyName
            ? model[propertyName]
            : undefined;
    };
    const getSqlColumnForPropertyName = (model, propertyName) => {
        const entity = orm.getEntityByModel(model);
        const column = entity.propertyToColumnMap.get(propertyName);
        return column;
    };
    /* ------------------------------------------------------------------------*/
    /* Built-in basic CRUD functions ------------------------------------------*/
    /* ------------------------------------------------------------------------*/
    // Standard create
    const create = (model) => {
        const entity = orm.getEntityByModel(model);
        const { columns, values, valuesVar } = getSqlInsertParts(model);
        const query = `
      INSERT INTO "${entity.tableName}" ( ${columns} )
      VALUES ( ${valuesVar} )
      RETURNING ${entity.selectColumnsClause};
    `;
        return orm.one(query, values);
    };
    // Standard update
    const update = (model, { on = 'id' } = {}) => {
        const entity = orm.getEntityByModel(model);
        const { clause, idVar, values } = getSqlUpdateParts(model, on);
        const query = `
      UPDATE "${entity.tableName}"
      SET ${clause}
      WHERE "${entity.tableName}".${getSqlColumnForPropertyName(model, on)} = ${idVar}
      RETURNING ${entity.selectColumnsClause};
    `;
        return orm.one(query, values);
    };
    // Standard delete
    const _delete = (model) => {
        const entity = orm.getEntityByModel(model);
        const id = model.id;
        const query = `
      DELETE FROM "${entity.tableName}"
      WHERE "${entity.tableName}".id = $(id)
    `;
        return orm.none(query, { id });
    };
    const deleteMatching = (model) => {
        const entity = orm.getEntityByModel(model);
        const { whereClause, values } = getMatchingParts(model);
        const query = `
      DELETE FROM "${entity.tableName}"
      WHERE ${whereClause};
    `;
        return orm.none(query, values);
    };
    const getMatching = (model) => {
        const entity = orm.getEntityByModel(model);
        const { whereClause, values } = getMatchingParts(model);
        const query = `
      SELECT ${entity.selectColumnsClause}
      FROM "${entity.tableName}"
      WHERE ${whereClause};
    `;
        return orm.one(query, values);
    };
    const getOneOrNoneMatching = (model) => {
        const entity = orm.getEntityByModel(model);
        const { whereClause, values } = getMatchingParts(model);
        const query = `
      SELECT ${entity.selectColumnsClause}
      FROM "${entity.tableName}"
      WHERE ${whereClause};
    `;
        return orm.oneOrNone(query, values);
    };
    const getAnyMatching = (model) => {
        const entity = orm.getEntityByModel(model);
        const { whereClause, values } = getMatchingParts(model);
        const query = `
      SELECT ${entity.selectColumnsClause}
      FROM "${entity.tableName}"
      WHERE ${whereClause};
    `;
        return orm.any(query, values);
    };
    const getAllMatching = (model) => {
        const entity = orm.getEntityByModel(model);
        const { whereClause, values } = getMatchingParts(model);
        const query = `
      SELECT ${entity.selectColumnsClause}
      FROM "${entity.tableName}"
      WHERE ${whereClause};
    `;
        return orm.many(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,
        getSqlColumnForPropertyName
    });
};
exports.create = create;