Beispiel #1
0
//ConnectDB is builder function of DB
func ConnectDB(dbType, conn string, maxOpenConn int) (DB, error) {
	var db DB
	if dbType == "json" || dbType == "yaml" {
		db = file.NewDB()
	} else {
		db = sql.NewDB()
	}
	err := db.Connect(dbType, conn, maxOpenConn)
	if err != nil {
		return nil, err
	}
	return db, nil
}
Beispiel #2
0
func getMigrateCommand() cli.Command {
	return cli.Command{
		Name:        "migrate",
		ShortName:   "mig",
		Usage:       "Generate goose migration script",
		Description: `Generates goose migraion script`,
		Flags: []cli.Flag{
			cli.StringFlag{Name: "name, n", Value: "init_schema", Usage: "name of migrate"},
			cli.StringFlag{Name: "schema, s", Value: "", Usage: "Schema definition"},
			cli.StringFlag{Name: "path, p", Value: "etc/db/migrations", Usage: "Migrate path"},
			cli.BoolFlag{Name: "cascade", Usage: "If true, FOREIGN KEYS in database will be created with ON DELETE CASCADE"},
		},
		Action: func(c *cli.Context) {
			schemaFile := c.String("schema")
			cascade := c.Bool("cascade")
			manager := schema.GetManager()
			manager.LoadSchemasFromFiles(schemaFile)
			name := c.String("name")
			now := time.Now()
			version := fmt.Sprintf("%s_%s.sql", now.Format("20060102150405"), name)
			path := filepath.Join(c.String("path"), version)
			var sqlString = bytes.NewBuffer(make([]byte, 0, 100))
			fmt.Printf("Generating goose migration file to %s ...\n", path)
			sqlDB := sql.NewDB()
			schemas := manager.Schemas()
			sqlString.WriteString("\n")
			sqlString.WriteString("-- +goose Up\n")
			sqlString.WriteString("-- SQL in section 'Up' is executed when this migration is applied\n")
			for _, s := range schemas {
				createSql, indices := sqlDB.GenTableDef(s, cascade)
				sqlString.WriteString(createSql + "\n")
				for _, indexSql := range indices {
					sqlString.WriteString(indexSql + "\n")
				}
			}
			sqlString.WriteString("\n")
			sqlString.WriteString("-- +goose Down\n")
			sqlString.WriteString("-- SQL section 'Down' is executed when this migration is rolled back\n")
			for _, s := range schemas {
				sqlString.WriteString(fmt.Sprintf("drop table %s;", s.GetDbTableName()))
				sqlString.WriteString("\n\n")
			}
			err := ioutil.WriteFile(path, sqlString.Bytes(), os.ModePerm)
			if err != nil {
				fmt.Println(err)
			}
		},
	}
}