big_query_utils.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. #!/usr/bin/env python2.7
  2. import argparse
  3. import json
  4. import uuid
  5. import httplib2
  6. from apiclient import discovery
  7. from apiclient.errors import HttpError
  8. from oauth2client.client import GoogleCredentials
  9. # 30 days in milliseconds
  10. _EXPIRATION_MS = 30 * 24 * 60 * 60 * 1000
  11. NUM_RETRIES = 3
  12. def create_big_query():
  13. """Authenticates with cloud platform and gets a BiqQuery service object
  14. """
  15. creds = GoogleCredentials.get_application_default()
  16. return discovery.build(
  17. 'bigquery', 'v2', credentials=creds, cache_discovery=False)
  18. def create_dataset(biq_query, project_id, dataset_id):
  19. is_success = True
  20. body = {
  21. 'datasetReference': {
  22. 'projectId': project_id,
  23. 'datasetId': dataset_id
  24. }
  25. }
  26. try:
  27. dataset_req = biq_query.datasets().insert(
  28. projectId=project_id, body=body)
  29. dataset_req.execute(num_retries=NUM_RETRIES)
  30. except HttpError as http_error:
  31. if http_error.resp.status == 409:
  32. print 'Warning: The dataset %s already exists' % dataset_id
  33. else:
  34. # Note: For more debugging info, print "http_error.content"
  35. print 'Error in creating dataset: %s. Err: %s' % (dataset_id,
  36. http_error)
  37. is_success = False
  38. return is_success
  39. def create_table(big_query, project_id, dataset_id, table_id, table_schema,
  40. description):
  41. fields = [{
  42. 'name': field_name,
  43. 'type': field_type,
  44. 'description': field_description
  45. } for (field_name, field_type, field_description) in table_schema]
  46. return create_table2(big_query, project_id, dataset_id, table_id, fields,
  47. description)
  48. def create_partitioned_table(big_query,
  49. project_id,
  50. dataset_id,
  51. table_id,
  52. table_schema,
  53. description,
  54. partition_type='DAY',
  55. expiration_ms=_EXPIRATION_MS):
  56. """Creates a partitioned table. By default, a date-paritioned table is created with
  57. each partition lasting 30 days after it was last modified.
  58. """
  59. fields = [{
  60. 'name': field_name,
  61. 'type': field_type,
  62. 'description': field_description
  63. } for (field_name, field_type, field_description) in table_schema]
  64. return create_table2(big_query, project_id, dataset_id, table_id, fields,
  65. description, partition_type, expiration_ms)
  66. def create_table2(big_query,
  67. project_id,
  68. dataset_id,
  69. table_id,
  70. fields_schema,
  71. description,
  72. partition_type=None,
  73. expiration_ms=None):
  74. is_success = True
  75. body = {
  76. 'description': description,
  77. 'schema': {
  78. 'fields': fields_schema
  79. },
  80. 'tableReference': {
  81. 'datasetId': dataset_id,
  82. 'projectId': project_id,
  83. 'tableId': table_id
  84. }
  85. }
  86. if partition_type and expiration_ms:
  87. body["timePartitioning"] = {
  88. "type": partition_type,
  89. "expirationMs": expiration_ms
  90. }
  91. try:
  92. table_req = big_query.tables().insert(
  93. projectId=project_id, datasetId=dataset_id, body=body)
  94. res = table_req.execute(num_retries=NUM_RETRIES)
  95. print 'Successfully created %s "%s"' % (res['kind'], res['id'])
  96. except HttpError as http_error:
  97. if http_error.resp.status == 409:
  98. print 'Warning: Table %s already exists' % table_id
  99. else:
  100. print 'Error in creating table: %s. Err: %s' % (table_id,
  101. http_error)
  102. is_success = False
  103. return is_success
  104. def patch_table(big_query, project_id, dataset_id, table_id, fields_schema):
  105. is_success = True
  106. body = {
  107. 'schema': {
  108. 'fields': fields_schema
  109. },
  110. 'tableReference': {
  111. 'datasetId': dataset_id,
  112. 'projectId': project_id,
  113. 'tableId': table_id
  114. }
  115. }
  116. try:
  117. table_req = big_query.tables().patch(
  118. projectId=project_id,
  119. datasetId=dataset_id,
  120. tableId=table_id,
  121. body=body)
  122. res = table_req.execute(num_retries=NUM_RETRIES)
  123. print 'Successfully patched %s "%s"' % (res['kind'], res['id'])
  124. except HttpError as http_error:
  125. print 'Error in creating table: %s. Err: %s' % (table_id, http_error)
  126. is_success = False
  127. return is_success
  128. def insert_rows(big_query, project_id, dataset_id, table_id, rows_list):
  129. is_success = True
  130. body = {'rows': rows_list}
  131. try:
  132. insert_req = big_query.tabledata().insertAll(
  133. projectId=project_id,
  134. datasetId=dataset_id,
  135. tableId=table_id,
  136. body=body)
  137. res = insert_req.execute(num_retries=NUM_RETRIES)
  138. if res.get('insertErrors', None):
  139. print 'Error inserting rows! Response: %s' % res
  140. is_success = False
  141. except HttpError as http_error:
  142. print 'Error inserting rows to the table %s' % table_id
  143. is_success = False
  144. return is_success
  145. def sync_query_job(big_query, project_id, query, timeout=5000):
  146. query_data = {'query': query, 'timeoutMs': timeout}
  147. query_job = None
  148. try:
  149. query_job = big_query.jobs().query(
  150. projectId=project_id,
  151. body=query_data).execute(num_retries=NUM_RETRIES)
  152. except HttpError as http_error:
  153. print 'Query execute job failed with error: %s' % http_error
  154. print http_error.content
  155. return query_job
  156. # List of (column name, column type, description) tuples
  157. def make_row(unique_row_id, row_values_dict):
  158. """row_values_dict is a dictionary of column name and column value.
  159. """
  160. return {'insertId': unique_row_id, 'json': row_values_dict}