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
Open
Show file tree
Hide file tree
Changes from 3 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
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,66 @@
// 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 pg_spanner_dml_last_statement]
Copy link
Contributor

Choose a reason for hiding this comment

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

this needs to be a valid region tag starting with a product prefix.

Copy link
Author

Choose a reason for hiding this comment

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

Updated to prefix with spanner_postgresql, thanks


import (
"context"
"fmt"
"io"

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

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()

// Insert records into the Singers table and then updates
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: maintain consistent conjugation of verb forms in comment (e.g. "Inserts" and "updates" OR "Insert" and "update")

Copy link
Author

Choose a reason for hiding this comment

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

Done, and moved this to be the function comment

// the row while also setting the update DML as the last
// statement.
_, err = client.ReadWriteTransaction(ctx, func(ctx context.Context, txn *spanner.ReadWriteTransaction) error {
insert_stmt := spanner.Statement{
Copy link
Collaborator

Choose a reason for hiding this comment

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

issue: put variables in camelCase.

Copy link
Author

Choose a reason for hiding this comment

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

Done

SQL: `INSERT INTO Singers (SingerId, FirstName, LastName)
VALUES (54214, 'John', 'Do')`,
}
insertRowCount, err := txn.Update(ctx, insert_stmt)
if err != nil {
return err
}
fmt.Fprintf(w, "%d record(s) inserted.\n", insertRowCount)

update_stmt := spanner.Statement{
SQL: `UPDATE Singers SET LastName = 'Doe' WHERE SingerId = 54214`,
}
updateRowCount, err := txn.UpdateWithOptions(context.Background(), update_stmt, spanner.QueryOptions{LastStatement: true})
Copy link
Collaborator

Choose a reason for hiding this comment

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

issue: instantiate Context and QueryOptions objects on new lines, not inside call to UpdateWithOptions()

Copy link
Author

Choose a reason for hiding this comment

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

Updated QueryOptions to be instantiated on new line as suggested, and used the existing ctx instead of calling context.Background()

if err != nil {
return err
}
fmt.Fprintf(w, "%d record(s) updated.\n", updateRowCount)
return nil
})
if err != nil {
return err
}

return nil
}

// [END pg_spanner_dml_last_statement]
66 changes: 66 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,66 @@
// 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"
)

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()

// Insert records into the Singers table and then updates
// the row while also setting the update DML as the last
// statement.
_, err = client.ReadWriteTransaction(ctx, func(ctx context.Context, txn *spanner.ReadWriteTransaction) error {
insert_stmt := spanner.Statement{
SQL: `INSERT Singers (SingerId, FirstName, LastName)
VALUES (54213, 'John', 'Do')`,
}
insertRowCount, err := txn.Update(ctx, insert_stmt)
if err != nil {
return err
}
fmt.Fprintf(w, "%d record(s) inserted.\n", insertRowCount)

update_stmt := spanner.Statement{
Copy link
Collaborator

Choose a reason for hiding this comment

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

issue: use camelCase for variable names.

See: https://github.com/GoogleCloudPlatform/golang-samples/pulls

Copy link
Author

Choose a reason for hiding this comment

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

Done

SQL: `UPDATE Singers SET LastName = 'Doe' WHERE SingerId = 54213`,
}
updateRowCount, err := txn.UpdateWithOptions(context.Background(), update_stmt, spanner.QueryOptions{LastStatement: true})
Copy link
Collaborator

Choose a reason for hiding this comment

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

issue: create new Context and QueryOption objects outside of the call to UpdateWithOptions().

Suggestion:

ctx := context.Background()
opts := spanner.QueryOptions{ LastStatement: true }
updateRowCount, err := txn.UpdateWithOptions(ctx, updateStmt, opts)

Copy link
Author

Choose a reason for hiding this comment

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

Thank you for the suggested code block, updated QueryOptions to be instantiated on new line as suggested, and used the existing ctx instead of calling context.Background()

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]
Loading