ImportDatabase imports data from backup archive in JSON Lines format.
(ctx context.Context, db *gorm.DB, dirPath string, verbose bool)
| 141 | |
| 142 | // ImportDatabase imports data from backup archive in JSON Lines format. |
| 143 | func ImportDatabase(ctx context.Context, db *gorm.DB, dirPath string, verbose bool) error { |
| 144 | err := importLegacyTables(ctx, dirPath, verbose) |
| 145 | if err != nil { |
| 146 | return errors.Wrap(err, "import legacy tables") |
| 147 | } |
| 148 | |
| 149 | for _, table := range Tables { |
| 150 | select { |
| 151 | case <-ctx.Done(): |
| 152 | return ctx.Err() |
| 153 | default: |
| 154 | } |
| 155 | |
| 156 | tableName := strings.TrimPrefix(fmt.Sprintf("%T", table), "*database.") |
| 157 | err := func() error { |
| 158 | tableFile := filepath.Join(dirPath, tableName+".json") |
| 159 | if !osutil.IsFile(tableFile) { |
| 160 | log.Info("Skipped table %q", tableName) |
| 161 | return nil |
| 162 | } |
| 163 | |
| 164 | if verbose { |
| 165 | log.Trace("Importing table %q...", tableName) |
| 166 | } |
| 167 | |
| 168 | f, err := os.Open(tableFile) |
| 169 | if err != nil { |
| 170 | return errors.Wrap(err, "open table file") |
| 171 | } |
| 172 | defer func() { _ = f.Close() }() |
| 173 | |
| 174 | return importTable(ctx, db, table, f) |
| 175 | }() |
| 176 | if err != nil { |
| 177 | return errors.Wrapf(err, "import table %q", tableName) |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | return nil |
| 182 | } |
| 183 | |
| 184 | func importTable(ctx context.Context, db *gorm.DB, table any, r io.Reader) error { |
| 185 | err := db.WithContext(ctx).Migrator().DropTable(table) |
no test coverage detected