Drivers

BigQuery Driver Documentation

This documentation explains the BigQuery driver implementation and how connection parameters map to UI fields in the Gigantic application. The driver reads and writes the tables of a Google BigQuery dataset (or of every dataset of a project) through the BigQuery REST API.

BigQuery is listed under Cloud datasources in the driver selector and requires a Cloud license tier.

Connection Parameters

UI FieldTechnical ImplementationDescriptionRequiredDefault Value
Project IDprojectId (sent as database)Project of the tables, for example people-analyticsYes, unless the credentials have a projectThe project of the service account key or of the environment
Datasetdataset (sent as dbSchema)Dataset with the tables. Empty: every dataset of the project, and the entities are named <dataset>.<table>NoEvery dataset
Locationlocation (sent as owner)Location the jobs run in, for example US, EU or europe-west1NoThe location of the dataset
Impersonate service accountimpersonateServiceAccount (sent as container)Service account the credentials act as, with a token of one hourNoNone

Notes:

  • The form has no Host or Port field. The driver connects over HTTPS to bigquery.googleapis.com.
  • Tables are addressed as `<project>`.`<dataset>`.`<table>`, each part quoted with backticks.
  • The jobs run in the project of the tables. To bill them to another project, set billingProjectId in Custom Params.

If the project cannot be found the connection fails with:

BigQuery project ID is required

Authentication Options

Auth TypeUI MappingDescription
Service AccountService account key fieldJSON key of a service account ("type": "service_account"). It is stored encrypted. Other types of credential files are refused
Application Default CredentialsNo credentialsThe credentials of the Gigantics server: GOOGLE_APPLICATION_CREDENTIALS, gcloud auth application-default login, or the metadata server of Compute Engine and of GKE with Workload Identity
Password ManagerPassword manager fieldsThe JSON key is read from the password manager as the password

With Impersonate service account the credentials only need the role Service Account Token Creator on that account.

Roles

UseRoles of the service account
TapBigQuery Data Viewer on the dataset and BigQuery Job User on the project the jobs run in
SinkBigQuery Data Editor on the dataset and BigQuery Job User
Sink with a staging bucketAlso Storage Object User on the bucket

Technical Details

The BigQuery driver uses the BigQuery REST API v2 through the googleapis library, which Gigantics already uses for Google Drive.

Connection process:

  1. Gets a token for the service account, the default credentials or the impersonated account
  2. Reads the dataset to find its location, when the form has none
  3. Runs SELECT 1 to check the connection

Schema discovery:

  • Lists the tables, views, materialized views, external tables and snapshots of the dataset
  • Reads the schema, row count, size, description, partitioning, clustering and table constraints of each table with tables.get (8 tables at the same time)
  • Primary keys and foreign keys come from the table constraints (PRIMARY KEY ... NOT ENFORCED). Tables without them have no keys: define the relations of the model by hand for referential integrity
  • Stores the DDL of each table from INFORMATION_SCHEMA.TABLES, one metadata query per dataset
  • Column descriptions become field descriptions. The policy tags of a column are kept with the field

Nested and repeated fields

BigQuery columnGigantic fields
STRUCT (RECORD)One field per leaf, named by its path: address STRUCT<city STRING, zip STRING> gives address.city and address.zip. A STRUCT inside a STRUCT goes on: address.geo.lat
ARRAY<...> (REPEATED)One field of type object, with the whole array. A STRUCT inside it is not flattened
JSONOne field of type object

Each leaf of a STRUCT is discovered, labeled and anonymized as a field of its own. When writing, the leaves go back into their STRUCT; a STRUCT whose leaves are all null is written as NULL. Set flattenStructs: false in Custom Params to keep each STRUCT as one object field.

Type mapping

BigQuery TypeGigantic TypeValues
INT64numberNumbers. Past 2^53 the exact text
FLOAT64floatNumbers
NUMERIC, BIGNUMERICfloatThe exact decimal text, for example "1234.50"
BOOLbooleanBooleans
TIMESTAMPdateThe instant. Microseconds are cut to milliseconds
DATETIME, DATEdateThe local time of the Gigantics server, as with the other drivers
TIME, STRING, GEOGRAPHY, INTERVAL, RANGEstringText (GEOGRAPHY as WKT)
BYTESbufferBytes
STRUCT, ARRAY, JSONobjectSee above

Reading process

  1. A table read whole (no where, no order, no custom query) is listed page by page with tabledata.list: no query runs and nothing is billed
  2. A view, a where, an order, random rows or a custom query run as a query job. The rows are then read from the result of the job, which is also free
  3. Pages of the read batch size of the job or rule (when none is set, the driver batchSize, 10000) are read 4 at a time (readConcurrency) and streamed in order
  4. Random rows of a big table (limit with Random rows) read a sample of its blocks with TABLESAMPLE SYSTEM, so the query scans a part of the table

BigQuery reads cannot resume from the record where a job stopped: an entity read again starts from the beginning. As a sink, BigQuery can take a resumed read of another tap.

Cost controls

Custom ParamDescriptionDefault
maximumBytesBilledThe most a query may bill, in bytes. A query that would scan more fails before it runsNo limit
estimateCostRuns a free dry run before each query and logs what it scans, for example the query scans 12.3 GB, about $0.0700 on demandtrue
pricePerTiBUS dollars per TiB scanned, for the estimate in the log6.25

The row count of a filtered read (Exact Count) is a query of its own: set it to Never on big tables to save it.

Writing process

  1. Rows are loaded with load jobs of newline-delimited JSON, uploaded in resumable chunks. Load jobs are free on the shared slot pool
  2. A table takes 1500 load jobs a day, so each load takes at least 100000 rows (loadBatchRows), even when the write batch of the job or rule is smaller
  3. With stagingBucket (for example gs://my-bucket/gigantics) each batch is first uploaded to the bucket and loaded from there, then the file is deleted
  4. Only the columns of the target table are written. A value that does not fit its column type is written as NULL
  5. Update and merge load each batch into a staging table (_gig_stage_<table>_<random>, deleted when the writer ends and set to expire in a day), then run one MERGE by the primary key. A key repeated in a batch keeps its last row. A table that requires a partition filter is merged with the partitions of the batch
  6. When Retry On Fail is enabled, failed batches are split in half and retried. Rate limits and backend errors are always retried, with backoff

Write modes:

Write modeBehaviour
DropDROP TABLE IF EXISTS and creates the table again
TruncateTRUNCATE TABLE before loading
AppendLoads rows into the existing table
Update / MergeKeeps the table and runs MERGE by primary key. Fails if the table has no primary key

When the target table does not exist, it is created: from the DDL of a BigQuery source, without its table options (expiration, required partition filter, labels), or from the fields of another source (number as INT64, float as FLOAT64 or NUMERIC, date as TIMESTAMP, DATETIME or DATE, object as JSON; dotted names as STRUCT columns).

Filters and referential integrity

Where conditions run in BigQuery as a WHERE clause with typed query parameters. ISO dates are compared by the column type: a TIMESTAMP with the instant, a DATETIME or DATE with the local time. LIKE filters on columns that are not text compare their text (CAST(... AS STRING)). A field of a STRUCT is filtered by its path (address.city).

Referential integrity, in filter and seed mode, works on the relations of the table constraints or of the model. Random rows of a limited parent are ordered by FARM_FINGERPRINT of the key, so the same rows are picked in every query.

SSH Tunnel Support

The BigQuery driver does not use SSH tunnels: the form has no Enable SSH? option. To reach Google APIs through a proxy, set the HTTPS_PROXY environment variable of the Gigantics server.

API Endpoints Used

BigQuery connections are used in:

  • Tap creation (data source discovery)
  • Sink creation (data destination for anonymized data)
  • Pipeline execution (data extraction and loading)

Node.js Driver Dependency

  • Library: googleapis (BigQuery API v2)
  • Purpose: BigQuery queries, table listing and load jobs

Custom Params

Custom Params (YAML) are merged into the driver configuration, so they can set or override these keys:

projectId: people-analytics        # Overrides the Project ID field
dataset: fivetran_workday          # Overrides the Dataset field
location: US                       # Overrides the Location field
billingProjectId: gig-jobs         # Project the jobs run in and are billed to
maximumBytesBilled: 107374182400   # 100 GiB at most per query
estimateCost: true                 # Dry run and log what each query scans
flattenStructs: true               # STRUCT columns as one field per leaf
stagingBucket: gs://my-bucket/gig  # Loads go through this bucket
loadBatchRows: 100000              # Rows per load job, at least
batchSize: 10000                   # Rows per page read
readConcurrency: 4                 # Pages read at the same time

Example Configurations

A Fivetran dataset, with a cap on the bytes billed

dataset: fivetran_workday
maximumBytesBilled: 53687091200

With Application Default Credentials on GKE, the Kubernetes service account of Gigantics is bound to a Google service account with Workload Identity: no key is stored.