Skip to content

Commit 46e02f2

Browse files
committed
fix lazy tx example
1 parent 11e948f commit 46e02f2

File tree

1 file changed

+45
-14
lines changed

1 file changed

+45
-14
lines changed

table/example_test.go

Lines changed: 45 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -189,23 +189,54 @@ func Example_lazyTransaction() {
189189
}
190190
defer db.Close(ctx)
191191
err = db.Table().Do(ctx,
192-
func(ctx context.Context, s table.Session) (err error) {
193-
// lazy open transaction on first execute query
194-
tx, res, err := s.Execute(ctx, table.DefaultTxControl(), "SELECT 1", nil)
192+
func(ctx context.Context, session table.Session) (err error) {
193+
// execute query with opening lazy transaction
194+
tx, result, err := session.Execute(ctx,
195+
table.SerializableReadWriteTxControl(),
196+
"DECLARE $id AS Uint64; "+
197+
"SELECT `title`, `description` FROM `path/to/mytable` WHERE id = $id",
198+
table.NewQueryParameters(
199+
table.ValueParam("$id", types.Uint64Value(1)),
200+
),
201+
)
195202
if err != nil {
196-
return err // for auto-retry with driver
203+
panic(err)
197204
}
198-
defer res.Close() // cleanup resources
199-
if err = res.Err(); err != nil {
200-
return err
201-
}
202-
// close transaction on last execute query
203-
res, err = tx.Execute(ctx, "SELECT 2", nil, options.WithCommit())
204-
if err != nil {
205-
return err
205+
defer tx.Rollback(ctx)
206+
defer result.Close()
207+
if result.NextResultSet(ctx) {
208+
if result.NextRow() {
209+
var (
210+
id uint64
211+
title string
212+
description string
213+
)
214+
if err = result.ScanNamed(
215+
named.OptionalWithDefault("id", &id),
216+
named.OptionalWithDefault("title", &title),
217+
named.OptionalWithDefault("description", &description),
218+
); err != nil {
219+
panic(err)
220+
}
221+
fmt.Println(id, title, description)
222+
_, err = tx.Execute(ctx,
223+
"DECLARE $id AS Uint64; "+
224+
"DECLARE $description AS Text; "+
225+
"UPSERT INTO `path/to/mytable` "+
226+
"(id, description) "+
227+
"VALUES ($id, $description);",
228+
table.NewQueryParameters(
229+
table.ValueParam("$id", types.Uint64Value(1)),
230+
table.ValueParam("$description", types.TextValue("changed description")),
231+
),
232+
options.WithCommit(),
233+
)
234+
if err != nil {
235+
return err
236+
}
237+
}
206238
}
207-
defer res.Close()
208-
return res.Err()
239+
return result.Err()
209240
},
210241
table.WithIdempotent(),
211242
)

0 commit comments

Comments
 (0)