1// Copyright 2018 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
15package spanner
16
17import (
18	"context"
19
20	"cloud.google.com/go/internal/trace"
21	"github.com/googleapis/gax-go/v2"
22	sppb "google.golang.org/genproto/googleapis/spanner/v1"
23	"google.golang.org/grpc/codes"
24)
25
26// PartitionedUpdate executes a DML statement in parallel across the database,
27// using separate, internal transactions that commit independently. The DML
28// statement must be fully partitionable: it must be expressible as the union
29// of many statements each of which accesses only a single row of the table. The
30// statement should also be idempotent, because it may be applied more than once.
31//
32// PartitionedUpdate returns an estimated count of the number of rows affected.
33// The actual number of affected rows may be greater than the estimate.
34func (c *Client) PartitionedUpdate(ctx context.Context, statement Statement) (count int64, err error) {
35	ctx = trace.StartSpan(ctx, "cloud.google.com/go/spanner.PartitionedUpdate")
36	defer func() { trace.EndSpan(ctx, err) }()
37	if err := checkNestedTxn(ctx); err != nil {
38		return 0, err
39	}
40	var (
41		s  *session
42		sh *sessionHandle
43	)
44	// Create session.
45	s, err = c.sc.createSession(ctx)
46	if err != nil {
47		return 0, toSpannerError(err)
48	}
49	// Delete the session at the end of the request. If the PDML statement
50	// timed out or was cancelled, the DeleteSession request might not succeed,
51	// but the session will eventually be garbage collected by the server.
52	defer s.delete(ctx)
53	sh = &sessionHandle{session: s}
54	// Create the parameters and the SQL request, but without a transaction.
55	// The transaction reference will be added by the executePdml method.
56	params, paramTypes, err := statement.convertParams()
57	if err != nil {
58		return 0, toSpannerError(err)
59	}
60	req := &sppb.ExecuteSqlRequest{
61		Session:    sh.getID(),
62		Sql:        statement.SQL,
63		Params:     params,
64		ParamTypes: paramTypes,
65	}
66
67	// Make a retryer for Aborted errors.
68	// TODO: use generic Aborted retryer when merged with master
69	retryer := gax.OnCodes([]codes.Code{codes.Aborted}, DefaultRetryBackoff)
70	// Execute the PDML and retry if the transaction is aborted.
71	executePdmlWithRetry := func(ctx context.Context) (int64, error) {
72		for {
73			count, err := executePdml(ctx, sh, req)
74			if err == nil {
75				return count, nil
76			}
77			delay, shouldRetry := retryer.Retry(err)
78			if !shouldRetry {
79				return 0, err
80			}
81			if err := gax.Sleep(ctx, delay); err != nil {
82				return 0, err
83			}
84		}
85	}
86	return executePdmlWithRetry(ctx)
87}
88
89// executePdml executes the following steps:
90// 1. Begin a PDML transaction
91// 2. Add the ID of the PDML transaction to the SQL request.
92// 3. Execute the update statement on the PDML transaction
93//
94// Note that PDML transactions cannot be committed or rolled back.
95func executePdml(ctx context.Context, sh *sessionHandle, req *sppb.ExecuteSqlRequest) (count int64, err error) {
96	// Begin transaction.
97	res, err := sh.getClient().BeginTransaction(contextWithOutgoingMetadata(ctx, sh.getMetadata()), &sppb.BeginTransactionRequest{
98		Session: sh.getID(),
99		Options: &sppb.TransactionOptions{
100			Mode: &sppb.TransactionOptions_PartitionedDml_{PartitionedDml: &sppb.TransactionOptions_PartitionedDml{}},
101		},
102	})
103	if err != nil {
104		return 0, toSpannerError(err)
105	}
106	// Add a reference to the PDML transaction on the ExecuteSql request.
107	req.Transaction = &sppb.TransactionSelector{
108		Selector: &sppb.TransactionSelector_Id{Id: res.Id},
109	}
110	resultSet, err := sh.getClient().ExecuteSql(ctx, req)
111	if err != nil {
112		return 0, err
113	}
114	if resultSet.Stats == nil {
115		return 0, spannerErrorf(codes.InvalidArgument, "query passed to Update: %q", req.Sql)
116	}
117	return extractRowCount(resultSet.Stats)
118}
119