happyDomain/generators/gen_database_migration.go

69 lines
1.2 KiB
Go

package main
// +build ignore
import (
"io/ioutil"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"text/template"
)
const tpl = `// Code generated by go generate. DO NOT EDIT.
package database // import "happydns.org/database"
const schemaVersion = {{ .MaxVersion }}
var schemaRevisions = map[uint16]string{
{{ range $constant, $content := .Map }}` + "\t" + `{{ $constant }}: ` + "`{{ $content }}`" + `,
{{ end }}}
`
var bundleTpl = template.Must(template.New("").Parse(tpl))
type valTpl struct {
MaxVersion uint64
Map map[uint16]string
}
func main() {
srcFiles, err := filepath.Glob("storage/mysql/schemas/*.sql")
if err != nil {
panic(err)
}
d := valTpl{
MaxVersion: 0,
Map: map[uint16]string{},
}
for _, srcFile := range srcFiles {
data, err := ioutil.ReadFile(srcFile)
if err != nil {
panic(err)
}
v, err := strconv.ParseUint(strings.TrimSuffix(path.Base(srcFile), ".sql"), 10, 16)
if err != nil {
panic(err)
}
d.Map[uint16(v)] = string(data)
if v > d.MaxVersion {
d.MaxVersion = v
}
}
f, err := os.Create("storage/mysql/schemas.go")
if err != nil {
panic(err)
}
defer f.Close()
bundleTpl.Execute(f, d)
}