aboutsummaryrefslogtreecommitdiff
path: root/benchmark/postgres_test.go
blob: 320ea2adc47e17ca0a657aed6eb546ec1c015d68 (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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
// SPDX-FileCopyrightText: 2026 Stefan Majewsky <majewsky@gmx.net>
// SPDX-License-Identifier: Apache-2.0

package main_test

import (
	"cmp"
	"crypto/sha256"
	"database/sql"
	"fmt"
	"os"
	"strconv"
	"testing"
	"time"

	"github.com/jackc/pgx/v5"
	_ "github.com/lib/pq"
	"go.xyrillian.de/oblast"
	"go.xyrillian.de/oblast/benchmark/internal/oblast_pgx"
	"go.xyrillian.de/oblast/internal/testhelpers/assert"
	"go.xyrillian.de/oblast/internal/testhelpers/must"
)

// NOTE: In this file, we benchmark different PostgreSQL database drivers against each other with or without Oblast inbetween.
// All benchmarks are called "BenchmarkPostgres...".
// To run these benchmarks, you need to have provide a DSN to a PostgreSQL database in $BENCHMARK_POSTGRES_DSN.

// This is not a real benchmark (obviously).
// Its purpose is to be the first line that is printed, while having one of the longest names,
// so that all other results are aligned with it and the table looks nice.
func BenchmarkPostgresHeadingHeadingHeadingHeadingHeadingHeadingHeadingHeading(b *testing.B) {
	for b.Loop() {
		time.Sleep(time.Microsecond)
	}
}

const defaultPostgresDSN = "host=localhost user=postgres dbname=oblast_benchmark sslmode=disable"

func connectToPostgresTestDB(t testing.TB, recordCount int) *sql.DB {
	dsn := cmp.Or(os.Getenv("BENCHMARK_POSTGRES_DSN"), defaultPostgresDSN)
	db := must.Return(sql.Open("postgres", dsn))(t)
	_ = must.Return(db.Exec(`CREATE TEMPORARY TABLE entries (id BIGSERIAL, message TEXT)`))(t)

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

	return db
}

func connectToPgxTestDB(t testing.TB, recordCount int) *pgx.Conn {
	ctx := t.Context()
	dsn := cmp.Or(os.Getenv("BENCHMARK_POSTGRES_DSN"), defaultPostgresDSN)
	conn := must.Return(pgx.Connect(ctx, dsn))(t)
	_ = must.Return(conn.Exec(ctx, `CREATE TEMPORARY TABLE entries (id BIGSERIAL, message TEXT)`))(t)

	if recordCount > 0 {
		// fill in some random-looking, but deterministic data
		sql := `INSERT INTO entries (id, message) VALUES ($1, $2)`
		stmt := must.Return(conn.Prepare(ctx, sql, sql))(t)
		for idx := range recordCount {
			buf := sha256.Sum256([]byte(strconv.Itoa(idx)))
			_ = must.Return(conn.Exec(ctx, sql, idx, fmt.Sprintf("sha256:%x", buf[:])))(t)
		}
		must.Succeed(t, conn.Deallocate(ctx, stmt.Name))
	}

	return conn
}

func BenchmarkPostgresSelect(b *testing.B) {
	pqDB := connectToPostgresTestDB(b, totalRecordCountForSelect)
	pqDBH := oblast.Wrap(pqDB)
	pgxConn := connectToPgxTestDB(b, totalRecordCountForSelect)
	pgxConnH := oblast_pgx.Wrap(pgxConn)

	store := oblast.MustNewStore[OblastEntry](
		oblast.PostgresDialect(),
		oblast.TableNameIs("entries"),
		oblast.PrimaryKeyIs("id"),
	)

	for _, batchSize := range batchSizesForSelect {
		b.Run("N="+strconv.Itoa(batchSize), func(b *testing.B) {
			partialQuery := `id < ` + strconv.Itoa(batchSize)
			query := `SELECT * FROM entries WHERE ` + partialQuery

			b.Run("driver=pq/strategy=oblast", func(b *testing.B) {
				for b.Loop() {
					records := must.Return(store.Select(noctx, pqDBH, query))(b)
					assert.Equal(b, len(records), batchSize)
				}
			})

			b.Run("driver=pgx/strategy=oblast", func(b *testing.B) {
				for b.Loop() {
					records := must.Return(store.Select(noctx, pgxConnH, query))(b)
					assert.Equal(b, len(records), batchSize)
				}
			})

			b.Run("driver=pq/strategy=straight", func(b *testing.B) {
				for b.Loop() {
					var records []OblastEntry
					rows := must.Return(pqDB.Query(query))(b) //nolint:rowserrcheck // false positive
					for rows.Next() {
						var e OblastEntry
						must.Succeed(b, rows.Scan(&e.ID, &e.Message))
						records = append(records, e)
					}
					must.Succeed(b, rows.Close())
					assert.Equal(b, len(records), batchSize)
				}
			})

			b.Run("driver=pgx/strategy=straight", func(b *testing.B) {
				for b.Loop() {
					var records []OblastEntry
					rows := must.Return(pgxConn.Query(noctx, query))(b) //nolint:rowserrcheck // false positive
					for rows.Next() {
						var e OblastEntry
						must.Succeed(b, rows.Scan(&e.ID, &e.Message))
						records = append(records, e)
					}
					rows.Close()
					assert.Equal(b, len(records), batchSize)
				}
			})
		})
	}
}

func BenchmarkPostgresSelectOne(b *testing.B) {
	pqDB := connectToPostgresTestDB(b, totalRecordCountForSelect)
	pqDBH := oblast.Wrap(pqDB)
	pgxConn := connectToPgxTestDB(b, totalRecordCountForSelect)
	pgxConnH := oblast_pgx.Wrap(pgxConn)

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

	store := oblast.MustNewStore[OblastEntry](
		oblast.PostgresDialect(),
		oblast.TableNameIs("entries"),
		oblast.PrimaryKeyIs("id"),
	)

	partialQuery := `id = ` + strconv.Itoa(recordID)
	query := `SELECT * FROM entries WHERE ` + partialQuery
	precomputedQuery := store.MustPrepareSelectQueryWhere(partialQuery)

	b.Run("driver=pq/strategy=oblast", func(b *testing.B) {
		for b.Loop() {
			r := must.Return(precomputedQuery.SelectOne(noctx, pqDBH))(b)
			assert.Equal(b, r.ID, recordID)
		}
	})

	b.Run("driver=pgx/strategy=oblast", func(b *testing.B) {
		for b.Loop() {
			r := must.Return(precomputedQuery.SelectOne(noctx, pgxConnH))(b)
			assert.Equal(b, r.ID, recordID)
		}
	})

	b.Run("driver=pq/strategy=straight", func(b *testing.B) {
		for b.Loop() {
			var (
				id      int64
				message string
			)
			must.Succeed(b, pqDB.QueryRow(query).Scan(&id, &message))
			assert.Equal(b, id, int64(recordID))
		}
	})

	b.Run("driver=pgx/strategy=straight", func(b *testing.B) {
		for b.Loop() {
			var (
				id      int64
				message string
			)
			must.Succeed(b, pgxConn.QueryRow(noctx, query).Scan(&id, &message))
			assert.Equal(b, id, int64(recordID))
		}
	})
}

func BenchmarkPostgresInsertAndDelete(b *testing.B) {
	pqDB := connectToPostgresTestDB(b, 0)
	pqDBH := oblast.Wrap(pqDB)
	pgxConn := connectToPgxTestDB(b, 0)
	pgxConnH := oblast_pgx.Wrap(pgxConn)

	store := oblast.MustNewStore[OblastEntry](
		oblast.PostgresDialect(),
		oblast.TableNameIs("entries"),
		oblast.PrimaryKeyIs("id"),
	)

	// test with different amounts of records
	for _, batchSize := range batchSizesForInsertDelete {
		b.Run("N="+strconv.Itoa(batchSize), func(b *testing.B) {
			insertAndDeleteWithOblast := func(b *testing.B, dbh oblast.Handle) {
				records := make([]OblastEntry, batchSize)
				recordsForInsert := make([]*OblastEntry, batchSize)
				for idx := range records {
					records[idx] = OblastEntry{Message: "hello"}
					recordsForInsert[idx] = &records[idx]
				}
				must.Succeed(b, store.Insert(noctx, dbh, recordsForInsert...))
				for _, r := range records {
					if r.ID == 0 {
						b.Errorf("ID was not filled!")
					}
				}
				must.Succeed(b, store.Delete(noctx, dbh, records...))
			}

			b.Run("driver=pq/strategy=oblast", func(b *testing.B) {
				for b.Loop() {
					insertAndDeleteWithOblast(b, pqDBH)
				}
			})

			b.Run("driver=pgx/strategy=oblast", func(b *testing.B) {
				for b.Loop() {
					insertAndDeleteWithOblast(b, pgxConnH)
				}
			})

			insertQuery := `INSERT INTO entries (message) VALUES ($1) RETURNING id`
			deleteQuery := `DELETE FROM entries WHERE id = $1`

			b.Run("driver=pq/strategy=straight", func(b *testing.B) {
				for b.Loop() {
					ids := make([]int64, batchSize)
					for idx := range ids {
						must.Succeed(b, pqDB.QueryRow(insertQuery, "hello").Scan(&ids[idx]))
					}
					for _, id := range ids {
						_ = must.Return(pqDB.Exec(deleteQuery, id))(b)
					}
				}
			})

			b.Run("driver=pgx/strategy=straight", func(b *testing.B) {
				for b.Loop() {
					ids := make([]int64, batchSize)
					for idx := range ids {
						must.Succeed(b, pgxConn.QueryRow(noctx, insertQuery, "hello").Scan(&ids[idx]))
					}
					for _, id := range ids {
						_ = must.Return(pgxConn.Exec(noctx, deleteQuery, id))(b)
					}
				}
			})

			b.Run("driver=pq/strategy=prepared", func(b *testing.B) {
				for b.Loop() {
					ids := make([]int64, batchSize)
					stmtInsert := must.Return(pqDB.Prepare(insertQuery))(b)
					defer stmtInsert.Close()
					for idx := range ids {
						must.Succeed(b, stmtInsert.QueryRow("hello").Scan(&ids[idx]))
					}
					stmtDelete := must.Return(pqDB.Prepare(deleteQuery))(b)
					defer stmtDelete.Close()
					for _, id := range ids {
						_ = must.Return(stmtDelete.Exec(id))(b)
					}
				}
			})

			b.Run("driver=pgx/strategy=prepared", func(b *testing.B) {
				for b.Loop() {
					stmtInsert := must.Return(pgxConn.Prepare(noctx, "my-insert", insertQuery))(b)
					ids := make([]int64, batchSize)
					for idx := range ids {
						must.Succeed(b, pgxConn.QueryRow(noctx, stmtInsert.Name, "hello").Scan(&ids[idx]))
					}
					must.Succeed(b, pgxConn.Deallocate(noctx, stmtInsert.Name))
					stmtDelete := must.Return(pgxConn.Prepare(noctx, "my-delete", deleteQuery))(b)
					for _, id := range ids {
						_ = must.Return(pgxConn.Exec(noctx, stmtDelete.Name, id))(b)
					}
					must.Succeed(b, pgxConn.Deallocate(noctx, stmtDelete.Name))
				}
			})
		})
	}
}

func BenchmarkPostgresUpdate(b *testing.B) {
	pqDB := connectToPostgresTestDB(b, 0)
	pqDBH := oblast.Wrap(pqDB)
	pgxConn := connectToPgxTestDB(b, 0)
	pgxConnH := oblast_pgx.Wrap(pgxConn)

	store := oblast.MustNewStore[OblastEntry](
		oblast.PostgresDialect(),
		oblast.TableNameIs("entries"),
		oblast.PrimaryKeyIs("id"),
	)

	// test with different amounts of records
	for _, batchSize := range batchSizesForInsertDelete {
		b.Run("N="+strconv.Itoa(batchSize), func(b *testing.B) {
			// prepare a bunch of records that we can update, in a reproducible way
			_ = must.Return(pqDB.Exec(`DELETE FROM entries`))
			_ = must.Return(pgxConn.Exec(noctx, `DELETE FROM entries`))
			pqRecords := make([]OblastEntry, batchSize)
			pqRecordsForInsert := make([]*OblastEntry, batchSize)
			pgxRecords := make([]OblastEntry, batchSize)
			pgxRecordsForInsert := make([]*OblastEntry, batchSize)
			for idx := range batchSize {
				pqRecords[idx] = OblastEntry{Message: "hello"}
				pqRecordsForInsert[idx] = &pqRecords[idx]
				pgxRecords[idx] = OblastEntry{Message: "hello"}
				pgxRecordsForInsert[idx] = &pgxRecords[idx]
			}
			must.Succeed(b, store.Insert(noctx, pqDBH, pqRecordsForInsert...))
			must.Succeed(b, store.Insert(noctx, pgxConnH, pgxRecordsForInsert...))

			// each benchmark will, while looping, write changing values each time in the same way
			loop := func(b *testing.B, action func(string)) {
				idx := 0
				for b.Loop() {
					idx++
					message := fmt.Sprintf("round %d", idx)
					action(message)
				}
			}

			updateWithOblast := func(b *testing.B, dbh oblast.Handle, records []OblastEntry) func(string) {
				return func(message string) {
					for idx := range records {
						records[idx].Message = message
					}
					must.Succeed(b, store.Update(noctx, dbh, records...))
				}
			}

			b.Run("driver=pq/strategy=oblast", func(b *testing.B) {
				loop(b, updateWithOblast(b, pqDBH, pqRecords))
			})

			b.Run("driver=pgx/strategy=oblast", func(b *testing.B) {
				loop(b, updateWithOblast(b, pgxConnH, pgxRecords))
			})

			updateQuery := `UPDATE entries SET message = $1 WHERE id = $2`

			b.Run("driver=pq/strategy=straight", func(b *testing.B) {
				loop(b, func(message string) {
					for _, r := range pqRecords {
						_ = must.Return(pqDB.Exec(updateQuery, message, r.ID))(b)
					}
				})
			})

			b.Run("driver=pgx/strategy=straight", func(b *testing.B) {
				loop(b, func(message string) {
					for _, r := range pgxRecords {
						_ = must.Return(pgxConn.Exec(noctx, updateQuery, message, r.ID))(b)
					}
				})
			})

			b.Run("driver=pq/strategy=prepared", func(b *testing.B) {
				loop(b, func(message string) {
					stmt := must.Return(pqDB.Prepare(updateQuery))(b)
					for _, r := range pqRecords {
						_ = must.Return(stmt.Exec(message, r.ID))(b)
					}
				})
			})

			b.Run("driver=pgx/strategy=prepared", func(b *testing.B) {
				loop(b, func(message string) {
					stmt := must.Return(pgxConn.Prepare(noctx, "my-update", updateQuery))(b)
					for _, r := range pgxRecords {
						_ = must.Return(pgxConn.Exec(noctx, stmt.Name, message, r.ID))(b)
					}
					must.Succeed(b, pgxConn.Deallocate(noctx, stmt.Name))
				})
			})
		})
	}
}