All files / myorm base-entity.ts

84.68% Statements 94/111
74.28% Branches 26/35
89.47% Functions 17/19
84.76% Lines 89/105

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                                                                                      5x   5x   5x   5x       5x                                                                                                                             13x 13x   13x   19x 19x   38x 1x           37x 4x   33x     18x     12x                                                             4x 4x 4x   3x 3x   3x     3x                                                                   31x 31x 31x   30x 30x   30x     30x                             11x   11x 10x 10x     10x                               13x   12x 12x   12x           12x 12x                             3x     3x   2x                       183x   183x     183x 6x     183x 3x   183x 3x     183x 8x             175x                             112x   112x   112x 112x   112x 112x 112x   112x     485x   112x     112x 373x     373x 1x         372x 45x     327x     111x 111x         111x   110x 1x 1x     372x   372x   110x             110x     110x 110x       1x   1x       1x   1x        
import * as SQLite from "expo-sqlite";
import {
  ColumnMetadata,
  EntityConstructor,
  EntityPrototype,
} from "./decorators";
import { InvalidEntityError } from "@/utils/ErrorTypes";
import assert from "assert";
import logger from "@/utils/logger";
 
// The function signatures is based off of the code in typeorm
// repository: https://github.com/typeorm/typeorm/blob/master/src/repository/BaseEntity.ts
// this is the part I stole:
// funName<T extends BaseEntity>(
//     this: { new (): T } & typeof BaseEntity,
// ): void {
 
// NOTE: this is not an abstract class because i want the `db` attribute
// to be taken from the `BaseEntity` class, so all entities share the same
// database. If it is abstract i cannot do that
/**
 * Core class for all db entities. Db entities
 * must extend this class.
 */
export default class BaseEntity {
  /**
   * An sqlite database connection.
   */
  static db: SQLite.SQLiteDatabase;
 
  /**
   * Finds and returns all records of the current entity.
   * @preconditions This must be called from a class that extends `BaseEntity`,
   * has one primary attribute, and the class has an `Entity` decorator. The mysql
   * database must also be initialized using the hook `useInitDataSource`.
   * @template T The type of the entity.
   * @returns An array of entities.
   * @throws {InvalidEntityError} If the entity prototype is not properly defined.
   */
  static async find<T extends BaseEntity>(
    this: { new (): T } & typeof BaseEntity
  ): Promise<T[]> {
    // ensure prototype is properly defined
    assert(this.verifyPrototype());
 
    const db = BaseEntity.db;
 
    const prototype = this.prototype as EntityPrototype;
 
    const result = await db.getAllAsync(
      `SELECT * FROM ${prototype._tableName}`
    );
 
    return this.convertToObj<T>(result);
  }
 
  /**
   * Takes a option value of SELECT and/or WHERE. Retrieves in the SELECT format if given
   * and all if not. Finds the first instance that matches WHERE
   * @preconditions This must be called from a class that extends `BaseEntity`,
   * has one primary attribute, and the class has an `Entity` decorator. The mysql
   * database must also be initialized using the hook `useInitDataSource`. There must be a where value
   * given and it must be the condiiton you want to select one
   * @param options an object which containst the query modifiers
   * @template T The type of the entity.
   * @returns An single BaseEntity type containing the first instance of the WHERE claus
   * @throws {InvalidEntityError} If the entity prototype is not properly defined.
   */
  static async findOne<T extends BaseEntity>(
    this: { new (): T } & typeof BaseEntity,
    options: { where: { [key: string]: any }; select?: { [key: string]: any } }
  ): Promise<T | null> {
    const { where, select } = options;
 
    if (!where || Object.keys(where).length === 0) {
      throw new Error("findOne requires at least one condition.");
    }
 
    const db = BaseEntity.db;
    const prototype = this.prototype as EntityPrototype;
 
    const whereKeys = Object.keys(where);
    const whereValues = Object.values(where);
    const whereClause = whereKeys.map((key) => `${key} = ?`).join(" AND ");
 
    // Default to `*` if no `select` fields are provided
    const selectClause = select && select.length > 0 ? select.join(", ") : "*";
 
    const queryString = `SELECT ${selectClause} FROM ${prototype._tableName} WHERE ${whereClause} LIMIT 1`;
 
    try {
      const results = await db.getAllAsync(queryString, whereValues);
      return this.convertToObj<T>(results)[0];
    } catch (error) {
      logger.error(`Error in findOne: ${error}`);
      return null;
    }
  }
 
  /**
   * A helper function that takes the object returned by sqlite's `SQLiteDatabase.getAllAsync`
   * and turns it into an object of type `T`.
   * @preconditions This must be called from a class that extends `BaseEntity`,
   * has one primary attribute, and the class has an `Entity` decorator. The mysql
   * database must also be initialized using the hook `useInitDataSource`.
   * @param queryResult mysql query result that contains an array of objects that
   * correspond to the table defined in the class that calls this function. Only nullable fields
   * can be null. All of the rows must match the columns for the table that represents the calling
   * class in the database
   * @template T The type of the entity.
   * @returns An array of entities.
   */
  private static convertToObj<T extends BaseEntity>(
    this: { new (): T } & typeof BaseEntity,
    queryResult: Array<any>
  ): T[] {
    const objArr: T[] = [];
    const prototype = this.prototype as EntityPrototype;
 
    queryResult!.forEach((row: any) => {
      // build a new object for each row in `result`
      const obj = new this() as any;
      prototype._columns!.forEach((col) => {
        // verify that the object contains the proper rows
        if (!(col.name! in row)) {
          throw new InvalidEntityError(
            `Query result does not contain column: "${col.name}"`
          );
        }
 
        // convert string value to list
        if (col.isList) {
          obj[col.propertyKey] = JSON.parse(row[col.name!]);
        } else {
          obj[col.propertyKey] = row[col.name!];
        }
      });
      objArr.push(obj);
    });
 
    return objArr;
  }
 
  /**
   * Executes a query that returns a list of objects of the type this
   * is called with.
   * It automatically replaces `$table` with the entity’s table name.
   * @preconditions This must be called from a class that extends `BaseEntity`,
   * has one primary attribute, and the class has an `Entity` decorator. The mysql
   * database must also be initialized using the hook `useInitDataSource`.
   * @template T The type of the entity.
   * @param query A valid SQL query string. Use `$table` within the query
   * to reference this entity's table name. Needs to return a list of objects
   * @param params Additional parameters for the query (optional).
   * @returns An array of entities resulting from the query.
   * @throws {InvalidEntityError} If the entity prototype is not properly defined.
   *
   * @example
   * // The table name is "employees"
   * const results = await Employee.query(
   *    "SELECT * FROM $table WHERE salary > ?",
   *    100000
   * );
   * // This runs:
   * //   SELECT * FROM employees WHERE salary > 100000
   */
  static async queryObjs<T extends BaseEntity>(
    this: { new (): T } & typeof BaseEntity,
    query: string,
    ...params: any[]
  ): Promise<T[]> {
    const db = this.db;
    const prototype = this.prototype as EntityPrototype;
    assert(this.verifyPrototype());
 
    const tableName = prototype._tableName;
    const finalQuery = query.replace(/\$table/g, tableName!);
 
    const result = await db.getAllAsync(finalQuery, ...params);
 
    // Convert rows to entity instances
    return this.convertToObj<T>(result);
  }
 
  /**
   * Executes a query.
   * It automatically replaces `$table` with the entity’s table name.
   *
   * @template T The type of the entity.
   * @param query A valid SQL query string. Use `$table` within the query
   * to reference this entity's table name. Needs to return a list of objects
   * @param params Additional parameters for the query (optional).
   * @returns An the result of the query the same way as the expo-sqlite database does
   * see @link https://docs.expo.dev/versions/latest/sdk/sqlite/.
   * If, after reading the documentation, you are still unsure what kind of object will be
   * returned, don't worry, that is normal. Their documentation is terrible.
   * Each Column where `isList: true` will be returned as a json string, convert
   * it from a json to a list (ex. Array<Obj> list = listField.json();)
   * @throws {InvalidEntityError} If the entity prototype is not properly defined.
   * @effects modifys the sqlite database based on the given `query`
   *
   * @example
   * // The table name is "employees"
   * const results = await Employee.query(
   *    "SELECT * FROM $table WHERE salary > ?",
   *    100000
   * );
   * // This runs:
   * //   SELECT * FROM employees WHERE salary > 100000
   */
  static async query<T extends BaseEntity>(
    this: { new (): T } & typeof BaseEntity,
    query: string,
    ...params: any[]
  ): Promise<any> {
    const db = this.db;
    const prototype = this.prototype as EntityPrototype;
    assert(this.verifyPrototype());
 
    const tableName = prototype._tableName;
    const finalQuery = query.replace(/\$table/g, tableName!);
 
    const result = await db.getAllAsync(finalQuery, ...params);
 
    // Convert rows to entity instances
    return result;
  }
 
  /**
   * Get the number of entities in the table.
   * @preconditions This must be called from a class that extends `BaseEntity`,
   * has one primary attribute, and the class has an `Entity` decorator. The mysql
   * database must also be initialized using the hook `useInitDataSource`.
   * @template T The type of the entity.
   * @returns The number of entities in the table.
   * @throws {InvalidEntityError} If the entity prototype is not properly defined.
   */
  static async count<T extends BaseEntity>(
    this: { new (): T } & typeof BaseEntity
  ): Promise<number> {
    const prototype = this.prototype as EntityPrototype;
    // ensure prototype is properly defined
    assert(this.verifyPrototype());
    const db = this.db;
    const result = (await db.getFirstAsync(
      `SELECT COUNT(*) as count FROM ${prototype._tableName}`
    )) as any;
    return result.count;
  }
 
  /**
   * Clears all entities from the table.
   * @preconditions This must be called from a class that extends `BaseEntity`,
   * has one primary attribute, and the class has an `Entity` decorator. The mysql
   * database must also be initialized using the hook `useInitDataSource`.
   * @template T The type of the entity.
   * @throws {InvalidEntityError} If the entity prototype is not properly defined.
   * @effects Deletes all of the rows in the database.
   */
  static async clear<T extends BaseEntity>(
    this: { new (): T } & typeof BaseEntity
  ): Promise<void> {
    // ensure prototype is properly defined
    assert(this.verifyPrototype());
 
    const db = this.db;
    const prototype = this.prototype as EntityPrototype;
 
    Iif (prototype._tableName == undefined) {
      throw new InvalidEntityError(
        `Entity prototype has undefined attribute: _tableName`
      );
    }
 
    await db.execAsync(`DELETE FROM ${prototype._tableName}`);
    return;
  }
 
  /**
   * Get a list of all database column names.
   * @preconditions This must be called from a class that extends `BaseEntity`,
   * has one primary attribute, and the class has an `Entity` decorator. The mysql
   * database must also be initialized using the hook `useInitDataSource`.
   * @template T The type of the entity.
   * @returns A list of column data.
   * @throws {InvalidEntityError} If the entity prototype is not properly defined.
   */
  static getColumns<T extends BaseEntity>(
    this: { new (): T } & typeof BaseEntity
  ): Promise<Array<ColumnMetadata>> {
    const prototype = this.prototype as EntityPrototype;
 
    // ensure prototype is properly defined
    assert(this.verifyPrototype());
 
    return (this.prototype as any)._columns;
  }
 
  /**
   * Checks if the prototype of the current class contains the information needed to
   * set up a table.
   * @returns 1 on success
   * @throws {InvalidEntityError} If the entity prototype is not properly defined.
   */
  private static verifyPrototype<T extends BaseEntity>(
    this: { new (): T } & typeof BaseEntity
  ): number {
    const prototype = this.prototype as EntityPrototype;
 
    const undefinedAttrs: string[] = [];
 
    // check if the entity is defined correctly
    if (prototype._tableName == undefined) {
      undefinedAttrs.push("_tableName");
    }
 
    if (prototype._primaryKey == undefined) {
      undefinedAttrs.push("_primaryKey");
    }
    if (prototype._columns == undefined) {
      undefinedAttrs.push("_columns");
    }
 
    if (undefinedAttrs.length > 0) {
      throw new InvalidEntityError(
        `Entity prototype has undefined attribute(s): ${undefinedAttrs.join(
          ", "
        )}`
      );
    }
 
    return 1;
  }
 
  /**
   * Saves the current object to the database.
   * @preconditions All columns that are not nullable must contain a value.
   * This must be called from a class that extends `BaseEntity`,
   * has one primary attribute, and the class has an `Entity` decorator (this
   * also initializes the database).
   * @throws {InvalidEntityError} If a required field is empty or
   *      the entity prototype is not properly defined.
   * @effects Adds a row to the database with the objects data.
   */
  async save(): Promise<void> {
    // ensure prototype is properly defined
    assert((this.constructor as typeof BaseEntity).verifyPrototype());
 
    const db = BaseEntity.db;
 
    const constructor = this.constructor as EntityConstructor;
    const prototype = constructor.prototype;
 
    const tableName = prototype._tableName;
    const pk = prototype._primaryKey;
    const columns = prototype._columns;
 
    const pkValue = (this as any)[pk!];
 
    // columns without primary key
    const cols = columns!.filter((col) => !col.isPrimary);
 
    const pkColumn = columns!.find((col) => col.isPrimary)!;
 
    // values for the columns
    const values = cols.map((col) => {
      let val = (this as any)[col.propertyKey];
 
      // check if non-nullable values are null
      if ((val === null || val === undefined) && !col.isNullable) {
        throw new InvalidEntityError(
          `Field "${col.propertyKey}" is ${val} and is not nullable`
        );
      }
      // store string as a list
      if (col.isList) {
        return JSON.stringify(val);
      }
 
      return val;
    }) as string[];
 
    logger;
    const { recordExists } = (await db.getFirstAsync(
      `SELECT EXISTS(SELECT 1 FROM ${tableName} WHERE id = ?) as recordExists;`,
      pkValue
    )) as any;
    // INSERT
    if (!recordExists) {
      // if id is defined insert it
      if (pkValue !== undefined && pkValue !== null) {
        cols.push(pkColumn);
        values.push(pkValue);
      }
 
      const colNames = cols.map((col) => col.name);
 
      const placeholders = cols.map((_) => "?").join(", ");
 
      logger.debug(
        `table ${tableName} info`,
        await db.runAsync(
          `SELECT sql FROM sqlite_master WHERE type='table' AND name='${tableName}';');`
        )
      );
 
      const sql = `INSERT INTO ${tableName} ( ${colNames.join(
        ", "
      )} ) VALUES ( ${placeholders} )`;
      const result = await db.runAsync(sql, ...values);
      (this as any)[pk!] = result.lastInsertRowId;
    }
    // UPDATE
    else {
      const assignments = cols.map((col) => `${col.name} = ?`);
 
      const sql = `UPDATE ${tableName} SET ${assignments.join(", ")} WHERE ${
        pkColumn.name
      } = ?`;
 
      values.push(pkValue);
 
      await db.runAsync(sql, ...values);
    }
  }
}