summaryrefslogtreecommitdiff
path: root/ledger/store/trackerdb/sqlitedriver/sqlitedriver.go
blob: 02c290be2dc384ce826d65e59b85af44720f1e9f (plain)
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
// Copyright (C) 2019-2023 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand.  If not, see <https://www.gnu.org/licenses/>.

package sqlitedriver

import (
	"context"
	"database/sql"
	"errors"
	"testing"
	"time"

	"github.com/algorand/go-algorand/config"
	"github.com/algorand/go-algorand/data/basics"
	"github.com/algorand/go-algorand/ledger/store/trackerdb"
	"github.com/algorand/go-algorand/logging"
	"github.com/algorand/go-algorand/protocol"
	"github.com/algorand/go-algorand/util/db"
	"github.com/mattn/go-sqlite3"
)

type trackerSQLStore struct {
	pair db.Pair
	trackerdb.Reader
	trackerdb.Writer
	trackerdb.Catchpoint
}

// Open opens the sqlite database store
func Open(dbFilename string, dbMem bool, log logging.Logger) (store trackerdb.Store, err error) {
	pair, err := db.OpenPair(dbFilename, dbMem)
	if err != nil {
		return
	}
	pair.Rdb.SetLogger(log)
	pair.Wdb.SetLogger(log)
	return MakeStore(pair), nil
}

// MakeStore crates a tracker SQL db from sql db handle.
func MakeStore(pair db.Pair) trackerdb.Store {
	return &trackerSQLStore{pair, &sqlReader{pair.Rdb.Handle}, &sqlWriter{pair.Wdb.Handle}, &sqlCatchpoint{pair.Wdb.Handle}}
}

func (s *trackerSQLStore) SetSynchronousMode(ctx context.Context, mode db.SynchronousMode, fullfsync bool) (err error) {
	return s.pair.Wdb.SetSynchronousMode(ctx, mode, fullfsync)
}

func (s *trackerSQLStore) IsSharedCacheConnection() bool {
	return s.pair.Wdb.IsSharedCacheConnection()
}

func (s *trackerSQLStore) Batch(fn trackerdb.BatchFn) (err error) {
	return s.BatchContext(context.Background(), fn)
}

func (s *trackerSQLStore) BatchContext(ctx context.Context, fn trackerdb.BatchFn) (err error) {
	return wrapIOError(s.pair.Wdb.AtomicContext(ctx, func(ctx context.Context, tx *sql.Tx) error {
		return fn(ctx, &sqlBatchScope{tx, false, &sqlWriter{tx}})
	}))
}

func (s *trackerSQLStore) BeginBatch(ctx context.Context) (trackerdb.Batch, error) {
	handle, err := s.pair.Wdb.Handle.BeginTx(ctx, nil)
	if err != nil {
		return nil, wrapIOError(err)
	}
	return &sqlBatchScope{handle, false, &sqlWriter{handle}}, nil
}

func (s *trackerSQLStore) Snapshot(fn trackerdb.SnapshotFn) (err error) {
	return wrapIOError(s.SnapshotContext(context.Background(), fn))
}

func (s *trackerSQLStore) SnapshotContext(ctx context.Context, fn trackerdb.SnapshotFn) (err error) {
	return wrapIOError(s.pair.Rdb.AtomicContext(ctx, func(ctx context.Context, tx *sql.Tx) error {
		return fn(ctx, &sqlSnapshotScope{tx, &sqlReader{tx}})
	}))
}

func (s *trackerSQLStore) BeginSnapshot(ctx context.Context) (trackerdb.Snapshot, error) {
	handle, err := s.pair.Rdb.Handle.BeginTx(ctx, nil)
	if err != nil {
		return nil, wrapIOError(err)
	}
	return &sqlSnapshotScope{handle, &sqlReader{handle}}, nil
}

func (s *trackerSQLStore) Transaction(fn trackerdb.TransactionFn) (err error) {
	return wrapIOError(s.TransactionContext(context.Background(), fn))
}

func (s *trackerSQLStore) TransactionContext(ctx context.Context, fn trackerdb.TransactionFn) (err error) {
	return wrapIOError(s.pair.Wdb.AtomicContext(ctx, func(ctx context.Context, tx *sql.Tx) error {
		return fn(ctx, &sqlTransactionScope{tx, false, &sqlReader{tx}, &sqlWriter{tx}, &sqlCatchpoint{tx}})
	}))
}

func (s *trackerSQLStore) BeginTransaction(ctx context.Context) (trackerdb.Transaction, error) {
	handle, err := s.pair.Wdb.Handle.BeginTx(ctx, nil)
	if err != nil {
		return nil, wrapIOError(err)
	}
	return &sqlTransactionScope{handle, false, &sqlReader{handle}, &sqlWriter{handle}, &sqlCatchpoint{handle}}, nil
}

func (s trackerSQLStore) RunMigrations(ctx context.Context, params trackerdb.Params, log logging.Logger, targetVersion int32) (mgr trackerdb.InitParams, err error) {
	err = wrapIOError(s.pair.Wdb.AtomicContext(ctx, func(ctx context.Context, tx *sql.Tx) error {
		mgr, err = RunMigrations(ctx, tx, params, log, targetVersion)
		return err
	}))
	return
}

// TODO: rename: this is a sqlite specific name, this could also be used to trigger compact on KV stores.
// it seems to only be used during a v2 migration
func (s *trackerSQLStore) Vacuum(ctx context.Context) (stats db.VacuumStats, err error) {
	_, err = s.pair.Wdb.Vacuum(ctx)
	return
}

func (s *trackerSQLStore) ResetToV6Test(ctx context.Context) error {
	var resetExprs = []string{
		`DROP TABLE IF EXISTS onlineaccounts`,
		`DROP TABLE IF EXISTS txtail`,
		`DROP TABLE IF EXISTS onlineroundparamstail`,
		`DROP TABLE IF EXISTS catchpointfirststageinfo`,
	}

	return s.pair.Wdb.AtomicContext(ctx, func(ctx context.Context, tx *sql.Tx) error {
		for _, stmt := range resetExprs {
			_, err := tx.ExecContext(ctx, stmt)
			if err != nil {
				return err
			}
		}
		return nil
	})
}

func (s *trackerSQLStore) Close() {
	s.pair.Close()
}

type sqlReader struct {
	q db.Queryable
}

// MakeAccountsOptimizedReader implements trackerdb.Reader
func (r *sqlReader) MakeAccountsOptimizedReader() (trackerdb.AccountsReader, error) {
	return AccountsInitDbQueries(r.q)
}

// MakeAccountsReader implements trackerdb.Reader
func (r *sqlReader) MakeAccountsReader() (trackerdb.AccountsReaderExt, error) {
	// TODO: create and use a make accounts reader that takes just a queryable
	return NewAccountsSQLReader(r.q), nil
}

// MakeOnlineAccountsOptimizedReader implements trackerdb.Reader
func (r *sqlReader) MakeOnlineAccountsOptimizedReader() (trackerdb.OnlineAccountsReader, error) {
	return OnlineAccountsInitDbQueries(r.q)
}

// MakeSpVerificationCtxReader implements trackerdb.Reader
func (r *sqlReader) MakeSpVerificationCtxReader() trackerdb.SpVerificationCtxReader {
	return makeStateProofVerificationReader(r.q)
}

// MakeCatchpointPendingHashesIterator implements trackerdb.Reader
func (r *sqlReader) MakeCatchpointPendingHashesIterator(hashCount int) trackerdb.CatchpointPendingHashesIter {
	return MakeCatchpointPendingHashesIterator(hashCount, r.q)
}

// MakeCatchpointReader implements trackerdb.Reader
func (r *sqlReader) MakeCatchpointReader() (trackerdb.CatchpointReader, error) {
	return makeCatchpointReader(r.q), nil
}

// MakeEncodedAccoutsBatchIter implements trackerdb.Reader
func (r *sqlReader) MakeEncodedAccoutsBatchIter() trackerdb.EncodedAccountsBatchIter {
	return MakeEncodedAccoutsBatchIter(r.q)
}

// MakeKVsIter implements trackerdb.Reader
func (r *sqlReader) MakeKVsIter(ctx context.Context) (trackerdb.KVsIter, error) {
	return MakeKVsIter(ctx, r.q)
}

type sqlWriter struct {
	e db.Executable
}

// MakeAccountsOptimizedWriter implements trackerdb.Writer
func (w *sqlWriter) MakeAccountsOptimizedWriter(hasAccounts, hasResources, hasKvPairs, hasCreatables bool) (trackerdb.AccountsWriter, error) {
	return MakeAccountsSQLWriter(w.e, hasAccounts, hasResources, hasKvPairs, hasCreatables)
}

// MakeAccountsWriter implements trackerdb.Writer
func (w *sqlWriter) MakeAccountsWriter() (trackerdb.AccountsWriterExt, error) {
	return NewAccountsSQLReaderWriter(w.e), nil
}

// MakeOnlineAccountsOptimizedWriter implements trackerdb.Writer
func (w *sqlWriter) MakeOnlineAccountsOptimizedWriter(hasAccounts bool) (trackerdb.OnlineAccountsWriter, error) {
	return MakeOnlineAccountsSQLWriter(w.e, hasAccounts)
}

// MakeSpVerificationCtxWriter implements trackerdb.Writer
func (w *sqlWriter) MakeSpVerificationCtxWriter() trackerdb.SpVerificationCtxWriter {
	return makeStateProofVerificationWriter(w.e)
}

// Testing implements trackerdb.Writer
func (w *sqlWriter) Testing() trackerdb.WriterTestExt {
	return w
}

// AccountsInitLightTest implements trackerdb.WriterTestExt
func (w *sqlWriter) AccountsInitLightTest(tb testing.TB, initAccounts map[basics.Address]basics.AccountData, proto config.ConsensusParams) (newDatabase bool, err error) {
	return AccountsInitLightTest(tb, w.e, initAccounts, proto)
}

// AccountsInitTest implements trackerdb.WriterTestExt
func (w *sqlWriter) AccountsInitTest(tb testing.TB, initAccounts map[basics.Address]basics.AccountData, proto protocol.ConsensusVersion) (newDatabase bool) {
	return AccountsInitTest(tb, w.e, initAccounts, proto)
}

// AccountsUpdateSchemaTest implements trackerdb.WriterTestExt
func (w *sqlWriter) AccountsUpdateSchemaTest(ctx context.Context) (err error) {
	return AccountsUpdateSchemaTest(ctx, w.e)
}

// ModifyAcctBaseTest implements trackerdb.WriterTestExt
func (w *sqlWriter) ModifyAcctBaseTest() error {
	return modifyAcctBaseTest(w.e)
}

type sqlCatchpoint struct {
	e db.Executable
}

// MakeCatchpointReaderWriter implements trackerdb.Catchpoint
func (c *sqlCatchpoint) MakeCatchpointReaderWriter() (trackerdb.CatchpointReaderWriter, error) {
	return NewCatchpointSQLReaderWriter(c.e), nil
}

// MakeCatchpointWriter implements trackerdb.Catchpoint
func (c *sqlCatchpoint) MakeCatchpointWriter() (trackerdb.CatchpointWriter, error) {
	return NewCatchpointSQLReaderWriter(c.e), nil
}

// MakeMerkleCommitter implements trackerdb.Catchpoint
func (c *sqlCatchpoint) MakeMerkleCommitter(staging bool) (trackerdb.MerkleCommitter, error) {
	return MakeMerkleCommitter(c.e, staging)
}

// MakeOrderedAccountsIter implements trackerdb.Catchpoint
func (c *sqlCatchpoint) MakeOrderedAccountsIter(accountCount int) trackerdb.OrderedAccountsIter {
	return MakeOrderedAccountsIter(c.e, accountCount)
}

type sqlBatchScope struct {
	tx        *sql.Tx
	committed bool
	trackerdb.Writer
}

func (bs *sqlBatchScope) ResetTransactionWarnDeadline(ctx context.Context, deadline time.Time) (prevDeadline time.Time, err error) {
	return db.ResetTransactionWarnDeadline(ctx, bs.tx, deadline)
}

func (bs *sqlBatchScope) Close() error {
	if !bs.committed {
		return wrapIOError(bs.tx.Rollback())
	}
	return nil
}

func (bs *sqlBatchScope) Commit() error {
	err := bs.tx.Commit()
	if err != nil {
		return wrapIOError(err)
	}
	bs.committed = true
	return nil
}

type sqlSnapshotScope struct {
	tx *sql.Tx
	trackerdb.Reader
}

func (ss *sqlSnapshotScope) ResetTransactionWarnDeadline(ctx context.Context, deadline time.Time) (prevDeadline time.Time, err error) {
	return db.ResetTransactionWarnDeadline(ctx, ss.tx, deadline)
}

func (ss *sqlSnapshotScope) Close() error {
	return wrapIOError(ss.tx.Rollback())
}

type sqlTransactionScope struct {
	tx        *sql.Tx
	committed bool
	trackerdb.Reader
	trackerdb.Writer
	trackerdb.Catchpoint
}

func (txs *sqlTransactionScope) RunMigrations(ctx context.Context, params trackerdb.Params, log logging.Logger, targetVersion int32) (mgr trackerdb.InitParams, err error) {
	return RunMigrations(ctx, txs.tx, params, log, targetVersion)
}

func (txs *sqlTransactionScope) ResetTransactionWarnDeadline(ctx context.Context, deadline time.Time) (prevDeadline time.Time, err error) {
	return db.ResetTransactionWarnDeadline(ctx, txs.tx, deadline)
}

func (txs *sqlTransactionScope) Close() error {
	if !txs.committed {
		return wrapIOError(txs.tx.Rollback())
	}
	return nil
}

func (txs *sqlTransactionScope) Commit() error {
	err := txs.tx.Commit()
	if err != nil {
		return wrapIOError(err)
	}
	txs.committed = true
	return nil
}

// wrapIOError allows for SQL IO Errors to be represented as trackerdb.ErrIoErr
// in places which may enconter them.
func wrapIOError(err error) error {
	if err == nil {
		return nil
	}
	// if it's already a trackerdb error, don't wrap it again
	var alreadyWrapped *trackerdb.ErrIoErr
	if errors.As(err, &alreadyWrapped) {
		return err
	}
	var sqliteErr sqlite3.Error
	if errors.As(err, &sqliteErr) {
		if sqliteErr.Code == sqlite3.ErrIoErr {
			return &trackerdb.ErrIoErr{InnerError: err}
		}
	}
	return err
}