Skip to content

Commit

Permalink
feat: fetch last_insert_id when asked for it
Browse files Browse the repository at this point in the history
Signed-off-by: Andres Taylor <[email protected]>
  • Loading branch information
systay committed Dec 16, 2024
1 parent f6c0859 commit bde6be1
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
10 changes: 10 additions & 0 deletions go/vt/vttablet/endtoend/misc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -618,6 +618,16 @@ func TestLastInsertId(t *testing.T) {
assert.Truef(t, qr.Rows[0][0].Equal(wantCol), "Execute: \n%#v, want \n%#v", qr.Rows[0][0], wantCol)
}

func TestSelectLastInsertId(t *testing.T) {
client := framework.NewClient()
rs, err := client.ExecuteWithOptions("select 1 from dual where last_insert_id(42) = 42", nil, &querypb.ExecuteOptions{
IncludedFields: querypb.ExecuteOptions_ALL,
FetchLastInsertId: true,
})
require.NoError(t, err)
assert.EqualValues(t, 42, rs.InsertID)
}

func TestAppDebugRequest(t *testing.T) {
client := framework.NewClient()

Expand Down
39 changes: 37 additions & 2 deletions go/vt/vttablet/tabletserver/query_executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -1121,7 +1121,17 @@ func (qre *QueryExecutor) execDBConn(conn *connpool.Conn, sql string, wantfields
}
defer qre.tsv.statelessql.Remove(qd)

return conn.Exec(ctx, sql, int(qre.tsv.qe.maxResultSize.Load()), wantfields)
exec, err := conn.Exec(ctx, sql, int(qre.tsv.qe.maxResultSize.Load()), wantfields)
if err != nil {
return nil, err
}
if qre.options.FetchLastInsertId {
err := qre.fetchLastInsertID(ctx, conn, exec)
if err != nil {
return nil, err
}
}
return exec, nil
}

func (qre *QueryExecutor) execStatefulConn(conn *StatefulConnection, sql string, wantfields bool) (*sqltypes.Result, error) {
Expand All @@ -1137,7 +1147,32 @@ func (qre *QueryExecutor) execStatefulConn(conn *StatefulConnection, sql string,
}
defer qre.tsv.statefulql.Remove(qd)

return conn.Exec(ctx, sql, int(qre.tsv.qe.maxResultSize.Load()), wantfields)
exec, err := conn.Exec(ctx, sql, int(qre.tsv.qe.maxResultSize.Load()), wantfields)
if err != nil {
return nil, err
}
if qre.options.FetchLastInsertId {
err = qre.fetchLastInsertID(ctx, conn.UnderlyingDBConn().Conn, exec)
if err != nil {
return nil, err
}
}
return exec, nil
}

func (qre *QueryExecutor) fetchLastInsertID(ctx context.Context, conn *connpool.Conn, exec *sqltypes.Result) error {
result, err := conn.Exec(ctx, "select last_insert_id()", 1, false)
if err != nil {
return err
}

cell := result.Rows[0][0]
insertID, err := cell.ToCastUint64()
if err != nil {
return err
}
exec.InsertID = insertID
return nil
}

func (qre *QueryExecutor) execStreamSQL(conn *connpool.PooledConn, isTransaction bool, sql string, callback func(*sqltypes.Result) error) error {
Expand Down

0 comments on commit bde6be1

Please sign in to comment.