Repository navigation
Expand file tree
/
Copy pathcache.go
More file actions
241 lines (224 loc) · 7.97 KB
/
Copy pathcache.go
File metadata and controls
241 lines (224 loc) · 7.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
// Copyright (c) 2026 The liustack/sqlite Authors.
// SPDX-License-Identifier: MIT
// Use of this source code is governed by the MIT license in LICENSE at the
// root of this repository.
//go:build ((linux || darwin) && (amd64 || arm64)) || (windows && (amd64 || arm64))
package sqlite
import (
"context"
"database/sql/driver"
"strings"
)
// maxQueries is the most statements a connection keeps for QueryContext.
const maxQueries = 64
// maxKeptBytes is the most bytes the statements of the query cache of a
// connection hold, their SQL counted, and the most its write cache holds. A
// statement of more than maxKeptBytes/8 is kept by neither, as one with a
// long list of values in its SQL: preparing it costs little beside running
// it.
const maxKeptBytes = 512 << 10
// queryStmt gives the statement of QueryContext for query: the one the
// connection keeps for it when its rows are closed, or one prepared now. One
// prepared now is kept when it only reads the main database (read-only, not
// Private, not EXPLAIN), holds no more than maxKeptBytes/8, and the cache
// has room or statements no rows use to let go. Otherwise its rows finalize
// it.
//
// Writes are not kept here: they have rules of their own (keepsWrite). A
// PRAGMA is not kept either, as SQLite prepares one again each time it runs.
// And conn.prepare empties the cache when the connection prepares a
// statement that changes it. A connection a host callback broke keeps
// nothing (keepsWrite).
func (c *conn) queryStmt(ctx context.Context, query string) (*stmt, error) {
if c.retired() {
return nil, c.refusal() // before Stats counts a statement found or prepared
}
c.queryTick++
if s := c.queries[query]; s != nil && s.rows == nil {
s.used = c.queryTick
c.hits.Add(1)
return s, nil
}
c.misses.Add(1)
p, sql, err := c.prepareOne(ctx, query)
if err != nil {
return nil, err
}
s := newStmt(c, p, sql, true)
if c.c.Broken() || !p.ReadOnly() || p.Private() || p.IsExplain() || c.queries[query] != nil {
return s, nil
}
size := p.MemUsed() + len(query)
if size > maxKeptBytes/8 || !c.queryRoom(size) {
return s, nil
}
if c.queries == nil {
c.queries = map[string]*stmt{}
}
// A copy: query may be cut from a longer string of the caller's.
query = strings.Clone(query)
s.once, s.kept, s.used, s.keptAt, s.size = false, query, c.queryTick, p.Reprepares(), size
c.queries[query] = s
c.queryBytes += size
return s, nil
}
// queryRoom makes room in the cache for one more statement that holds size
// bytes, finalizing those used longest ago of the ones no rows use. It says
// false when that is not enough.
func (c *conn) queryRoom(size int) bool {
for len(c.queries) >= maxQueries || c.queryBytes+size > maxKeptBytes {
var old *stmt
for _, s := range c.queries {
if s.rows == nil && (old == nil || s.used < old.used) {
old = s
}
}
if old == nil {
return false
}
c.dropQuery(old)
}
return true
}
// dropQuery takes s out of the cache and finalizes it.
func (c *conn) dropQuery(s *stmt) {
delete(c.queries, s.kept)
c.queryBytes -= s.size
s.kept = ""
s.Close()
}
// keepQuery is what the rows of a kept statement do as they close, after the
// reset gave err: the statement goes back to the cache with its text and
// BLOB arguments let go (letGo). A statement that failed is finalized
// instead, so that the next query prepares from nothing, and so is one
// SQLite prepared again: after a change of the schema what it reads may have
// changed, and the next query sorts it again (a table may have become a Go
// table, whose plan is made in Go as SQLite prepares the query).
func (c *conn) keepQuery(s *stmt, err error) error {
if err == nil && s.s.Reprepares() == s.keptAt {
err = s.letGo()
if err == nil {
return nil
}
}
c.dropQuery(s)
return err
}
// letGo binds NULL to the parameters that hold text or a BLOB, so that a
// kept statement holds no copy of a caller's argument. Its other parameters
// keep their numbers, which take no memory: a NULL there could make SQLite
// prepare the statement again (bind).
func (s *stmt) letGo() error {
for _, i := range s.held {
if err := s.s.BindNull(i); err != nil {
return err
}
}
s.held = s.held[:0]
return nil
}
// dropQueries empties the cache: as the connection closes, or when it
// prepared a statement that changes it. A statement whose rows are still
// open is finalized by its rows.
func (c *conn) dropQueries() {
for _, s := range c.queries {
if s.rows != nil {
delete(c.queries, s.kept)
c.queryBytes -= s.size
s.kept, s.once = "", true
continue
}
c.dropQuery(s)
}
}
// maxWrites is the most writes a connection keeps for ExecContext. They
// hold maxKeptBytes at most.
const maxWrites = 64
// keepsWrite says s, run by an Exec of that one statement, may be kept for
// its SQL: it writes the main database and touches nothing only its
// connection has (Mergeable), it is no EXPLAIN, and c never changed itself.
// SQLite codes settings of the connection, such as foreign_keys and
// defer_foreign_keys, into a write as it prepares it, and does not always
// prepare it again when they change. On a connection that never changed
// itself those settings are the DSN's from the start and stay so, and one
// whose DSN turns defer_foreign_keys on, which SQLite turns off at the end
// of each transaction, is alone. It is the rule of the batch cache, whose
// statements are run for connections of the same key.
//
// A write SQLite prepared again is not kept, as one whose plan looks at an
// argument is once it ran on c (LIMIT ?, a partial index): bind clears such
// a statement before each run, and so a kept write is one bind never
// clears. One that another connection ran in its batch was never bound on
// c: SQLite prepares it again at its first run on c, and execKept lets it
// go.
//
// A connection a host callback broke keeps nothing, as it runs no more C
// (internal/csqlite): its own write can succeed before the batch it then
// runs for others breaks it.
func (c *conn) keepsWrite(s *stmt) bool {
return !c.c.Broken() && !c.private() && !s.explain && !s.changesConn && !s.s.PreparedAgain() && s.s.Mergeable()
}
// keepWrite keeps s, which ran once, for query, with its text and BLOB
// arguments let go. While the cache is full, in count or in bytes, the write
// used longest ago goes.
func (c *conn) keepWrite(query string, s *stmt) {
if s.letGo() != nil {
s.Close()
return
}
size := s.s.MemUsed() + len(query)
if size > maxKeptBytes/8 {
s.Close()
return
}
if c.writes == nil {
c.writes = map[string]*stmt{}
}
for len(c.writes) > 0 && (len(c.writes) >= maxWrites || c.writeBytes+size > maxKeptBytes) {
var old *stmt
var oldKey string
for k, w := range c.writes {
if old == nil || w.used < old.used {
old, oldKey = w, k
}
}
c.dropWrite(oldKey)
}
c.writeTick++
s.used, s.keptAt, s.size = c.writeTick, s.s.Reprepares(), size
c.writes[strings.Clone(query)] = s // query may be cut from a longer string
c.writeBytes += size
}
// execKept runs s, the write kept for query, with args. It lets s go when it
// failed, so that the next Exec prepares from nothing, when SQLite prepared
// it again (the schema changed), so that the next one is sorted again, and
// when the connection broke (keepsWrite). Otherwise its text and BLOB
// arguments go.
func (c *conn) execKept(ctx context.Context, query string, s *stmt, args []driver.NamedValue) (driver.Result, error) {
c.writeTick++
s.used = c.writeTick
r, err := s.exec(ctx, args)
if err != nil || c.c.Broken() || s.s.Reprepares() != s.keptAt || s.letGo() != nil {
c.dropWrite(query)
}
if err != nil {
return nil, err
}
return r, nil
}
// dropWrite lets go of the write kept for query.
func (c *conn) dropWrite(query string) {
if s := c.writes[query]; s != nil {
delete(c.writes, query)
c.writeBytes -= s.size
s.Close()
}
}
// dropWrites lets go of every write kept: as the connection closes, or when
// it prepared a statement that changes it.
func (c *conn) dropWrites() {
for _, s := range c.writes {
s.Close()
}
c.writes, c.writeBytes = nil, 0
}