|
| 1 | +package loopd |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "path/filepath" |
| 8 | + |
| 9 | + "github.com/lightninglabs/lndclient" |
| 10 | + "github.com/lightninglabs/loop/loopdb" |
| 11 | + "github.com/lightningnetwork/lnd/lnrpc" |
| 12 | +) |
| 13 | + |
| 14 | +// migrateBoltdb migrates the boltdb to sqlite. |
| 15 | +func migrateBoltdb(ctx context.Context, cfg *Config) error { |
| 16 | + // First get the chain params. |
| 17 | + chainParams, err := lndclient.Network(cfg.Network).ChainParams() |
| 18 | + if err != nil { |
| 19 | + return err |
| 20 | + } |
| 21 | + |
| 22 | + // First open the bolt db. |
| 23 | + boltdb, err := loopdb.NewBoltSwapStore(cfg.DataDir, chainParams) |
| 24 | + if err != nil { |
| 25 | + return err |
| 26 | + } |
| 27 | + defer boltdb.Close() |
| 28 | + |
| 29 | + var db loopdb.SwapStore |
| 30 | + switch cfg.DatabaseBackend { |
| 31 | + case DatabaseBackendSqlite: |
| 32 | + log.Infof("Opening sqlite3 database at: %v", |
| 33 | + cfg.Sqlite.DatabaseFileName) |
| 34 | + db, err = loopdb.NewSqliteStore( |
| 35 | + cfg.Sqlite, chainParams, |
| 36 | + ) |
| 37 | + |
| 38 | + case DatabaseBackendPostgres: |
| 39 | + log.Infof("Opening postgres database at: %v", |
| 40 | + cfg.Postgres.DSN(true)) |
| 41 | + db, err = loopdb.NewPostgresStore( |
| 42 | + cfg.Postgres, chainParams, |
| 43 | + ) |
| 44 | + |
| 45 | + default: |
| 46 | + return fmt.Errorf("unknown database backend: %s", |
| 47 | + cfg.DatabaseBackend) |
| 48 | + } |
| 49 | + if err != nil { |
| 50 | + return fmt.Errorf("unable to open database: %v", err) |
| 51 | + } |
| 52 | + |
| 53 | + defer db.Close() |
| 54 | + |
| 55 | + // Create a new migrator manager. |
| 56 | + migrator := loopdb.NewMigratorManager(boltdb, db) |
| 57 | + |
| 58 | + // Run the migration. |
| 59 | + err = migrator.RunMigrations(ctx) |
| 60 | + if err != nil { |
| 61 | + return err |
| 62 | + } |
| 63 | + |
| 64 | + // If the migration was successfull we'll rename the bolt db to |
| 65 | + // loop.db.bk. |
| 66 | + err = os.Rename( |
| 67 | + filepath.Join(cfg.DataDir, "loop.db"), |
| 68 | + filepath.Join(cfg.DataDir, "loop.db.bk"), |
| 69 | + ) |
| 70 | + if err != nil { |
| 71 | + return err |
| 72 | + } |
| 73 | + |
| 74 | + return nil |
| 75 | +} |
| 76 | + |
| 77 | +// needSqlMigration checks if the boltdb exists at it's default location |
| 78 | +// and returns true if it does. |
| 79 | +func needSqlMigration(cfg *Config) bool { |
| 80 | + // First check if the data directory exists. |
| 81 | + if !lnrpc.FileExists(cfg.DataDir) { |
| 82 | + return false |
| 83 | + } |
| 84 | + |
| 85 | + // Now we'll check if the bolt db exists. |
| 86 | + if !lnrpc.FileExists(filepath.Join(cfg.DataDir, "loop.db")) { |
| 87 | + return false |
| 88 | + } |
| 89 | + |
| 90 | + // If both the folder and the bolt db exist, we'll return true. |
| 91 | + return true |
| 92 | +} |
0 commit comments