Debian Codegraph @

backup_test.go

raw
1 // Copyright (C) 2019 Yasuhiro Matsumoto <[email protected]>.
2 //
3 // Use of this source code is governed by an MIT-style
4 // license that can be found in the LICENSE file.
5
6 //go:build cgo
7 // +build cgo
8
9 package sqlite3
10
11 import (
12 "database/sql"
13 "fmt"
14 "os"
15 "testing"
16 "time"
17 )
18
19 // The number of rows of test data to create in the source database.
20 // Can be used to control how many pages are available to be backed up.
21 const testRowCount = 100
22
23 // The maximum number of seconds after which the page-by-page backup is considered to have taken too long.
24 const usePagePerStepsTimeoutSeconds = 30
25
26 // Test the backup functionality.
27 func testBackup(t *testing.T, testRowCount int, usePerPageSteps bool) {
28 // This function will be called multiple times.
29 // It uses sql.Register(), which requires the name parameter value to be unique.
30 // There does not currently appear to be a way to unregister a registered driver, however.
31 // So generate a database driver name that will likely be unique.
32 var driverName = fmt.Sprintf("sqlite3_testBackup_%v_%v_%v", testRowCount, usePerPageSteps, time.Now().UnixNano())
33
34 // The driver's connection will be needed in order to perform the backup.
35 driverConns := []*SQLiteConn{}
36 sql.Register(driverName, &SQLiteDriver{
37 ConnectHook: func(conn *SQLiteConn) error {
38 driverConns = append(driverConns, conn)
39 return nil
40 },
41 })
42
43 // Connect to the source database.
44 srcTempFilename := TempFilename(t)
45 defer os.Remove(srcTempFilename)
46 srcDb, err := sql.Open(driverName, srcTempFilename)
47 if err != nil {
48 t.Fatal("Failed to open the source database:", err)
49 }
50 defer srcDb.Close()
51 err = srcDb.Ping()
52 if err != nil {
53 t.Fatal("Failed to connect to the source database:", err)
54 }
55
56 // Connect to the destination database.
57 destTempFilename := TempFilename(t)
58 defer os.Remove(destTempFilename)
59 destDb, err := sql.Open(driverName, destTempFilename)
60 if err != nil {
61 t.Fatal("Failed to open the destination database:", err)
62 }
63 defer destDb.Close()
64 err = destDb.Ping()
65 if err != nil {
66 t.Fatal("Failed to connect to the destination database:", err)
67 }
68
69 // Check the driver connections.
70 if len(driverConns) != 2 {
71 t.Fatalf("Expected 2 driver connections, but found %v.", len(driverConns))
72 }
73 srcDbDriverConn := driverConns[0]
74 if srcDbDriverConn == nil {
75 t.Fatal("The source database driver connection is nil.")
76 }
77 destDbDriverConn := driverConns[1]
78 if destDbDriverConn == nil {
79 t.Fatal("The destination database driver connection is nil.")
80 }
81
82 // Generate some test data for the given ID.
83 var generateTestData = func(id int) string {
84 return fmt.Sprintf("test-%v", id)
85 }
86
87 // Populate the source database with a test table containing some test data.
88 tx, err := srcDb.Begin()
89 if err != nil {
90 t.Fatal("Failed to begin a transaction when populating the source database:", err)
91 }
92 _, err = srcDb.Exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)")
93 if err != nil {
94 tx.Rollback()
95 t.Fatal("Failed to create the source database \"test\" table:", err)
96 }
97 for id := 0; id < testRowCount; id++ {
98 _, err = srcDb.Exec("INSERT INTO test (id, value) VALUES (?, ?)", id, generateTestData(id))
99 if err != nil {
100 tx.Rollback()
101 t.Fatal("Failed to insert a row into the source database \"test\" table:", err)
102 }
103 }
104 err = tx.Commit()
105 if err != nil {
106 t.Fatal("Failed to populate the source database:", err)
107 }
108
109 // Confirm that the destination database is initially empty.
110 var destTableCount int
111 err = destDb.QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table'").Scan(&destTableCount)
112 if err != nil {
113 t.Fatal("Failed to check the destination table count:", err)
114 }
115 if destTableCount != 0 {
116 t.Fatalf("The destination database is not empty; %v table(s) found.", destTableCount)
117 }
118
119 // Prepare to perform the backup.
120 backup, err := destDbDriverConn.Backup("main", srcDbDriverConn, "main")
121 if err != nil {
122 t.Fatal("Failed to initialize the backup:", err)
123 }
124
125 // Allow the initial page count and remaining values to be retrieved.
126 // According to <https://www.sqlite.org/c3ref/backup_finish.html>, the page count and remaining values are "... only updated by sqlite3_backup_step()."
127 isDone, err := backup.Step(0)
128 if err != nil {
129 t.Fatal("Unable to perform an initial 0-page backup step:", err)
130 }
131 if isDone {
132 t.Fatal("Backup is unexpectedly done.")
133 }
134
135 // Check that the page count and remaining values are reasonable.
136 initialPageCount := backup.PageCount()
137 if initialPageCount <= 0 {
138 t.Fatalf("Unexpected initial page count value: %v", initialPageCount)
139 }
140 initialRemaining := backup.Remaining()
141 if initialRemaining <= 0 {
142 t.Fatalf("Unexpected initial remaining value: %v", initialRemaining)
143 }
144 if initialRemaining != initialPageCount {
145 t.Fatalf("Initial remaining value differs from the initial page count value; remaining: %v; page count: %v", initialRemaining, initialPageCount)
146 }
147
148 // Perform the backup.
149 if usePerPageSteps {
150 var startTime = time.Now().Unix()
151
152 // Test backing-up using a page-by-page approach.
153 var latestRemaining = initialRemaining
154 for {
155 // Perform the backup step.
156 isDone, err = backup.Step(1)
157 if err != nil {
158 t.Fatal("Failed to perform a backup step:", err)
159 }
160
161 // The page count should remain unchanged from its initial value.
162 currentPageCount := backup.PageCount()
163 if currentPageCount != initialPageCount {
164 t.Fatalf("Current page count differs from the initial page count; initial page count: %v; current page count: %v", initialPageCount, currentPageCount)
165 }
166
167 // There should now be one less page remaining.
168 currentRemaining := backup.Remaining()
169 expectedRemaining := latestRemaining - 1
170 if currentRemaining != expectedRemaining {
171 t.Fatalf("Unexpected remaining value; expected remaining value: %v; actual remaining value: %v", expectedRemaining, currentRemaining)
172 }
173 latestRemaining = currentRemaining
174
175 if isDone {
176 break
177 }
178
179 // Limit the runtime of the backup attempt.
180 if (time.Now().Unix() - startTime) > usePagePerStepsTimeoutSeconds {
181 t.Fatal("Backup is taking longer than expected.")
182 }
183 }
184 } else {
185 // Test the copying of all remaining pages.
186 isDone, err = backup.Step(-1)
187 if err != nil {
188 t.Fatal("Failed to perform a backup step:", err)
189 }
190 if !isDone {
191 t.Fatal("Backup is unexpectedly not done.")
192 }
193 }
194
195 // Check that the page count and remaining values are reasonable.
196 finalPageCount := backup.PageCount()
197 if finalPageCount != initialPageCount {
198 t.Fatalf("Final page count differs from the initial page count; initial page count: %v; final page count: %v", initialPageCount, finalPageCount)
199 }
200 finalRemaining := backup.Remaining()
201 if finalRemaining != 0 {
202 t.Fatalf("Unexpected remaining value: %v", finalRemaining)
203 }
204
205 // Finish the backup.
206 err = backup.Finish()
207 if err != nil {
208 t.Fatal("Failed to finish backup:", err)
209 }
210
211 // Confirm that the "test" table now exists in the destination database.
212 var doesTestTableExist bool
213 err = destDb.QueryRow("SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'test' LIMIT 1) AS test_table_exists").Scan(&doesTestTableExist)
214 if err != nil {
215 t.Fatal("Failed to check if the \"test\" table exists in the destination database:", err)
216 }
217 if !doesTestTableExist {
218 t.Fatal("The \"test\" table could not be found in the destination database.")
219 }
220
221 // Confirm that the number of rows in the destination database's "test" table matches that of the source table.
222 var actualTestTableRowCount int
223 err = destDb.QueryRow("SELECT COUNT(*) FROM test").Scan(&actualTestTableRowCount)
224 if err != nil {
225 t.Fatal("Failed to determine the rowcount of the \"test\" table in the destination database:", err)
226 }
227 if testRowCount != actualTestTableRowCount {
228 t.Fatalf("Unexpected destination \"test\" table row count; expected: %v; found: %v", testRowCount, actualTestTableRowCount)
229 }
230
231 // Check each of the rows in the destination database.
232 for id := 0; id < testRowCount; id++ {
233 var checkedValue string
234 err = destDb.QueryRow("SELECT value FROM test WHERE id = ?", id).Scan(&checkedValue)
235 if err != nil {
236 t.Fatal("Failed to query the \"test\" table in the destination database:", err)
237 }
238
239 var expectedValue = generateTestData(id)
240 if checkedValue != expectedValue {
241 t.Fatalf("Unexpected value in the \"test\" table in the destination database; expected value: %v; actual value: %v", expectedValue, checkedValue)
242 }
243 }
244 }
245
246 func TestBackupStepByStep(t *testing.T) {
247 testBackup(t, testRowCount, true)
248 }
249
250 func TestBackupAllRemainingPages(t *testing.T) {
251 testBackup(t, testRowCount, false)
252 }
253
254 // Test the error reporting when preparing to perform a backup.
255 func TestBackupError(t *testing.T) {
256 const driverName = "sqlite3_TestBackupError"
257
258 // The driver's connection will be needed in order to perform the backup.
259 var dbDriverConn *SQLiteConn
260 sql.Register(driverName, &SQLiteDriver{
261 ConnectHook: func(conn *SQLiteConn) error {
262 dbDriverConn = conn
263 return nil
264 },
265 })
266
267 // Connect to the database.
268 dbTempFilename := TempFilename(t)
269 defer os.Remove(dbTempFilename)
270 db, err := sql.Open(driverName, dbTempFilename)
271 if err != nil {
272 t.Fatal("Failed to open the database:", err)
273 }
274 defer db.Close()
275 db.Ping()
276
277 // Need the driver connection in order to perform the backup.
278 if dbDriverConn == nil {
279 t.Fatal("Failed to get the driver connection.")
280 }
281
282 // Prepare to perform the backup.
283 // Intentionally using the same connection for both the source and destination databases, to trigger an error result.
284 backup, err := dbDriverConn.Backup("main", dbDriverConn, "main")
285 if err == nil {
286 t.Fatal("Failed to get the expected error result.")
287 }
288 const expectedError = "source and destination must be distinct"
289 if err.Error() != expectedError {
290 t.Fatalf("Unexpected error message; expected value: \"%v\"; actual value: \"%v\"", expectedError, err.Error())
291 }
292 if backup != nil {
293 t.Fatal("Failed to get the expected nil backup result.")
294 }
295 }