You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

311 lines
9.6 KiB

  1. // Copyright 2015 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /*
  15. Package bigquery provides a client for the BigQuery service.
  16. Note: This package is in beta. Some backwards-incompatible changes may occur.
  17. The following assumes a basic familiarity with BigQuery concepts.
  18. See https://cloud.google.com/bigquery/docs.
  19. See https://godoc.org/cloud.google.com/go for authentication, timeouts,
  20. connection pooling and similar aspects of this package.
  21. Creating a Client
  22. To start working with this package, create a client:
  23. ctx := context.Background()
  24. client, err := bigquery.NewClient(ctx, projectID)
  25. if err != nil {
  26. // TODO: Handle error.
  27. }
  28. Querying
  29. To query existing tables, create a Query and call its Read method:
  30. q := client.Query(`
  31. SELECT year, SUM(number) as num
  32. FROM ` + "`bigquery-public-data.usa_names.usa_1910_2013`" + `
  33. WHERE name = "William"
  34. GROUP BY year
  35. ORDER BY year
  36. `)
  37. it, err := q.Read(ctx)
  38. if err != nil {
  39. // TODO: Handle error.
  40. }
  41. Then iterate through the resulting rows. You can store a row using
  42. anything that implements the ValueLoader interface, or with a slice or map of bigquery.Value.
  43. A slice is simplest:
  44. for {
  45. var values []bigquery.Value
  46. err := it.Next(&values)
  47. if err == iterator.Done {
  48. break
  49. }
  50. if err != nil {
  51. // TODO: Handle error.
  52. }
  53. fmt.Println(values)
  54. }
  55. You can also use a struct whose exported fields match the query:
  56. type Count struct {
  57. Year int
  58. Num int
  59. }
  60. for {
  61. var c Count
  62. err := it.Next(&c)
  63. if err == iterator.Done {
  64. break
  65. }
  66. if err != nil {
  67. // TODO: Handle error.
  68. }
  69. fmt.Println(c)
  70. }
  71. You can also start the query running and get the results later.
  72. Create the query as above, but call Run instead of Read. This returns a Job,
  73. which represents an asynchronous operation.
  74. job, err := q.Run(ctx)
  75. if err != nil {
  76. // TODO: Handle error.
  77. }
  78. Get the job's ID, a printable string. You can save this string to retrieve
  79. the results at a later time, even in another process.
  80. jobID := job.ID()
  81. fmt.Printf("The job ID is %s\n", jobID)
  82. To retrieve the job's results from the ID, first look up the Job:
  83. job, err = client.JobFromID(ctx, jobID)
  84. if err != nil {
  85. // TODO: Handle error.
  86. }
  87. Use the Job.Read method to obtain an iterator, and loop over the rows.
  88. Query.Read is just a convenience method that combines Query.Run and Job.Read.
  89. it, err = job.Read(ctx)
  90. if err != nil {
  91. // TODO: Handle error.
  92. }
  93. // Proceed with iteration as above.
  94. Datasets and Tables
  95. You can refer to datasets in the client's project with the Dataset method, and
  96. in other projects with the DatasetInProject method:
  97. myDataset := client.Dataset("my_dataset")
  98. yourDataset := client.DatasetInProject("your-project-id", "your_dataset")
  99. These methods create references to datasets, not the datasets themselves. You can have
  100. a dataset reference even if the dataset doesn't exist yet. Use Dataset.Create to
  101. create a dataset from a reference:
  102. if err := myDataset.Create(ctx, nil); err != nil {
  103. // TODO: Handle error.
  104. }
  105. You can refer to tables with Dataset.Table. Like bigquery.Dataset, bigquery.Table is a reference
  106. to an object in BigQuery that may or may not exist.
  107. table := myDataset.Table("my_table")
  108. You can create, delete and update the metadata of tables with methods on Table.
  109. For instance, you could create a temporary table with:
  110. err = myDataset.Table("temp").Create(ctx, &bigquery.TableMetadata{
  111. ExpirationTime: time.Now().Add(1*time.Hour)})
  112. if err != nil {
  113. // TODO: Handle error.
  114. }
  115. We'll see how to create a table with a schema in the next section.
  116. Schemas
  117. There are two ways to construct schemas with this package.
  118. You can build a schema by hand, like so:
  119. schema1 := bigquery.Schema{
  120. {Name: "Name", Required: true, Type: bigquery.StringFieldType},
  121. {Name: "Grades", Repeated: true, Type: bigquery.IntegerFieldType},
  122. {Name: "Optional", Required: false, Type: bigquery.IntegerFieldType},
  123. }
  124. Or you can infer the schema from a struct:
  125. type student struct {
  126. Name string
  127. Grades []int
  128. Optional bigquery.NullInt64
  129. }
  130. schema2, err := bigquery.InferSchema(student{})
  131. if err != nil {
  132. // TODO: Handle error.
  133. }
  134. // schema1 and schema2 are identical.
  135. Struct inference supports tags like those of the encoding/json package, so you can
  136. change names, ignore fields, or mark a field as nullable (non-required). Fields
  137. declared as one of the Null types (NullInt64, NullFloat64, NullString, NullBool,
  138. NullTimestamp, NullDate, NullTime, NullDateTime, and NullGeography) are
  139. automatically inferred as nullable, so the "nullable" tag is only needed for []byte,
  140. *big.Rat and pointer-to-struct fields.
  141. type student2 struct {
  142. Name string `bigquery:"full_name"`
  143. Grades []int
  144. Secret string `bigquery:"-"`
  145. Optional []byte `bigquery:",nullable"
  146. }
  147. schema3, err := bigquery.InferSchema(student2{})
  148. if err != nil {
  149. // TODO: Handle error.
  150. }
  151. // schema3 has required fields "full_name" and "Grade", and nullable BYTES field "Optional".
  152. Having constructed a schema, you can create a table with it like so:
  153. if err := table.Create(ctx, &bigquery.TableMetadata{Schema: schema1}); err != nil {
  154. // TODO: Handle error.
  155. }
  156. Copying
  157. You can copy one or more tables to another table. Begin by constructing a Copier
  158. describing the copy. Then set any desired copy options, and finally call Run to get a Job:
  159. copier := myDataset.Table("dest").CopierFrom(myDataset.Table("src"))
  160. copier.WriteDisposition = bigquery.WriteTruncate
  161. job, err = copier.Run(ctx)
  162. if err != nil {
  163. // TODO: Handle error.
  164. }
  165. You can chain the call to Run if you don't want to set options:
  166. job, err = myDataset.Table("dest").CopierFrom(myDataset.Table("src")).Run(ctx)
  167. if err != nil {
  168. // TODO: Handle error.
  169. }
  170. You can wait for your job to complete:
  171. status, err := job.Wait(ctx)
  172. if err != nil {
  173. // TODO: Handle error.
  174. }
  175. Job.Wait polls with exponential backoff. You can also poll yourself, if you
  176. wish:
  177. for {
  178. status, err := job.Status(ctx)
  179. if err != nil {
  180. // TODO: Handle error.
  181. }
  182. if status.Done() {
  183. if status.Err() != nil {
  184. log.Fatalf("Job failed with error %v", status.Err())
  185. }
  186. break
  187. }
  188. time.Sleep(pollInterval)
  189. }
  190. Loading and Uploading
  191. There are two ways to populate a table with this package: load the data from a Google Cloud Storage
  192. object, or upload rows directly from your program.
  193. For loading, first create a GCSReference, configuring it if desired. Then make a Loader, optionally configure
  194. it as well, and call its Run method.
  195. gcsRef := bigquery.NewGCSReference("gs://my-bucket/my-object")
  196. gcsRef.AllowJaggedRows = true
  197. loader := myDataset.Table("dest").LoaderFrom(gcsRef)
  198. loader.CreateDisposition = bigquery.CreateNever
  199. job, err = loader.Run(ctx)
  200. // Poll the job for completion if desired, as above.
  201. To upload, first define a type that implements the ValueSaver interface, which has a single method named Save.
  202. Then create an Uploader, and call its Put method with a slice of values.
  203. u := table.Uploader()
  204. // Item implements the ValueSaver interface.
  205. items := []*Item{
  206. {Name: "n1", Size: 32.6, Count: 7},
  207. {Name: "n2", Size: 4, Count: 2},
  208. {Name: "n3", Size: 101.5, Count: 1},
  209. }
  210. if err := u.Put(ctx, items); err != nil {
  211. // TODO: Handle error.
  212. }
  213. You can also upload a struct that doesn't implement ValueSaver. Use the StructSaver type
  214. to specify the schema and insert ID by hand, or just supply the struct or struct pointer
  215. directly and the schema will be inferred:
  216. type Item2 struct {
  217. Name string
  218. Size float64
  219. Count int
  220. }
  221. // Item implements the ValueSaver interface.
  222. items2 := []*Item2{
  223. {Name: "n1", Size: 32.6, Count: 7},
  224. {Name: "n2", Size: 4, Count: 2},
  225. {Name: "n3", Size: 101.5, Count: 1},
  226. }
  227. if err := u.Put(ctx, items2); err != nil {
  228. // TODO: Handle error.
  229. }
  230. Extracting
  231. If you've been following so far, extracting data from a BigQuery table
  232. into a Google Cloud Storage object will feel familiar. First create an
  233. Extractor, then optionally configure it, and lastly call its Run method.
  234. extractor := table.ExtractorTo(gcsRef)
  235. extractor.DisableHeader = true
  236. job, err = extractor.Run(ctx)
  237. // Poll the job for completion if desired, as above.
  238. Errors
  239. Errors returned by this client are often of the type [`googleapi.Error`](https://godoc.org/google.golang.org/api/googleapi#Error).
  240. These errors can be introspected for more information by type asserting to the richer `googleapi.Error` type. For example:
  241. if e, ok := err.(*googleapi.Error); ok {
  242. if e.Code = 409 { ... }
  243. }
  244. */
  245. package bigquery // import "cloud.google.com/go/bigquery"