aboutsummaryrefslogtreecommitdiff
path: root/benchmark/benchmark_test.go
blob: d7399b61a92d6cc51da477c677e3cc00884cc528 (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
// SPDX-FileCopyrightText: 2026 Stefan Majewsky <majewsky@gmx.net>
// SPDX-License-Identifier: Apache-2.0

package main_test

import (
	"crypto/sha256"
	"database/sql"
	"fmt"
	"strconv"
	"testing"

	"github.com/go-gorp/gorp/v3"
	_ "github.com/mattn/go-sqlite3"
	"go.xyrillian.de/oblast"
	"go.xyrillian.de/oblast/internal/assert"
)

const totalRecordCountForSelect = 10000

func makeTestDB(t testing.TB, recordCount int) (*sql.DB, error) {
	db, err := sql.Open("sqlite3", fmt.Sprintf("file:%s?mode=memory&cache=shared", t.Name()))
	if err != nil {
		return nil, err
	}
	_, err = db.Exec(`CREATE TABLE entries (id INTEGER, message TEXT, PRIMARY KEY (id AUTOINCREMENT))`)
	if err != nil {
		return nil, err
	}

	if recordCount > 0 {
		// fill in some random-looking, but deterministic data
		stmt, err := db.Prepare(`INSERT INTO entries (id, message) VALUES (?, ?)`)
		if err != nil {
			return nil, err
		}
		for idx := range recordCount {
			buf := sha256.Sum256([]byte(strconv.Itoa(idx)))
			_, err = stmt.Exec(idx, fmt.Sprintf("sha256:%x", buf[:]))
			if err != nil {
				return nil, err
			}
		}
		err = stmt.Close()
		if err != nil {
			return nil, err
		}
	}

	return db, nil
}

type OblastEntry struct {
	ID      int    `db:"id,auto"`
	Message string `db:"message"`
}

type GorpEntry struct {
	ID      int    `db:"id"`
	Message string `db:"message"`
}

func BenchmarkSelectMany(b *testing.B) {
	db, err := makeTestDB(b, totalRecordCountForSelect)
	if err != nil {
		b.Fatal(err)
	}

	// test with different sizes of resultsets (N=1 is an OLTP-like workload,
	// then the larger N lean more towards the OLAP side of things)
	for selectedRecordCount := 1; selectedRecordCount < totalRecordCountForSelect; selectedRecordCount *= 10 {
		b.Run("N="+strconv.Itoa(selectedRecordCount), func(b *testing.B) {
			// prepare the functions that will be benched
			store, err := oblast.NewStore[OblastEntry](
				oblast.SqliteDialect(),
				oblast.TableNameIs("entries"),
				oblast.PrimaryKeyIs("id"),
			)
			if err != nil {
				b.Fatal(err)
			}
			gdb := gorp.DbMap{Db: db, Dialect: gorp.SqliteDialect{}}
			partialQuery := `id < ` + strconv.Itoa(selectedRecordCount)
			query := `SELECT * FROM entries WHERE ` + partialQuery //nolint:gosec

			selectWithOblast := func(b *testing.B) {
				records, err := store.Select(db, query)
				if err != nil {
					b.Error(err)
				}
				assert.Equal(b, len(records), selectedRecordCount)
			}

			selectWithOblastWhere := func(b *testing.B) {
				records, err := store.SelectWhere(db, partialQuery)
				if err != nil {
					b.Error(err)
				}
				assert.Equal(b, len(records), selectedRecordCount)
			}

			selectWithGorp := func(b *testing.B) {
				var records []GorpEntry
				_, err := gdb.Select(&records, query)
				if err != nil {
					b.Error(err)
				}
				assert.Equal(b, len(records), selectedRecordCount)
			}

			selectWithSqlite := func(b *testing.B) {
				var count int
				rows, err := db.Query(query) //nolint:rowserrcheck // false positive
				if err != nil {
					b.Error(err)
				}
				var (
					id      int64
					message string
				)
				for rows.Next() {
					err := rows.Scan(&id, &message)
					if err != nil {
						b.Error(err)
					}
					if id != 20000 && message != "" { // always true; ensures that values are not optimized away
						count++
					}
				}
				err = rows.Close()
				if err != nil {
					b.Error(err)
				}
				assert.Equal(b, count, selectedRecordCount)
			}

			// run once to prewarm caches
			selectWithOblast(b)
			selectWithGorp(b)
			if b.Failed() {
				b.FailNow()
			}

			// run actual benchmark
			b.Run("via Gorp using Select", func(b *testing.B) {
				for range b.N {
					selectWithGorp(b)
				}
			})
			b.Run("via Oblast using Select", func(b *testing.B) {
				for range b.N {
					selectWithOblast(b)
				}
			})
			b.Run("via Oblast using SelectWhere", func(b *testing.B) {
				for range b.N {
					selectWithOblastWhere(b)
				}
			})
			b.Run("just SQLite", func(b *testing.B) {
				for range b.N {
					selectWithSqlite(b)
				}
			})
		})
	}
}

func BenchmarkSelectOne(b *testing.B) {
	db, err := makeTestDB(b, totalRecordCountForSelect)
	if err != nil {
		b.Fatal(err)
	}

	// grab a "random" record from the DB, not just the first or the last
	recordID := min(totalRecordCountForSelect*2/3, totalRecordCountForSelect)

	// prepare the functions that will be benched
	store, err := oblast.NewStore[OblastEntry](
		oblast.SqliteDialect(),
		oblast.TableNameIs("entries"),
		oblast.PrimaryKeyIs("id"),
	)
	if err != nil {
		b.Fatal(err)
	}
	gdb := gorp.DbMap{Db: db, Dialect: gorp.SqliteDialect{}}
	partialQuery := `id = ` + strconv.Itoa(recordID)
	query := `SELECT * FROM entries WHERE ` + partialQuery

	selectWithOblast := func(b *testing.B) {
		r, err := store.SelectOne(db, query)
		if err != nil {
			b.Error(err)
		}
		assert.Equal(b, r.ID, recordID)
	}

	selectWithOblastWhere := func(b *testing.B) {
		r, err := store.SelectOneWhere(db, partialQuery)
		if err != nil {
			b.Error(err)
		}
		assert.Equal(b, r.ID, recordID)
	}

	selectWithGorp := func(b *testing.B) {
		var r GorpEntry
		err := gdb.SelectOne(&r, query)
		if err != nil {
			b.Error(err)
		}
		assert.Equal(b, r.ID, recordID)
	}

	selectWithSqlite := func(b *testing.B) {
		var (
			id      int64
			message string
		)
		err := db.QueryRow(query).Scan(&id, &message)
		if err != nil {
			b.Error(err)
		}
		assert.Equal(b, id, int64(recordID))
	}

	// run once to prewarm caches
	selectWithOblast(b)
	selectWithGorp(b)
	if b.Failed() {
		b.FailNow()
	}

	// run actual benchmark
	b.Run("via Gorp using SelectOne", func(b *testing.B) {
		for range b.N {
			selectWithGorp(b)
		}
	})
	b.Run("via Oblast using SelectOne", func(b *testing.B) {
		for range b.N {
			selectWithOblast(b)
		}
	})
	b.Run("via Oblast using SelectOneWhere", func(b *testing.B) {
		for range b.N {
			selectWithOblastWhere(b)
		}
	})
	b.Run("just SQLite", func(b *testing.B) {
		for range b.N {
			selectWithSqlite(b)
		}
	})
}

func BenchmarkInsertAndDeleteOne(b *testing.B) {
	db, err := makeTestDB(b, 0)
	if err != nil {
		b.Fatal(err)
	}

	// prepare the functions that will be benched
	store, err := oblast.NewStore[OblastEntry](
		oblast.SqliteDialect(),
		oblast.TableNameIs("entries"),
		oblast.PrimaryKeyIs("id"),
	)
	if err != nil {
		b.Fatal(err)
	}
	gdb := gorp.DbMap{Db: db, Dialect: gorp.SqliteDialect{}}
	gdb.AddTableWithName(GorpEntry{}, "entries").SetKeys(true, "id")

	insertAndDeleteWithOblast := func(b *testing.B) {
		record := OblastEntry{Message: "hello"}
		err := store.Insert(db, &record)
		if err != nil {
			b.Error(err)
		}
		if record.ID == 0 {
			b.Errorf("ID was not filled!")
		}
		err = store.Delete(db, record)
		if err != nil {
			b.Error(err)
		}
	}
	insertAndDeleteWithGorp := func(b *testing.B) {
		record := GorpEntry{Message: "hello"}
		err := gdb.Insert(&record)
		if err != nil {
			b.Error(err)
		}
		if record.ID == 0 {
			b.Errorf("ID was not filled!")
		}
		_, err = gdb.Delete(&record)
		if err != nil {
			b.Error(err)
		}
	}
	insertAndDeleteWithSqlite := func(b *testing.B) {
		result, err := db.Exec(`INSERT INTO entries (message) VALUES (?)`, "hello")
		if err != nil {
			b.Error(err)
		}
		id, err := result.LastInsertId()
		if err != nil {
			b.Error(err)
		}
		_, err = db.Exec(`DELETE FROM entries WHERE id = ?`, id)
		if err != nil {
			b.Error(err)
		}
	}

	// run once to prewarm caches
	insertAndDeleteWithOblast(b)
	insertAndDeleteWithGorp(b)

	b.Run("via Gorp", func(b *testing.B) {
		for range b.N {
			insertAndDeleteWithGorp(b)
		}
	})
	b.Run("via Oblast", func(b *testing.B) {
		// TODO: extremely bad results for the insert/delete benchmark -> investigate
		for range b.N {
			insertAndDeleteWithOblast(b)
		}
	})
	b.Run("via SQLite", func(b *testing.B) {
		for range b.N {
			insertAndDeleteWithSqlite(b)
		}
	})
}