Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
29 changes: 27 additions & 2 deletions server/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,12 @@ func (h *uploadHandler) serveMultipart(w http.ResponseWriter, r *http.Request) {
uploadErrorResponse(ctx, w, err)
return
}
encodeResponse(ctx, w, uploadJob.Content())
content := uploadJob.Content()
// jobs.insert returns a Job whose output-only status is always populated,
// as the resumable upload path below already does. Without it, clients
// (e.g. google-cloud-bigquery's LoadJob) see no state and re-submit the job.
content.Status = &bigqueryv2.JobStatus{State: "DONE"}
encodeResponse(ctx, w, content)
}

func (h *uploadHandler) serveResumable(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -1990,10 +1995,30 @@ func deleteTableMetadata(ctx context.Context, server *Server, spec *googlesqlite
// addQueryResultToDynamicDestinationTable materializes the result of a query
// that had no explicit destination into an anonymous results table (named
// after the job id) and returns a reference to it.
// anonymousDatasetID names the hidden dataset that holds a query's anonymous
// result table. BigQuery dataset ids may only contain letters, digits and
// underscores (real BigQuery uses "_<hash>"), whereas job ids may also contain
// '-', e.g. the UUIDs generated by the Python client. Clients such as ibis
// have to quote an id with '-' in SQL and then pass the quoted form to
// tables.get, which cannot find it.
func anonymousDatasetID(jobID string) string {
var b strings.Builder
b.WriteByte('_')
for _, r := range jobID {
switch {
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '_':
b.WriteRune(r)
default:
b.WriteByte('_')
}
}
return b.String()
}

func (h *jobsInsertHandler) addQueryResultToDynamicDestinationTable(ctx context.Context, tx *connection.Tx, r *jobsInsertRequest, response *internaltypes.QueryResponse) (*bigqueryv2.TableReference, error) {
projectID := r.project.ID
jobID := r.job.JobReference.JobId
datasetID := jobID
datasetID := anonymousDatasetID(jobID)
tableID := jobID

tableDef, err := h.tableDefFromQueryResponse(tableID, response)
Expand Down
13 changes: 13 additions & 0 deletions server/handler_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,16 @@ func TestQueryProjectAndDataset(t *testing.T) {
})
}
}

func TestAnonymousDatasetID(t *testing.T) {
tests := map[string]string{
"job_123": "_job_123",
"3f2c1d9e-8a4b-4c1f-9d7e-0b6a5c4d3e2f": "_3f2c1d9e_8a4b_4c1f_9d7e_0b6a5c4d3e2f",
"Mixed-Case_9": "_Mixed_Case_9",
}
for jobID, want := range tests {
if got := anonymousDatasetID(jobID); got != want {
t.Errorf("anonymousDatasetID(%q) = %q, want %q", jobID, got, want)
}
}
}
86 changes: 86 additions & 0 deletions server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4797,3 +4797,89 @@ func TestExportDataStatement(t *testing.T) {
}
})
}

// TestUploadMultipartReportsJobStatus: jobs.insert returns a Job whose output-only
// status is always populated. Clients such as google-cloud-bigquery's LoadJob treat
// a missing status as "not started yet" and re-submit the job through the plain
// jobs.insert endpoint, which does not support media uploads.
func TestUploadMultipartReportsJobStatus(t *testing.T) {
ctx := context.Background()
bqServer, err := server.New(server.TempStorage)
if err != nil {
t.Fatal(err)
}
if err := bqServer.Load(server.StructSource(
types.NewProject("test", types.NewDataset("dataset1")),
)); err != nil {
t.Fatal(err)
}
testServer := bqServer.TestServer()
defer func() {
testServer.Close()
bqServer.Stop(ctx)
}()

jobJSON := `{"jobReference":{"projectId":"test","jobId":"upload-job"},` +
`"configuration":{"load":{"sourceFormat":"CSV","autodetect":true,` +
`"destinationTable":{"projectId":"test","datasetId":"dataset1","tableId":"uploaded"}}}}`
contentType, body := multipartUpload(jobJSON, "x,y\r\n1,a\r\n2,b")
code, resp := httpJSON(t, http.MethodPost,
testServer.URL+"/upload/bigquery/v2/projects/test/jobs?uploadType=multipart",
body, map[string]string{"Content-Type": contentType})
if code != http.StatusOK {
t.Fatalf("multipart upload: expected 200, got %d (%v)", code, resp)
}
status, _ := resp["status"].(map[string]any)
if state, _ := status["state"].(string); state != "DONE" {
t.Fatalf("multipart upload: expected status.state DONE, got %v", resp["status"])
}
}

// TestAnonymousQueryDatasetIDIsValid: a query without a destination stores its
// result in a hidden dataset. Its id must satisfy BigQuery's dataset-id rule
// (letters, digits, underscores) even when the job id has '-' (Python clients
// use UUIDs), otherwise clients that quote the id (e.g. ibis) cannot look up
// tables the query created in it.
func TestAnonymousQueryDatasetIDIsValid(t *testing.T) {
ctx := context.Background()
bqServer, err := server.New(server.TempStorage)
if err != nil {
t.Fatal(err)
}
if err := bqServer.Load(server.StructSource(types.NewProject("test"))); err != nil {
t.Fatal(err)
}
testServer := bqServer.TestServer()
defer func() {
testServer.Close()
bqServer.Stop(ctx)
}()

code, resp := httpJSON(t, http.MethodPost,
testServer.URL+"/projects/test/jobs",
`{"jobReference":{"projectId":"test","jobId":"3f2c1d9e-8a4b-4c1f-9d7e-0b6a5c4d3e2f"},`+
`"configuration":{"query":{"query":"SELECT 1 AS x","useLegacySql":false}}}`, nil)
if code != http.StatusOK {
t.Fatalf("jobs.insert: %d (%v)", code, resp)
}
configuration, _ := resp["configuration"].(map[string]any)
query, _ := configuration["query"].(map[string]any)
destination, _ := query["destinationTable"].(map[string]any)
datasetID, _ := destination["datasetId"].(string)
tableID, _ := destination["tableId"].(string)
if datasetID == "" || tableID == "" {
t.Fatalf("expected an anonymous destinationTable, got %v", query["destinationTable"])
}
for _, r := range datasetID {
valid := r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '_'
if !valid {
t.Fatalf("anonymous dataset id %q is not a valid BigQuery dataset id", datasetID)
}
}

code, resp = httpJSON(t, http.MethodGet,
testServer.URL+"/projects/test/datasets/"+datasetID+"/tables/"+tableID, "", nil)
if code != http.StatusOK {
t.Fatalf("tables.get on the anonymous table: %d (%v)", code, resp)
}
}