import { decryptDataSourceParams } from "../services/datasource" ; import * as bq from "@google-cloud/bigquery" ; import SqlIntegration from "./SqlIntegration" ; import { BigQueryConnectionParams } from "../../types/integrations/bigquery" ; import { getValidDate } from "../util/dates" ; export default class BigQuery extends SqlIntegration { params : BigQueryConnectionParams ; setParams ( encryptedParams ) { this . params = decryptDataSourceParams < BigQueryConnectionParams > ( encryptedParams ) ; } getSensitiveParamKeys ( ) { return [ "privateKey" ] ; } async runQuery ( sql ) { const client = new bq . BigQuery ( { projectId : this . params . projectId , credentials : { client_email : this . params . clientEmail , private_key : this . params . privateKey , } , } ) ; const [ job ] = await client . createQueryJob ( { query : sql , useLegacySql : false , } ) ; const [ rows ] = await job . getQueryResults ( ) ; return rows ; } toTimestamp ( date ) { return `DATETIME "${ date . toISOString ( ) . substr ( 0 , 19 ) . replace ( "T" , " " ) }"` ; } addHours ( col , hours ) { return `DATETIME_ADD(${ col }, INTERVAL ${ hours } HOUR)` ; } subtractHalfHour ( col ) { return `DATETIME_SUB(${ col }, INTERVAL 30 MINUTE)` ; } regexMatch ( col , regex ) { return `REGEXP_CONTAINS(${ col }, "${ regex }")` ; } percentile ( col , percentile ) { return `APPROX_QUANTILES(${ col }, 100)[OFFSET(${ Math . floor ( percentile * 100 ) })]` ; } convertDate ( fromDB ) { return getValidDate ( fromDB . value + "Z" ) ; } dateTrunc ( col ) { return `date_trunc(${ col }, DAY)` ; } dateDiff ( startCol , endCol ) { return `date_diff(${ endCol }, ${ startCol }, DAY)` ; } formatDate ( col ) { return `format_date("%F", ${ col })` ; } castToString ( col ) { return `cast(${ col } as string)` ; } }