-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmigrate_example_test.go
51 lines (45 loc) · 1.45 KB
/
migrate_example_test.go
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
package ds_test
import (
"fmt"
"github.com/ecnepsnai/ds"
)
func ExampleMigrate() {
// Define a struct that maps to the current type used in the table
type oldType struct {
Username string `ds:"primary"`
Email string `ds:"unique"`
FirstName string
LastName string
}
// Define your new struct
type newType struct {
Username string `ds:"primary"`
Email string `ds:"unique"`
Name string
}
// In this example, we're merging the "FirstName" and "LastName" fields of the User object to
// just a single "Name" field
result := ds.Migrate(ds.MigrateParams{
TablePath: "/path/to/table.db",
NewPath: "/path/to/table.db", // You can specify the same path, or a new one if you want
OldType: oldType{},
NewType: newType{}, // NewType can be the same as the old type if you aren't changing the struct
MigrateObject: func(o interface{}) (interface{}, error) {
old := o.(oldType)
// Within the MigrateObject function you can:
// 1. Return a object of the NewType (specified in the MigrateParams)
// 2. Return an error and the migration will abort
// 3. Return nil and this entry will be skipped
return newType{
Username: old.Username,
Email: old.Email,
Name: old.FirstName + " " + old.LastName,
}, nil
},
})
if !result.Success {
// Migration failed.
panic(result.Error)
}
fmt.Printf("Migration successful. Entries migrated: %d, skipped: %d\n", result.EntriesMigrated, result.EntriesSkipped)
}