Debian Codegraph @

tools/pgimport/main.go

raw
1 // pgimport is a one-off migration script to import ntfy data from SQLite to PostgreSQL.
2 // It is not a generic migration tool. It expects specific schema versions for each database
3 // (message cache v14, user db v6, web push v1) and will refuse to run if versions don't match.
4 package main
5
6 import (
7 "database/sql"
8 "fmt"
9 "net/url"
10 "os"
11 "strings"
12
13 _ "github.com/mattn/go-sqlite3"
14 "github.com/urfave/cli/v2"
15 "github.com/urfave/cli/v2/altsrc"
16 "gopkg.in/yaml.v2"
17 "heckel.io/ntfy/v2/db/pg"
18 )
19
20 const (
21 batchSize = 1000
22
23 expectedMessageSchemaVersion = 14
24 expectedUserSchemaVersion = 6
25 expectedWebPushSchemaVersion = 1
26
27 everyoneID = "u_everyone"
28
29 // Initial PostgreSQL schema for message store (from message/cache_postgres_schema.go)
30 createMessageSchemaQuery = `
31 CREATE TABLE IF NOT EXISTS message (
32 id BIGSERIAL PRIMARY KEY,
33 mid TEXT NOT NULL,
34 sequence_id TEXT NOT NULL,
35 time BIGINT NOT NULL,
36 event TEXT NOT NULL,
37 expires BIGINT NOT NULL,
38 topic TEXT NOT NULL,
39 message TEXT NOT NULL,
40 title TEXT NOT NULL,
41 priority INT NOT NULL,
42 tags TEXT NOT NULL,
43 click TEXT NOT NULL,
44 icon TEXT NOT NULL,
45 actions TEXT NOT NULL,
46 attachment_name TEXT NOT NULL,
47 attachment_type TEXT NOT NULL,
48 attachment_size BIGINT NOT NULL,
49 attachment_expires BIGINT NOT NULL,
50 attachment_url TEXT NOT NULL,
51 attachment_deleted BOOLEAN NOT NULL DEFAULT FALSE,
52 sender TEXT NOT NULL,
53 user_id TEXT NOT NULL,
54 content_type TEXT NOT NULL,
55 encoding TEXT NOT NULL,
56 published BOOLEAN NOT NULL DEFAULT FALSE
57 );
58 CREATE INDEX IF NOT EXISTS idx_message_mid ON message (mid);
59 CREATE INDEX IF NOT EXISTS idx_message_sequence_id ON message (sequence_id);
60 CREATE INDEX IF NOT EXISTS idx_message_topic_published_time ON message (topic, published, time, id);
61 CREATE INDEX IF NOT EXISTS idx_message_published_expires ON message (published, expires);
62 CREATE INDEX IF NOT EXISTS idx_message_sender_attachment_expires ON message (sender, attachment_expires) WHERE user_id = '';
63 CREATE INDEX IF NOT EXISTS idx_message_user_id_attachment_expires ON message (user_id, attachment_expires);
64 CREATE TABLE IF NOT EXISTS message_stats (
65 key TEXT PRIMARY KEY,
66 value BIGINT
67 );
68 INSERT INTO message_stats (key, value) VALUES ('messages', 0) ON CONFLICT (key) DO NOTHING;
69 CREATE TABLE IF NOT EXISTS schema_version (
70 store TEXT PRIMARY KEY,
71 version INT NOT NULL
72 );
73 INSERT INTO schema_version (store, version) VALUES ('message', 14) ON CONFLICT (store) DO NOTHING;
74 `
75
76 // Initial PostgreSQL schema for user store (from user/manager_postgres_schema.go)
77 createUserSchemaQuery = `
78 CREATE TABLE IF NOT EXISTS tier (
79 id TEXT PRIMARY KEY,
80 code TEXT NOT NULL,
81 name TEXT NOT NULL,
82 messages_limit BIGINT NOT NULL,
83 messages_expiry_duration BIGINT NOT NULL,
84 emails_limit BIGINT NOT NULL,
85 calls_limit BIGINT NOT NULL,
86 reservations_limit BIGINT NOT NULL,
87 attachment_file_size_limit BIGINT NOT NULL,
88 attachment_total_size_limit BIGINT NOT NULL,
89 attachment_expiry_duration BIGINT NOT NULL,
90 attachment_bandwidth_limit BIGINT NOT NULL,
91 stripe_monthly_price_id TEXT,
92 stripe_yearly_price_id TEXT,
93 UNIQUE(code),
94 UNIQUE(stripe_monthly_price_id),
95 UNIQUE(stripe_yearly_price_id)
96 );
97 CREATE TABLE IF NOT EXISTS "user" (
98 id TEXT PRIMARY KEY,
99 tier_id TEXT REFERENCES tier(id),
100 user_name TEXT NOT NULL UNIQUE,
101 pass TEXT NOT NULL,
102 role TEXT NOT NULL CHECK (role IN ('anonymous', 'admin', 'user')),
103 prefs JSONB NOT NULL DEFAULT '{}',
104 sync_topic TEXT NOT NULL,
105 provisioned BOOLEAN NOT NULL,
106 stats_messages BIGINT NOT NULL DEFAULT 0,
107 stats_emails BIGINT NOT NULL DEFAULT 0,
108 stats_calls BIGINT NOT NULL DEFAULT 0,
109 stripe_customer_id TEXT UNIQUE,
110 stripe_subscription_id TEXT UNIQUE,
111 stripe_subscription_status TEXT,
112 stripe_subscription_interval TEXT,
113 stripe_subscription_paid_until BIGINT,
114 stripe_subscription_cancel_at BIGINT,
115 created BIGINT NOT NULL,
116 deleted BIGINT
117 );
118 CREATE TABLE IF NOT EXISTS user_access (
119 user_id TEXT NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,
120 topic TEXT NOT NULL,
121 read BOOLEAN NOT NULL,
122 write BOOLEAN NOT NULL,
123 owner_user_id TEXT REFERENCES "user"(id) ON DELETE CASCADE,
124 provisioned BOOLEAN NOT NULL,
125 PRIMARY KEY (user_id, topic)
126 );
127 CREATE TABLE IF NOT EXISTS user_token (
128 user_id TEXT NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,
129 token TEXT NOT NULL UNIQUE,
130 label TEXT NOT NULL,
131 last_access BIGINT NOT NULL,
132 last_origin TEXT NOT NULL,
133 expires BIGINT NOT NULL,
134 provisioned BOOLEAN NOT NULL,
135 PRIMARY KEY (user_id, token)
136 );
137 CREATE TABLE IF NOT EXISTS user_phone (
138 user_id TEXT NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,
139 phone_number TEXT NOT NULL,
140 PRIMARY KEY (user_id, phone_number)
141 );
142 CREATE TABLE IF NOT EXISTS schema_version (
143 store TEXT PRIMARY KEY,
144 version INT NOT NULL
145 );
146 INSERT INTO "user" (id, user_name, pass, role, sync_topic, provisioned, created)
147 VALUES ('` + everyoneID + `', '*', '', 'anonymous', '', false, EXTRACT(EPOCH FROM NOW())::BIGINT)
148 ON CONFLICT (id) DO NOTHING;
149 INSERT INTO schema_version (store, version) VALUES ('user', 6) ON CONFLICT (store) DO NOTHING;
150 `
151
152 // Initial PostgreSQL schema for web push store (from webpush/store_postgres.go)
153 createWebPushSchemaQuery = `
154 CREATE TABLE IF NOT EXISTS webpush_subscription (
155 id TEXT PRIMARY KEY,
156 endpoint TEXT NOT NULL UNIQUE,
157 key_auth TEXT NOT NULL,
158 key_p256dh TEXT NOT NULL,
159 user_id TEXT NOT NULL,
160 subscriber_ip TEXT NOT NULL,
161 updated_at BIGINT NOT NULL,
162 warned_at BIGINT NOT NULL DEFAULT 0
163 );
164 CREATE INDEX IF NOT EXISTS idx_webpush_subscriber_ip ON webpush_subscription (subscriber_ip);
165 CREATE INDEX IF NOT EXISTS idx_webpush_updated_at ON webpush_subscription (updated_at);
166 CREATE INDEX IF NOT EXISTS idx_webpush_user_id ON webpush_subscription (user_id);
167 CREATE TABLE IF NOT EXISTS webpush_subscription_topic (
168 subscription_id TEXT NOT NULL REFERENCES webpush_subscription (id) ON DELETE CASCADE,
169 topic TEXT NOT NULL,
170 PRIMARY KEY (subscription_id, topic)
171 );
172 CREATE INDEX IF NOT EXISTS idx_webpush_topic ON webpush_subscription_topic (topic);
173 CREATE TABLE IF NOT EXISTS schema_version (
174 store TEXT PRIMARY KEY,
175 version INT NOT NULL
176 );
177 INSERT INTO schema_version (store, version) VALUES ('webpush', 1) ON CONFLICT (store) DO NOTHING;
178 `
179 )
180
181 var flags = []cli.Flag{
182 &cli.StringFlag{Name: "config", Aliases: []string{"c"}, Usage: "path to server.yml config file"},
183 altsrc.NewStringFlag(&cli.StringFlag{Name: "database-url", Aliases: []string{"database_url"}, Usage: "PostgreSQL connection string"}),
184 altsrc.NewStringFlag(&cli.StringFlag{Name: "cache-file", Aliases: []string{"cache_file"}, Usage: "SQLite message cache file path"}),
185 altsrc.NewStringFlag(&cli.StringFlag{Name: "auth-file", Aliases: []string{"auth_file"}, Usage: "SQLite user/auth database file path"}),
186 altsrc.NewStringFlag(&cli.StringFlag{Name: "web-push-file", Aliases: []string{"web_push_file"}, Usage: "SQLite web push database file path"}),
187 &cli.BoolFlag{Name: "create-schema", Usage: "create initial PostgreSQL schema before importing"},
188 &cli.BoolFlag{Name: "pre-import", Usage: "pre-import messages while ntfy is still running (only imports messages)"},
189 }
190
191 func main() {
192 app := &cli.App{
193 Name: "pgimport",
194 Usage: "One-off SQLite to PostgreSQL migration script for ntfy",
195 UsageText: "pgimport [OPTIONS]",
196 Flags: flags,
197 Before: loadConfigFile("config", flags),
198 Action: execImport,
199 }
200 if err := app.Run(os.Args); err != nil {
201 fmt.Fprintln(os.Stderr, err)
202 os.Exit(1)
203 }
204 }
205
206 func execImport(c *cli.Context) error {
207 databaseURL := c.String("database-url")
208 cacheFile := c.String("cache-file")
209 authFile := c.String("auth-file")
210 webPushFile := c.String("web-push-file")
211 preImport := c.Bool("pre-import")
212
213 if databaseURL == "" {
214 return fmt.Errorf("database-url must be set (via --database-url or config file)")
215 }
216 if preImport {
217 if cacheFile == "" {
218 return fmt.Errorf("--cache-file must be set when using --pre-import")
219 }
220 return execPreImport(c, databaseURL, cacheFile)
221 }
222 if cacheFile == "" && authFile == "" && webPushFile == "" {
223 return fmt.Errorf("at least one of --cache-file, --auth-file, or --web-push-file must be set")
224 }
225
226 fmt.Println("pgimport - SQLite to PostgreSQL migration tool for ntfy")
227 fmt.Println()
228 fmt.Println("Sources:")
229 printSource(" Cache file: ", cacheFile)
230 printSource(" Auth file: ", authFile)
231 printSource(" Web push file: ", webPushFile)
232 fmt.Println()
233 fmt.Println("Target:")
234 fmt.Printf(" Database URL: %s\n", maskPassword(databaseURL))
235 fmt.Println()
236 fmt.Println("This will import data from the SQLite databases into PostgreSQL.")
237 fmt.Print("Make sure ntfy is not running. Continue? (y/n): ")
238
239 var answer string
240 fmt.Scanln(&answer)
241 if strings.TrimSpace(strings.ToLower(answer)) != "y" {
242 fmt.Println("Aborted.")
243 return nil
244 }
245 fmt.Println()
246
247 pgHost, err := pg.Open(databaseURL)
248 if err != nil {
249 return fmt.Errorf("cannot connect to PostgreSQL: %w", err)
250 }
251 pgDB := pgHost.DB
252 defer pgDB.Close()
253
254 if c.Bool("create-schema") {
255 if err := createSchema(pgDB, cacheFile, authFile, webPushFile); err != nil {
256 return fmt.Errorf("cannot create schema: %w", err)
257 }
258 }
259
260 if authFile != "" {
261 if err := verifySchemaVersion(pgDB, "user", expectedUserSchemaVersion); err != nil {
262 return err
263 }
264 if err := importUsers(authFile, pgDB); err != nil {
265 return fmt.Errorf("cannot import users: %w", err)
266 }
267 }
268 if cacheFile != "" {
269 if err := verifySchemaVersion(pgDB, "message", expectedMessageSchemaVersion); err != nil {
270 return err
271 }
272 sinceTime := maxMessageTime(pgDB)
273 if err := importMessages(cacheFile, pgDB, sinceTime); err != nil {
274 return fmt.Errorf("cannot import messages: %w", err)
275 }
276 }
277 if webPushFile != "" {
278 if err := verifySchemaVersion(pgDB, "webpush", expectedWebPushSchemaVersion); err != nil {
279 return err
280 }
281 if err := importWebPush(webPushFile, pgDB); err != nil {
282 return fmt.Errorf("cannot import web push subscriptions: %w", err)
283 }
284 }
285
286 fmt.Println()
287 fmt.Println("Verifying migration ...")
288 failed := false
289 if authFile != "" {
290 if err := verifyUsers(authFile, pgDB, &failed); err != nil {
291 return fmt.Errorf("cannot verify users: %w", err)
292 }
293 }
294 if cacheFile != "" {
295 if err := verifyMessages(cacheFile, pgDB, &failed); err != nil {
296 return fmt.Errorf("cannot verify messages: %w", err)
297 }
298 }
299 if webPushFile != "" {
300 if err := verifyWebPush(webPushFile, pgDB, &failed); err != nil {
301 return fmt.Errorf("cannot verify web push: %w", err)
302 }
303 }
304 fmt.Println()
305 if failed {
306 return fmt.Errorf("verification FAILED, see above for details")
307 }
308 fmt.Println("Verification successful. Migration complete.")
309 return nil
310 }
311
312 func execPreImport(c *cli.Context, databaseURL, cacheFile string) error {
313 fmt.Println("pgimport - PRE-IMPORT mode (ntfy can keep running)")
314 fmt.Println()
315 fmt.Println("Source:")
316 printSource(" Cache file: ", cacheFile)
317 fmt.Println()
318 fmt.Println("Target:")
319 fmt.Printf(" Database URL: %s\n", maskPassword(databaseURL))
320 fmt.Println()
321 fmt.Println("This will pre-import messages into PostgreSQL while ntfy is still running.")
322 fmt.Println("After this completes, stop ntfy and run pgimport again without --pre-import")
323 fmt.Println("to import remaining messages, users, and web push subscriptions.")
324 fmt.Print("Continue? (y/n): ")
325
326 var answer string
327 fmt.Scanln(&answer)
328 if strings.TrimSpace(strings.ToLower(answer)) != "y" {
329 fmt.Println("Aborted.")
330 return nil
331 }
332 fmt.Println()
333
334 pgHost, err := pg.Open(databaseURL)
335 if err != nil {
336 return fmt.Errorf("cannot connect to PostgreSQL: %w", err)
337 }
338 pgDB := pgHost.DB
339 defer pgDB.Close()
340
341 if c.Bool("create-schema") {
342 if err := createSchema(pgDB, cacheFile, "", ""); err != nil {
343 return fmt.Errorf("cannot create schema: %w", err)
344 }
345 }
346
347 if err := verifySchemaVersion(pgDB, "message", expectedMessageSchemaVersion); err != nil {
348 return err
349 }
350 if err := importMessages(cacheFile, pgDB, 0); err != nil {
351 return fmt.Errorf("cannot import messages: %w", err)
352 }
353
354 fmt.Println()
355 fmt.Println("Pre-import complete. Now stop ntfy and run pgimport again without --pre-import")
356 fmt.Println("to import any remaining messages, users, and web push subscriptions.")
357 return nil
358 }
359
360 func createSchema(pgDB *sql.DB, cacheFile, authFile, webPushFile string) error {
361 fmt.Println("Creating initial PostgreSQL schema ...")
362 // User schema must be created before message schema, because message_stats and
363 // schema_version use "INSERT INTO" without "ON CONFLICT", so user schema (which
364 // also creates the schema_version table) must come first.
365 if authFile != "" {
366 fmt.Println(" Creating user schema ...")
367 if _, err := pgDB.Exec(createUserSchemaQuery); err != nil {
368 return fmt.Errorf("creating user schema: %w", err)
369 }
370 }
371 if cacheFile != "" {
372 fmt.Println(" Creating message schema ...")
373 if _, err := pgDB.Exec(createMessageSchemaQuery); err != nil {
374 return fmt.Errorf("creating message schema: %w", err)
375 }
376 }
377 if webPushFile != "" {
378 fmt.Println(" Creating web push schema ...")
379 if _, err := pgDB.Exec(createWebPushSchemaQuery); err != nil {
380 return fmt.Errorf("creating web push schema: %w", err)
381 }
382 }
383 fmt.Println(" Schema creation complete.")
384 fmt.Println()
385 return nil
386 }
387
388 func loadConfigFile(configFlag string, flags []cli.Flag) cli.BeforeFunc {
389 return func(c *cli.Context) error {
390 configFile := c.String(configFlag)
391 if configFile == "" {
392 return nil
393 }
394 if _, err := os.Stat(configFile); os.IsNotExist(err) {
395 return fmt.Errorf("config file %s does not exist", configFile)
396 }
397 inputSource, err := newYamlSourceFromFile(configFile, flags)
398 if err != nil {
399 return err
400 }
401 return altsrc.ApplyInputSourceValues(c, inputSource, flags)
402 }
403 }
404
405 func newYamlSourceFromFile(file string, flags []cli.Flag) (altsrc.InputSourceContext, error) {
406 var rawConfig map[any]any
407 b, err := os.ReadFile(file)
408 if err != nil {
409 return nil, err
410 }
411 if err := yaml.Unmarshal(b, &rawConfig); err != nil {
412 return nil, err
413 }
414 for _, f := range flags {
415 flagName := f.Names()[0]
416 for _, flagAlias := range f.Names()[1:] {
417 if _, ok := rawConfig[flagAlias]; ok {
418 rawConfig[flagName] = rawConfig[flagAlias]
419 }
420 }
421 }
422 return altsrc.NewMapInputSource(file, rawConfig), nil
423 }
424
425 func verifySchemaVersion(pgDB *sql.DB, store string, expected int) error {
426 var version int
427 err := pgDB.QueryRow(`SELECT version FROM schema_version WHERE store = $1`, store).Scan(&version)
428 if err != nil {
429 return fmt.Errorf("cannot read %s schema version from PostgreSQL (is the schema set up?): %w", store, err)
430 }
431 if version != expected {
432 return fmt.Errorf("%s schema version mismatch: expected %d, got %d", store, expected, version)
433 }
434 return nil
435 }
436
437 func printSource(label, path string) {
438 if path == "" {
439 fmt.Printf("%s(not set, skipping)\n", label)
440 } else if _, err := os.Stat(path); os.IsNotExist(err) {
441 fmt.Printf("%s%s (NOT FOUND, skipping)\n", label, path)
442 } else {
443 fmt.Printf("%s%s\n", label, path)
444 }
445 }
446
447 func maskPassword(databaseURL string) string {
448 u, err := url.Parse(databaseURL)
449 if err != nil {
450 return databaseURL
451 }
452 if u.User != nil {
453 if _, hasPass := u.User.Password(); hasPass {
454 masked := u.Scheme + "://" + u.User.Username() + ":****@" + u.Host + u.Path
455 if u.RawQuery != "" {
456 masked += "?" + u.RawQuery
457 }
458 return masked
459 }
460 }
461 return u.String()
462 }
463
464 func openSQLite(filename string) (*sql.DB, error) {
465 if _, err := os.Stat(filename); os.IsNotExist(err) {
466 return nil, fmt.Errorf("file %s does not exist", filename)
467 }
468 return sql.Open("sqlite3", filename+"?mode=ro")
469 }
470
471 // User import
472
473 func importUsers(sqliteFile string, pgDB *sql.DB) error {
474 sqlDB, err := openSQLite(sqliteFile)
475 if err != nil {
476 fmt.Printf("Skipping user import: %s\n", err)
477 return nil
478 }
479 defer sqlDB.Close()
480 fmt.Printf("Importing users from %s ...\n", sqliteFile)
481
482 count, err := importTiers(sqlDB, pgDB)
483 if err != nil {
484 return fmt.Errorf("importing tiers: %w", err)
485 }
486 fmt.Printf(" Imported %d tiers\n", count)
487
488 count, err = importUserRows(sqlDB, pgDB)
489 if err != nil {
490 return fmt.Errorf("importing users: %w", err)
491 }
492 fmt.Printf(" Imported %d users\n", count)
493
494 count, err = importUserAccess(sqlDB, pgDB)
495 if err != nil {
496 return fmt.Errorf("importing user access: %w", err)
497 }
498 fmt.Printf(" Imported %d access entries\n", count)
499
500 count, err = importUserTokens(sqlDB, pgDB)
501 if err != nil {
502 return fmt.Errorf("importing user tokens: %w", err)
503 }
504 fmt.Printf(" Imported %d tokens\n", count)
505
506 count, err = importUserPhones(sqlDB, pgDB)
507 if err != nil {
508 return fmt.Errorf("importing user phones: %w", err)
509 }
510 fmt.Printf(" Imported %d phone numbers\n", count)
511
512 return nil
513 }
514
515 func importTiers(sqlDB, pgDB *sql.DB) (int, error) {
516 rows, err := sqlDB.Query(`SELECT id, code, name, messages_limit, messages_expiry_duration, emails_limit, calls_limit, reservations_limit, attachment_file_size_limit, attachment_total_size_limit, attachment_expiry_duration, attachment_bandwidth_limit, stripe_monthly_price_id, stripe_yearly_price_id FROM tier`)
517 if err != nil {
518 return 0, err
519 }
520 defer rows.Close()
521
522 tx, err := pgDB.Begin()
523 if err != nil {
524 return 0, err
525 }
526 defer tx.Rollback()
527
528 stmt, err := tx.Prepare(`INSERT INTO tier (id, code, name, messages_limit, messages_expiry_duration, emails_limit, calls_limit, reservations_limit, attachment_file_size_limit, attachment_total_size_limit, attachment_expiry_duration, attachment_bandwidth_limit, stripe_monthly_price_id, stripe_yearly_price_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14) ON CONFLICT (id) DO NOTHING`)
529 if err != nil {
530 return 0, err
531 }
532 defer stmt.Close()
533
534 count := 0
535 for rows.Next() {
536 var id, code, name string
537 var messagesLimit, messagesExpiryDuration, emailsLimit, callsLimit, reservationsLimit int64
538 var attachmentFileSizeLimit, attachmentTotalSizeLimit, attachmentExpiryDuration, attachmentBandwidthLimit int64
539 var stripeMonthlyPriceID, stripeYearlyPriceID sql.NullString
540 if err := rows.Scan(&id, &code, &name, &messagesLimit, &messagesExpiryDuration, &emailsLimit, &callsLimit, &reservationsLimit, &attachmentFileSizeLimit, &attachmentTotalSizeLimit, &attachmentExpiryDuration, &attachmentBandwidthLimit, &stripeMonthlyPriceID, &stripeYearlyPriceID); err != nil {
541 return 0, err
542 }
543 if _, err := stmt.Exec(id, code, name, messagesLimit, messagesExpiryDuration, emailsLimit, callsLimit, reservationsLimit, attachmentFileSizeLimit, attachmentTotalSizeLimit, attachmentExpiryDuration, attachmentBandwidthLimit, stripeMonthlyPriceID, stripeYearlyPriceID); err != nil {
544 return 0, err
545 }
546 count++
547 }
548 return count, tx.Commit()
549 }
550
551 func importUserRows(sqlDB, pgDB *sql.DB) (int, error) {
552 rows, err := sqlDB.Query(`SELECT id, user, pass, role, prefs, sync_topic, provisioned, stats_messages, stats_emails, stats_calls, stripe_customer_id, stripe_subscription_id, stripe_subscription_status, stripe_subscription_interval, stripe_subscription_paid_until, stripe_subscription_cancel_at, created, deleted, tier_id FROM user`)
553 if err != nil {
554 return 0, err
555 }
556 defer rows.Close()
557
558 tx, err := pgDB.Begin()
559 if err != nil {
560 return 0, err
561 }
562 defer tx.Rollback()
563
564 stmt, err := tx.Prepare(`
565 INSERT INTO "user" (id, user_name, pass, role, prefs, sync_topic, provisioned, stats_messages, stats_emails, stats_calls, stripe_customer_id, stripe_subscription_id, stripe_subscription_status, stripe_subscription_interval, stripe_subscription_paid_until, stripe_subscription_cancel_at, created, deleted, tier_id)
566 VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19)
567 ON CONFLICT (id) DO NOTHING
568 `)
569 if err != nil {
570 return 0, err
571 }
572 defer stmt.Close()
573
574 count := 0
575 for rows.Next() {
576 var id, userName, pass, role, prefs, syncTopic string
577 var provisioned int
578 var statsMessages, statsEmails, statsCalls int64
579 var stripeCustomerID, stripeSubscriptionID, stripeSubscriptionStatus, stripeSubscriptionInterval sql.NullString
580 var stripeSubscriptionPaidUntil, stripeSubscriptionCancelAt sql.NullInt64
581 var created int64
582 var deleted sql.NullInt64
583 var tierID sql.NullString
584 if err := rows.Scan(&id, &userName, &pass, &role, &prefs, &syncTopic, &provisioned, &statsMessages, &statsEmails, &statsCalls, &stripeCustomerID, &stripeSubscriptionID, &stripeSubscriptionStatus, &stripeSubscriptionInterval, &stripeSubscriptionPaidUntil, &stripeSubscriptionCancelAt, &created, &deleted, &tierID); err != nil {
585 return 0, err
586 }
587 provisionedBool := provisioned != 0
588 if _, err := stmt.Exec(id, userName, pass, role, prefs, syncTopic, provisionedBool, statsMessages, statsEmails, statsCalls, stripeCustomerID, stripeSubscriptionID, stripeSubscriptionStatus, stripeSubscriptionInterval, stripeSubscriptionPaidUntil, stripeSubscriptionCancelAt, created, deleted, tierID); err != nil {
589 return 0, err
590 }
591 count++
592 }
593 return count, tx.Commit()
594 }
595
596 func importUserAccess(sqlDB, pgDB *sql.DB) (int, error) {
597 rows, err := sqlDB.Query(`SELECT a.user_id, a.topic, a.read, a.write, a.owner_user_id, a.provisioned FROM user_access a JOIN user u ON u.id = a.user_id`)
598 if err != nil {
599 return 0, err
600 }
601 defer rows.Close()
602
603 tx, err := pgDB.Begin()
604 if err != nil {
605 return 0, err
606 }
607 defer tx.Rollback()
608
609 stmt, err := tx.Prepare(`INSERT INTO user_access (user_id, topic, read, write, owner_user_id, provisioned) VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (user_id, topic) DO NOTHING`)
610 if err != nil {
611 return 0, err
612 }
613 defer stmt.Close()
614
615 count := 0
616 for rows.Next() {
617 var userID, topic string
618 var read, write, provisioned int
619 var ownerUserID sql.NullString
620 if err := rows.Scan(&userID, &topic, &read, &write, &ownerUserID, &provisioned); err != nil {
621 return 0, err
622 }
623 readBool := read != 0
624 writeBool := write != 0
625 provisionedBool := provisioned != 0
626 if _, err := stmt.Exec(userID, topic, readBool, writeBool, ownerUserID, provisionedBool); err != nil {
627 return 0, err
628 }
629 count++
630 }
631 return count, tx.Commit()
632 }
633
634 func importUserTokens(sqlDB, pgDB *sql.DB) (int, error) {
635 rows, err := sqlDB.Query(`SELECT t.user_id, t.token, t.label, t.last_access, t.last_origin, t.expires, t.provisioned FROM user_token t JOIN user u ON u.id = t.user_id`)
636 if err != nil {
637 return 0, err
638 }
639 defer rows.Close()
640
641 tx, err := pgDB.Begin()
642 if err != nil {
643 return 0, err
644 }
645 defer tx.Rollback()
646
647 stmt, err := tx.Prepare(`INSERT INTO user_token (user_id, token, label, last_access, last_origin, expires, provisioned) VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT (user_id, token) DO NOTHING`)
648 if err != nil {
649 return 0, err
650 }
651 defer stmt.Close()
652
653 count := 0
654 for rows.Next() {
655 var userID, token, label, lastOrigin string
656 var lastAccess, expires int64
657 var provisioned int
658 if err := rows.Scan(&userID, &token, &label, &lastAccess, &lastOrigin, &expires, &provisioned); err != nil {
659 return 0, err
660 }
661 provisionedBool := provisioned != 0
662 if _, err := stmt.Exec(userID, token, label, lastAccess, lastOrigin, expires, provisionedBool); err != nil {
663 return 0, err
664 }
665 count++
666 }
667 return count, tx.Commit()
668 }
669
670 func importUserPhones(sqlDB, pgDB *sql.DB) (int, error) {
671 rows, err := sqlDB.Query(`SELECT p.user_id, p.phone_number FROM user_phone p JOIN user u ON u.id = p.user_id`)
672 if err != nil {
673 return 0, err
674 }
675 defer rows.Close()
676
677 tx, err := pgDB.Begin()
678 if err != nil {
679 return 0, err
680 }
681 defer tx.Rollback()
682
683 stmt, err := tx.Prepare(`INSERT INTO user_phone (user_id, phone_number) VALUES ($1, $2) ON CONFLICT (user_id, phone_number) DO NOTHING`)
684 if err != nil {
685 return 0, err
686 }
687 defer stmt.Close()
688
689 count := 0
690 for rows.Next() {
691 var userID, phoneNumber string
692 if err := rows.Scan(&userID, &phoneNumber); err != nil {
693 return 0, err
694 }
695 if _, err := stmt.Exec(userID, phoneNumber); err != nil {
696 return 0, err
697 }
698 count++
699 }
700 return count, tx.Commit()
701 }
702
703 // Message import
704
705 const preImportTimeDelta = 30 // seconds to subtract from max time to account for in-flight messages
706
707 // maxMessageTime returns the maximum message time in PostgreSQL minus a small buffer,
708 // or 0 if there are no messages yet. This is used after a --pre-import run to only
709 // import messages that arrived since the pre-import.
710 func maxMessageTime(pgDB *sql.DB) int64 {
711 var maxTime sql.NullInt64
712 if err := pgDB.QueryRow(`SELECT MAX(time) FROM message`).Scan(&maxTime); err != nil || !maxTime.Valid || maxTime.Int64 == 0 {
713 return 0
714 }
715 sinceTime := maxTime.Int64 - preImportTimeDelta
716 if sinceTime < 0 {
717 return 0
718 }
719 fmt.Printf("Pre-imported messages detected (max time: %d), importing delta (since time %d) ...\n", maxTime.Int64, sinceTime)
720 return sinceTime
721 }
722
723 func importMessages(sqliteFile string, pgDB *sql.DB, sinceTime int64) error {
724 sqlDB, err := openSQLite(sqliteFile)
725 if err != nil {
726 fmt.Printf("Skipping message import: %s\n", err)
727 return nil
728 }
729 defer sqlDB.Close()
730
731 query := `SELECT mid, sequence_id, time, event, expires, topic, message, title, priority, tags, click, icon, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, attachment_deleted, sender, user, content_type, encoding, published FROM messages`
732 var rows *sql.Rows
733 if sinceTime > 0 {
734 fmt.Printf("Importing messages from %s (since time %d) ...\n", sqliteFile, sinceTime)
735 rows, err = sqlDB.Query(query+` WHERE time >= ?`, sinceTime)
736 } else {
737 fmt.Printf("Importing messages from %s ...\n", sqliteFile)
738 rows, err = sqlDB.Query(query)
739 }
740 if err != nil {
741 return fmt.Errorf("querying messages: %w", err)
742 }
743 defer rows.Close()
744
745 if _, err := pgDB.Exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_message_mid_unique ON message (mid)`); err != nil {
746 return fmt.Errorf("creating unique index on mid: %w", err)
747 }
748
749 insertQuery := `INSERT INTO message (mid, sequence_id, time, event, expires, topic, message, title, priority, tags, click, icon, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, attachment_deleted, sender, user_id, content_type, encoding, published) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24) ON CONFLICT (mid) DO NOTHING`
750
751 count := 0
752 batchCount := 0
753 tx, err := pgDB.Begin()
754 if err != nil {
755 return err
756 }
757 defer tx.Rollback()
758
759 stmt, err := tx.Prepare(insertQuery)
760 if err != nil {
761 return err
762 }
763 defer stmt.Close()
764
765 for rows.Next() {
766 var mid, sequenceID, event, topic, message, title, tags, click, icon, actions string
767 var attachmentName, attachmentType, attachmentURL, sender, userID, contentType, encoding string
768 var msgTime, expires, attachmentExpires int64
769 var priority int
770 var attachmentSize int64
771 var attachmentDeleted, published int
772 if err := rows.Scan(&mid, &sequenceID, &msgTime, &event, &expires, &topic, &message, &title, &priority, &tags, &click, &icon, &actions, &attachmentName, &attachmentType, &attachmentSize, &attachmentExpires, &attachmentURL, &attachmentDeleted, &sender, &userID, &contentType, &encoding, &published); err != nil {
773 return fmt.Errorf("scanning message: %w", err)
774 }
775 mid = toUTF8(mid)
776 sequenceID = toUTF8(sequenceID)
777 event = toUTF8(event)
778 topic = toUTF8(topic)
779 message = toUTF8(message)
780 title = toUTF8(title)
781 tags = toUTF8(tags)
782 click = toUTF8(click)
783 icon = toUTF8(icon)
784 actions = toUTF8(actions)
785 attachmentName = toUTF8(attachmentName)
786 attachmentType = toUTF8(attachmentType)
787 attachmentURL = toUTF8(attachmentURL)
788 sender = toUTF8(sender)
789 userID = toUTF8(userID)
790 contentType = toUTF8(contentType)
791 encoding = toUTF8(encoding)
792 attachmentDeletedBool := attachmentDeleted != 0
793 publishedBool := published != 0
794 if _, err := stmt.Exec(mid, sequenceID, msgTime, event, expires, topic, message, title, priority, tags, click, icon, actions, attachmentName, attachmentType, attachmentSize, attachmentExpires, attachmentURL, attachmentDeletedBool, sender, userID, contentType, encoding, publishedBool); err != nil {
795 return fmt.Errorf("inserting message: %w", err)
796 }
797 count++
798 batchCount++
799 if batchCount >= batchSize {
800 stmt.Close()
801 if err := tx.Commit(); err != nil {
802 return fmt.Errorf("committing message batch: %w", err)
803 }
804 fmt.Printf(" ... %d messages\n", count)
805 tx, err = pgDB.Begin()
806 if err != nil {
807 return err
808 }
809 stmt, err = tx.Prepare(insertQuery)
810 if err != nil {
811 return err
812 }
813 batchCount = 0
814 }
815 }
816 if batchCount > 0 {
817 stmt.Close()
818 if err := tx.Commit(); err != nil {
819 return fmt.Errorf("committing final message batch: %w", err)
820 }
821 }
822 fmt.Printf(" Imported %d messages\n", count)
823
824 var statsValue int64
825 err = sqlDB.QueryRow(`SELECT value FROM stats WHERE key = 'messages'`).Scan(&statsValue)
826 if err == nil {
827 if _, err := pgDB.Exec(`UPDATE message_stats SET value = $1 WHERE key = 'messages'`, statsValue); err != nil {
828 return fmt.Errorf("updating message stats: %w", err)
829 }
830 fmt.Printf(" Updated message stats (count: %d)\n", statsValue)
831 }
832
833 return nil
834 }
835
836 // Web push import
837
838 func importWebPush(sqliteFile string, pgDB *sql.DB) error {
839 sqlDB, err := openSQLite(sqliteFile)
840 if err != nil {
841 fmt.Printf("Skipping web push import: %s\n", err)
842 return nil
843 }
844 defer sqlDB.Close()
845 fmt.Printf("Importing web push subscriptions from %s ...\n", sqliteFile)
846
847 rows, err := sqlDB.Query(`SELECT id, endpoint, key_auth, key_p256dh, user_id, subscriber_ip, updated_at, warned_at FROM subscription`)
848 if err != nil {
849 return fmt.Errorf("querying subscriptions: %w", err)
850 }
851 defer rows.Close()
852
853 tx, err := pgDB.Begin()
854 if err != nil {
855 return err
856 }
857 defer tx.Rollback()
858
859 stmt, err := tx.Prepare(`INSERT INTO webpush_subscription (id, endpoint, key_auth, key_p256dh, user_id, subscriber_ip, updated_at, warned_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) ON CONFLICT (id) DO NOTHING`)
860 if err != nil {
861 return err
862 }
863 defer stmt.Close()
864
865 count := 0
866 for rows.Next() {
867 var id, endpoint, keyAuth, keyP256dh, userID, subscriberIP string
868 var updatedAt, warnedAt int64
869 if err := rows.Scan(&id, &endpoint, &keyAuth, &keyP256dh, &userID, &subscriberIP, &updatedAt, &warnedAt); err != nil {
870 return fmt.Errorf("scanning subscription: %w", err)
871 }
872 if _, err := stmt.Exec(id, endpoint, keyAuth, keyP256dh, userID, subscriberIP, updatedAt, warnedAt); err != nil {
873 return fmt.Errorf("inserting subscription: %w", err)
874 }
875 count++
876 }
877 stmt.Close()
878 if err := tx.Commit(); err != nil {
879 return fmt.Errorf("committing subscriptions: %w", err)
880 }
881 fmt.Printf(" Imported %d subscriptions\n", count)
882
883 topicRows, err := sqlDB.Query(`SELECT subscription_id, topic FROM subscription_topic`)
884 if err != nil {
885 return fmt.Errorf("querying subscription topics: %w", err)
886 }
887 defer topicRows.Close()
888
889 tx, err = pgDB.Begin()
890 if err != nil {
891 return err
892 }
893 defer tx.Rollback()
894
895 stmt, err = tx.Prepare(`INSERT INTO webpush_subscription_topic (subscription_id, topic) VALUES ($1, $2) ON CONFLICT (subscription_id, topic) DO NOTHING`)
896 if err != nil {
897 return err
898 }
899 defer stmt.Close()
900
901 topicCount := 0
902 for topicRows.Next() {
903 var subscriptionID, topic string
904 if err := topicRows.Scan(&subscriptionID, &topic); err != nil {
905 return fmt.Errorf("scanning subscription topic: %w", err)
906 }
907 if _, err := stmt.Exec(subscriptionID, topic); err != nil {
908 return fmt.Errorf("inserting subscription topic: %w", err)
909 }
910 topicCount++
911 }
912 stmt.Close()
913 if err := tx.Commit(); err != nil {
914 return fmt.Errorf("committing subscription topics: %w", err)
915 }
916 fmt.Printf(" Imported %d subscription topics\n", topicCount)
917
918 return nil
919 }
920
921 func toUTF8(s string) string {
922 s = strings.ToValidUTF8(s, "\uFFFD")
923 s = strings.ReplaceAll(s, "\x00", "")
924 return s
925 }
926
927 // Verification
928
929 func verifyUsers(sqliteFile string, pgDB *sql.DB, failed *bool) error {
930 sqlDB, err := openSQLite(sqliteFile)
931 if err != nil {
932 return nil
933 }
934 defer sqlDB.Close()
935
936 verifyCount(sqlDB, pgDB, "tier", `SELECT COUNT(*) FROM tier`, `SELECT COUNT(*) FROM tier`, failed)
937 verifyContent(sqlDB, pgDB, "tier",
938 `SELECT id, code, name FROM tier ORDER BY id`,
939 `SELECT id, code, name FROM tier ORDER BY id COLLATE "C"`,
940 failed)
941
942 verifyCount(sqlDB, pgDB, "user", `SELECT COUNT(*) FROM user`, `SELECT COUNT(*) FROM "user"`, failed)
943 verifyContent(sqlDB, pgDB, "user",
944 `SELECT id, user, role, sync_topic FROM user ORDER BY id`,
945 `SELECT id, user_name, role, sync_topic FROM "user" ORDER BY id COLLATE "C"`,
946 failed)
947
948 verifyCount(sqlDB, pgDB, "user_access", `SELECT COUNT(*) FROM user_access a JOIN user u ON u.id = a.user_id`, `SELECT COUNT(*) FROM user_access`, failed)
949 verifyContent(sqlDB, pgDB, "user_access",
950 `SELECT a.user_id, a.topic FROM user_access a JOIN user u ON u.id = a.user_id ORDER BY a.user_id, a.topic`,
951 `SELECT user_id, topic FROM user_access ORDER BY user_id COLLATE "C", topic COLLATE "C"`,
952 failed)
953
954 verifyCount(sqlDB, pgDB, "user_token", `SELECT COUNT(*) FROM user_token t JOIN user u ON u.id = t.user_id`, `SELECT COUNT(*) FROM user_token`, failed)
955 verifyContent(sqlDB, pgDB, "user_token",
956 `SELECT t.user_id, t.token, t.label FROM user_token t JOIN user u ON u.id = t.user_id ORDER BY t.user_id, t.token`,
957 `SELECT user_id, token, label FROM user_token ORDER BY user_id COLLATE "C", token COLLATE "C"`,
958 failed)
959
960 verifyCount(sqlDB, pgDB, "user_phone", `SELECT COUNT(*) FROM user_phone p JOIN user u ON u.id = p.user_id`, `SELECT COUNT(*) FROM user_phone`, failed)
961 verifyContent(sqlDB, pgDB, "user_phone",
962 `SELECT p.user_id, p.phone_number FROM user_phone p JOIN user u ON u.id = p.user_id ORDER BY p.user_id, p.phone_number`,
963 `SELECT user_id, phone_number FROM user_phone ORDER BY user_id COLLATE "C", phone_number COLLATE "C"`,
964 failed)
965
966 return nil
967 }
968
969 func verifyMessages(sqliteFile string, pgDB *sql.DB, failed *bool) error {
970 sqlDB, err := openSQLite(sqliteFile)
971 if err != nil {
972 return nil
973 }
974 defer sqlDB.Close()
975
976 verifyCount(sqlDB, pgDB, "messages", `SELECT COUNT(*) FROM messages`, `SELECT COUNT(*) FROM message`, failed)
977 verifySampledMessages(sqlDB, pgDB, failed)
978 return nil
979 }
980
981 func verifyWebPush(sqliteFile string, pgDB *sql.DB, failed *bool) error {
982 sqlDB, err := openSQLite(sqliteFile)
983 if err != nil {
984 return nil
985 }
986 defer sqlDB.Close()
987
988 verifyCount(sqlDB, pgDB, "subscription", `SELECT COUNT(*) FROM subscription`, `SELECT COUNT(*) FROM webpush_subscription`, failed)
989 verifyContent(sqlDB, pgDB, "subscription",
990 `SELECT id, endpoint, key_auth, key_p256dh, user_id FROM subscription ORDER BY id`,
991 `SELECT id, endpoint, key_auth, key_p256dh, user_id FROM webpush_subscription ORDER BY id COLLATE "C"`,
992 failed)
993
994 verifyCount(sqlDB, pgDB, "subscription_topic", `SELECT COUNT(*) FROM subscription_topic`, `SELECT COUNT(*) FROM webpush_subscription_topic`, failed)
995 verifyContent(sqlDB, pgDB, "subscription_topic",
996 `SELECT subscription_id, topic FROM subscription_topic ORDER BY subscription_id, topic`,
997 `SELECT subscription_id, topic FROM webpush_subscription_topic ORDER BY subscription_id COLLATE "C", topic COLLATE "C"`,
998 failed)
999
1000 return nil
1001 }
1002
1003 func verifyCount(sqlDB, pgDB *sql.DB, table, sqliteQuery, pgQuery string, failed *bool) {
1004 var sqliteCount, pgCount int64
1005 if err := sqlDB.QueryRow(sqliteQuery).Scan(&sqliteCount); err != nil {
1006 fmt.Printf(" %-25s count ERROR reading SQLite: %s\n", table, err)
1007 *failed = true
1008 return
1009 }
1010 if err := pgDB.QueryRow(pgQuery).Scan(&pgCount); err != nil {
1011 fmt.Printf(" %-25s count ERROR reading PostgreSQL: %s\n", table, err)
1012 *failed = true
1013 return
1014 }
1015 if sqliteCount == pgCount {
1016 fmt.Printf(" %-25s count OK (%d rows)\n", table, pgCount)
1017 } else {
1018 fmt.Printf(" %-25s count MISMATCH: SQLite=%d, PostgreSQL=%d\n", table, sqliteCount, pgCount)
1019 *failed = true
1020 }
1021 }
1022
1023 func verifyContent(sqlDB, pgDB *sql.DB, table, sqliteQuery, pgQuery string, failed *bool) {
1024 sqliteRows, err := sqlDB.Query(sqliteQuery)
1025 if err != nil {
1026 fmt.Printf(" %-25s content ERROR reading SQLite: %s\n", table, err)
1027 *failed = true
1028 return
1029 }
1030 defer sqliteRows.Close()
1031
1032 pgRows, err := pgDB.Query(pgQuery)
1033 if err != nil {
1034 fmt.Printf(" %-25s content ERROR reading PostgreSQL: %s\n", table, err)
1035 *failed = true
1036 return
1037 }
1038 defer pgRows.Close()
1039
1040 cols, err := sqliteRows.Columns()
1041 if err != nil {
1042 fmt.Printf(" %-25s content ERROR reading columns: %s\n", table, err)
1043 *failed = true
1044 return
1045 }
1046 numCols := len(cols)
1047
1048 rowNum := 0
1049 mismatches := 0
1050 for sqliteRows.Next() {
1051 rowNum++
1052 if !pgRows.Next() {
1053 fmt.Printf(" %-25s content MISMATCH: PostgreSQL has fewer rows (at row %d)\n", table, rowNum)
1054 *failed = true
1055 return
1056 }
1057 sqliteVals := makeStringSlice(numCols)
1058 pgVals := makeStringSlice(numCols)
1059 if err := sqliteRows.Scan(sqliteVals...); err != nil {
1060 fmt.Printf(" %-25s content ERROR scanning SQLite row %d: %s\n", table, rowNum, err)
1061 *failed = true
1062 return
1063 }
1064 if err := pgRows.Scan(pgVals...); err != nil {
1065 fmt.Printf(" %-25s content ERROR scanning PostgreSQL row %d: %s\n", table, rowNum, err)
1066 *failed = true
1067 return
1068 }
1069 for i := 0; i < numCols; i++ {
1070 sv := *(sqliteVals[i].(*sql.NullString))
1071 pv := *(pgVals[i].(*sql.NullString))
1072 if sv != pv {
1073 mismatches++
1074 if mismatches <= 3 {
1075 fmt.Printf(" %-25s content MISMATCH at row %d, col %s: SQLite=%q, PostgreSQL=%q\n", table, rowNum, cols[i], sv.String, pv.String)
1076 }
1077 }
1078 }
1079 }
1080 if pgRows.Next() {
1081 fmt.Printf(" %-25s content MISMATCH: PostgreSQL has more rows than SQLite\n", table)
1082 *failed = true
1083 return
1084 }
1085 if mismatches > 0 {
1086 if mismatches > 3 {
1087 fmt.Printf(" %-25s content ... and %d more mismatches\n", table, mismatches-3)
1088 }
1089 *failed = true
1090 } else {
1091 fmt.Printf(" %-25s content OK\n", table)
1092 }
1093 }
1094
1095 func verifySampledMessages(sqlDB, pgDB *sql.DB, failed *bool) {
1096 rows, err := sqlDB.Query(`SELECT mid, topic, time, message, title, tags, priority FROM messages ORDER BY mid`)
1097 if err != nil {
1098 fmt.Printf(" %-25s content ERROR reading SQLite: %s\n", "messages (sampled)", err)
1099 *failed = true
1100 return
1101 }
1102 defer rows.Close()
1103
1104 rowNum := 0
1105 checked := 0
1106 mismatches := 0
1107 for rows.Next() {
1108 rowNum++
1109 var mid, topic, message, title, tags string
1110 var msgTime int64
1111 var priority int
1112 if err := rows.Scan(&mid, &topic, &msgTime, &message, &title, &tags, &priority); err != nil {
1113 fmt.Printf(" %-25s content ERROR scanning SQLite row %d: %s\n", "messages (sampled)", rowNum, err)
1114 *failed = true
1115 return
1116 }
1117 if rowNum%100 != 1 {
1118 continue
1119 }
1120 checked++
1121 var pgTopic, pgMessage, pgTitle, pgTags string
1122 var pgTime int64
1123 var pgPriority int
1124 err := pgDB.QueryRow(`SELECT topic, time, message, title, tags, priority FROM message WHERE mid = $1`, mid).
1125 Scan(&pgTopic, &pgTime, &pgMessage, &pgTitle, &pgTags, &pgPriority)
1126 if err == sql.ErrNoRows {
1127 mismatches++
1128 if mismatches <= 3 {
1129 fmt.Printf(" %-25s content MISMATCH: mid=%s not found in PostgreSQL\n", "messages (sampled)", mid)
1130 }
1131 continue
1132 } else if err != nil {
1133 fmt.Printf(" %-25s content ERROR querying PostgreSQL for mid=%s: %s\n", "messages (sampled)", mid, err)
1134 *failed = true
1135 return
1136 }
1137 topic = toUTF8(topic)
1138 message = toUTF8(message)
1139 title = toUTF8(title)
1140 tags = toUTF8(tags)
1141 if topic != pgTopic || msgTime != pgTime || message != pgMessage || title != pgTitle || tags != pgTags || priority != pgPriority {
1142 mismatches++
1143 if mismatches <= 3 {
1144 fmt.Printf(" %-25s content MISMATCH at mid=%s\n", "messages (sampled)", mid)
1145 }
1146 }
1147 }
1148 if mismatches > 0 {
1149 if mismatches > 3 {
1150 fmt.Printf(" %-25s content ... and %d more mismatches\n", "messages (sampled)", mismatches-3)
1151 }
1152 *failed = true
1153 } else {
1154 fmt.Printf(" %-25s content OK (%d samples checked)\n", "messages (sampled)", checked)
1155 }
1156 }
1157
1158 func makeStringSlice(n int) []any {
1159 vals := make([]any, n)
1160 for i := range vals {
1161 vals[i] = &sql.NullString{}
1162 }
1163 return vals
1164 }