Files
EdgeAPI/cmd/sql-dump/main.go
2022-09-03 22:03:22 +08:00

76 lines
1.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"encoding/json"
"fmt"
"github.com/TeaOSLab/EdgeAPI/internal/setup"
_ "github.com/iwind/TeaGo/bootstrap"
"github.com/iwind/TeaGo/dbs"
"go/format"
"os"
"path/filepath"
"strconv"
)
func main() {
db, err := dbs.Default()
if err != nil {
fmt.Println("[ERROR]" + err.Error())
return
}
results, err := setup.NewSQLDump().Dump(db)
if err != nil {
fmt.Println("[ERROR]" + err.Error())
return
}
resultsJSON, err := json.Marshal(results)
if err != nil {
fmt.Println("[ERROR]" + err.Error())
return
}
dir, _ := os.Getwd()
var sqlFile string
for i := 0; i < 5; i++ {
lookupFile := dir + "/internal/setup/sql.go"
_, err = os.Stat(lookupFile)
if err != nil {
dir = filepath.Dir(dir)
continue
}
sqlFile = lookupFile
}
if len(sqlFile) == 0 {
fmt.Println("[ERROR]can not find sql.go")
return
}
content := []byte(`package setup
import (
"encoding/json"
"github.com/iwind/TeaGo/logs"
)
// 最新版本的数据库SQL语句用来对比并升级已有的数据库
// 由 sql-dump/main.go 自动生成
func init() {
err := json.Unmarshal([]byte(` + strconv.Quote(string(resultsJSON)) + `), LatestSQLResult)
if err != nil {
logs.Println("[ERROR]load sql failed: " + err.Error())
}
}
`)
dst, err := format.Source(content)
if err != nil {
fmt.Println("[ERROR]format code failed: " + err.Error())
return
}
err = os.WriteFile(sqlFile, dst, 0666)
if err != nil {
fmt.Println("[ERROR]write file failed: " + err.Error())
return
}
fmt.Println("ok")
}