Skip to content

feat(spanner): Add Cloud Spanner last statement samples #5296

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
38 changes: 38 additions & 0 deletions spanner/spanner_snippets/spanner/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1332,6 +1332,44 @@ func TestAddSplitPointsSample(t *testing.T) {
assertContains(t, out, "Added split points")
}

func TestDmlWithLastStatementSample(t *testing.T) {
_ = testutil.SystemTest(t)
t.Parallel()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: don't run these tests in parallel unless you are explicitly testing parallelization. This can cause race conditions and/or resource contention in our CI/CD.


_, dbName, cleanup := initTest(t, randomID())
defer cleanup()

_, cancel := context.WithTimeout(context.Background(), time.Hour)
defer cancel()
mustRunSample(t, createDatabase, dbName, "failed to create a database")

out := runSample(t, insertAndUpdateDmlWithLastStatement, dbName, "failed to insert and then update using DML with last statement option")
assertContains(t, out, "1 record(s) inserted.")
assertContains(t, out, "1 record(s) updated.")
}

func TestPgDmlWithLastStatementSample(t *testing.T) {
_ = testutil.SystemTest(t)
t.Parallel()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See previous comment. Please don't run tests in parallel.


_, dbName, cleanup := initTest(t, randomID())
defer cleanup()
dbCleanup, err := createTestPgDatabase(dbName,
`CREATE TABLE Singers (
SingerId bigint NOT NULL PRIMARY KEY,
FirstName varchar(1024),
LastName varchar(1024)
)`)
if err != nil {
t.Fatalf("failed to create test database: %v", err)
}
defer dbCleanup()

out := runSample(t, pgInsertAndUpdateDmlWithLastStatement, dbName, "failed to insert and then update using DML with last statement option")
assertContains(t, out, "1 record(s) inserted.")
assertContains(t, out, "1 record(s) updated.")
}

func maybeCreateKey(projectId, locationId, keyRingId, keyId string) error {
client, err := kms.NewKeyManagementClient(context.Background())
if err != nil {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package spanner

// [START spanner_postgresql_dml_last_statement]

import (
"context"
"fmt"
"io"

"cloud.google.com/go/spanner"
)

// Inserts a record into the Singers table and then updates
// the row while also setting the update DML as the last
// statement.
func pgInsertAndUpdateDmlWithLastStatement(w io.Writer, db string) error {
ctx := context.Background()
client, err := spanner.NewClient(ctx, db)
if err != nil {
return err
}
defer client.Close()

_, err = client.ReadWriteTransaction(ctx, func(ctx context.Context, txn *spanner.ReadWriteTransaction) error {
insertStmt := spanner.Statement{
SQL: `INSERT INTO Singers (SingerId, FirstName, LastName)
VALUES (54214, 'John', 'Do')`,
}
insertRowCount, err := txn.Update(ctx, insertStmt)
if err != nil {
return err
}
fmt.Fprintf(w, "%d record(s) inserted.\n", insertRowCount)

updateStmt := spanner.Statement{
SQL: `UPDATE Singers SET LastName = 'Doe' WHERE SingerId = 54214`,
}
opts := spanner.QueryOptions{LastStatement: true}
updateRowCount, err := txn.UpdateWithOptions(ctx, updateStmt, opts)
if err != nil {
return err
}
fmt.Fprintf(w, "%d record(s) updated.\n", updateRowCount)
return nil
})
if err != nil {
return err
}

return nil
}

// [END spanner_postgresql_dml_last_statement]
67 changes: 67 additions & 0 deletions spanner/spanner_snippets/spanner/spanner_dml_last_statement.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package spanner

// [START spanner_dml_last_statement]

import (
"context"
"fmt"
"io"

"cloud.google.com/go/spanner"
)

// Inserts a record into the Singers table and then updates
// the row while also setting the update DML as the last
// statement.
func insertAndUpdateDmlWithLastStatement(w io.Writer, db string) error {
ctx := context.Background()
client, err := spanner.NewClient(ctx, db)
if err != nil {
return err
}
defer client.Close()

_, err = client.ReadWriteTransaction(ctx, func(ctx context.Context, txn *spanner.ReadWriteTransaction) error {
insertStmt := spanner.Statement{
SQL: `INSERT Singers (SingerId, FirstName, LastName)
VALUES (54213, 'John', 'Do')`,
}
insertRowCount, err := txn.Update(ctx, insertStmt)
if err != nil {
return err
}
fmt.Fprintf(w, "%d record(s) inserted.\n", insertRowCount)

updateStmt := spanner.Statement{
SQL: `UPDATE Singers SET LastName = 'Doe' WHERE SingerId = 54213`,
}
opts := spanner.QueryOptions{LastStatement: true}
updateRowCount, err := txn.UpdateWithOptions(ctx, updateStmt, opts)
if err != nil {
return err
}
fmt.Fprintf(w, "%d record(s) updated.\n", updateRowCount)
return nil
})
if err != nil {
return err
}

return nil
}

// [END spanner_dml_last_statement]