Skip to content

Commit c2c3906

Browse files
committed
Add Stmt.bindIndex for mapping param name to index
1 parent 29c16de commit c2c3906

File tree

1 file changed

+14
-13
lines changed

1 file changed

+14
-13
lines changed

sqlite.go

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -439,11 +439,15 @@ func (conn *Conn) prepare(query string, flags C.uint) (*Stmt, int, error) {
439439
}
440440
trailingBytes := int(C.strlen(ctrailing))
441441

442-
stmt.bindNames = make([]string, int(C.sqlite3_bind_parameter_count(stmt.stmt)))
442+
bindCount := int(C.sqlite3_bind_parameter_count(stmt.stmt))
443+
stmt.bindNames = make([]string, bindCount)
444+
stmt.bindIndex = make(map[string]int, bindCount)
443445
for i := range stmt.bindNames {
444446
cname := C.sqlite3_bind_parameter_name(stmt.stmt, C.int(i+1))
445447
if cname != nil {
446-
stmt.bindNames[i] = C.GoString(cname)
448+
name := C.GoString(cname)
449+
stmt.bindNames[i] = name
450+
stmt.bindIndex[name] = i + 1
447451
}
448452
}
449453

@@ -523,6 +527,7 @@ type Stmt struct {
523527
stmt *C.sqlite3_stmt
524528
query string
525529
bindNames []string
530+
bindIndex map[string]int
526531
colNames map[string]int
527532
bindErr error
528533
prepInterrupt bool // set if Prep was interrupted
@@ -692,15 +697,11 @@ func (stmt *Stmt) handleBindErr(loc string, res C.int) {
692697
}
693698

694699
func (stmt *Stmt) findBindName(loc string, param string) int {
695-
for i, name := range stmt.bindNames {
696-
if name == param {
697-
return i + 1 // 1-based indices
698-
}
699-
}
700-
if stmt.bindErr == nil {
700+
pos := stmt.bindIndex[param]
701+
if pos == 0 && stmt.bindErr == nil {
701702
stmt.bindErr = reserr("Stmt."+loc, stmt.query, "unknown parameter: "+param, C.SQLITE_ERROR)
702703
}
703-
return 0
704+
return pos
704705
}
705706

706707
// DataCount returns the number of columns in the current row of the result
@@ -743,12 +744,12 @@ func (stmt *Stmt) BindParamCount() int {
743744
// Parameters indices start at 1.
744745
//
745746
// https://www.sqlite.org/c3ref/bind_parameter_name.html
746-
func (stmt *Stmt) BindParamName(i int) string {
747-
i-- // map from 1-based to 0-based
748-
if i < 0 || i >= len(stmt.bindNames) {
747+
func (stmt *Stmt) BindParamName(param int) string {
748+
param-- // map from 1-based to 0-based
749+
if param < 0 || param >= len(stmt.bindNames) {
749750
return ""
750751
}
751-
return stmt.bindNames[i]
752+
return stmt.bindNames[param]
752753
}
753754

754755
// BindInt64 binds value to a numbered stmt parameter.

0 commit comments

Comments
 (0)