github.com/reggieriser/pop@v4.13.1+incompatible/genny/fizz/ctable/options.go (about) 1 package ctable 2 3 import ( 4 "fmt" 5 "time" 6 7 "github.com/gobuffalo/fizz" 8 9 "github.com/gobuffalo/attrs" 10 "github.com/gobuffalo/flect/name" 11 "github.com/pkg/errors" 12 ) 13 14 var nowFunc = time.Now 15 16 // Options for the table create generator. 17 type Options struct { 18 // TableName is the name of the table. 19 TableName string 20 // Name is the name of the generated file. 21 Name string 22 // Path is the dir path where to generate the migration files. 23 Path string 24 // Attrs is a slice of columns to add to the table. 25 Attrs attrs.Attrs 26 // Translator is a Fizz translator to use when asking for SQL migrations. 27 Translator fizz.Translator 28 // Type is the type of migration to generate (sql or fizz). 29 // For sql migrations, you'll have to provide a valid Translator too. 30 Type string 31 // ForceDefaultTimestamps enables auto timestamping for the generated table. 32 ForceDefaultTimestamps bool `json:"force_default_timestamps"` 33 // ForceDefaultID enables auto UUID for the generated table. 34 ForceDefaultID bool `json:"force_default_id"` 35 } 36 37 // Validate that options are usuable 38 func (opts *Options) Validate() error { 39 if len(opts.TableName) == 0 { 40 return errors.New("you must set a name for your table") 41 } 42 opts.TableName = name.New(opts.TableName).Tableize().String() 43 if len(opts.Path) == 0 { 44 opts.Path = "migrations" 45 } 46 if len(opts.Name) == 0 { 47 timestamp := nowFunc().UTC().Format("20060102150405") 48 opts.Name = fmt.Sprintf("%s_create_%s", timestamp, opts.TableName) 49 } 50 if len(opts.Type) == 0 { 51 opts.Type = "fizz" 52 } 53 if opts.Type != "fizz" && opts.Type != "sql" { 54 return errors.Errorf("%s migration type is not allowed", opts.Type) 55 } 56 if opts.Type == "sql" && opts.Translator == nil { 57 return errors.New("sql migrations require a fizz translator") 58 } 59 if opts.ForceDefaultID { 60 var idFound bool 61 for _, a := range opts.Attrs { 62 switch a.Name.Underscore().String() { 63 case "id": 64 idFound = true 65 } 66 } 67 if !idFound { 68 // Add a default UUID 69 id, err := attrs.Parse("id:uuid") 70 if err != nil { 71 return err 72 } 73 opts.Attrs = append([]attrs.Attr{id}, opts.Attrs...) 74 } 75 } 76 return nil 77 }