github.com/Accefy/pop@v0.0.0-20230428174248-e9f677eab5b9/genny/fizz/ctable/options.go (about)

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