25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(oracle): release connections after query panics
Zzz3b20148a14b4
diff --git a/agents/drivers/oracle-go/main.go b/agents/drivers/oracle-go/main.goindex c78664945a..813bd117d0 100644--- a/agents/drivers/oracle-go/main.go+++ b/agents/drivers/oracle-go/main.go@@ -1075,6 +1075,9 @@ func oracleServerMajorVersionFromDBConn(ctx context.Context, db *sql.DB) (int, b}func oracleServerMajorVersionFromDriverConn(driverConn any) (int, bool) {+ if guarded, ok := driverConn.(*oracleQueryConnection); ok {+ driverConn = guarded.oracleThinConnection+ }conn, ok := driverConn.(*go_ora.Connection)if !ok {return 0, false@@ -1276,7 +1279,7 @@ func openDBWithStringConverter(params connectParams, stringConverter converters.if stringConverter != nil {go_ora.SetStringConverter(connector, stringConverter, nil)}- db := sql.OpenDB(connector)+ db := sql.OpenDB(oracleQueryConnector{connector})db.SetMaxOpenConns(4)db.SetMaxIdleConns(1)db.SetConnMaxLifetime(30 * time.Minute)@@ -3892,11 +3895,16 @@ func (s *server) executeQueryPage(opts queryOptions, pageSize int) (queryPageRes// projection so the remaining columns stay readable; panics on later pages// surface as errors instead.func (s *server) runPagedOracleSelect(sqlText string, opts queryOptions, pageSize int, start time.Time) (queryPageResult, *querySession, error) {+ // Until a cursor is handed to the caller, this function owns its rows,+ // including panics while reading Columns/ColumnTypes before the first page.+ var ownedRows *sql.Rows+ defer func() { s.closeRows(ownedRows) }()for attempt := 0; ; attempt++ {rows, err := s.queryRowsWithOracleValueRewriteIfNeeded(sqlText, opts.TimeoutSecs, opts.DeferLOBs)if err != nil {return queryPageResult{}, nil, err}+ ownedRows = rowscolumns, err := rows.Columns()if err != nil {s.closeRows(rows)@@ -3913,7 +3921,7 @@ func (s *server) runPagedOracleSelect(sqlText string, opts queryOptions, pageSizif err != nil {s.closeRows(rows)var panicErr oracleDriverPanicError- if attempt == 0 && !oracleSQLLocksRows(sqlText) && errors.As(err, &panicErr) {+ if attempt == 0 && !s.hasManualTransaction() && !oracleSQLLocksRows(sqlText) && errors.As(err, &panicErr) {if placeholder, ok := oraclePlaceholderRetrySQL(sqlText, s.loadOracleColumnMeta); ok {sqlText = placeholdercontinue@@ -3922,6 +3930,7 @@ func (s *server) runPagedOracleSelect(sqlText string, opts queryOptions, pageSizreturn queryPageResult{}, nil, err}if result.HasMore {+ ownedRows = nilreturn result, session, nil}s.closeRows(rows)@@ -4257,7 +4266,7 @@ func columnTypeNames(rows *sql.Rows) []string {return result}-func (s *server) queryRowsWithOracleValueRewriteIfNeeded(sqlText string, timeoutSecs int, deferLOBs bool) (*sql.Rows, error) {+func (s *server) queryRowsWithOracleValueRewriteIfNeeded(sqlText string, timeoutSecs int, deferLOBs bool) (resultRows *sql.Rows, queryErr error) {// A statement that keeps row locks while it runs is rewritten before the// first attempt: when such a statement panics after the rows were locked,// the locks stay behind and the retry below blocks on them until the query@@ -4281,7 +4290,7 @@ func (s *server) queryRowsWithOracleValueRewriteIfNeeded(sqlText string, timeout// worth retrying through the value-rewrite fallback below; other// failures keep their own error.var panicErr oracleDriverPanicError- if !errors.As(rewrittenErr, &panicErr) {+ if s.hasManualTransaction() || !errors.As(rewrittenErr, &panicErr) {return nil, rewrittenErr}}@@ -4289,7 +4298,7 @@ func (s *server) queryRowsWithOracleValueRewriteIfNeeded(sqlText string, timeoutrows, err := s.queryRowsWithTimeout(sqlText, nil, timeoutSecs)if err != nil {var panicErr oracleDriverPanicError- if errors.As(err, &panicErr) {+ if !s.hasManualTransaction() && errors.As(err, &panicErr) {rewritten, rewriteErr := rewriteOracleSelectSQL(sqlText, s.loadOracleColumnMeta, false)if rewriteErr == nil && rewritten != sqlText {rewrittenRows, rewrittenErr := s.queryRowsWithTimeout(rewritten, nil, timeoutSecs)@@ -4310,6 +4319,13 @@ func (s *server) queryRowsWithOracleValueRewriteIfNeeded(sqlText string, timeout}return nil, err}+ // Metadata access can panic too. Retain ownership until rows are actually+ // returned; the caller cannot clean up rows it has not received.+ defer func() {+ if rows != resultRows {+ s.closeRows(rows)+ }+ }()typeNames := columnTypeNames(rows)if !oracleColumnTypeNamesContainXMLType(typeNames) {return rows, nildiff --git a/agents/drivers/oracle-go/main_test.go b/agents/drivers/oracle-go/main_test.goindex 40421cf034..37fdaa1836 100644--- a/agents/drivers/oracle-go/main_test.go+++ b/agents/drivers/oracle-go/main_test.go@@ -3254,6 +3254,7 @@ type oracleViewSourceQueryStep struct {panicText stringnextPanicText stringcolumnsPanicText string+ columnsPanicCall int}type oracleViewSourceDriver struct {@@ -3319,6 +3320,7 @@ func (c *oracleViewSourceConn) QueryContext(values: step.rows,nextPanicText: step.nextPanicText,columnsPanicText: step.columnsPanicText,+ columnsPanicCall: step.columnsPanicCall,}, nil}@@ -3354,10 +3356,13 @@ type oracleViewSourceRows struct {next intnextPanicText stringcolumnsPanicText string+ columnsPanicCall int+ columnsCalls int}func (r *oracleViewSourceRows) Columns() []string {- if r.columnsPanicText != "" {+ r.columnsCalls+++ if r.columnsPanicText != "" && (r.columnsPanicCall == 0 || r.columnsPanicCall == r.columnsCalls) {panic(r.columnsPanicText)}return r.columns@@ -3561,12 +3566,7 @@ func TestOracleCursorSurvivesDeadlineWindow(t *testing.T) {}func TestOracleQueryRowsRecoversDriverPanic(t *testing.T) {- driverName := "oracle-test-panic-" + strings.ReplaceAll(t.Name(), "/", "-")- sql.Register(driverName, &oraclePanicDriver{})- db, err := sql.Open(driverName, "dsn")- if err != nil {- t.Fatal(err)- }+ db := sql.OpenDB(oracleQueryConnector{oracleGuardTestConnector{&oraclePanicDriver{}}})t.Cleanup(func() { _ = db.Close() })s := newServer()@@ -3579,6 +3579,9 @@ func TestOracleQueryRowsRecoversDriverPanic(t *testing.T) {if !errors.As(err, &panicErr) {t.Fatalf("expected oracle driver panic error, got %v", err)}+ if stats := db.Stats(); stats.InUse != 0 {+ t.Errorf("driver panic leaked a pool connection: in_use=%d open=%d", stats.InUse, stats.OpenConnections)+ }s.activeCancelMu.Lock()defer s.activeCancelMu.Unlock()if s.activeCancel != nil || s.activeTimer != nil || len(s.activeRows) != 0 {@@ -3780,6 +3783,9 @@ func TestRuntimeHandleLineRecoversRequestPanic(t *testing.T) {if string(resp.ID) != "5" {t.Fatalf("panic response must keep the request id, got %s", resp.ID)}+ if stats := db.Stats(); stats.InUse != 0 || len(session.activeRows) != 0 {+ t.Errorf("metadata panic leaked rows/connection: in_use=%d active_rows=%d", stats.InUse, len(session.activeRows))+ }// The RPC stream must survive the panic and keep serving requests.followUp, shutdown := runtime.handleLine(`{"jsonrpc":"2.0","id":6,"method":"handshake","params":{}}`)@@ -3981,13 +3987,8 @@ type oracleManualTxDriver struct {func openOracleManualTxTestDB(t *testing.T) (*sql.DB, *oracleManualTxDriver) {t.Helper()- driverName := "oracle-test-manual-tx-" + strings.ReplaceAll(t.Name(), "/", "-") + "-" + time.Now().Format("150405.000000000")drv := &oracleManualTxDriver{}- sql.Register(driverName, drv)- db, err := sql.Open(driverName, "")- if err != nil {- t.Fatal(err)- }+ db := sql.OpenDB(oracleQueryConnector{oracleGuardTestConnector{drv}})db.SetMaxOpenConns(1)t.Cleanup(func() {_ = db.Close()diff --git a/agents/drivers/oracle-go/query_guard.go b/agents/drivers/oracle-go/query_guard.gonew file mode 100644index 0000000000..19fb48a2e1--- /dev/null+++ b/agents/drivers/oracle-go/query_guard.go@@ -0,0 +1,116 @@+package main++import (+ "context"+ "database/sql/driver"+ "fmt"+)++// Preserve the thin driver's optional interfaces (notably transaction options,+// cancellation and named values) while handling query panics below database/sql.+// Recovering above sql.DB.QueryContext skips its releaseConn call; above+// sql.Tx.QueryContext it also leaves the transaction's read lock held.+type oracleThinConnection interface {+ driver.Conn+ driver.ConnBeginTx+ driver.ConnPrepareContext+ driver.QueryerContext+ driver.ExecerContext+ driver.Pinger+ driver.NamedValueChecker+ driver.SessionResetter+}++type oracleQueryConnector struct{ driver.Connector }++func (c oracleQueryConnector) Connect(ctx context.Context) (driver.Conn, error) {+ conn, err := c.Connector.Connect(ctx)+ if err != nil {+ return nil, err+ }+ thin, ok := conn.(oracleThinConnection)+ if !ok {+ _ = conn.Close()+ return nil, fmt.Errorf("Oracle thin connection does not implement the required context interfaces")+ }+ return &oracleQueryConnection{oracleThinConnection: thin}, nil+}++type oracleQueryConnection struct {+ oracleThinConnection+ // database/sql serializes access to a driver connection, including IsValid.+ failed error+}++func (c *oracleQueryConnection) unusableError() error {+ return fmt.Errorf("Oracle connection is unusable after a driver panic; roll back the transaction or reconnect: %w", c.failed)+}++func (c *oracleQueryConnection) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (rows driver.Rows, err error) {+ if c.failed != nil {+ return nil, c.unusableError()+ }+ defer func() {+ if recovered := recover(); recovered != nil {+ c.failed = oracleDriverPanicError{value: recovered}+ rows, err = nil, c.unusableError()+ }+ }()+ return c.oracleThinConnection.QueryContext(ctx, query, args)+}++// Invalidate via Validator, not ErrBadConn: ErrBadConn would tell database/sql+// to replay the original statement, even when it has already acquired locks or+// invoked a function with side effects. The original panic remains diagnostic.+func (c *oracleQueryConnection) IsValid() bool { return c.failed == nil }++func (c *oracleQueryConnection) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) {+ if c.failed != nil {+ return nil, c.unusableError()+ }+ return c.oracleThinConnection.ExecContext(ctx, query, args)+}++func (c *oracleQueryConnection) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {+ if c.failed != nil {+ return nil, c.unusableError()+ }+ return c.oracleThinConnection.PrepareContext(ctx, query)+}++func (c *oracleQueryConnection) Prepare(query string) (driver.Stmt, error) {+ return c.PrepareContext(context.Background(), query)+}++func (c *oracleQueryConnection) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) {+ if c.failed != nil {+ return nil, c.unusableError()+ }+ tx, err := c.oracleThinConnection.BeginTx(ctx, opts)+ if err != nil {+ return nil, err+ }+ return &oracleQueryTransaction{Tx: tx, conn: c}, nil+}++func (c *oracleQueryConnection) Begin() (driver.Tx, error) {+ return c.BeginTx(context.Background(), driver.TxOptions{})+}++type oracleQueryTransaction struct {+ driver.Tx+ conn *oracleQueryConnection+}++func (t *oracleQueryTransaction) Commit() error {+ if t.conn.failed != nil {+ // sql.Tx considers Commit final even when it returns an error. Roll back+ // instead of committing a transaction whose query outcome is uncertain.+ err := t.Tx.Rollback()+ if err != nil {+ return fmt.Errorf("%w (rollback failed: %v)", t.conn.unusableError(), err)+ }+ return t.conn.unusableError()+ }+ return t.Tx.Commit()+}diff --git a/agents/drivers/oracle-go/query_guard_test.go b/agents/drivers/oracle-go/query_guard_test.gonew file mode 100644index 0000000000..c383eb36aa--- /dev/null+++ b/agents/drivers/oracle-go/query_guard_test.go@@ -0,0 +1,258 @@+package main++import (+ "context"+ "database/sql"+ "database/sql/driver"+ "encoding/json"+ "errors"+ "fmt"+ "testing"+ "time"+)++// Adapt the existing scripted drivers to the same interfaces as go-ora. The+// production connector and database/sql still own all recovery and lifecycle.+type oracleGuardTestConnector struct{ drv driver.Driver }++func (c oracleGuardTestConnector) Driver() driver.Driver { return c.drv }++func (c oracleGuardTestConnector) Connect(context.Context) (driver.Conn, error) {+ conn, err := c.drv.Open("")+ return &oracleGuardTestConn{Conn: conn}, err+}++type oracleGuardTestConn struct{ driver.Conn }++func (c *oracleGuardTestConn) QueryContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Rows, error) {+ return c.Conn.(driver.QueryerContext).QueryContext(ctx, q, args)+}+func (c *oracleGuardTestConn) ExecContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Result, error) {+ return c.Conn.(driver.ExecerContext).ExecContext(ctx, q, args)+}+func (c *oracleGuardTestConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) {+ return c.Conn.(driver.ConnBeginTx).BeginTx(ctx, opts)+}+func (c *oracleGuardTestConn) PrepareContext(_ context.Context, q string) (driver.Stmt, error) {+ return c.Conn.Prepare(q)+}+func (c *oracleGuardTestConn) Ping(context.Context) error { return nil }+func (c *oracleGuardTestConn) ResetSession(context.Context) error { return nil }+func (c *oracleGuardTestConn) CheckNamedValue(*driver.NamedValue) error { return driver.ErrSkip }++type oracleGuardFaultDriver struct {+ oracleManualTxDriver+ queryCalls int+ closed int+ blocked chan struct{}+}++func (d *oracleGuardFaultDriver) Open(string) (driver.Conn, error) {+ return &oracleGuardFaultConn{oracleManualTxConn: &oracleManualTxConn{driver: &d.oracleManualTxDriver}, fault: d}, nil+}++type oracleGuardFaultConn struct {+ *oracleManualTxConn+ fault *oracleGuardFaultDriver+}++func (c *oracleGuardFaultConn) QueryContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Rows, error) {+ c.fault.queryCalls+++ if q == "SELECT WAIT_QUERY FROM DUAL" {+ close(c.fault.blocked)+ <-ctx.Done()+ return nil, ctx.Err()+ }+ if q == "SELECT WAIT_FETCH FROM DUAL" {+ return &oracleGuardBlockedRows{ctx: ctx, blocked: c.fault.blocked}, nil+ }+ if q == "SELECT FAULT FROM DUAL" {+ panic("injected query decode failure")+ }+ return c.oracleManualTxConn.QueryContext(ctx, q, args)+}++type oracleGuardBlockedRows struct {+ ctx context.Context+ blocked chan struct{}+}++func (*oracleGuardBlockedRows) Columns() []string { return []string{"A"} }+func (*oracleGuardBlockedRows) Close() error { return nil }+func (r *oracleGuardBlockedRows) Next([]driver.Value) error {+ close(r.blocked)+ <-r.ctx.Done()+ return r.ctx.Err()+}++func TestRuntimeMetadataPanicReleasesRowsBeforeAndDuringFirstPage(t *testing.T) {+ for _, method := range []string{"execute_query", "execute_query_page", "start_table_read"} {+ for _, call := range []int{1, 2, 3} {+ t.Run(fmt.Sprintf("%s/column_call_%d", method, call), func(t *testing.T) {+ steps := []oracleViewSourceQueryStep{}+ for i := 0; i < 6; i++ {+ steps = append(steps,+ oracleViewSourceQueryStep{queryContains: "SELECT 1", args: []driver.Value{}, columnsPanicText: "injected metadata failure", columnsPanicCall: call},+ oracleViewSourceQueryStep{queryContains: "SELECT 1", args: []driver.Value{}, rows: [][]driver.Value{{int64(1)}}},+ )+ }+ db, _ := openOracleViewSourceTestDB(t, steps)+ db.SetMaxOpenConns(1)+ s := newServer()+ s.db = db+ runtime := newRuntimeServer()+ runtime.sessions["a"] = &agentSession{server: s}+ for i := 0; i < 6; i++ {+ request := fmt.Sprintf(`{"id":1,"method":%q,"params":{"agentSessionId":"a","sql":"SELECT 1 FROM DUAL","pageSize":2,"timeoutSecs":1}}`, method)+ resp, shutdown := runtime.handleLine(request)+ if shutdown || resp.Error == nil {+ t.Fatalf("expected metadata panic: %+v", resp)+ }+ if db.Stats().InUse != 0 || len(s.activeRows) != 0 || len(s.sessions) != 0 || len(s.tableReadSessions) != 0 {+ t.Fatalf("panic %d leaked cursor/connection: %+v", i, db.Stats())+ }+ resp, _ = runtime.handleLine(`{"id":2,"method":"execute_query","params":{"agentSessionId":"a","sql":"SELECT 1 FROM DUAL","timeoutSecs":1}}`)+ if resp.Error != nil {+ t.Fatalf("same session is unusable: %v", resp.Error)+ }+ }+ })+ }+ }+}++func TestRuntimeCancellationRestoresQueryAndFetch(t *testing.T) {+ for _, phase := range []string{"QUERY", "FETCH"} {+ t.Run(phase, func(t *testing.T) {+ drv := &oracleGuardFaultDriver{blocked: make(chan struct{})}+ db := sql.OpenDB(oracleQueryConnector{oracleGuardTestConnector{drv}})+ db.SetMaxOpenConns(1)+ t.Cleanup(func() { db.Close() })+ s := newServer()+ s.db = db+ runtime := newRuntimeServer()+ runtime.sessions["a"] = &agentSession{server: s}+ done := make(chan response, 1)+ go func() {+ request, _ := json.Marshal(map[string]any{"id": 1, "method": "execute_query_page", "params": map[string]any{"agentSessionId": "a", "sql": "SELECT WAIT_" + phase + " FROM DUAL", "pageSize": 2}})+ resp, _ := runtime.handleLine(string(request))+ done <- resp+ }()+ select {+ case <-drv.blocked:+ case <-time.After(time.Second):+ t.Fatal("query did not reach blocking phase")+ }+ resp, _ := runtime.handleLine(`{"id":2,"method":"cancel_session","params":{"agentSessionId":"a"}}`)+ if resp.Error != nil {+ t.Fatal(resp.Error)+ }+ select {+ case resp := <-done:+ if resp.Error == nil {+ t.Fatal("cancel lost its error")+ }+ case <-time.After(time.Second):+ t.Fatal("cancel did not release session lock")+ }+ if db.Stats().InUse != 0 || len(s.activeRows) != 0 {+ t.Fatal("cancel leaked resources")+ }+ resp, _ = runtime.handleLine(`{"id":3,"method":"execute_query","params":{"agentSessionId":"a","sql":"SELECT 1 FROM DUAL","timeoutSecs":1}}`)+ if resp.Error != nil {+ t.Fatalf("query after cancel failed: %v", resp.Error)+ }+ })+ }+}+func (c *oracleGuardFaultConn) Close() error {+ c.fault.closed+++ return c.oracleManualTxConn.Close()+}++func TestOracleQueryPanicDoesNotExhaustPoolOrReplay(t *testing.T) {+ drv := &oracleGuardFaultDriver{}+ db := sql.OpenDB(oracleQueryConnector{oracleGuardTestConnector{drv}})+ db.SetMaxOpenConns(1)+ t.Cleanup(func() { db.Close() })+ s := newServer()+ s.db = db+ for i := 0; i < 8; i++ {+ _, err := s.executeSelectOnce("SELECT 1 FROM DUAL", 10, 1, false)+ if err != nil {+ t.Fatal(err)+ }+ calls := drv.queryCalls+ _, err = s.queryRowsWithTimeout("SELECT FAULT FROM DUAL", nil, 1)+ var panicErr oracleDriverPanicError+ if !errors.As(err, &panicErr) {+ t.Fatalf("lost panic: %v", err)+ }+ if drv.queryCalls != calls+1 {+ t.Fatal("statement was implicitly replayed")+ }+ if stats := db.Stats(); stats.InUse != 0 || stats.OpenConnections != 0 || len(s.activeRows) != 0 {+ t.Fatalf("failure %d leaked resources: %+v active_rows=%d", i, stats, len(s.activeRows))+ }+ if drv.closed != i+1 {+ t.Fatalf("poisoned connection was not closed: %d", drv.closed)+ }+ }+ if _, err := s.executeSelectOnce("SELECT 1 FROM DUAL", 10, 1, false); err != nil {+ t.Fatal(err)+ }+}++func TestOracleQueryPanicAllowsManualTransactionCleanup(t *testing.T) {+ for _, commit := range []bool{false, true} {+ t.Run(fmt.Sprint("commit=", commit), func(t *testing.T) {+ drv := &oracleGuardFaultDriver{}+ db := sql.OpenDB(oracleQueryConnector{oracleGuardTestConnector{drv}})+ db.SetMaxOpenConns(1)+ t.Cleanup(func() { db.Close() })+ s := newServer()+ s.db = db+ if err := s.beginManualTransaction(""); err != nil {+ t.Fatal(err)+ }+ if _, err := s.queryRowsWithTimeout("SELECT FAULT FROM DUAL", nil, 1); err == nil {+ t.Fatal("expected failure")+ }+ if !s.hasManualTransaction() {+ t.Fatal("transaction state silently cleared")+ }+ calls := drv.queryCalls+ if _, err := s.executeQuery(queryOptions{SQL: "SELECT 1 FROM DUAL"}); err == nil {+ t.Fatal("poisoned transaction reused")+ }+ if _, err := s.executeQuery(queryOptions{SQL: "UPDATE t SET a=2"}); err == nil {+ t.Fatal("write ran in poisoned transaction")+ }+ if drv.queryCalls != calls || len(drv.execs) != 0 {+ t.Fatal("failed transaction reached driver again")+ }+ done := make(chan error, 1)+ go func() {+ if commit {+ done <- s.commitManualTransaction()+ } else {+ done <- s.rollbackManualTransaction()+ }+ }()+ select {+ case err := <-done:+ if (err != nil) != commit {+ t.Fatalf("unexpected cleanup error: %v", err)+ }+ case <-time.After(time.Second):+ t.Fatal("panic left transaction lock held")+ }+ if drv.committed || !drv.rolledBack || s.hasManualTransaction() || db.Stats().InUse != 0 {+ t.Fatal("incorrect transaction cleanup")+ }+ if _, err := s.executeSelectOnce("SELECT 1 FROM DUAL", 10, 1, false); err != nil {+ t.Fatal(err)+ }+ })+ }+}