Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
5925b0f
feat(bigquery): initial project setup
hivanalejandro Feb 13, 2025
e24c2e8
feat(bigquery): basic structure
hivanalejandro Feb 13, 2025
84ec0f6
feat(bigquery): Add table and view access policy viewer
hivanalejandro Feb 13, 2025
21f786e
feat(bigquery): Add viewDatasetAccessPolicy tests
hivanalejandro Feb 13, 2025
5d408c7
feat(bigquery): Add viewTableOrViewAccessPolicy tests
hivanalejandro Feb 14, 2025
62e343a
fix(bigquery): Fix linting errors
hivanalejandro Feb 14, 2025
c87d659
Merge branch 'main' into hivanalejandro/bigquery/create-sample/view-d…
hivanalejandro Feb 14, 2025
58ee72a
feat(bigquery): Add revokeTableOrViewAccess feawture and tests
hivanalejandro Feb 17, 2025
62ebc2c
feat(bigquery): Update app.js file to add revokeTableOrViewAccess & f…
hivanalejandro Feb 17, 2025
9d0ce88
fix(bigquery):Fix headers for revokeTableOrViewAccess.js & revokeTabl…
hivanalejandro Feb 17, 2025
627536a
feat(bigquery): Add bigquery_revoke_access_to_table_or_view tag
hivanalejandro Feb 17, 2025
70cfb83
fix(bigquery): Update if/else to if/else if
hivanalejandro Feb 18, 2025
ff35988
feat(bigquery): Add grantAccessToDataset sample and tests
hivanalejandro Feb 20, 2025
b8ad0f4
Merge branch 'main' into hivanalejandro/bigquery/create-sample/view-d…
hivanalejandro Feb 20, 2025
7b38e5a
fix(bigquery): Update lint error
hivanalejandro Feb 20, 2025
5cfa8dc
feat(bigquery): Add grantAccessToTableOrView sample
hivanalejandro Feb 20, 2025
ccf30d6
feat(bigquery): Add grantAccessToTableOrView test
hivanalejandro Feb 20, 2025
eb32aa8
feat(bigquery): Update app.js file with new samples
hivanalejandro Feb 20, 2025
0a5f5dd
feat(bigquery): Add revokeDatasetAccess sample
hivanalejandro Feb 20, 2025
6c40940
feat(bigquery): Add revokeDatasetAccess tests
hivanalejandro Feb 20, 2025
b600729
feat(bigquery): Update app.js file with new sample
hivanalejandro Feb 20, 2025
c7a1821
Merge branch 'main' into hivanalejandro/bigquery/create-sample/view-d…
hivanalejandro Feb 20, 2025
db956a7
chore(bigquery): Update project structure
hivanalejandro Feb 20, 2025
b013b3c
fix(bigquery): Update samples and tests related to Dataset
hivanalejandro Feb 27, 2025
3f3d68a
Merge branch 'main' into hivanalejandro/bigquery/create-sample/view-d…
hivanalejandro Feb 27, 2025
12bc84b
fix(bigquery): Update format issues
hivanalejandro Feb 27, 2025
b9e4bb1
fix(bigquery): Update samples and tests related to Table or View
hivanalejandro Mar 3, 2025
e6e886f
Merge branch 'main' into hivanalejandro/bigquery/create-sample/view-d…
hivanalejandro Mar 3, 2025
ec3c990
fix(bigquery): Update samples and tests according to PR comments
hivanalejandro Mar 3, 2025
232b73b
Merge branch 'main' into hivanalejandro/bigquery/create-sample/view-d…
hivanalejandro Mar 4, 2025
7c45228
fix(bigquery): Update samples and tests format issues
hivanalejandro Mar 5, 2025
f6a685d
Merge branch 'main' into hivanalejandro/bigquery/create-sample/view-d…
hivanalejandro Mar 5, 2025
dbb3a4d
fix(bigquery): Update samples and tests according to PR comments
hivanalejandro Mar 5, 2025
5c04884
fix(bigquery): Standardized punctuation and style in all documents
hivanalejandro Mar 5, 2025
eed264a
fix(bigquery): Add punctuation to test and standardize format in all …
hivanalejandro Mar 6, 2025
20609bf
Merge branch 'main' into hivanalejandro/bigquery/create-sample/view-d…
hivanalejandro Mar 6, 2025
f721a80
Merge branch 'main' into hivanalejandro/bigquery/create-sample/view-d…
hivanalejandro Mar 7, 2025
158f0b0
fix(bigquery): Update samples and tests according to PR comments
hivanalejandro Mar 7, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 65 additions & 27 deletions bigquery/cloud-client/grantAccessToDataset.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,61 +14,99 @@

'use strict';

const {BigQuery} = require('@google-cloud/bigquery');

/**
* Grants access to a BigQuery dataset for a specified entity
*
* @param {object} options The configuration object
* @param {string} options.datasetId ID of the dataset to grant access to (e.g. "my_project_id.my_dataset")
* @param {string} options.entityId ID of the user or group to grant access to (e.g. "[email protected]")
* @param {string} options.role One of the basic roles for datasets (e.g. "READER")
* @param {string} datasetId ID of the dataset to grant access to
* @param {string} entityId ID of the entity to grant access to
* @param {string} role Role to grant
* @returns {Promise<Array>} Array of access entries
*/
// [START bigquery_grant_access_to_dataset]
async function grantAccessToDataset(options) {
// Create a BigQuery client
const bigquery = new BigQuery();
async function grantAccessToDataset(datasetId, entityId, role) {
// [START bigquery_grant_access_to_dataset]
const {BigQuery} = require('@google-cloud/bigquery');

// TODO(developer): Update and un-comment below lines

// ID of the dataset to revoke access to.
// datasetId = "my_project_id.my_dataset";

// ID of the user or group from whom you are adding access.
// Alternatively, the JSON REST API representation of the entity,
// such as a view's table reference.
// entityId = "[email protected]";

// One of the "Basic roles for datasets" described here:
// https://cloud.google.com/bigquery/docs/access-control-basic-roles#dataset-basic-roles
// role = "READER";

const {datasetId, entityId, role} = options;
// Type of entity you are granting access to.
// Find allowed allowed entity type names here:
// https://cloud.google.com/python/docs/reference/bigquery/latest/enums#class-googlecloudbigqueryenumsentitytypesvalue
// In this case, we're using the equivalent of GROUP_BY_EMAIL
const entityType = 'groupByEmail';

// Instantiate a client.
const client = new BigQuery();

try {
// Get a reference to the dataset
const dataset = bigquery.dataset(datasetId);
const [metadata] = await dataset.getMetadata();
// Get a reference to the dataset.
const [dataset] = await client.dataset(datasetId).get();

// The access entries list is immutable. Create a copy for modifications
const entries = [...(metadata.access || [])];
// The 'access entries' list is immutable. Create a copy for modifications.
const entries = Array.isArray(dataset.metadata.access)
? [...dataset.metadata.access]
: [];

// Add the new access entry
// Append an AccessEntry to grant the role to a dataset.
// Find more details about the AccessEntry object in the BigQuery documentation
entries.push({
role: role,
groupByEmail: entityId, // For group access. Use userByEmail for user access
[entityType]: entityId,
});

// Update the dataset's access entries
const [updatedMetadata] = await dataset.setMetadata({
...metadata,
// Assign the list of AccessEntries back to the dataset.
const metadata = {
access: entries,
});
};

// Update will only succeed if the dataset
// has not been modified externally since retrieval.
//
// See the BigQuery client library documentation for more details on metadata updates

// Update just the 'access entries' property of the dataset.
const [updatedDataset] = await client
.dataset(datasetId)
.setMetadata(metadata);

// Show a success message.
const fullDatasetId =
updatedDataset &&
updatedDataset.metadata &&
updatedDataset.metadata.datasetReference
? `${updatedDataset.metadata.datasetReference.projectId}.${updatedDataset.metadata.datasetReference.datasetId}`
: datasetId;

console.log(
`Role '${role}' granted for entity '${entityId}' in dataset '${datasetId}'.`
`Role '${role}' granted for entity '${entityId}'` +
` in dataset '${fullDatasetId}'.`
);

return updatedMetadata.access;
return updatedDataset.access;
} catch (error) {
if (error.code === 412) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd suggest avoiding Magic numbers like 412, and using a const instead

ERROR_PRECONDITION_FAILED = 412

if (error.code === ERROR_PRECONDITION_FAILED)

Usually these constants are available in the client-library, although I can't find it for Node.JS.
Also it seems that this message is specific for Python:
https://cloud.google.com/bigquery/docs/error-messages#connecterrors

Could you replicate that error in your runs?
Otherwise, you could try to replicate the error to manually see what's the caught error for this specific case.
What I did was reading metadata (as in line 50), adding a 15 seconds pause, modifying the dataset from the Web page, and trying to save the metadata as you do in line 50.

// 412 Precondition Failed - Dataset was modified between get and update
// A read-modify-write error (PreconditionFailed equivalent)
console.error(
`Dataset '${datasetId}' was modified remotely before this update. ` +
'Fetch the latest version and retry.'
);
} else {
throw error;
}
throw error;
}
// [END bigquery_grant_access_to_dataset]
}
// [END bigquery_grant_access_to_dataset]

module.exports = {
grantAccessToDataset,
Expand Down
86 changes: 66 additions & 20 deletions bigquery/cloud-client/revokeDatasetAccess.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,43 +18,89 @@ const {BigQuery} = require('@google-cloud/bigquery');

// [START bigquery_revoke_dataset_access]
/**
* Revokes access to a BigQuery dataset for a specified entity.
* Revokes access to a dataset for a specified entity.
*
* @param {Object} params The parameters for revoking dataset access
* @param {string} params.datasetId The ID of the dataset to revoke access from
* @param {string} params.entityId The ID of the user or group to revoke access from
* @param {string} datasetId - ID of the dataset to revoke access to.
* @param {string} entityId - ID of the user or group from whom you are revoking access.
* Alternatively, the JSON REST API representation of the entity,
* such as a view's table reference.
* @returns {Promise<Array>} A promise that resolves to the updated access entries
*/
async function revokeDatasetAccess({datasetId, entityId}) {
// Instantiate a client
async function revokeDatasetAccess(datasetId, entityId) {
// Import the Google Cloud client library.
const bigquery = new BigQuery();

try {
// Get a reference to the dataset
const [dataset] = await bigquery.dataset(datasetId).get();
// TODO (developer): Update and un-comment below lines

// Filter out the access entry for the specified entity
dataset.metadata.access = dataset.metadata.access.filter(
entry => entry.userByEmail !== entityId && entry.groupByEmail !== entityId
);
// ID of the dataset to revoke access to.
// datasetId = "your-project.your_dataset"

// ID of the user or group from whom you are revoking access.
// Alternatively, the JSON REST API representation of the entity,
// such as a view's table reference.
// entityId = "[email protected]"

// Get a reference to the dataset.
const [dataset] = await bigquery.dataset(datasetId).get();

// To revoke access to a dataset, remove elements from the access list.
//
// See the BigQuery client library documentation for more details on access entries

// Update the dataset with the new access entries
// Filter access entries to exclude entries matching the specified entity_id
// and assign a new list back to the access list.
dataset.metadata.access = dataset.metadata.access.filter(entry => {
// Check for entity_id (specific match)
if (entry.entity_id === entityId) {
console.log(
`Found matching entity_id: ${entry.entity_id}, removing entry`
);
return false;
}

// Check for userByEmail field
if (entry.userByEmail === entityId) {
console.log(
`Found matching userByEmail: ${entry.userByEmail}, removing entry`
);
return false;
}

// Check for groupByEmail field
if (entry.groupByEmail === entityId) {
console.log(
`Found matching groupByEmail: ${entry.groupByEmail}, removing entry`
);
return false;
}

// Keep all other entries
return true;
});

// Update will only succeed if the dataset
// has not been modified externally since retrieval.

try {
// Update just the access entries property of the dataset.
const [updatedDataset] = await dataset.setMetadata(dataset.metadata);

const fullDatasetId = `${dataset.parent.projectId}.${dataset.id}`;
console.log(
`Revoked dataset access for '${entityId}' to dataset '${dataset.id}'.`
`Revoked dataset access for '${entityId}' to dataset '${fullDatasetId}'.`
);

return updatedDataset.metadata.access;
return updatedDataset.access;
} catch (error) {
// Check if it's a precondition failed error (a read-modify-write error)
if (error.code === 412) {
// Handle precondition failed error (dataset modified externally)
console.error(
`Dataset '${datasetId}' was modified remotely before this update. ` +
console.log(
`Dataset '${dataset.id}' was modified remotely before this update. ` +
'Fetch the latest version and retry.'
);
} else {
throw error;
}
throw error;
}
}
// [END bigquery_revoke_dataset_access]
Expand Down
Loading
Loading