Skip to content

Commit 604aac6

Browse files
committed
Fix exponential memory allocation in Exec and improve performance
This commit changes SQLiteConn.Exec to use the raw Go query string instead of repeatedly converting it to a C string (which it would do for every statement in the provided query). This yields a ~20% performance improvement for a query containing one statement and a significantly larger improvement when the query contains multiple statements as is common when importing a SQL dump (our benchmark shows a 5x improvement for handling 1k SQL statements). Additionally, this commit improves the performance of Exec by 2x or more and makes number and size of allocations constant when there are no bind parameters (the performance improvement scales with the number of SQL statements in the query). This is achieved by having the entire query processed in C code thus requiring only one CGO call. The speedup for Exec'ing single statement queries means that wrapping simple statements in a transaction is now twice as fast. This commit also improves the test coverage of Exec, which previously failed to test that Exec could process multiple statements like INSERT. It also adds some Exec specific benchmarks that highlight both the improvements here and the overhead of using a cancellable Context. This commit is a slimmed down and improved version of PR mattn#1133: mattn#1133 ``` goos: darwin goarch: arm64 pkg: github.com/mattn/go-sqlite3 cpu: Apple M1 Max │ b.txt │ n.txt │ │ sec/op │ sec/op vs base │ Suite/BenchmarkExec/Params-10 1.434µ ± 1% 1.186µ ± 0% -17.27% (p=0.000 n=10) Suite/BenchmarkExec/NoParams-10 1267.5n ± 0% 759.2n ± 1% -40.10% (p=0.000 n=10) Suite/BenchmarkExecContext/Params-10 2.886µ ± 0% 2.517µ ± 0% -12.80% (p=0.000 n=10) Suite/BenchmarkExecContext/NoParams-10 2.605µ ± 1% 1.829µ ± 1% -29.81% (p=0.000 n=10) Suite/BenchmarkExecStep-10 1852.6µ ± 1% 582.3µ ± 0% -68.57% (p=0.000 n=10) Suite/BenchmarkExecContextStep-10 3053.3µ ± 3% 582.0µ ± 0% -80.94% (p=0.000 n=10) Suite/BenchmarkExecTx-10 4.126µ ± 2% 2.200µ ± 1% -46.67% (p=0.000 n=10) geomean 16.40µ 8.455µ -48.44% │ b.txt │ n.txt │ │ B/op │ B/op vs base │ Suite/BenchmarkExec/Params-10 248.0 ± 0% 240.0 ± 0% -3.23% (p=0.000 n=10) Suite/BenchmarkExec/NoParams-10 128.00 ± 0% 64.00 ± 0% -50.00% (p=0.000 n=10) Suite/BenchmarkExecContext/Params-10 408.0 ± 0% 400.0 ± 0% -1.96% (p=0.000 n=10) Suite/BenchmarkExecContext/NoParams-10 288.0 ± 0% 208.0 ± 0% -27.78% (p=0.000 n=10) Suite/BenchmarkExecStep-10 5406674.50 ± 0% 64.00 ± 0% -100.00% (p=0.000 n=10) Suite/BenchmarkExecContextStep-10 5566758.5 ± 0% 208.0 ± 0% -100.00% (p=0.000 n=10) Suite/BenchmarkExecTx-10 712.0 ± 0% 520.0 ± 0% -26.97% (p=0.000 n=10) geomean 4.899Ki 189.7 -96.22% │ b.txt │ n.txt │ │ allocs/op │ allocs/op vs base │ Suite/BenchmarkExec/Params-10 10.000 ± 0% 9.000 ± 0% -10.00% (p=0.000 n=10) Suite/BenchmarkExec/NoParams-10 7.000 ± 0% 4.000 ± 0% -42.86% (p=0.000 n=10) Suite/BenchmarkExecContext/Params-10 12.00 ± 0% 11.00 ± 0% -8.33% (p=0.000 n=10) Suite/BenchmarkExecContext/NoParams-10 9.000 ± 0% 6.000 ± 0% -33.33% (p=0.000 n=10) Suite/BenchmarkExecStep-10 7000.000 ± 0% 4.000 ± 0% -99.94% (p=0.000 n=10) Suite/BenchmarkExecContextStep-10 9001.000 ± 0% 6.000 ± 0% -99.93% (p=0.000 n=10) Suite/BenchmarkExecTx-10 27.00 ± 0% 18.00 ± 0% -33.33% (p=0.000 n=10) geomean 74.60 7.224 -90.32% ```
1 parent abdd47b commit 604aac6

File tree

3 files changed

+189
-22
lines changed

3 files changed

+189
-22
lines changed

sqlite3.go

Lines changed: 149 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,61 @@ _sqlite3_prepare_v2_internal(sqlite3 *db, const char *zSql, int nBytes, sqlite3_
137137
}
138138
#endif
139139
140+
static int _sqlite3_prepare_v2(sqlite3 *db, const char *zSql, int nBytes, sqlite3_stmt **ppStmt, int *oBytes) {
141+
const char *tail;
142+
int rv = _sqlite3_prepare_v2_internal(db, zSql, nBytes, ppStmt, &tail);
143+
if (rv != SQLITE_OK) {
144+
return rv;
145+
}
146+
if (tail) {
147+
// Set oBytes to the number of bytes consumed instead of using the
148+
// **pzTail out param since that requires storing a Go pointer in
149+
// a C pointer, which is not allowed by CGO and will cause
150+
// runtime.cgoCheckPointer to fail.
151+
*oBytes = tail - zSql;
152+
} else {
153+
// NB: this should not happen, but if it does advance oBytes to the
154+
// end of the string so that we do not loop infinitely.
155+
*oBytes = nBytes;
156+
}
157+
return SQLITE_OK;
158+
}
159+
160+
// _sqlite3_exec_no_args executes all of the statements in zSql. None of the
161+
// statements are allowed to have positional arguments.
162+
int _sqlite3_exec_no_args(sqlite3 *db, const char *zSql, int nBytes, int64_t *rowid, int64_t *changes) {
163+
while (*zSql && nBytes > 0) {
164+
sqlite3_stmt *stmt;
165+
const char *tail;
166+
int rv = sqlite3_prepare_v2(db, zSql, nBytes, &stmt, &tail);
167+
if (rv != SQLITE_OK) {
168+
return rv;
169+
}
170+
171+
// Process statement
172+
do {
173+
rv = _sqlite3_step_internal(stmt);
174+
} while (rv == SQLITE_ROW);
175+
176+
// Only record the number of changes made by the last statement.
177+
*changes = sqlite3_changes64(db);
178+
*rowid = sqlite3_last_insert_rowid(db);
179+
180+
if (rv != SQLITE_OK && rv != SQLITE_DONE) {
181+
sqlite3_finalize(stmt);
182+
return rv;
183+
}
184+
rv = sqlite3_finalize(stmt);
185+
if (rv != SQLITE_OK) {
186+
return rv;
187+
}
188+
189+
nBytes -= tail - zSql;
190+
zSql = tail;
191+
}
192+
return SQLITE_OK;
193+
}
194+
140195
void _sqlite3_result_text(sqlite3_context* ctx, const char* s) {
141196
sqlite3_result_text(ctx, s, -1, &free);
142197
}
@@ -858,54 +913,119 @@ func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, err
858913
}
859914

860915
func (c *SQLiteConn) exec(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) {
861-
start := 0
916+
// Trim the query. This is mostly important for getting rid
917+
// of any trailing space.
918+
query = strings.TrimSpace(query)
919+
if len(args) > 0 {
920+
return c.execArgs(ctx, query, args)
921+
}
922+
return c.execNoArgs(ctx, query)
923+
}
924+
925+
func (c *SQLiteConn) execArgs(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) {
926+
var (
927+
stmtArgs []driver.NamedValue
928+
start int
929+
s SQLiteStmt // escapes to the heap so reuse it
930+
sz C.int // number of query bytes consumed: escapes to the heap
931+
)
862932
for {
863-
s, err := c.prepare(ctx, query)
864-
if err != nil {
865-
return nil, err
933+
s = SQLiteStmt{c: c} // reset
934+
sz = 0
935+
rv := C._sqlite3_prepare_v2(c.db, (*C.char)(unsafe.Pointer(stringData(query))),
936+
C.int(len(query)), &s.s, &sz)
937+
if rv != C.SQLITE_OK {
938+
return nil, c.lastError()
866939
}
940+
query = strings.TrimSpace(query[sz:])
941+
867942
var res driver.Result
868-
if s.(*SQLiteStmt).s != nil {
869-
stmtArgs := make([]driver.NamedValue, 0, len(args))
943+
if s.s != nil {
870944
na := s.NumInput()
871945
if len(args)-start < na {
872-
s.Close()
946+
s.finalize()
873947
return nil, fmt.Errorf("not enough args to execute query: want %d got %d", na, len(args))
874948
}
875949
// consume the number of arguments used in the current
876950
// statement and append all named arguments not
877951
// contained therein
878-
if len(args[start:start+na]) > 0 {
879-
stmtArgs = append(stmtArgs, args[start:start+na]...)
880-
for i := range args {
881-
if (i < start || i >= na) && args[i].Name != "" {
882-
stmtArgs = append(stmtArgs, args[i])
883-
}
884-
}
885-
for i := range stmtArgs {
886-
stmtArgs[i].Ordinal = i + 1
952+
stmtArgs = append(stmtArgs[:0], args[start:start+na]...)
953+
for i := range args {
954+
if (i < start || i >= na) && args[i].Name != "" {
955+
stmtArgs = append(stmtArgs, args[i])
887956
}
888957
}
889-
res, err = s.(*SQLiteStmt).exec(ctx, stmtArgs)
958+
for i := range stmtArgs {
959+
stmtArgs[i].Ordinal = i + 1
960+
}
961+
var err error
962+
res, err = s.exec(ctx, stmtArgs)
890963
if err != nil && err != driver.ErrSkip {
891-
s.Close()
964+
s.finalize()
892965
return nil, err
893966
}
894967
start += na
895968
}
896-
tail := s.(*SQLiteStmt).t
897-
s.Close()
898-
if tail == "" {
969+
s.finalize()
970+
if len(query) == 0 {
899971
if res == nil {
900972
// https://github.com/mattn/go-sqlite3/issues/963
901973
res = &SQLiteResult{0, 0}
902974
}
903975
return res, nil
904976
}
905-
query = tail
906977
}
907978
}
908979

980+
// execNoArgsSync processes every SQL statement in query. All processing occurs
981+
// in C code, which reduces the overhead of CGO calls.
982+
func (c *SQLiteConn) execNoArgsSync(query string) (_ driver.Result, err error) {
983+
var rowid, changes C.int64_t
984+
rv := C._sqlite3_exec_no_args(c.db, (*C.char)(unsafe.Pointer(stringData(query))),
985+
C.int(len(query)), &rowid, &changes)
986+
if rv != C.SQLITE_OK {
987+
err = c.lastError()
988+
}
989+
return &SQLiteResult{id: int64(rowid), changes: int64(changes)}, err
990+
}
991+
992+
func (c *SQLiteConn) execNoArgs(ctx context.Context, query string) (driver.Result, error) {
993+
done := ctx.Done()
994+
if done == nil {
995+
return c.execNoArgsSync(query)
996+
}
997+
998+
// Fast check if the Context is cancelled
999+
if err := ctx.Err(); err != nil {
1000+
return nil, err
1001+
}
1002+
1003+
ch := make(chan struct{})
1004+
defer close(ch)
1005+
go func() {
1006+
select {
1007+
case <-done:
1008+
C.sqlite3_interrupt(c.db)
1009+
// Wait until signaled. We need to ensure that this goroutine
1010+
// will not call interrupt after this method returns, which is
1011+
// why we can't check if only done is closed when waiting below.
1012+
<-ch
1013+
case <-ch:
1014+
}
1015+
}()
1016+
1017+
res, err := c.execNoArgsSync(query)
1018+
1019+
// Stop the goroutine and make sure we're at a point where
1020+
// sqlite3_interrupt cannot be called again.
1021+
ch <- struct{}{}
1022+
1023+
if isInterruptErr(err) {
1024+
err = ctx.Err()
1025+
}
1026+
return res, err
1027+
}
1028+
9091029
// Query implements Queryer.
9101030
func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, error) {
9111031
list := make([]driver.NamedValue, len(args))
@@ -1914,6 +2034,13 @@ func (s *SQLiteStmt) Close() error {
19142034
return nil
19152035
}
19162036

2037+
func (s *SQLiteStmt) finalize() {
2038+
if s.s != nil {
2039+
C.sqlite3_finalize(s.s)
2040+
s.s = nil
2041+
}
2042+
}
2043+
19172044
// NumInput return a number of parameters.
19182045
func (s *SQLiteStmt) NumInput() int {
19192046
return int(C.sqlite3_bind_parameter_count(s.s))

unsafe_go120.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
//go:build !go1.21
2+
// +build !go1.21
3+
4+
package sqlite3
5+
6+
import "unsafe"
7+
8+
// stringData is a safe version of unsafe.StringData that handles empty strings.
9+
func stringData(s string) *byte {
10+
if len(s) != 0 {
11+
b := *(*[]byte)(unsafe.Pointer(&s))
12+
return &b[0]
13+
}
14+
// The return value of unsafe.StringData
15+
// is unspecified if the string is empty.
16+
return &placeHolder[0]
17+
}

unsafe_go121.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
//go:build go1.21
2+
// +build go1.21
3+
4+
// The unsafe.StringData function was made available in Go 1.20 but it
5+
// was not until Go 1.21 that Go was changed to interpret the Go version
6+
// in go.mod (1.19 as of writing this) as the minimum version required
7+
// instead of the exact version.
8+
//
9+
// See: https://github.com/golang/go/issues/59033
10+
11+
package sqlite3
12+
13+
import "unsafe"
14+
15+
// stringData is a safe version of unsafe.StringData that handles empty strings.
16+
func stringData(s string) *byte {
17+
if len(s) != 0 {
18+
return unsafe.StringData(s)
19+
}
20+
// The return value of unsafe.StringData
21+
// is unspecified if the string is empty.
22+
return &placeHolder[0]
23+
}

0 commit comments

Comments
 (0)