Files
2021-12-28 09:18:32 +08:00

70 lines
2.2 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 migrate
import (
"SciencesServer/app/common/migrate"
"SciencesServer/serve/orm"
"SciencesServer/serve/orm/logic"
"fmt"
"github.com/spf13/cobra"
)
type mysql struct {
host string
port int
database string
username string
password string
}
type sqlite struct {
path string
name string
}
var (
Cmd = &cobra.Command{
Use: "init",
Short: "初始化配置",
Example: "serve init -m mysql -d sciences -u root -p 123456",
Run: func(cmd *cobra.Command, args []string) {
run()
},
}
mode string
_mysql = new(mysql)
_sqlite = new(sqlite)
)
func init() {
Cmd.PersistentFlags().StringVarP(&mode, "mode", "m", "mysql", "数据引擎支持mysql和sqlite默认mysql")
Cmd.PersistentFlags().StringVarP(&_mysql.host, "mysql_host", "H", "127.0.0.1", "主机名默认127.0.0.1")
Cmd.PersistentFlags().IntVarP(&_mysql.port, "mysql_port", "P", 3306, "端口号默认为3306")
Cmd.PersistentFlags().StringVarP(&_mysql.database, "mysql_database", "d", "", "数据库,默认为空")
Cmd.PersistentFlags().StringVarP(&_mysql.username, "mysql_username", "u", "root", "用户名默认为root")
Cmd.PersistentFlags().StringVarP(&_mysql.password, "mysql_password", "p", "", "密码,默认为空")
Cmd.PersistentFlags().StringVarP(&_sqlite.path, "sqlite_path", "a", "data", "Sqlite文件存放地址默认data")
Cmd.PersistentFlags().StringVarP(&_sqlite.name, "sqlite_name", "n", "app.db", "Sqlite文件存放地址默认app.db")
}
func run() {
fmt.Println("========================\n=== 初始化项目配置 ===\n========================")
// 初始化数据引擎
engine := orm.NewInstance(
orm.WithDBMode(mode),
orm.WithMysqlOption(&logic.Mysql{
User: _mysql.username, Password: _mysql.password,
Host: _mysql.host, Port: _mysql.port,
DBName: _mysql.database, Parameters: "charset=utf8mb4,utf8&parseTime=True&loc=Local",
}),
orm.WithSqliteOption(&logic.Sqlite{Path: _sqlite.path, Name: _sqlite.name}),
).Init()
fmt.Println("========================\n=== 数据引擎创建成功 ===\n========================")
// 迁移数据
migrate.NewInstance(migrate.WithGormDBOption(engine.Engine)).Handle()
fmt.Println("========================\n=== 数据初始化成功 ===\n========================")
}