├── version.py ├── setup.py ├── README.md ├── test_helper.py ├── bq_helper.py └── LICENSE /version.py: -------------------------------------------------------------------------------- 1 | __version__ = '0.4.1' 2 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | from version import __version__ as version 3 | 4 | 5 | setup(name='bq_helper', 6 | version=version, 7 | description='Helper class to simplify common read-only BigQuery tasks.', 8 | author='Sohier Dane', 9 | url='https://github.com/SohierDane/BigQuery_Helper', 10 | license='Apache 2.0', 11 | install_requires=['pandas', 'google-cloud-bigquery'], 12 | classifiers=['Programming Language :: Python :: 3'], 13 | ) 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This library was intended to address limitations of the core tool that have since been resolved. We now recommend that you use the [google-cloud-bigquery](https://cloud.google.com/python/docs/reference/bigquery/latest) instead. 2 | 3 | 4 | ## Summary 5 | 6 | BigQuery_Helper is a helper class to simplify common read-only BigQuery tasks. It makes it easy to execute queries while you're learning SQL, and provides a convenient stepping stone on the path to using [the core BigQuery python API](https://googlecloudplatform.github.io/google-cloud-python/latest/bigquery/reference.html). You can try it for yourself by forking [this Kaggle kernel](https://www.kaggle.com/sohier/introduction-to-the-bq-helper-package/). 7 | 8 | ## Installation 9 | You can install BigQuery_Helper with the following command in your console: 10 | 11 | 12 | `pip install -e git+https://github.com/SohierDane/BigQuery_Helper#egg=bq_helper` 13 | 14 | If you aren't running BigQuery_Helper on [Kaggle](http://kaggle.com/), you will also need to go through the [standard BigQuery client setup and authentication process](https://cloud.google.com/bigquery/docs/reference/libraries). 15 | 16 | This repo has only been tested on Python 3.6+ and the v0.29+ of the bigquery API. 17 | 18 | ## Changelog 19 | #### 0.4.0: 20 | - `BigQueryHelper.table_schema` has been overhauled. It now returns a Pandas DataFrame and unrolls nested fields so that the results are in the format expected by queries. For example, the `github_repos.commits` nested field `author` now returns sub-fields names in the format like `author.email`. 21 | 22 | #### 0.3.0: 23 | - Each helper instance now logs the total bytes counted towards your quota or bill used across all queries run with that helper instance. You can access it with `BigQueryHelper.total_gb_used_net_cache`. Repeated queries are likely to hit the cache and may show up as 0 GB used. 24 | - Queries that take longer than the maximum wait time, which defaults to 3 minutes, will be cancelled. 25 | - Contributing to bq_helper should be easier now that there is a set of tests. 26 | 27 | #### 0.2.0: 28 | - `query_to_pandas` now returns an empty DataFrame when the query returns no results. Previously, this returned `None`. 29 | -------------------------------------------------------------------------------- /test_helper.py: -------------------------------------------------------------------------------- 1 | """ 2 | Tests all public methods of the BigQueryHelper class. 3 | 4 | Run from command line with: 5 | python -m unittest test_helper.py 6 | 7 | 8 | BILLING WARNING: 9 | Running these tests requires a working BigQuery account and MAY CAUSE CHARGES. 10 | However the dataset used for the tests is only ~2 MB, so any charges should 11 | be very minimal. The downside is that this particular dataset is completely 12 | refreshed every hour, so it's not possible to check for any specific return values. 13 | 14 | For details on the test dataset, please see: 15 | https://bigquery.cloud.google.com/table/bigquery-public-data:openaq.global_air_quality?tab=details 16 | """ 17 | 18 | 19 | import unittest 20 | 21 | 22 | from bq_helper import BigQueryHelper 23 | from google.api_core.exceptions import BadRequest 24 | from pandas.core.frame import DataFrame 25 | from random import random 26 | 27 | 28 | class TestBQHelper(unittest.TestCase): 29 | def setUp(self): 30 | self.my_bq = BigQueryHelper("bigquery-public-data", "openaq") 31 | self.query = "SELECT location FROM `bigquery-public-data.openaq.global_air_quality`" 32 | # Query randomized so it won't hit the cache across multiple test runs 33 | self.randomizable_query = """ 34 | SELECT value FROM `bigquery-public-data.openaq.global_air_quality` 35 | WHERE value = {0}""" 36 | 37 | def test_list_tables(self): 38 | self.assertEqual(self.my_bq.list_tables(), ['global_air_quality']) 39 | 40 | def test_list_schema(self): 41 | self.assertEqual(len(self.my_bq.table_schema('global_air_quality')), 11) 42 | 43 | def test_estimate_query_size(self): 44 | self.assertIsInstance(self.my_bq.estimate_query_size(self.query), float) 45 | 46 | def test_query_to_pandas(self): 47 | self.assertIsInstance(self.my_bq.query_to_pandas(self.query), DataFrame) 48 | 49 | def test_query_safe_passes(self): 50 | self.assertIsInstance(self.my_bq.query_to_pandas_safe(self.query), DataFrame) 51 | 52 | def test_query_safe_fails(self): 53 | # Different query must be used for this test to ensure we don't hit the 54 | # cache and end up passing by testing a query that would use zero bytes. 55 | fail_query = self.randomizable_query.format(random()) 56 | self.assertIsNone(self.my_bq.query_to_pandas_safe(fail_query, 10**-10)) 57 | 58 | def test_head(self): 59 | self.assertIsInstance(self.my_bq.head('global_air_quality'), DataFrame) 60 | 61 | def test_useage_tracker(self): 62 | self.my_bq.query_to_pandas(self.randomizable_query.format(random())) 63 | self.assertNotEqual(self.my_bq.total_gb_used_net_cache, 0) 64 | 65 | def test_bad_query_raises_right_error(self): 66 | with self.assertRaises(BadRequest): 67 | self.my_bq.query_to_pandas("Not a valid query") 68 | 69 | def test_list_nested_schema(self): 70 | nested_helper = BigQueryHelper("bigquery-public-data", "github_repos") 71 | self.assertEqual(len(nested_helper.table_schema('commits')), 33) 72 | 73 | 74 | if __name__ == '__main__': 75 | unittest.main() 76 | -------------------------------------------------------------------------------- /bq_helper.py: -------------------------------------------------------------------------------- 1 | """ 2 | Helper class to simplify common read-only BigQuery tasks. 3 | """ 4 | 5 | 6 | import pandas as pd 7 | import time 8 | 9 | from google.cloud import bigquery 10 | 11 | 12 | class BigQueryHelper(object): 13 | """ 14 | Helper class to simplify common BigQuery tasks like executing queries, 15 | showing table schemas, etc without worrying about table or dataset pointers. 16 | 17 | See the BigQuery docs for details of the steps this class lets you skip: 18 | https://googlecloudplatform.github.io/google-cloud-python/latest/bigquery/reference.html 19 | """ 20 | 21 | def __init__(self, active_project, dataset_name, max_wait_seconds=180): 22 | self.project_name = active_project 23 | self.dataset_name = dataset_name 24 | self.max_wait_seconds = max_wait_seconds 25 | self.client = bigquery.Client() 26 | self.__dataset_ref = self.client.dataset(self.dataset_name, project=self.project_name) 27 | self.dataset = None 28 | self.tables = dict() # {table name (str): table object} 29 | self.__table_refs = dict() # {table name (str): table reference} 30 | self.total_gb_used_net_cache = 0 31 | self.BYTES_PER_GB = 2**30 32 | 33 | def __fetch_dataset(self): 34 | """ 35 | Lazy loading of dataset. For example, 36 | if the user only calls `self.query_to_pandas` then the 37 | dataset never has to be fetched. 38 | """ 39 | if self.dataset is None: 40 | self.dataset = self.client.get_dataset(self.__dataset_ref) 41 | 42 | def __fetch_table(self, table_name): 43 | """ 44 | Lazy loading of table 45 | """ 46 | self.__fetch_dataset() 47 | if table_name not in self.__table_refs: 48 | self.__table_refs[table_name] = self.dataset.table(table_name) 49 | if table_name not in self.tables: 50 | self.tables[table_name] = self.client.get_table(self.__table_refs[table_name]) 51 | 52 | def __handle_record_field(self, row, schema_details, top_level_name=''): 53 | """ 54 | Unpack a single row, including any nested fields. 55 | """ 56 | name = row['name'] 57 | if top_level_name != '': 58 | name = top_level_name + '.' + name 59 | schema_details.append([{ 60 | 'name': name, 61 | 'type': row['type'], 62 | 'mode': row['mode'], 63 | 'fields': pd.np.nan, 64 | 'description': row['description'] 65 | }]) 66 | # float check is to dodge row['fields'] == np.nan 67 | if type(row.get('fields', 0.0)) == float: 68 | return None 69 | for entry in row['fields']: 70 | self.__handle_record_field(entry, schema_details, name) 71 | 72 | def __unpack_all_schema_fields(self, schema): 73 | """ 74 | Unrolls nested schemas. Returns dataframe with one row per field, 75 | and the field names in the format accepted by the API. 76 | Results will look similar to the website schema, such as: 77 | https://bigquery.cloud.google.com/table/bigquery-public-data:github_repos.commits?pli=1 78 | 79 | Args: 80 | schema: DataFrame derived from api repr of raw table.schema 81 | Returns: 82 | Dataframe of the unrolled schema. 83 | """ 84 | schema_details = [] 85 | schema.apply(lambda row: 86 | self.__handle_record_field(row, schema_details), axis=1) 87 | result = pd.concat([pd.DataFrame.from_dict(x) for x in schema_details]) 88 | result.reset_index(drop=True, inplace=True) 89 | del result['fields'] 90 | return result 91 | 92 | def table_schema(self, table_name): 93 | """ 94 | Get the schema for a specific table from a dataset. 95 | Unrolls nested field names into the format that can be copied 96 | directly into queries. For example, for the `github.commits` table, 97 | the this will return `committer.name`. 98 | 99 | This is a very different return signature than BigQuery's table.schema. 100 | """ 101 | self.__fetch_table(table_name) 102 | raw_schema = self.tables[table_name].schema 103 | schema = pd.DataFrame.from_dict([x.to_api_repr() for x in raw_schema]) 104 | # the api_repr only has the fields column for tables with nested data 105 | if 'fields' in schema.columns: 106 | schema = self.__unpack_all_schema_fields(schema) 107 | # Set the column order 108 | schema = schema[['name', 'type', 'mode', 'description']] 109 | return schema 110 | 111 | def list_tables(self): 112 | """ 113 | List the names of the tables in a dataset 114 | """ 115 | self.__fetch_dataset() 116 | return([x.table_id for x in self.client.list_tables(self.dataset)]) 117 | 118 | def estimate_query_size(self, query): 119 | """ 120 | Estimate gigabytes scanned by query. 121 | Does not consider if there is a cached query table. 122 | See https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.dryRun 123 | """ 124 | my_job_config = bigquery.job.QueryJobConfig() 125 | my_job_config.dry_run = True 126 | my_job = self.client.query(query, job_config=my_job_config) 127 | return my_job.total_bytes_processed / self.BYTES_PER_GB 128 | 129 | def query_to_pandas(self, query): 130 | """ 131 | Execute a SQL query & return a pandas dataframe 132 | """ 133 | my_job = self.client.query(query) 134 | start_time = time.time() 135 | while not my_job.done(): 136 | if (time.time() - start_time) > self.max_wait_seconds: 137 | print("Max wait time elapsed, query cancelled.") 138 | self.client.cancel_job(my_job.job_id) 139 | return None 140 | time.sleep(0.1) 141 | # Queries that hit errors will return an exception type. 142 | # Those exceptions don't get raised until we call my_job.to_dataframe() 143 | # In that case, my_job.total_bytes_billed can be called but is None 144 | if my_job.total_bytes_billed: 145 | self.total_gb_used_net_cache += my_job.total_bytes_billed / self.BYTES_PER_GB 146 | return my_job.to_dataframe() 147 | 148 | def query_to_pandas_safe(self, query, max_gb_scanned=1): 149 | """ 150 | Execute a query, but only if the query would scan less than `max_gb_scanned` of data. 151 | """ 152 | query_size = self.estimate_query_size(query) 153 | if query_size <= max_gb_scanned: 154 | return self.query_to_pandas(query) 155 | msg = "Query cancelled; estimated size of {0} exceeds limit of {1} GB" 156 | print(msg.format(query_size, max_gb_scanned)) 157 | 158 | def head(self, table_name, num_rows=5, start_index=None, selected_columns=None): 159 | """ 160 | Get the first n rows of a table as a DataFrame. 161 | Does not perform a full table scan; should use a trivial amount of data as long as n is small. 162 | """ 163 | self.__fetch_table(table_name) 164 | active_table = self.tables[table_name] 165 | schema_subset = None 166 | if selected_columns: 167 | schema_subset = [col for col in active_table.schema if col.name in selected_columns] 168 | results = self.client.list_rows(active_table, selected_fields=schema_subset, 169 | max_results=num_rows, start_index=start_index) 170 | results = [x for x in results] 171 | return pd.DataFrame( 172 | data=[list(x.values()) for x in results], columns=list(results[0].keys())) 173 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------