All files / libs/vendors/google-cloud/big-query/src/lib big-query.service.ts

82.43% Statements 183/222
86.66% Branches 26/30
85.71% Functions 12/14
82.43% Lines 183/222

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 2231x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 3x 3x 2x 2x 3x 1x 1x 1x 1x 1x 5x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 8x 8x 1x 1x 1x 1x 1x 7x 7x 1x 1x 1x 1x 1x 1x 1x 29x 29x 1x 1x 1x 1x 1x 1x 1x 14x 14x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 4x 1x 1x 2x 2x 2x 4x       2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 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 { BigQuery, type Query, type TableField, type TableSchema } from '@google-cloud/bigquery';
import { type PagedResponse } from '@google-cloud/bigquery/build/src/bigquery';
import type bigquery from '@google-cloud/bigquery/build/src/types';
import { Inject, Injectable, Logger } from '@nestjs/common';
 
import { assert } from '@amalia/ext/typescript';
 
type QueryRecord = Record<string, string>;
type ParamsRecord = Record<string, unknown>;
 
const REGION = 'EU';
 
@Injectable()
export class BigQueryService {
  private readonly logger = new Logger(BigQueryService.name);
 
  /**
   * Convert a query record to a string:
   *
   * - if it's a string, return it.
   * - if it's a QueryRecord, return the values joined by a space.
   */
  private static convertQueryRecordToString(query: QueryRecord | string) {
    return typeof query === 'string' ? query : Object.values(query).join(' ');
  }
 
  /**
   * Transform QueryRecord to query string and remove invalid params.
   */
  public static buildQuery(query: QueryRecord | string, params?: ParamsRecord) {
    // If the query is a string, we can return it no transforamtion needed.
    if (typeof query === 'string') return query;
 
    // If there is no params, we can return the query converted.
    if (!params) return BigQueryService.convertQueryRecordToString(query);
 
    // Else we need to filter the params to keep only the valid ones.
    const wrongParams = BigQueryService.filterParams(params, BigQueryService.isInvalidParam);
 
    const querySanitized: QueryRecord = Object.entries(query).reduce((acc, [key, value]) => {
      if (key in wrongParams) return acc;
 
      return { ...acc, [key]: value };
    }, {});
 
    return BigQueryService.convertQueryRecordToString(querySanitized);
  }
 
  /**
   * Filter the params to keep only the ones that match the predicate.
   *
   * Default predicate is to keep only non null values and non empty arrays.
   *
   * @param params params for big query
   * @param predicate predicate to filter params
   *
   * @returns params cleaned.
   */
  public static filterParams(
    params: ParamsRecord = {},
    predicate: (value: unknown) => boolean = BigQueryService.isValidParam,
  ): ParamsRecord {
    return Object.entries(params)
      .filter(([, value]) => predicate(value))
      .reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {});
  }
 
  /**
   * Only letters, numbers and underscore are allowed in dataset.
   */
  public static isDatasetValidName(name: string) {
    return /^\w*$/gu.test(name);
  }
 
  /**
   * Only letters, numbers and dash are allowed in table.
   */
  public static isTableValidName(name: string) {
    return /^[a-zA-Z0-9-]*$/gu.test(name);
  }
 
  /** Check if a param is valid for big query, valid if:
   *
   * - not null
   * - not empty array
   */
  public static isValidParam(value: unknown) {
    return !(value === null || (Array.isArray(value) && value.length === 0));
  }
 
  /**
   * Check if a param is invalid for big query, invalid if not valid. ¯\\_(ツ)_/¯
   *
   * @see isValidParam
   */
  public static isInvalidParam(value: unknown) {
    return !BigQueryService.isValidParam(value);
  }
 
  public constructor(@Inject(BigQuery) private readonly client: BigQuery | null) {}
 
  /**
   * Convert a string to a BigQueryDateTime.
   */
  public convertIsoStringToDateTime(isoString: string) {
    assert(this.client !== null, 'BigQuery client not initialized');
    return this.client.datetime(isoString);
  }
 
  /**
   * Check if the BigQuery client is not null.
   */
  public isBigQueryClientInitialized() {
    return this.client !== null;
  }
 
  /**
   * Check if datasetId and tableId are valid then create dataset (if not exists), table (if not exists) with a schema.
   *
   * @returns true if table created otherwise false.
   */
  public async createTableIfNotExists(
    datasetId: string,
    tableId: string,
    schema: TableField[] | TableSchema | string,
  ): Promise<boolean> {
    assert(this.client !== null, 'BigQuery client not initialized');
 
    assert(
      BigQueryService.isDatasetValidName(datasetId),
      'BigQuery dataset ID not valid: accept letters, numbers and underscore',
    );
 
    assert(BigQueryService.isTableValidName(tableId), 'BigQuery table ID not valid: accept letters, numbers and dash');
 
    const [datasetExists] = await this.client.dataset(datasetId).exists();
 
    if (!datasetExists) {
      await this.client.createDataset(datasetId, { location: REGION });
    }
 
    const [tableExistsBeforeCreation] = await this.client.dataset(datasetId).table(tableId).exists();
 
    if (tableExistsBeforeCreation) {
      // Table already exists, no need to create it again.
      return false;
    }
 
    const [table] = await this.client.dataset(datasetId).createTable(tableId, {
      location: REGION,
      schema,
    });
 
    const [tableExistsAfterCreation] = await table.exists();
 
    // I hope this returns true...
    return tableExistsAfterCreation;
  }
 
  /**
   * Execute a query against a BigQuery dataset and return the result.
   */
  public async execQuery<TResult>(
    datasetId: string,
    tableId: string,
    query: QueryRecord | string,
    params?: ParamsRecord,
  ) {
    if (!this.isBigQueryClientInitialized()) return [];

    assert(this.client !== null, 'BigQuery client not initialized');

    const options: Query = {
      location: REGION,
      query: BigQueryService.buildQuery(query, params),
      params: BigQueryService.filterParams(params),
    };

    const [job] = await this.client.dataset(datasetId).table(tableId).createQueryJob(options);
    const [rows] = (await job.getQueryResults()) as PagedResponse<TResult, Query, bigquery.IGetQueryResultsResponse>;
    return rows;
  }
 
  /**
   * Insert rows in the BigQuery dataset and return the result.
   */
  public async insert(datasetId: string, tableId: string, rows: unknown) {
    assert(this.client !== null, 'BigQuery client not initialized');
    const [data] = await this.client.dataset(datasetId).table(tableId).insert(rows);
    return data;
  }
 
  /**
   * Remove a dataset from BigQuery.
   */
  public async deleteTable(datasetId: string, tableId: string) {
    assert(this.client !== null, 'BigQuery client not initialized');
 
    const [datasetExists] = await this.client.dataset(datasetId).exists();
 
    if (!datasetExists) {
      this.logger.warn({
        message: `BigQuery ${datasetId} not found`,
        datasetId,
      });
      return;
    }
 
    const [tableExists] = await this.client.dataset(datasetId).table(tableId).exists();
 
    if (!tableExists) {
      this.logger.warn({
        message: `BigQuery ${datasetId}.${tableId} not found`,
        datasetId,
        tableId,
      });
      return;
    }
 
    await this.client.dataset(datasetId).table(tableId).delete();
  }
}