### Install Google BigQuery PHP Client Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/README.md Use Composer to install the google/cloud-bigquery package. This is the first step to using the BigQuery client library in your PHP project. ```sh $ composer require google/cloud-bigquery ``` -------------------------------- ### Start a Query Asynchronously Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/BigQueryClient.md Use startQuery to execute a query and get a job object immediately. This is useful for long-running queries where you don't need to wait for results. ```php $queryJobConfig = $bigQuery->query( 'SELECT commit FROM `bigquery-public-data.github_repos.commits` LIMIT 100' ); $job = $bigQuery->startQuery($queryJobConfig); $queryResults = $job->queryResults(); foreach ($queryResults as $row) { echo $row['commit']; } ``` -------------------------------- ### Managing Tables Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/FILES.txt Provides examples for managing BigQuery tables, such as creating and deleting them. ```php $projectId]); // Get the table $table = $bigQuery->dataset($datasetId)->table($tableId); // Example: Update table metadata (e.g., expiration) $table->update(['expiration' => time() + 3600]); // Expires in 1 hour // Example: Delete the table // $table->delete(); printf('Managed table: %s.%s%s', $datasetId, $tableId, PHP_EOL); } ``` -------------------------------- ### Install and Initialize BigQuery Client Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/QUICK_REFERENCE.md Include the autoloader and instantiate the BigQuery client with your project ID and desired location. ```php require 'vendor/autoload.php'; use Google\Cloud\BigQuery\BigQueryClient; $bigQuery = new BigQueryClient([ 'projectId' => 'my-project', 'location' => 'us-west1' ]); ``` -------------------------------- ### startJob() Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/BigQueryClient.md Start a job asynchronously. Returns immediately without waiting for completion. ```APIDOC ## startJob() ### Description Start a job asynchronously. Returns immediately without waiting for completion. ### Method `public function startJob(JobConfigurationInterface $config, array $options = []): Job` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **config** (JobConfigurationInterface) - Required - Job configuration object * **options** (array) - Optional - Configuration options ### Request Example ```php $job = $bigQuery->startJob($jobConfig); ``` ### Response #### Success Response * **Job** - An asynchronous job object. #### Response Example None provided in source. ``` -------------------------------- ### Run an Asynchronous BigQuery Query Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/QUICK_REFERENCE.md Start a query asynchronously and perform other operations while waiting for completion. Use waitUntilComplete() and queryResults() to get the results. ```php $job = $bigQuery->startQuery($queryConfig); // Do other work... $job->waitUntilComplete(); $results = $job->queryResults(); ``` -------------------------------- ### runJob() Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/BigQueryClient.md Start a job synchronously and wait for completion. ```APIDOC ## runJob() ### Description Start a job synchronously and wait for completion. ### Method `public function runJob(JobConfigurationInterface $config, array $options = []): Job` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **config** (JobConfigurationInterface) - Required - Job configuration object * **options** (array) - Optional - Configuration options * **maxRetries** (int) - Number of retry attempts (default: 100) ### Request Example ```php $job = $bigQuery->runJob($jobConfig); echo $job->isComplete(); // true ``` ### Response #### Success Response * **Job** - A completed job object where `isComplete()` returns true. #### Response Example None provided in source. ``` -------------------------------- ### Start a Job Asynchronously Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/BigQueryClient.md Use startJob to initiate a job without waiting for its completion. This returns an asynchronous job object. ```php $job = $bigQuery->startJob($jobConfig); ``` -------------------------------- ### Get Table Description Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Table.md Retrieves the descriptive text associated with the BigQuery table. ```php $table->description(); ``` -------------------------------- ### Execute a Job Asynchronously Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/INDEX.md Start a BigQuery job and perform other operations while it runs. The job can be waited upon to complete. ```php $job = $bigQuery->startJob($config); // ... do other work ... $job->waitUntilComplete(); ``` -------------------------------- ### Manage BigQuery Datasets Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/QUICK_REFERENCE.md Perform operations on datasets, including creating, getting, listing, and deleting them. Specify the location when creating a new dataset. ```php // Create $dataset = $bigQuery->createDataset('new_dataset', [ 'location' => 'us-west1' ]); // Get $dataset = $bigQuery->dataset('my_dataset'); // List foreach ($bigQuery->datasets() as $ds) { echo $ds->id(); } // Delete $dataset->delete(['deleteContents' => true]); ``` -------------------------------- ### info() Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Dataset.md Get dataset metadata. Optionally retrieve a single key or nested key using dot notation. ```APIDOC ## info() ### Description Get dataset metadata. Optionally retrieve a single key or nested key using dot notation. ### Method GET ### Endpoint Not applicable (SDK method) ### Parameters #### Query Parameters - **key** (string) - Optional - Metadata key to retrieve (supports dot notation for nested keys) ### Response #### Success Response - **return** (array|mixed) - Full metadata array or specific value. ### Example ```php $info = $dataset->info(); $createdTime = $dataset->info('creationTime'); ``` ``` -------------------------------- ### Initialize BigQuery Client with Manual Configuration Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/configuration.md Sets up the BigQuery client with manual configuration, including service account credentials and a custom HTTP handler. This allows for more control over the client's behavior. ```php use Google\Auth\Credentials\ServiceAccountCredentials; use GuzzleHttp\Client; $credentials = new ServiceAccountCredentials( ['https://www.googleapis.com/auth/bigquery'], $keyFileArray ); $httpHandler = function ($request) { return (new Client())->send($request); }; $bigQuery = new BigQueryClient([ 'projectId' => 'my-project', 'credentialsFetcher' => $credentials, 'httpHandler' => $httpHandler ]); ``` -------------------------------- ### Initialize BigQuery Client with Configuration Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/configuration.md Instantiate the BigQueryClient with specific project ID, location, and data type handling preferences. This is useful for setting up your BigQuery service with custom configurations. ```php use Google\Cloud\BigQuery\BigQueryClient; $bigQuery = new BigQueryClient([ 'projectId' => 'my-gcp-project', 'location' => 'us-west1', 'returnInt64AsObject' => true ]); ``` -------------------------------- ### Get Total Row Count Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/QueryResults.md Get the total number of rows in the complete result set. Returns null if the total count is unavailable. ```php echo $queryResults->totalRows(); ``` -------------------------------- ### Managing Datasets Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/FILES.txt Demonstrates how to manage BigQuery datasets, including creation and deletion. ```php $projectId]); // Get the dataset $dataset = $bigQuery->dataset($datasetId); // Example: Update dataset metadata (e.g., description) $dataset->update(['description' => 'My updated dataset description']); // Example: Delete the dataset // $dataset->delete(); printf('Managed dataset: %s%s', $datasetId, PHP_EOL); } ``` -------------------------------- ### Get Current Row Count Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/QueryResults.md Get the number of rows currently available in the result set. This count may be less than the total if pagination is incomplete. ```php echo $queryResults->rows(); ``` -------------------------------- ### Initialize BigQuery Client with Service Account Key File Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/configuration.md Configures the BigQuery client using a service account key file. This is the recommended approach for production environments. Ensure the 'credentials.json' file contains valid service account key information. ```php use Google\Auth\Credentials\ServiceAccountCredentials; $credentials = new ServiceAccountCredentials( ['https://www.googleapis.com/auth/bigquery'], json_decode(file_get_contents('credentials.json'), true) ); $bigQuery = new BigQueryClient([ 'projectId' => 'my-project', 'credentialsFetcher' => $credentials ]); ``` -------------------------------- ### Run a Job Synchronously Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/BigQueryClient.md Use runJob to start a job and wait for it to complete. This method returns a completed job object. ```php $job = $bigQuery->runJob($jobConfig); echo $job->isComplete(); // true ``` -------------------------------- ### Get BigQuery Table Metadata Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Table.md Use the info() method to retrieve table metadata. You can get the entire metadata object or a specific key using dot notation. ```php $info = $table->info(); $schema = $table->info('schema'); ``` -------------------------------- ### Configuration Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/README.md Client constructor options and configuration settings. ```APIDOC ## Configuration ### Description Client constructor options and configuration settings. ### Example ```php use Google\Cloud\BigQuery\BigQueryClient; $bigquery = new BigQueryClient([ 'projectId' => 'your-project-id', 'keyFilePath' => '/path/to/your/keyfile.json' ]); ``` ``` -------------------------------- ### Get Query Result Metadata Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/QueryResults.md Retrieve metadata about the query results. You can get the entire metadata array or a specific value using dot notation for nested keys. ```php $info = $queryResults->info(); $totalRows = $queryResults->info('totalRows'); ``` -------------------------------- ### BigQuery API Error Response Structure Example Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/errors.md Illustrates the typical structure of an error response within the job status object from the BigQuery API. Shows how to access specific error details. ```php [ 'status' => [ 'state' => 'DONE', // Job completed 'errorResult' => [ 'reason' => 'invalidQuery', 'message' => 'Syntax error in query', 'location' => 'Query line 1, column 5' // Optional ] ] ] ``` -------------------------------- ### Initialize BigQuery Client and Load/Query Data Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/README.md This snippet demonstrates initializing the BigQuery client, loading data from a CSV file into a table, and running a query. Ensure you have authenticated your client and replaced placeholder dataset and table names with your actual values. ```php require 'vendor/autoload.php'; use Google\Cloud\BigQuery\BigQueryClient; $bigQuery = new BigQueryClient(); // Get an instance of a previously created table. $dataset = $bigQuery->dataset('my_dataset'); $table = $dataset->table('my_table'); // Begin a job to import data from a CSV file into the table. $loadJobConfig = $table->load( fopen('/data/my_data.csv', 'r') ); $job = $table->runJob($loadJobConfig); // Run a query and inspect the results. $queryJobConfig = $bigQuery->query( 'SELECT * FROM `my_project.my_dataset.my_table`' ); $queryResults = $bigQuery->runQuery($queryJobConfig); foreach ($queryResults as $row) { print_r($row); } ``` -------------------------------- ### Get Table IAM Policy Manager Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Table.md Retrieve an IAM policy manager instance for the table to manage access control. This object can be used to get and set IAM policies. ```php $iam = $table->iam(); ``` -------------------------------- ### Running Queries Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/FILES.txt Learn how to execute queries using the BigQuery client library. This involves using the BigQueryClient and QueryResults classes. ```php $projectId]); // Run a query $query = $bigQuery->query('SELECT name FROM `bigquery-public-data.usa_names.usa_1910_current` LIMIT 10'); /** @var QueryResults $queryResults */ $queryResults = $bigQuery->runQuery($query); // Print the results foreach ($queryResults as $row) { print_r($row['name']); } } ``` -------------------------------- ### id() Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Dataset.md Get the dataset ID. ```APIDOC ## id() ### Description Get the dataset ID. ### Method GET ### Endpoint Not applicable (SDK method) ### Parameters None ### Response #### Success Response - **return** (string) - The dataset ID. ### Example ```php echo $dataset->id(); ``` ``` -------------------------------- ### iam() Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Dataset.md Get the IAM policy manager for the dataset. ```APIDOC ## iam() ### Description Get the IAM policy manager for the dataset. ### Method GET ### Endpoint Not applicable (SDK method) ### Parameters None ### Response #### Success Response - **return** (Iam) - IAM instance for managing access control. ### Example ```php $iam = $dataset->iam(); ``` ``` -------------------------------- ### Initialize BigQuery Client Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/README.md Initializes the BigQuery client using Application Default Credentials. Specify your project ID and desired location. ```php use Google\Cloud\BigQuery\BigQueryClient; // Uses Application Default Credentials $bigQuery = new BigQueryClient([ 'projectId' => 'my-project-id', 'location' => 'us-west1' ]); ``` -------------------------------- ### startQuery() Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/BigQueryClient.md Execute a query asynchronously. Returns immediately with a job object. ```APIDOC ## startQuery() ### Description Execute a query asynchronously. Returns immediately with a job object. ### Method `public function startQuery(JobConfigurationInterface $query, array $options = []): Job` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **query** (JobConfigurationInterface) - Required - Query job configuration * **options** (array) - Optional - Configuration options ### Request Example ```php $queryJobConfig = $bigQuery->query( 'SELECT commit FROM `bigquery-public-data.github_repos.commits` LIMIT 100' ); $job = $bigQuery->startQuery($queryJobConfig); $queryResults = $job->queryResults(); foreach ($queryResults as $row) { echo $row['commit']; } ``` ### Response #### Success Response * **Job** - An asynchronous job object. #### Response Example None provided in source. ``` -------------------------------- ### Instantiate BigQueryClient Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/BigQueryClient.md Create a BigQuery client instance using your project ID. You can also specify default location and options for handling 64-bit integers. ```php use Google\Cloud\BigQuery\BigQueryClient; $bigQuery = new BigQueryClient([ 'projectId' => 'my-project-id' ]); $bigQuery = new BigQueryClient([ 'projectId' => 'my-project-id', 'location' => 'us-west1', 'returnInt64AsObject' => true ]); ``` -------------------------------- ### iam() Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Routine.md Gets the IAM policy manager for the BigQuery routine. ```APIDOC ## iam() ### Description Get the IAM policy manager for the routine. ### Method N/A (Object Method) ### Parameters None ### Response #### Success Response - **return** (Iam) - An object to manage the IAM policy. ### Example ```php $iam = $routine->iam(); ``` ``` -------------------------------- ### primaryKey() Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Dataset.md Get the dataset's primary key (dataset ID). ```APIDOC ## primaryKey() ### Description Get the dataset's primary key (dataset ID). ### Method GET ### Endpoint Not applicable (SDK method) ### Parameters None ### Response #### Success Response - **return** (string) - The dataset ID. ### Example ```php // Example not provided in source, but would typically be: // echo $dataset->primaryKey(); ``` ``` -------------------------------- ### Create a Copy Job Configuration Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/BigQueryClient.md Use this method to create a copy job configuration. The configuration can then be executed using `runJob()` or `startJob()`. ```php $copyJobConfig = $bigQuery->copy() ->sourceTable($sourceTable) ->destinationTable($destTable); $job = $bigQuery->runJob($copyJobConfig); ``` -------------------------------- ### job() Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/QueryResults.md Get the associated job object that produced these query results. ```APIDOC ## job() ### Description Get the associated job object. ### Returns `Job` - The job that produced these results. ### Example: ```php $job = $queryResults->job(); echo $job->id(); ``` ``` -------------------------------- ### Get Dataset ID Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Dataset.md Retrieves the unique identifier for the BigQuery dataset. ```php echo $dataset->id(); ``` -------------------------------- ### Instantiate BigQuery Client with Int64 Support Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/types.md Demonstrates how to instantiate the BigQuery client, enabling the return of 64-bit integers as Int64 objects. This is useful when interacting with large integer values. ```php $bigQuery = new BigQueryClient([ 'returnInt64AsObject' => true // Return 64-bit ints as Int64 objects ]); $int64 = $bigQuery->int64('9223372036854775807'); $queryConfig = $bigQuery->query( 'SELECT * FROM data WHERE id = @bigId' )->parameters(['bigId' => $int64]); ``` -------------------------------- ### Create Query Job Configuration Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/BigQueryClient.md Use the `query()` method to create a query job configuration. This configuration can then be executed using `runQuery()` or `startQuery()`. ```php $queryJobConfig = $bigQuery->query( 'SELECT commit FROM `bigquery-public-data.github_repos.commits` LIMIT 100' ); ``` ```php $queryJobConfig = $bigQuery->query( 'SELECT name FROM `my_project.users_dataset.users` LIMIT 100' )->createDisposition('CREATE_NEVER'); ``` ```php $queryJobConfig = $bigQuery->query( 'SELECT * FROM `my_project.my_dataset.my_table`', [ 'configuration' => [ 'query' => [ 'createDisposition' => 'CREATE_NEVER' ] ] ] ); ``` ```php $queryJobConfig = $bigQuery->query( 'SELECT name FROM users' )->location('asia-northeast1'); ``` -------------------------------- ### Get Model Info Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Model.md Retrieves metadata associated with the BigQuery ML model. ```APIDOC ## info() ### Description Get model metadata. ### Method `info(string $key = null): array|mixed` ### Parameters #### Key - **key** (string) - Optional. Metadata key (dot notation supported) to retrieve a specific piece of information. ### Returns `array|mixed` - An array of all metadata, or a specific value if a key is provided. ### Example ```php $info = $model->info(); $modelType = $model->info('modelType'); $createdTime = $model->info('creationTime'); ``` ``` -------------------------------- ### Get Model ID Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Model.md Retrieves the unique identifier for the BigQuery ML model. ```APIDOC ## id() ### Description Get the model ID. ### Method `id(): string` ### Returns `string` - The model's unique identifier. ### Example ```php echo $model->id(); ``` ``` -------------------------------- ### Run a Simple Query Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/INDEX.md Execute a SQL query and iterate over the results. Ensure the BigQuery client and table are properly configured. ```php $queryConfig = $bigQuery->query('SELECT * FROM dataset.table'); $results = $bigQuery->runQuery($queryConfig); foreach ($results as $row) { // process row } ``` -------------------------------- ### Complete BigQuery Client Configuration Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/configuration.md Instantiate the BigQuery client with custom credentials, project ID, location, and advanced options like return type, timeouts, retries, quota projects, API endpoints, and logging. ```php use Google\Cloud\BigQuery\BigQueryClient; use Google\Auth\Credentials\ServiceAccountCredentials; use Psr\Cache\CacheItemPoolInterface; // With inline credentials $credentials = new ServiceAccountCredentials( ['https://www.googleapis.com/auth/bigquery'], json_decode(file_get_contents('/path/to/keyfile.json'), true) ); $bigQuery = new BigQueryClient([ 'projectId' => 'my-project-id', 'credentialsFetcher' => $credentials, 'location' => 'us-west1', 'returnInt64AsObject' => true, 'requestTimeout' => 60, 'retries' => 5, 'quotaProject' => 'optional-billing-project', 'apiEndpoint' => 'custom-api.example.com', 'logger' => $logger // PSR-3 logger instance ]); ``` -------------------------------- ### copy() Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/BigQueryClient.md Create a copy job configuration. The configuration can be executed via runJob() or startJob(). ```APIDOC ## copy() ### Description Create a copy job configuration. The configuration can be executed via `runJob()` or `startJob()`. ### Method `public function copy(array $options = []): CopyJobConfiguration` ### Parameters #### Options - **configuration** (array) - Required - Job configuration array - **configuration.copy** (array) - Required - Copy job configuration ### Returns `CopyJobConfiguration` - A copy job configuration object. ### Example ```php $copyJobConfig = $bigQuery->copy() ->sourceTable($sourceTable) ->destinationTable($destTable); $job = $bigQuery->runJob($copyJobConfig); ``` ``` -------------------------------- ### Get Table Friendly Name Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Table.md Retrieves the human-readable name assigned to the BigQuery table. ```php $table->friendlyName(); ``` -------------------------------- ### schema() Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/QueryResults.md Get the schema of the result columns. This provides details about each field in the query results. ```APIDOC ## schema() ### Description Get the schema of the result columns. ### Returns: `array` - Schema array with field definitions. ### Example: ```php $schema = $queryResults->schema(); foreach ($schema['fields'] as $field) { echo $field['name'] . ' (' . $field['type'] . ')'; } ``` ``` -------------------------------- ### Configure Project and Credentials via Environment Variables Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/configuration.md Set GOOGLE_APPLICATION_CREDENTIALS and GOOGLE_CLOUD_PROJECT environment variables to automatically configure the BigQuery client. This is useful for deployment environments. ```bash export GOOGLE_APPLICATION_CREDENTIALS=/path/to/keyfile.json export GOOGLE_CLOUD_PROJECT=my-project-id # Client uses these automatically $bigQuery = new BigQueryClient(); ``` -------------------------------- ### Get Table Primary Key (Table ID) Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Table.md Retrieves the unique identifier for the BigQuery table. ```php $table->primaryKey(); ``` -------------------------------- ### Get a BigQuery Job by ID Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/QUICK_REFERENCE.md Retrieve a BigQuery job object using its unique identifier. ```php // Get by ID $job = $bigQuery->job('job-id'); ``` -------------------------------- ### Create a Load Job Configuration Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/BigQueryClient.md Use this method to create a load job configuration for importing data into BigQuery. The configuration can be executed via `runJob()` or `startJob()`. ```php $loadJobConfig = $bigQuery->load() ->destinationTable($table) ->sourceUris(['gs://my-bucket/table.csv']); $job = $bigQuery->runJob($loadJobConfig); ``` -------------------------------- ### Initialize BigQuery Client with Application Default Credentials Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/configuration.md Instantiates the BigQuery client using Application Default Credentials. This method automatically resolves credentials from environment variables, Google Cloud SDK, or service account information. ```php $bigQuery = new BigQueryClient(); ``` -------------------------------- ### Get Dataset Primary Key Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Dataset.md Returns the primary key of the dataset, which is its unique dataset ID. ```php echo $dataset->primaryKey(); ``` -------------------------------- ### Create a BigQuery Dataset Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/README.md Creates a new BigQuery dataset with a specified ID and location. Requires the project ID and location. ```php // Create $dataset = $bigQuery->createDataset('new_dataset', [ 'location' => 'us-west1' ]); ``` -------------------------------- ### Get BigQuery Model ID Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Model.md Retrieves the unique identifier for the BigQuery model. Returns a string. ```php echo $model->id(); ``` -------------------------------- ### Create Load Job Configuration Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Table.md Use the `load` method to create a configuration for importing data into a BigQuery table. You can specify the data source and various load options. ```php $loadJobConfig = $table->load(fopen('/path/to/data.csv', 'r')); ``` ```php $loadJobConfig = $table->load( fopen('/path/to/data.json', 'r'), ['sourceFormat' => 'NEWLINE_DELIMITED_JSON'] ); ``` -------------------------------- ### Get BigQuery Table ID Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Table.md Use the id() method to retrieve the unique identifier for a BigQuery table. ```php echo $table->id(); ``` -------------------------------- ### Get BigQuery Job ID Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Job.md Retrieve the unique identifier for a BigQuery job using the `id()` method. ```php echo $job->id(); ``` -------------------------------- ### Set Create Disposition Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/JobConfigurations.md Configures how BigQuery should handle the creation of the destination table. Use 'CREATE_IF_NEEDED' to create the table if it doesn't exist, or 'CREATE_NEVER' to fail if the table already exists. ```php $queryConfig->createDisposition('CREATE_IF_NEEDED'); ``` -------------------------------- ### Migrate from keyFile to credentialsFetcher Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/configuration.md Replace the deprecated 'keyFile' option with the 'credentialsFetcher' for service account authentication. This involves creating a ServiceAccountCredentials object. ```php use Google\Auth\Credentials\ServiceAccountCredentials; $credentials = new ServiceAccountCredentials( ['https://www.googleapis.com/auth/bigquery'], $serviceAccountArray ); $bigQuery = new BigQueryClient([ 'credentialsFetcher' => $credentials ]); ``` -------------------------------- ### Get Model Primary Key Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Model.md Retrieves the primary key, which is the model ID, for the BigQuery ML model. ```APIDOC ## primaryKey() ### Description Get the model's primary key (model ID). ### Method `primaryKey(): string` ### Returns `string` - The model's primary key. ### Example ```php $primaryKey = $model->primaryKey(); ``` ``` -------------------------------- ### load() Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Table.md Creates a load job configuration to import data into this table. Accepts a data source (file path, stream, or resource) and optional load configurations. ```APIDOC ## load() ### Description Create a load job configuration to import data into this table. ### Method load ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **source** (string|resource|StreamInterface) - Required - Source data (file path, stream, or resource) - **options** (array) - Optional - Load options ### Request Example ```php $loadJobConfig = $table->load(fopen('/path/to/data.csv', 'r')); // With options $loadJobConfig = $table->load( fopen('/path/to/data.json', 'r'), ['sourceFormat' => 'NEWLINE_DELIMITED_JSON'] ); ``` ### Response #### Success Response - **LoadJobConfiguration** - The created load job configuration. #### Response Example None provided in source. ``` -------------------------------- ### Get Table Creation Time Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Table.md Retrieves the timestamp when the BigQuery table was created, in milliseconds since the POSIX epoch. ```php $table->creationTime(); ``` -------------------------------- ### Get BigQuery Job Results Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/QUICK_REFERENCE.md Retrieve the results of a completed BigQuery job. This is typically used after a query job. ```php // Get results $results = $job->queryResults(); ``` -------------------------------- ### Set Create Disposition for Load Job Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/JobConfigurations.md Define the behavior when the destination table does not exist. Specify how the table should be created. ```php public function createDisposition(string $disposition): LoadJobConfiguration ``` -------------------------------- ### Migrate from keyFilePath to credentialsFetcher Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/configuration.md Update from the deprecated 'keyFilePath' option to use 'credentialsFetcher' for service account authentication. This requires reading the key file content and creating a ServiceAccountCredentials object. ```php use Google\Auth\Credentials\ServiceAccountCredentials; $keyFile = json_decode( file_get_contents('/path/to/keyfile.json'), true ); $credentials = new ServiceAccountCredentials( ['https://www.googleapis.com/auth/bigquery'], $keyFile ); $bigQuery = new BigQueryClient([ 'credentialsFetcher' => $credentials ]); ``` -------------------------------- ### totalRows() Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/QueryResults.md Get the total number of rows in the complete result set. This provides the final count after all pagination is complete. ```APIDOC ## totalRows() ### Description Get the total number of rows in the complete result set. ### Returns: `int|null` - Total row count or null if unavailable. ### Example: ```php echo $queryResults->totalRows(); ``` ``` -------------------------------- ### Job Configuration Methods Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/INDEX.md Methods for creating and configuring BigQuery jobs. ```APIDOC ## BigQueryClient::load() ### Description Creates a load job configuration for BigQuery. ### Method (Not specified in source) ### Endpoint (Not specified in source) ### Parameters (Not specified in source) ### Request Example (Not specified in source) ### Response (Not specified in source) ``` ```APIDOC ## BigQueryClient::extract() ### Description Creates an extract job configuration for BigQuery. ### Method (Not specified in source) ### Endpoint (Not specified in source) ### Parameters (Not specified in source) ### Request Example (Not specified in source) ### Response (Not specified in source) ``` ```APIDOC ## BigQueryClient::copy() ### Description Creates a copy job configuration for BigQuery. ### Method (Not specified in source) ### Endpoint (Not specified in source) ### Parameters (Not specified in source) ### Request Example (Not specified in source) ### Response (Not specified in source) ``` -------------------------------- ### rows() Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/QueryResults.md Get the number of rows currently available. Note that this count may be less than the total if pagination is incomplete. ```APIDOC ## rows() ### Description Get the number of rows currently available. May be less than total if pagination is incomplete. ### Returns: `int|null` - Row count or null if unavailable. ### Example: ```php echo $queryResults->rows(); ``` ``` -------------------------------- ### Using Date in BigQuery Queries Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/types.md Demonstrates how to create a Date object from a DateTime instance and use it as a parameter in a BigQuery query. ```php $date = $bigQuery->date(new DateTime('1995-02-04')); $queryConfig = $bigQuery->query( 'SELECT * FROM events WHERE event_date = @date' )->parameters(['date' => $date]); ``` -------------------------------- ### info() Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/QueryResults.md Get result metadata. This method can optionally retrieve a single metadata key using dot notation. ```APIDOC ## info() ### Description Get result metadata. Optionally retrieve a single key. ### Parameters: | Parameter | Type | Required | Description | |-----------|--------|----------|---------------------------------| | key | string | No | Metadata key (supports dot notation) | ### Returns: `array|mixed` - Full metadata or specific value. ### Example: ```php $info = $queryResults->info(); $totalRows = $queryResults->info('totalRows'); ``` ``` -------------------------------- ### Set Create Disposition for Copy Job Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/JobConfigurations.md Configure how the destination table should be created. This method returns the configuration object for chaining. ```php public function createDisposition(string $disposition): CopyJobConfiguration ``` -------------------------------- ### getIterator() Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/QueryResults.md Get an iterator over query result rows. This method allows for easy traversal of each row in the query results. ```APIDOC ## getIterator() ### Description Get an iterator over query result rows. ### Returns `Iterator` - Iterator over row arrays. ### Example ```php $queryResults = $bigquery->runQuery($queryJobConfig); foreach ($queryResults as $row) { echo $row['name']; } // Manual iteration $iterator = $queryResults->getIterator(); while ($iterator->valid()) { $row = $iterator->current(); echo $row['name']; $iterator->next(); } ``` ``` -------------------------------- ### Run a Job with Table Configuration Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Table.md Use the `runQuery` method to execute a job that is configured with a specific table, either as a source or destination. This method accepts a job configuration and optional settings. ```php $loadJobConfig = $table->load(fopen('/data.csv', 'r')); $job = $table->runJob($loadJobConfig); ``` -------------------------------- ### Get Associated Job Object Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/QueryResults.md Retrieve the job object that produced these query results. The job ID can then be accessed. ```php $job = $queryResults->job(); echo $job->id(); ``` -------------------------------- ### Client Configuration Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/SUMMARY.md Options for configuring the BigQuery client, including authentication, timeouts, and logging. ```APIDOC ## Configuration ### Description Options for customizing the behavior of the BigQuery client. ### Options - **Authentication options**: Settings for authenticating API requests. - **Timeout and retry settings**: Configuration for request timeouts and retries. - **Logging configuration**: Settings for enabling and configuring logging. - **Location handling**: Specifies the default location for resources. - **Type conversion options**: Options for controlling data type conversions. ``` -------------------------------- ### Get BigQuery Routine Primary Key Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Routine.md Retrieve the primary key of the routine, which is its ID, using the `primaryKey()` method. ```php echo $routine->primaryKey(); ``` -------------------------------- ### Default BigQuery Client Configuration Options Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/configuration.md Understand the default settings applied by the BigQuery client during construction, including scopes, project ID requirement, integer return type, retry functions, and logger. ```php [ 'scopes' => ['https://www.googleapis.com/auth/bigquery'], 'projectIdRequired' => true, 'returnInt64AsObject' => false, 'restRetryFunction' => , 'restCalcDelayFunction' => , 'logger' => null ] ``` -------------------------------- ### BigQueryClient Constructor Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/BigQueryClient.md Initializes a new instance of the BigQueryClient class. This client is the primary interface for all BigQuery operations. ```APIDOC ## Constructor ```php public function __construct(array $config = []) ``` ### Description Creates a BigQuery client instance with optional configuration settings. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Configuration Options - **projectId** (string) - Required - The project ID from the Google Cloud Console. - **apiEndpoint** (string) - Optional - Custom API endpoint hostname with optional port (e.g., `foobar.com` or `foobar.com:1234`). - **authCache** (CacheItemPoolInterface) - Optional - Cache for storing access tokens. Defaults to in-memory. - **authCacheOptions** (array) - Optional - Cache configuration options. - **authHttpHandler** (callable) - Optional - PSR-7 request handler for authentication. - **credentialsFetcher** (FetchAuthTokenInterface) - Optional - Custom credentials fetcher instance. - **httpHandler** (callable) - Optional - PSR-7 request handler for REST requests. - **keyFile** (array) - Optional - **DEPRECATED** Service account key file array. - **keyFilePath** (string) - Optional - **DEPRECATED** Path to service account key file. - **requestTimeout** (float) - Optional - Timeout in seconds for requests. Defaults to 0 (REST), 60 (gRPC). - **retries** (int) - Optional - Number of retries for failed requests. Defaults to 3. - **scopes** (array) - Optional - OAuth 2.0 scopes to request. Defaults to `[SCOPE]`. - **quotaProject** (string) - Optional - User project to bill for access charges. - **returnInt64AsObject** (bool) - Optional - Return 64-bit integers as `Int64` objects. Defaults to false. - **location** (string) - Optional - Default geographic location for datasets and jobs. - **logger** (LoggerInterface|false|null) - Optional - PSR-3 compatible logger instance. ### Request Example ```php use Google\Cloud\BigQuery\BigQueryClient; $bigQuery = new BigQueryClient([ 'projectId' => 'my-project-id' ]); $bigQuery = new BigQueryClient([ 'projectId' => 'my-project-id', 'location' => 'us-west1', 'returnInt64AsObject' => true ]); ``` ### Response None ``` -------------------------------- ### List BigQuery Datasets Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/README.md Lists all datasets within the configured BigQuery project. Iterates through each dataset and prints its ID. ```php // List foreach ($bigQuery->datasets() as $dataset) { echo $dataset->id() . PHP_EOL; } ``` -------------------------------- ### pageToken() Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/QueryResults.md Get the page token for resuming result retrieval. This is used to continue fetching results from where a previous request left off. ```APIDOC ## pageToken() ### Description Get the page token for resuming result retrieval. ### Returns: `string|null` - Page token or null if on last page. ### Example: ```php if ($token = $queryResults->pageToken()) { // Resume from this token } ``` ``` -------------------------------- ### Run Query with Positional Parameters Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/BigQueryClient.md Execute a query with positional parameters bound using the `parameters()` method on the query configuration. Parameters are substituted in the order they appear in the query. ```php $query = 'SELECT name FROM users WHERE age > ? LIMIT 100'; $queryJobConfig = $bigQuery->query($query)->parameters([21]); $queryResults = $bigQuery->runQuery($queryJobConfig); foreach ($queryResults as $row) { echo $row['name']; } ``` -------------------------------- ### Get Query Result Schema Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/QueryResults.md Retrieve the schema of the result columns. The schema is returned as an array containing field definitions. ```php $schema = $queryResults->schema(); foreach ($schema['fields'] as $field) { echo $field['name'] . ' (' . $field['type'] . ')'; } ``` -------------------------------- ### BigQueryClient Public Methods Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/FILES.txt The BigQueryClient class is the main entry point for interacting with the BigQuery API. It provides methods for query operations, dataset and table management, job management, and data type creation. ```APIDOC ## BigQueryClient ### Description The main client class for interacting with the Google BigQuery API. It encapsulates various operations including querying data, managing datasets and tables, and handling jobs. ### Methods This class exposes over 20 public methods, including: - **Query Operations**: Methods for executing SQL queries against BigQuery. - **Dataset Management**: Methods for creating, retrieving, updating, and deleting datasets. - **Table Management**: Methods for creating, retrieving, updating, and deleting tables within datasets. - **Job Management**: Methods for creating, listing, getting, canceling, and waiting for jobs to complete. - **Data Type Creation**: Methods for creating various BigQuery data types. ### Initialization ```php use Google\Cloud\BigQuery\BigQueryClient; // Creates a BigQuery client $bigquery = new BigQueryClient(); ``` ### Example Usage (Query) ```php // Run a query $query = $bigquery->query('SELECT name FROM `bigquery-public-data.usa_names.usa_1910_current` LIMIT 10'); // Iterate over results foreach ($query->rows() as $row) { print($row['name'] . PHP_EOL); } ``` ``` -------------------------------- ### Configure Int64 Handling as Objects Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/configuration.md On 32-bit platforms, configure the client to return 64-bit integers as Int64 objects to prevent precision loss. This is automatically detected based on the PHP build. ```php // Platform detection $is32bit = PHP_INT_MAX === 2147483647; $bigQuery = new BigQueryClient([ 'returnInt64AsObject' => $is32bit ]); ``` -------------------------------- ### createDisposition() Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/JobConfigurations.md Set the create disposition: how to handle destination table creation. This method supports fluent chaining. ```APIDOC ## createDisposition() ### Description Set the create disposition: how to handle destination table creation. ### Method ```php public function createDisposition(string $disposition): QueryJobConfiguration ``` ### Parameters #### Path Parameters - **disposition** (string) - Required - One of: CREATE_IF_NEEDED, CREATE_NEVER ### Request Example ```php $queryConfig->createDisposition('CREATE_IF_NEEDED'); ``` ### Response #### Success Response - **QueryJobConfiguration** - For method chaining. ``` -------------------------------- ### Get BigQuery Query Job Results Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/README.md Retrieves the results of a completed BigQuery query job. Iterates through the rows of the query results. ```php // Get results (for query jobs) $results = $job->queryResults(); foreach ($results as $row) { echo $row['name']; } ``` -------------------------------- ### Get and Reload a BigQuery Dataset Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/README.md Retrieves an existing BigQuery dataset by its ID and reloads its information. Displays the dataset's description. ```php // Get $dataset = $bigQuery->dataset('existing_dataset'); $dataset->reload(); echo $dataset->info('description'); ``` -------------------------------- ### query() Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/BigQueryClient.md Creates a query job configuration that can be executed later. This method allows for fluent configuration of query options. ```APIDOC ## query() ### Description Create a query job configuration. The configuration can be executed via `runQuery()` or `startQuery()`. ### Method Signature ```php public function query(string $query, array $options = []): QueryJobConfiguration ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | query | string | Yes | A BigQuery SQL query string | | options | array | No | Configuration options | ### Options #### configuration - **configuration** (array) - Job configuration array - **configuration.query** (array) - Query-specific configuration ### Returns `QueryJobConfiguration` - A query job configuration object with fluent methods for setting additional options. ### Throws None directly. Exceptions may be thrown when executing the job. ### Example ```php // Basic usage $queryJobConfig = $bigQuery->query( 'SELECT commit FROM `bigquery-public-data.github_repos.commits` LIMIT 100' ); // With fluent configuration $queryJobConfig = $bigQuery->query( 'SELECT name FROM `my_project.users_dataset.users` LIMIT 100' )->createDisposition('CREATE_NEVER'); // With array configuration $queryJobConfig = $bigQuery->query( 'SELECT * FROM `my_project.my_dataset.my_table`', [ 'configuration' => [ 'query' => [ 'createDisposition' => 'CREATE_NEVER' ] ] ] ); // With location $queryJobConfig = $bigQuery->query( 'SELECT name FROM users' )->location('asia-northeast1'); ``` ``` -------------------------------- ### Get IAM Policy Manager Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Dataset.md Retrieves an IAM policy manager instance for the dataset, which can be used to manage access control policies. ```php $iam = $dataset->iam(); ``` -------------------------------- ### Load Data from Local File Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/QUICK_REFERENCE.md Load data into a BigQuery table from a local file. Ensure the file is opened in read mode. ```php // From local file $loadConfig = $table->load(fopen('/data.csv', 'r')); ``` -------------------------------- ### Create a New BigQuery Dataset Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/BigQueryClient.md Create a new dataset with the specified ID. Optionally provide creation options such as location or metadata. Does not retry by default. ```php $dataset = $bigQuery->createDataset('aDataset'); $dataset = $bigQuery->createDataset('aDataset', [ 'location' => 'us-west1' ]); ``` -------------------------------- ### Get BigQuery Job Primary Key Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Job.md Retrieve the primary key, which is the job ID, for a BigQuery job using the `primaryKey()` method. ```php $job->primaryKey(); ``` -------------------------------- ### Get IAM Policy Manager Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Model.md Retrieves the IAM policy manager for the BigQuery ML model, allowing for access control management. ```APIDOC ## iam() ### Description Get the IAM policy manager for the model. ### Method `iam(): Iam` ### Returns `Iam` - An instance of the IAM policy manager. ### Example ```php $iam = $model->iam(); ``` ``` -------------------------------- ### Get BigQuery Model Primary Key Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Model.md Retrieves the primary key of the BigQuery model, which is equivalent to its model ID. Returns a string. ```php echo $model->primaryKey(); ``` -------------------------------- ### info() Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Routine.md Retrieves metadata for the BigQuery routine. ```APIDOC ## info() ### Description Get routine metadata. ### Method N/A (Object Method) ### Parameters #### Query Parameters - **key** (string) - Optional. Metadata key (dot notation supported). ### Response #### Success Response - **return** (array|mixed) - Routine metadata, or a specific metadata value if a key is provided. ### Example ```php $info = $routine->info(); $routineType = $routine->info('routineType'); // FUNCTION or PROCEDURE $language = $routine->info('language'); // SQL, JAVASCRIPT, PYTHON, etc. $definition = $routine->info('definitionBody'); ``` ``` -------------------------------- ### Get BigQuery Job State Source: https://github.com/googleapis/google-cloud-php-bigquery/blob/main/_autodocs/api-reference/Job.md Retrieve the current operational state of a BigQuery job, which can be `PENDING`, `RUNNING`, or `DONE`, using the `state()` method. ```php echo $job->state(); ```