All files / libs/kernel/testing/server/bed/src/test-utils database.test-utils.ts

40.19% Statements 121/301
0% Branches 0/2
0% Functions 0/12
40.19% Lines 121/301

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 3021x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x           1x 1x 1x 1x 1x 1x 1x 1x                                                                     1x 1x 1x 1x 1x 1x 1x 1x 1x                       1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x           1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x                                         1x 1x 1x 1x 1x 1x 1x             1x 1x 1x 1x 1x 1x 1x 1x                                                                               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                               1x 1x 1x 1x 1x 1x 1x 1x 1x                                         1x 1x 1x 1x 1x 1x 1x 1x 1x                                         1x  
import fs from 'node:fs';
import Path from 'node:path';
 
import { Injectable, Logger } from '@nestjs/common';
import { InjectDataSource } from '@nestjs/typeorm';
import { clone, isEmpty, values } from 'lodash-es';
import { match } from 'ts-pattern';
import { DataSource, ObjectLiteral, type Repository } from 'typeorm';
 
import {
  DataConnectionName,
  DefaultConnectionName,
  Plan,
  Statement,
  type Company,
  type globalConfiguration,
} from '@amalia/core/models';
import { AnyRecord, promiseAllSettledAutoThrow, toError } from '@amalia/ext/typescript';
 
import { fixtures, fixturesConfiguration } from './fixtures/fixtures';
 
type GlobalConfiguration = ReturnType<typeof globalConfiguration>;
 
type EntityConfiguration = {
  name: string;
  order: number;
  tableName: string;
};
 
@Injectable()
export class DatabaseTestUtils {
  private readonly logger = new Logger(DatabaseTestUtils.name);
 
  public constructor(
    @InjectDataSource(DefaultConnectionName)
    private readonly defaultDataSource: DataSource,
    @InjectDataSource(DataConnectionName)
    private readonly dataDataSource: DataSource,
  ) {}
 
  /**
   * Prepare the schema that will be populated with fixtures
   *
   * @param databaseSchemaName the database schema name
   * @param configuration the global app configuration
   */
  public static async prepareSchemas(databaseSchemaName: string, configuration: GlobalConfiguration) {
    // Connecting to the public schema because it's the only one we're sure it exists.
    const connectionOptions = {
      ...configuration.database.defaultConnection,
      migrationsRun: false,
      synchronize: false,
      schema: 'public',
      name: `jest-setup-${databaseSchemaName}`,
    };

    const dataSource = new DataSource(connectionOptions);

    await dataSource.initialize();

    const schemaNames = [
      DatabaseTestUtils.makeSchemaName(databaseSchemaName, configuration.database.defaultConnection.name),
      DatabaseTestUtils.makeSchemaName(databaseSchemaName, configuration.database.dataConnection.name),
    ];

    try {
      await promiseAllSettledAutoThrow(
        schemaNames.map(async (schemaName) => {
          // We use to delete tables one by one but, it's slow and doesn't properly
          // delete types like enums for instance. That way is cleaner and faster.
          await dataSource.query(`DROP SCHEMA IF EXISTS "${schemaName}" CASCADE`);
          await dataSource.query(`CREATE SCHEMA "${schemaName}"`);
        }),
      );
    } catch (error) {
      new Logger(`${DatabaseTestUtils.name}-static`).error(`ERROR when setuping test db: ${error}`);
      throw new Error(`ERROR when setuping test db: ${error}`);
    } finally {
      await dataSource.destroy();
    }
  }
 
  /**
   * Clone the configuration and rewrite the schema name for the given nx package name
   *
   * @param databaseSchemaName the database schema name
   * @param configuration the global app configuration
   * @returns the configuration with the schema name rewritten
   */
  public static rewriteSchemasInConfiguration(databaseSchemaName: string, configuration: GlobalConfiguration) {
    const clonedConfig = clone(configuration);
    clonedConfig.database.defaultConnection.schema = DatabaseTestUtils.makeSchemaName(
      databaseSchemaName,
      clonedConfig.database.defaultConnection.name,
    );
    clonedConfig.database.dataConnection.schema = DatabaseTestUtils.makeSchemaName(
      databaseSchemaName,
      clonedConfig.database.dataConnection.name,
    );
    return clonedConfig;
  }
 
  /**
   * Return the schema name for the given nx package name and connection name + a random UUID to avoid collision
   *
   * @param databaseSchemaName the database schema name
   * @param connectionName the connection name default or data
   */
  private static makeSchemaName(databaseSchemaName: string, connectionName: string) {
    return `${databaseSchemaName}-${connectionName}`;
  }
 
  /**
   * Returns the order id
   * @param entityName The entity name of which you want to have the order from
   */
  private static getOrder(entityName: string) {
    const order: string[] = JSON.parse(
      fs.readFileSync(Path.join(__dirname, './fixtures/_order.json'), 'utf8'),
    ) as string[];
    return order.indexOf(entityName);
  }
 
  /**
   * Cleans the database and reloads the entries
   */
  public async reloadFixtures() {
    await this.loadFixtures(this.defaultDataSource);
    await this.loadFixtures(this.dataDataSource);
  }
 
  /**
   * Load the fixtures for the given datasource
   *
   * @param dataSource the datasource to load the fixtures on
   */
  public async loadFixtures(dataSource: DataSource) {
    let lastEntity: EntityConfiguration | null = null;

    // Load default connexion fixtures
    try {
      const entities = this.getEntities(dataSource);

      // We use a for loop here because we need to create tables in order because table can depend on others.
      for (const entity of entities.toSorted((a, b) => a.order - b.order)) {
        lastEntity = entity;

        await this.loadFixtureTable(entity, dataSource);
      }
    } catch (error) {
      this.logger.error(`ERROR when Loading fixtures on test db: ${error}`, toError(error).stack);
      if (lastEntity) {
        this.logger.error(`Fixtures for ${lastEntity.name} could not be applied`);
      }
      throw new Error(`ERROR when Loading fixtures on test db: ${error}`);
    }
  }
 
  /**
   * Returns the entities from the given datasource
   *
   * @param dataSource the datasource to get the entities from
   */
  private getEntities(dataSource: DataSource) {
    return dataSource.entityMetadatas.map((metadata) => ({
      name: metadata.name,
      tableName: metadata.tableName,
      order: DatabaseTestUtils.getOrder(metadata.name),
    }));
  }
 
  /**
   * Load the records for the given entity configuration and datasource
   *
   * @param entity the entity to load the records for
   * @param dataSource the datasource to load the records on
   */
  private async loadFixtureTable(entity: EntityConfiguration, dataSource: DataSource) {
    const repository = dataSource.getRepository(entity.name);

    const fixtureFile = Path.join(__dirname, `./fixtures/${entity.name}.json`);
    if (fs.existsSync(fixtureFile)) {
      const items = JSON.parse(fs.readFileSync(fixtureFile, 'utf8')) as unknown[] | null;

      if (items?.length) {
        await repository.createQueryBuilder(entity.name).insert().values(items).execute();
      }
    } else {
      for (const companyFixtures of fixtures) {
        const fixtureConfiguration = values(fixturesConfiguration).find((c) => c.entity === entity.name);

        const fixtureValue = fixtureConfiguration?.name ? companyFixtures[fixtureConfiguration.name] : undefined;

        if (fixtureValue) {
          await match(fixtureConfiguration?.type)
            .with('records', async () =>
              this.loadEntityRecords(companyFixtures.company, repository, entity, values(fixtureValue)),
            )
            .with('array', async () =>
              this.loadEntityRecords(companyFixtures.company, repository, entity, fixtureValue as AnyRecord[]),
            )
            .with('object', async () =>
              this.loadEntityRecords(companyFixtures.company, repository, entity, [fixtureValue as AnyRecord]),
            )
            .with('statements', async () =>
              this.loadStatements(companyFixtures.company, dataSource, values(fixtureValue) as Statement[]),
            )
            .with('plans', async () =>
              this.loadPlans(companyFixtures.company, dataSource, values(fixtureValue) as Plan[]),
            )
            .otherwise(() => {
              // Do nothing
            });
        }
      }
    }
  }
 
  /**
   * Load the records for the given company
   *
   * @param company the company to load the records for
   * @param repository the repository to load the records on
   * @param entity the entity to load the records for
   * @param items the items to load
   */
  private async loadEntityRecords<TEntity extends ObjectLiteral, TRecord extends AnyRecord>(
    company: Company,
    repository: Repository<TEntity>,
    entity: EntityConfiguration,
    items: TRecord[],
  ) {
    const companyItems = items.map((i) => ({
      ...i,
      company: entity.name === 'Company' ? undefined : company,
      companyId: entity.name === 'Company' ? undefined : company.id,
    }));

    if (companyItems.length) {
      await repository.createQueryBuilder(entity.name).insert().values(companyItems).execute();
    }
  }
 
  /**
   * Load the statements fixtures for the given company
   *
   * @param company the company to load the records for
   * @param dataSource the datasource to load the records on
   * @param statements the statements fixtures to load
   */
  private async loadStatements(company: Company, dataSource: DataSource, statements: Statement[]) {
    if (isEmpty(statements)) {
      return;
    }

    const companyStatements = statements.map((i) => ({
      ...i,
      company,
      companyId: company.id,
      forecast: i.forecast
        ? {
            ...i.forecast,
            companyId: company.id,
            company,
            statementId: i.id,
          }
        : undefined,
    }));

    await dataSource.getRepository<Statement>(Statement).save(companyStatements);
  }
 
  /**
   * Load the plans fixtures for the given company
   *
   * @param company the company to load the records for
   * @param dataSource the datasource to load the records on
   * @param plans the plans fixtures to load
   */
  private async loadPlans(company: Company, dataSource: DataSource, plans: Plan[]) {
    if (isEmpty(plans)) {
      return;
    }

    const companyPlans = plans.map((plan) => ({
      ...plan,
      company,
      companyId: company.id,
      forecast: plan.forecast
        ? {
            ...plan.forecast,
            companyId: company.id,
            company,
            planId: plan.id,
          }
        : undefined,
    }));

    await dataSource.getRepository<Plan>(Plan).save(companyPlans);
  }
}