Skip to content
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

feat(PreparedStmtDB): support reset #5782

Merged
merged 4 commits into from Oct 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 12 additions & 0 deletions prepare_stmt.go
Expand Up @@ -44,6 +44,18 @@ func (db *PreparedStmtDB) Close() {
}
}

func (db *PreparedStmtDB) Reset() {
db.Mux.Lock()
defer db.Mux.Unlock()
for query, stmt := range db.Stmts {
delete(db.Stmts, query)
go stmt.Close()
}

db.PreparedSQL = make([]string, 0, 100)
db.Stmts = map[string](*Stmt){}
}

func (db *PreparedStmtDB) prepare(ctx context.Context, conn ConnPool, isTransaction bool, query string) (Stmt, error) {
db.Mux.RLock()
if stmt, ok := db.Stmts[query]; ok && (!stmt.Transaction || isTransaction) {
Expand Down
28 changes: 27 additions & 1 deletion tests/prepared_stmt_test.go
Expand Up @@ -2,8 +2,8 @@ package tests_test

import (
"context"
"sync"
"errors"
"sync"
"testing"
"time"

Expand Down Expand Up @@ -168,3 +168,29 @@ func TestPreparedStmtInTransaction(t *testing.T) {
t.Errorf("Failed, got error: %v", err)
}
}

func TestPreparedStmtReset(t *testing.T) {
tx := DB.Session(&gorm.Session{PrepareStmt: true})

user := *GetUser("prepared_stmt_reset", Config{})
tx = tx.Create(&user)

pdb, ok := tx.ConnPool.(*gorm.PreparedStmtDB)
if !ok {
t.Fatalf("should assign PreparedStatement Manager back to database when using PrepareStmt mode")
}

pdb.Mux.Lock()
if len(pdb.Stmts) == 0 {
pdb.Mux.Unlock()
t.Fatalf("prepared stmt can not be empty")
}
pdb.Mux.Unlock()

pdb.Reset()
pdb.Mux.Lock()
defer pdb.Mux.Unlock()
if len(pdb.Stmts) != 0 {
t.Fatalf("prepared stmt should be empty")
}
}