bigquery-jupyter-plugin 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. bigquery_jupyter_plugin/__init__.py +25 -0
  2. bigquery_jupyter_plugin/_version.py +4 -0
  3. bigquery_jupyter_plugin/handlers.py +307 -0
  4. bigquery_jupyter_plugin/services/__init__.py +6 -0
  5. bigquery_jupyter_plugin/services/bq_client.py +42 -0
  6. bigquery_jupyter_plugin/services/credentials.py +62 -0
  7. bigquery_jupyter_plugin/services/details.py +131 -0
  8. bigquery_jupyter_plugin/services/explorer.py +87 -0
  9. bigquery_jupyter_plugin/services/query.py +115 -0
  10. bigquery_jupyter_plugin/services/query_history.py +76 -0
  11. bigquery_jupyter_plugin/services/search.py +136 -0
  12. bigquery_jupyter_plugin/services/serviceusage.py +63 -0
  13. bigquery_jupyter_plugin/tests/__init__.py +7 -0
  14. bigquery_jupyter_plugin/tests/test_credentials.py +59 -0
  15. bigquery_jupyter_plugin/tests/test_details.py +177 -0
  16. bigquery_jupyter_plugin/tests/test_explorer.py +100 -0
  17. bigquery_jupyter_plugin/tests/test_handlers.py +60 -0
  18. bigquery_jupyter_plugin/tests/test_query.py +159 -0
  19. bigquery_jupyter_plugin/tests/test_query_history.py +137 -0
  20. bigquery_jupyter_plugin/tests/test_search.py +178 -0
  21. bigquery_jupyter_plugin/tests/test_serviceusage.py +71 -0
  22. bigquery_jupyter_plugin-0.1.0.data/data/etc/jupyter/jupyter_server_config.d/bigquery_jupyter_plugin.json +7 -0
  23. bigquery_jupyter_plugin-0.1.0.data/data/share/jupyter/labextensions/bigquery-jupyter-plugin/install.json +5 -0
  24. bigquery_jupyter_plugin-0.1.0.data/data/share/jupyter/labextensions/bigquery-jupyter-plugin/package.json +250 -0
  25. bigquery_jupyter_plugin-0.1.0.data/data/share/jupyter/labextensions/bigquery-jupyter-plugin/schemas/bigquery-jupyter-plugin/package.json.orig +245 -0
  26. bigquery_jupyter_plugin-0.1.0.data/data/share/jupyter/labextensions/bigquery-jupyter-plugin/schemas/bigquery-jupyter-plugin/plugin.json +17 -0
  27. bigquery_jupyter_plugin-0.1.0.data/data/share/jupyter/labextensions/bigquery-jupyter-plugin/static/128.af147272d3c404d1f228.js +2 -0
  28. bigquery_jupyter_plugin-0.1.0.data/data/share/jupyter/labextensions/bigquery-jupyter-plugin/static/128.af147272d3c404d1f228.js.LICENSE.txt +9 -0
  29. bigquery_jupyter_plugin-0.1.0.data/data/share/jupyter/labextensions/bigquery-jupyter-plugin/static/216.8228a8bd99d14654a23f.js +1 -0
  30. bigquery_jupyter_plugin-0.1.0.data/data/share/jupyter/labextensions/bigquery-jupyter-plugin/static/277.efbf56dfd7620facf18e.js +1 -0
  31. bigquery_jupyter_plugin-0.1.0.data/data/share/jupyter/labextensions/bigquery-jupyter-plugin/static/36.f911e304e0813bf2da60.js +2 -0
  32. bigquery_jupyter_plugin-0.1.0.data/data/share/jupyter/labextensions/bigquery-jupyter-plugin/static/36.f911e304e0813bf2da60.js.LICENSE.txt +8 -0
  33. bigquery_jupyter_plugin-0.1.0.data/data/share/jupyter/labextensions/bigquery-jupyter-plugin/static/43.c06a146a9598e149f8ec.js +1 -0
  34. bigquery_jupyter_plugin-0.1.0.data/data/share/jupyter/labextensions/bigquery-jupyter-plugin/static/remoteEntry.9302beae30bdc684fb88.js +1 -0
  35. bigquery_jupyter_plugin-0.1.0.data/data/share/jupyter/labextensions/bigquery-jupyter-plugin/static/style.js +4 -0
  36. bigquery_jupyter_plugin-0.1.0.data/data/share/jupyter/labextensions/bigquery-jupyter-plugin/static/third-party-licenses.json +70 -0
  37. bigquery_jupyter_plugin-0.1.0.dist-info/METADATA +4112 -0
  38. bigquery_jupyter_plugin-0.1.0.dist-info/RECORD +40 -0
  39. bigquery_jupyter_plugin-0.1.0.dist-info/WHEEL +4 -0
  40. bigquery_jupyter_plugin-0.1.0.dist-info/licenses/LICENSE +24 -0
@@ -0,0 +1,25 @@
1
+ # Copyright 2024 Google LLC
2
+ #
3
+ # Use of this source code is governed by a BSD-style
4
+ # license that can be found in the LICENSE file or at
5
+ # https://developers.google.com/open-source/licenses/bsd
6
+
7
+ from .handlers import setup_handlers
8
+
9
+
10
+ def _jupyter_labextension_paths():
11
+ return [{"src": "labextension", "dest": "bigquery-jupyter-plugin"}]
12
+
13
+
14
+ def _jupyter_server_extension_points():
15
+ return [{"module": "bigquery_jupyter_plugin"}]
16
+
17
+
18
+ def _load_jupyter_server_extension(server_app):
19
+ """Register the API handlers that serve the frontend extension.
20
+
21
+ Args:
22
+ server_app: The JupyterLab/Jupyter Server application.
23
+ """
24
+ setup_handlers(server_app.web_app)
25
+ server_app.log.info("Registered the 'bigquery_jupyter_plugin' server extension")
@@ -0,0 +1,4 @@
1
+ # This file is auto-generated by Hatchling. As such, do not:
2
+ # - modify
3
+ # - track in version control e.g. be sure to add to .gitignore
4
+ __version__ = VERSION = '0.1.0'
@@ -0,0 +1,307 @@
1
+ # Copyright 2024 Google LLC
2
+ #
3
+ # Use of this source code is governed by a BSD-style
4
+ # license that can be found in the LICENSE file or at
5
+ # https://developers.google.com/open-source/licenses/bsd
6
+
7
+ import json
8
+ import re
9
+
10
+ import tornado
11
+ from jupyter_server.base.handlers import APIHandler
12
+ from jupyter_server.utils import url_path_join
13
+ from tornado.ioloop import IOLoop
14
+
15
+ from bigquery_jupyter_plugin.services import (
16
+ credentials,
17
+ details,
18
+ explorer,
19
+ query,
20
+ query_history,
21
+ search,
22
+ serviceusage,
23
+ )
24
+
25
+
26
+ def _clean_error(e):
27
+ """Turn a Google API error into a short, human-readable message.
28
+
29
+ Prefers the structured error message BigQuery returns (e.g. "Syntax error:
30
+ ...") over the raw ``str(e)``, which carries the HTTP verb, full request URL,
31
+ a duplicated reason/message, and a trailing job id.
32
+ """
33
+ errors = getattr(e, "errors", None)
34
+ if isinstance(errors, (list, tuple)):
35
+ for err in errors:
36
+ if isinstance(err, dict) and err.get("message"):
37
+ return err["message"]
38
+ msg = getattr(e, "message", None) or str(e)
39
+ # Drop the "NNN VERB https://...: " API-call prefix, or a bare status code.
40
+ msg = re.sub(r"^\d{3}\s+[A-Z]+\s+https?://\S+:\s*", "", msg)
41
+ msg = re.sub(r"^\d{3}\s+", "", msg)
42
+ # Drop the duplicated "; reason: ...; message: ..." tail and any job id tail.
43
+ msg = re.split(r";\s*reason:", msg)[0]
44
+ msg = re.sub(r"\s*Location:\s*\S+.*?Job ID:\s*\S+\s*$", "", msg)
45
+ return msg.strip()
46
+
47
+
48
+ async def _finish_json(handler, fn):
49
+ """Run a blocking service call in an executor and finish with JSON.
50
+
51
+ Known Google API errors (NotFound, Forbidden, BadRequest, ...) carry an
52
+ HTTP ``code``; surface it and a clean message instead of a blanket 500.
53
+ """
54
+ try:
55
+ result = await IOLoop.current().run_in_executor(None, fn)
56
+ handler.finish(json.dumps(result))
57
+ except Exception as e: # noqa: BLE001 - surface a clean error to the client
58
+ status = getattr(e, "code", None)
59
+ if not isinstance(status, int) or not 400 <= status <= 599:
60
+ status = 500
61
+ handler.log.exception("BigQuery plugin request failed")
62
+ handler.set_status(status)
63
+ handler.finish(json.dumps({"error": _clean_error(e)}))
64
+
65
+
66
+ class HealthCheckHandler(APIHandler):
67
+ """Report whether the BigQuery Jupyter Plugin server extension is healthy."""
68
+
69
+ @tornado.web.authenticated
70
+ def get(self):
71
+ self.finish("ok")
72
+
73
+
74
+ class ConfigHandler(APIHandler):
75
+ """Return the active principal and default project (Application Default Creds)."""
76
+
77
+ @tornado.web.authenticated
78
+ async def get(self):
79
+ await _finish_json(self, credentials.get_identity)
80
+
81
+
82
+ class ProjectsHandler(APIHandler):
83
+ """List ACTIVE projects the user can access (paginated)."""
84
+
85
+ @tornado.web.authenticated
86
+ async def get(self):
87
+ page_token = self.get_argument("pageToken", default="") or None
88
+ page_size = int(self.get_argument("pageSize", default="100"))
89
+ await _finish_json(self, lambda: explorer.list_projects(page_token, page_size))
90
+
91
+
92
+ class DatasetsHandler(APIHandler):
93
+ """List datasets in a project (paginated)."""
94
+
95
+ @tornado.web.authenticated
96
+ async def get(self):
97
+ project_id = self.get_argument("project_id")
98
+ page_token = self.get_argument("pageToken", default="") or None
99
+ page_size = int(self.get_argument("pageSize", default="100"))
100
+ await _finish_json(
101
+ self, lambda: explorer.list_datasets(project_id, page_token, page_size)
102
+ )
103
+
104
+
105
+ class TablesHandler(APIHandler):
106
+ """List tables/views in a dataset (paginated)."""
107
+
108
+ @tornado.web.authenticated
109
+ async def get(self):
110
+ project_id = self.get_argument("project_id")
111
+ dataset_id = self.get_argument("dataset_id")
112
+ page_token = self.get_argument("pageToken", default="") or None
113
+ page_size = int(self.get_argument("pageSize", default="100"))
114
+ await _finish_json(
115
+ self,
116
+ lambda: explorer.list_tables(project_id, dataset_id, page_token, page_size),
117
+ )
118
+
119
+
120
+ class TableHandler(APIHandler):
121
+ """Return schema and metadata for a single table."""
122
+
123
+ @tornado.web.authenticated
124
+ async def get(self):
125
+ project_id = self.get_argument("project_id")
126
+ dataset_id = self.get_argument("dataset_id")
127
+ table_id = self.get_argument("table_id")
128
+ await _finish_json(
129
+ self, lambda: details.get_table(project_id, dataset_id, table_id)
130
+ )
131
+
132
+
133
+ class PreviewHandler(APIHandler):
134
+ """Return a page of table rows via tabledata.list (no query cost)."""
135
+
136
+ @tornado.web.authenticated
137
+ async def get(self):
138
+ project_id = self.get_argument("project_id")
139
+ dataset_id = self.get_argument("dataset_id")
140
+ table_id = self.get_argument("table_id")
141
+ max_results = int(self.get_argument("maxResults", default="100"))
142
+ start_index = int(self.get_argument("startIndex", default="0"))
143
+ await _finish_json(
144
+ self,
145
+ lambda: details.preview_table(
146
+ project_id, dataset_id, table_id, max_results, start_index
147
+ ),
148
+ )
149
+
150
+
151
+ class DryRunHandler(APIHandler):
152
+ """Estimate the bytes a query would process (no execution)."""
153
+
154
+ @tornado.web.authenticated
155
+ async def post(self):
156
+ body = json.loads(self.request.body or b"{}")
157
+ sql = body.get("query", "")
158
+ project_id = body.get("projectId") or None
159
+ await _finish_json(self, lambda: query.dry_run(sql, project_id))
160
+
161
+
162
+ class QueryHandler(APIHandler):
163
+ """Submit a query job and return its reference immediately."""
164
+
165
+ @tornado.web.authenticated
166
+ async def post(self):
167
+ body = json.loads(self.request.body or b"{}")
168
+ sql = body.get("query", "")
169
+ project_id = body.get("projectId") or None
170
+ location = body.get("location") or None
171
+ await _finish_json(
172
+ self, lambda: query.execute_query(sql, project_id, location)
173
+ )
174
+
175
+
176
+ class QueryResultsHandler(APIHandler):
177
+ """Return a page of a query job's results (or its state if still running)."""
178
+
179
+ @tornado.web.authenticated
180
+ async def get(self):
181
+ job_id = self.get_argument("jobId")
182
+ project_id = self.get_argument("projectId", default="") or None
183
+ location = self.get_argument("location", default="") or None
184
+ start_index = int(self.get_argument("startIndex", default="0"))
185
+ max_results = int(self.get_argument("maxResults", default="100"))
186
+ await _finish_json(
187
+ self,
188
+ lambda: query.get_query_results(
189
+ job_id, project_id, location, start_index, max_results
190
+ ),
191
+ )
192
+
193
+
194
+ class CancelQueryHandler(APIHandler):
195
+ """Request cancellation of a running query job."""
196
+
197
+ @tornado.web.authenticated
198
+ async def post(self):
199
+ body = json.loads(self.request.body or b"{}")
200
+ job_id = body.get("jobId", "")
201
+ project_id = body.get("projectId") or None
202
+ location = body.get("location") or None
203
+ await _finish_json(
204
+ self, lambda: query.cancel_query(job_id, project_id, location)
205
+ )
206
+
207
+
208
+ class QueryHistoryHandler(APIHandler):
209
+ """List the caller's recent query jobs in a project (paginated)."""
210
+
211
+ @tornado.web.authenticated
212
+ async def get(self):
213
+ project_id = self.get_argument("project_id", default="") or None
214
+ max_results = int(self.get_argument("maxResults", default="50"))
215
+ min_creation = self.get_argument("minCreationTime", default="")
216
+ min_creation_ms = int(min_creation) if min_creation else None
217
+ page_token = self.get_argument("pageToken", default="") or None
218
+ await _finish_json(
219
+ self,
220
+ lambda: query_history.list_query_history(
221
+ project_id, max_results, min_creation_ms, page_token
222
+ ),
223
+ )
224
+
225
+
226
+ class SearchTablesHandler(APIHandler):
227
+ """Search tables/views by name across datasets via Dataplex searchEntries."""
228
+
229
+ @tornado.web.authenticated
230
+ async def get(self):
231
+ project_id = self.get_argument("project_id")
232
+ term = self.get_argument("term", default="")
233
+ projects_arg = self.get_argument("projects", default="")
234
+ projects = [p for p in projects_arg.split(",") if p] or None
235
+ await _finish_json(
236
+ self,
237
+ lambda: search.search_tables(project_id, term, projects),
238
+ )
239
+
240
+
241
+ class DataplexStatusHandler(APIHandler):
242
+ """Report whether the Dataplex API is enabled on a project."""
243
+
244
+ @tornado.web.authenticated
245
+ async def get(self):
246
+ project_id = self.get_argument("project_id")
247
+ await _finish_json(self, lambda: search.dataplex_status(project_id))
248
+
249
+
250
+ class EnableDataplexHandler(APIHandler):
251
+ """Enable the Dataplex API on a project (needs serviceusage.services.enable)."""
252
+
253
+ @tornado.web.authenticated
254
+ async def post(self):
255
+ body = json.loads(self.request.body or b"{}")
256
+ project_id = body.get("projectId", "")
257
+ await _finish_json(self, lambda: search.enable_dataplex(project_id))
258
+
259
+
260
+ class BigqueryStatusHandler(APIHandler):
261
+ """Report whether the BigQuery API is enabled on a project."""
262
+
263
+ @tornado.web.authenticated
264
+ async def get(self):
265
+ project_id = self.get_argument("project_id")
266
+ await _finish_json(self, lambda: serviceusage.bigquery_status(project_id))
267
+
268
+
269
+ class EnableBigqueryHandler(APIHandler):
270
+ """Enable the BigQuery API on a project (needs serviceusage.services.enable)."""
271
+
272
+ @tornado.web.authenticated
273
+ async def post(self):
274
+ body = json.loads(self.request.body or b"{}")
275
+ project_id = body.get("projectId", "")
276
+ await _finish_json(self, lambda: serviceusage.enable_bigquery(project_id))
277
+
278
+
279
+ def setup_handlers(web_app):
280
+ host_pattern = ".*$"
281
+ base_url = web_app.settings["base_url"]
282
+ application_url = "bigquery-jupyter-plugin"
283
+
284
+ def full_path(name):
285
+ return url_path_join(base_url, application_url, name)
286
+
287
+ handlers_map = {
288
+ "health": HealthCheckHandler,
289
+ "config": ConfigHandler,
290
+ "projects": ProjectsHandler,
291
+ "datasets": DatasetsHandler,
292
+ "tables": TablesHandler,
293
+ "table": TableHandler,
294
+ "preview": PreviewHandler,
295
+ "dryRun": DryRunHandler,
296
+ "query": QueryHandler,
297
+ "queryResults": QueryResultsHandler,
298
+ "cancelQuery": CancelQueryHandler,
299
+ "queryHistory": QueryHistoryHandler,
300
+ "searchTables": SearchTablesHandler,
301
+ "dataplexStatus": DataplexStatusHandler,
302
+ "enableDataplex": EnableDataplexHandler,
303
+ "bigqueryStatus": BigqueryStatusHandler,
304
+ "enableBigquery": EnableBigqueryHandler,
305
+ }
306
+ handlers = [(full_path(name), handler) for name, handler in handlers_map.items()]
307
+ web_app.add_handlers(host_pattern, handlers)
@@ -0,0 +1,6 @@
1
+ # Copyright 2024 Google LLC
2
+ #
3
+ # Use of this source code is governed by a BSD-style
4
+ # license that can be found in the LICENSE file or at
5
+ # https://developers.google.com/open-source/licenses/bsd
6
+
@@ -0,0 +1,42 @@
1
+ # Copyright 2024 Google LLC
2
+ #
3
+ # Use of this source code is governed by a BSD-style
4
+ # license that can be found in the LICENSE file or at
5
+ # https://developers.google.com/open-source/licenses/bsd
6
+
7
+ """Cached BigQuery client factory built on ADC credentials."""
8
+
9
+ import threading
10
+ import time
11
+
12
+ from google.cloud import bigquery
13
+
14
+ from . import credentials as _credentials
15
+
16
+ _DEFAULT_TTL_SECONDS = 30 * 60
17
+ _lock = threading.Lock()
18
+ _cache = {} # cache_key -> (client, created_at)
19
+
20
+
21
+ def get_bq_client(project=None, ttl_seconds=_DEFAULT_TTL_SECONDS):
22
+ """Return a cached :class:`google.cloud.bigquery.Client` for ``project``.
23
+
24
+ ``project`` defaults to the ADC project. Clients are cached per project
25
+ and rebuilt after ``ttl_seconds`` so refreshed credentials are picked up.
26
+ """
27
+ key = project or "__adc_default__"
28
+ now = time.time()
29
+ with _lock:
30
+ entry = _cache.get(key)
31
+ if entry is not None and (now - entry[1]) < ttl_seconds:
32
+ return entry[0]
33
+ creds, adc_project = _credentials.load_credentials()
34
+ client = bigquery.Client(project=project or adc_project, credentials=creds)
35
+ _cache[key] = (client, now)
36
+ return client
37
+
38
+
39
+ def clear_cache():
40
+ """Drop all cached clients (used by tests and on credential changes)."""
41
+ with _lock:
42
+ _cache.clear()
@@ -0,0 +1,62 @@
1
+ # Copyright 2024 Google LLC
2
+ #
3
+ # Use of this source code is governed by a BSD-style
4
+ # license that can be found in the LICENSE file or at
5
+ # https://developers.google.com/open-source/licenses/bsd
6
+
7
+ """Application Default Credentials for the BigQuery Jupyter plugin.
8
+
9
+ Authentication goes through :func:`google.auth.default`, so the plugin uses
10
+ end-user credentials on Workbench (managed EUC) and the service account
11
+ elsewhere -- without depending on gcloud or the Workbench proxy.
12
+ """
13
+
14
+ import json
15
+ import urllib.request
16
+
17
+ import google.auth
18
+ from google.auth.transport.requests import Request
19
+
20
+ CLOUD_PLATFORM_SCOPE = "https://www.googleapis.com/auth/cloud-platform"
21
+ USERINFO_EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email"
22
+ SCOPES = [CLOUD_PLATFORM_SCOPE, USERINFO_EMAIL_SCOPE]
23
+
24
+ _USERINFO_URL = "https://www.googleapis.com/oauth2/v3/userinfo"
25
+
26
+
27
+ def load_credentials():
28
+ """Return ``(credentials, adc_project)`` from Application Default Credentials."""
29
+ return google.auth.default(scopes=SCOPES)
30
+
31
+
32
+ def _principal_from_credentials(credentials):
33
+ """Best-effort resolution of the identity behind ``credentials``."""
34
+ sa_email = getattr(credentials, "service_account_email", None)
35
+ if sa_email and sa_email != "default":
36
+ return sa_email
37
+ # End-user credentials: resolve the email via the OAuth2 userinfo endpoint.
38
+ if not getattr(credentials, "valid", False):
39
+ credentials.refresh(Request())
40
+ req = urllib.request.Request(
41
+ _USERINFO_URL, headers={"Authorization": f"Bearer {credentials.token}"}
42
+ )
43
+ with urllib.request.urlopen(req, timeout=10) as resp:
44
+ return json.load(resp).get("email")
45
+
46
+
47
+ def get_identity():
48
+ """Resolve the active principal and default project.
49
+
50
+ Returns a dict with ``principal``, ``project`` and ``credential_type``.
51
+ ``principal`` is ``None`` when it cannot be resolved.
52
+ """
53
+ credentials, project = load_credentials()
54
+ try:
55
+ principal = _principal_from_credentials(credentials)
56
+ except Exception:
57
+ principal = None
58
+ return {
59
+ "principal": principal,
60
+ "project": project,
61
+ "credential_type": type(credentials).__name__,
62
+ }
@@ -0,0 +1,131 @@
1
+ # Copyright 2024 Google LLC
2
+ #
3
+ # Use of this source code is governed by a BSD-style
4
+ # license that can be found in the LICENSE file or at
5
+ # https://developers.google.com/open-source/licenses/bsd
6
+
7
+ """Table details and data preview.
8
+
9
+ ``get_table`` returns schema and metadata; ``preview_table`` returns a page of
10
+ rows via ``tabledata.list`` (``client.list_rows``), which reads stored rows
11
+ directly and incurs no query cost. Cells are serialized to JSON-friendly,
12
+ already-typed values here on the server, so the frontend renders them without
13
+ reconstructing types. All calls run under ADC / end-user credentials.
14
+ """
15
+
16
+ import base64
17
+ import datetime
18
+ import decimal
19
+
20
+ from google.cloud import bigquery
21
+
22
+ from . import bq_client as _bq_client
23
+
24
+ _DEFAULT_PREVIEW_ROWS = 100
25
+
26
+
27
+ def _schema_to_json(fields):
28
+ """Recursively serialize a sequence of ``SchemaField`` to plain dicts.
29
+
30
+ Nested ``RECORD``/``STRUCT`` fields and the ``REPEATED`` mode are preserved
31
+ so the frontend can render nested and repeated columns faithfully.
32
+ """
33
+ return [
34
+ {
35
+ "name": f.name,
36
+ "type": f.field_type,
37
+ "mode": f.mode,
38
+ "description": f.description,
39
+ "fields": _schema_to_json(f.fields) if f.fields else [],
40
+ }
41
+ for f in fields
42
+ ]
43
+
44
+
45
+ def _time_partitioning(tp, require_partition_filter=None):
46
+ if tp is None:
47
+ return None
48
+ return {
49
+ "type": tp.type_,
50
+ "field": tp.field,
51
+ "expirationMs": tp.expiration_ms,
52
+ "requirePartitionFilter": require_partition_filter,
53
+ }
54
+
55
+
56
+ def get_table(project_id, dataset_id, table_id):
57
+ """Return schema and metadata for ``project_id.dataset_id.table_id``."""
58
+ client = _bq_client.get_bq_client(project=project_id)
59
+ ref = bigquery.TableReference(
60
+ bigquery.DatasetReference(project_id, dataset_id), table_id
61
+ )
62
+ table = client.get_table(ref)
63
+ return {
64
+ "id": table.table_id,
65
+ "projectId": table.project,
66
+ "datasetId": table.dataset_id,
67
+ "type": table.table_type,
68
+ "schema": _schema_to_json(table.schema),
69
+ "numRows": table.num_rows,
70
+ "sizeBytes": table.num_bytes,
71
+ "location": table.location,
72
+ "description": table.description,
73
+ "friendlyName": table.friendly_name,
74
+ "created": table.created.isoformat() if table.created else None,
75
+ "modified": table.modified.isoformat() if table.modified else None,
76
+ "expires": table.expires.isoformat() if table.expires else None,
77
+ "timePartitioning": _time_partitioning(
78
+ table.time_partitioning, table.require_partition_filter
79
+ ),
80
+ "clusteringFields": table.clustering_fields,
81
+ "viewQuery": table.view_query,
82
+ }
83
+
84
+
85
+ def _cell(value):
86
+ """Serialize one BigQuery cell to a JSON-friendly, typed value.
87
+
88
+ Recurses into ``RECORD`` (dict) and ``REPEATED`` (list) values. Temporal,
89
+ decimal and bytes values become strings so no precision or type is lost in
90
+ transit; ``None`` is preserved so the UI can distinguish null from empty.
91
+ """
92
+ if value is None:
93
+ return None
94
+ if isinstance(value, (str, bool, int, float)):
95
+ return value
96
+ if isinstance(value, decimal.Decimal):
97
+ return str(value)
98
+ if isinstance(value, (datetime.date, datetime.datetime, datetime.time)):
99
+ return value.isoformat()
100
+ if isinstance(value, bytes):
101
+ return base64.b64encode(value).decode("ascii")
102
+ if isinstance(value, dict):
103
+ return {k: _cell(v) for k, v in value.items()}
104
+ if isinstance(value, (list, tuple)):
105
+ return [_cell(v) for v in value]
106
+ return str(value)
107
+
108
+
109
+ def preview_table(
110
+ project_id, dataset_id, table_id, max_results=_DEFAULT_PREVIEW_ROWS, start_index=0
111
+ ):
112
+ """Return one page of rows via ``tabledata.list`` (no query cost).
113
+
114
+ Returns ``{schema, rows, totalRows}`` where ``rows`` is a list of rows, each
115
+ a list of typed cells in schema order. Not valid for logical views or
116
+ models (no stored rows); the caller hides preview for those types and the
117
+ handler maps any resulting error to a clean status.
118
+ """
119
+ client = _bq_client.get_bq_client(project=project_id)
120
+ ref = bigquery.TableReference(
121
+ bigquery.DatasetReference(project_id, dataset_id), table_id
122
+ )
123
+ row_iter = client.list_rows(
124
+ ref, max_results=max_results, start_index=start_index or 0
125
+ )
126
+ rows = [[_cell(v) for v in row.values()] for row in row_iter]
127
+ return {
128
+ "schema": _schema_to_json(row_iter.schema),
129
+ "rows": rows,
130
+ "totalRows": row_iter.total_rows,
131
+ }
@@ -0,0 +1,87 @@
1
+ # Copyright 2024 Google LLC
2
+ #
3
+ # Use of this source code is governed by a BSD-style
4
+ # license that can be found in the LICENSE file or at
5
+ # https://developers.google.com/open-source/licenses/bsd
6
+
7
+ """Explorer backend: list projects, datasets and tables for the tree view.
8
+
9
+ Projects are enumerated via the Cloud Resource Manager REST API (paginated, since
10
+ an end user may have access to a very large number of projects); datasets and
11
+ tables use the BigQuery client. All calls run under ADC / end-user credentials.
12
+ """
13
+
14
+ from google.auth.transport.requests import AuthorizedSession
15
+ from google.cloud import bigquery
16
+
17
+ from . import bq_client as _bq_client
18
+ from . import credentials as _credentials
19
+
20
+ _RESOURCE_MANAGER_URL = "https://cloudresourcemanager.googleapis.com/v1/projects"
21
+ PUBLIC_PROJECT = "bigquery-public-data"
22
+ _DEFAULT_PAGE_SIZE = 100
23
+
24
+
25
+ def _authorized_session():
26
+ creds, _ = _credentials.load_credentials()
27
+ return AuthorizedSession(creds)
28
+
29
+
30
+ def list_projects(page_token=None, page_size=_DEFAULT_PAGE_SIZE):
31
+ """One page of ACTIVE projects the caller can access, with a nextPageToken."""
32
+ params = {"filter": "lifecycleState:ACTIVE", "pageSize": page_size}
33
+ if page_token:
34
+ params["pageToken"] = page_token
35
+ resp = _authorized_session().get(_RESOURCE_MANAGER_URL, params=params, timeout=30)
36
+ resp.raise_for_status()
37
+ data = resp.json()
38
+ projects = [
39
+ {"projectId": p["projectId"], "name": p.get("name", p["projectId"])}
40
+ for p in data.get("projects", [])
41
+ ]
42
+ return {"projects": projects, "nextPageToken": data.get("nextPageToken")}
43
+
44
+
45
+ def _first_page(iterator):
46
+ """Return (items, next_page_token) for the first page of an HTTPIterator."""
47
+ try:
48
+ page = next(iterator.pages)
49
+ except StopIteration:
50
+ return [], None
51
+ items = list(page)
52
+ return items, iterator.next_page_token
53
+
54
+
55
+ def list_datasets(project_id, page_token=None, page_size=_DEFAULT_PAGE_SIZE):
56
+ """One page of datasets in ``project_id``."""
57
+ client = _bq_client.get_bq_client(project=project_id)
58
+ it = client.list_datasets(
59
+ project=project_id, max_results=page_size, page_token=page_token or None
60
+ )
61
+ items, token = _first_page(it)
62
+ datasets = [
63
+ {"id": d.dataset_id, "projectId": d.project, "friendlyName": d.friendly_name}
64
+ for d in items
65
+ ]
66
+ return {"datasets": datasets, "nextPageToken": token}
67
+
68
+
69
+ def list_tables(project_id, dataset_id, page_token=None, page_size=_DEFAULT_PAGE_SIZE):
70
+ """One page of tables/views in ``project_id.dataset_id``."""
71
+ client = _bq_client.get_bq_client(project=project_id)
72
+ ref = bigquery.DatasetReference(project_id, dataset_id)
73
+ it = client.list_tables(ref, max_results=page_size, page_token=page_token or None)
74
+ items, token = _first_page(it)
75
+ # partitioned/clustered come free from the list response (TableListItem),
76
+ # so the tree can badge them without a per-table get_table call. Note: only
77
+ # time partitioning is exposed here; range-partitioned tables aren't flagged.
78
+ tables = [
79
+ {
80
+ "id": t.table_id,
81
+ "type": t.table_type,
82
+ "partitioned": bool(t.time_partitioning or t.partitioning_type),
83
+ "clustered": bool(t.clustering_fields),
84
+ }
85
+ for t in items
86
+ ]
87
+ return {"tables": tables, "nextPageToken": token}