1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-18 11:50:55 +00:00
Beego/orm/cmd.go

276 lines
5.5 KiB
Go
Raw Normal View History

2014-04-12 05:18:18 +00:00
// Beego (http://beego.me/)
// @description beego is an open-source, high-performance web framework for the Go programming language.
// @link http://github.com/astaxie/beego for the canonical source repository
// @license http://github.com/astaxie/beego/blob/master/LICENSE
// @authors slene
2013-08-19 14:37:39 +00:00
package orm
import (
"flag"
"fmt"
"os"
"strings"
)
type commander interface {
Parse([]string)
2013-08-27 04:33:27 +00:00
Run() error
2013-08-19 14:37:39 +00:00
}
var (
commands = make(map[string]commander)
)
2014-01-17 09:04:15 +00:00
// print help.
2013-08-19 14:37:39 +00:00
func printHelp(errs ...string) {
content := `orm command usage:
syncdb - auto create tables
sqlall - print sql of create tables
help - print this help
`
if len(errs) > 0 {
fmt.Println(errs[0])
}
fmt.Println(content)
os.Exit(2)
}
2014-01-17 09:04:15 +00:00
// listen for orm command and then run it if command arguments passed.
2013-08-19 14:37:39 +00:00
func RunCommand() {
if len(os.Args) < 2 || os.Args[1] != "orm" {
return
}
BootStrap()
args := argString(os.Args[2:])
name := args.Get(0)
if name == "help" {
printHelp()
}
if cmd, ok := commands[name]; ok {
cmd.Parse(os.Args[3:])
cmd.Run()
os.Exit(0)
} else {
if name == "" {
printHelp()
} else {
printHelp(fmt.Sprintf("unknown command %s", name))
}
}
}
2014-01-17 09:04:15 +00:00
// sync database struct command interface.
2013-08-19 14:37:39 +00:00
type commandSyncDb struct {
2013-08-27 04:33:27 +00:00
al *alias
force bool
verbose bool
noInfo bool
rtOnError bool
2013-08-19 14:37:39 +00:00
}
2014-01-17 09:04:15 +00:00
// parse orm command line arguments.
2013-08-19 14:37:39 +00:00
func (d *commandSyncDb) Parse(args []string) {
var name string
flagSet := flag.NewFlagSet("orm command: syncdb", flag.ExitOnError)
flagSet.StringVar(&name, "db", "default", "DataBase alias name")
flagSet.BoolVar(&d.force, "force", false, "drop tables before create")
flagSet.BoolVar(&d.verbose, "v", false, "verbose info")
flagSet.Parse(args)
d.al = getDbAlias(name)
}
2014-01-17 09:04:15 +00:00
// run orm line command.
2013-08-27 04:33:27 +00:00
func (d *commandSyncDb) Run() error {
2013-08-19 14:37:39 +00:00
var drops []string
if d.force {
drops = getDbDropSql(d.al)
}
db := d.al.DB
if d.force {
for i, mi := range modelCache.allOrdered() {
query := drops[i]
2013-08-27 04:33:27 +00:00
if !d.noInfo {
fmt.Printf("drop table `%s`\n", mi.table)
2013-08-19 14:37:39 +00:00
}
2013-08-27 04:33:27 +00:00
_, err := db.Exec(query)
2013-08-19 14:37:39 +00:00
if d.verbose {
fmt.Printf(" %s\n\n", query)
}
2013-08-27 04:33:27 +00:00
if err != nil {
if d.rtOnError {
return err
}
fmt.Printf(" %s\n", err.Error())
}
2013-08-19 14:37:39 +00:00
}
}
2013-08-25 03:31:07 +00:00
sqls, indexes := getDbCreateSql(d.al)
2013-08-19 14:37:39 +00:00
2013-08-27 04:33:27 +00:00
tables, err := d.al.DbBaser.GetTables(db)
if err != nil {
if d.rtOnError {
return err
}
fmt.Printf(" %s\n", err.Error())
}
2013-08-19 14:37:39 +00:00
for i, mi := range modelCache.allOrdered() {
2013-08-27 04:33:27 +00:00
if tables[mi.table] {
if !d.noInfo {
fmt.Printf("table `%s` already exists, skip\n", mi.table)
}
var fields []*fieldInfo
columns, err := d.al.DbBaser.GetColumns(db, mi.table)
if err != nil {
if d.rtOnError {
return err
}
fmt.Printf(" %s\n", err.Error())
}
for _, fi := range mi.fields.fieldsDB {
if _, ok := columns[fi.column]; ok == false {
fields = append(fields, fi)
}
}
for _, fi := range fields {
query := getColumnAddQuery(d.al, fi)
if !d.noInfo {
fmt.Printf("add column `%s` for table `%s`\n", fi.fullName, mi.table)
}
_, err := db.Exec(query)
if d.verbose {
fmt.Printf(" %s\n", query)
}
if err != nil {
if d.rtOnError {
return err
}
fmt.Printf(" %s\n", err.Error())
}
}
for _, idx := range indexes[mi.table] {
if d.al.DbBaser.IndexExists(db, idx.Table, idx.Name) == false {
if !d.noInfo {
fmt.Printf("create index `%s` for table `%s`\n", idx.Name, idx.Table)
}
query := idx.Sql
_, err := db.Exec(query)
if d.verbose {
fmt.Printf(" %s\n", query)
}
if err != nil {
if d.rtOnError {
return err
}
fmt.Printf(" %s\n", err.Error())
}
}
}
continue
}
if !d.noInfo {
fmt.Printf("create table `%s` \n", mi.table)
}
2013-08-25 03:31:07 +00:00
queries := []string{sqls[i]}
2013-08-27 04:33:27 +00:00
for _, idx := range indexes[mi.table] {
queries = append(queries, idx.Sql)
}
2013-08-25 03:31:07 +00:00
for _, query := range queries {
_, err := db.Exec(query)
if d.verbose {
query = " " + strings.Join(strings.Split(query, "\n"), "\n ")
fmt.Println(query)
}
if err != nil {
2013-08-27 04:33:27 +00:00
if d.rtOnError {
return err
}
2013-08-25 03:31:07 +00:00
fmt.Printf(" %s\n", err.Error())
}
2013-08-19 14:37:39 +00:00
}
if d.verbose {
fmt.Println("")
}
}
2013-08-27 04:33:27 +00:00
return nil
2013-08-19 14:37:39 +00:00
}
2014-01-17 09:04:15 +00:00
// database creation commander interface implement.
2013-08-19 14:37:39 +00:00
type commandSqlAll struct {
al *alias
}
2014-01-17 09:04:15 +00:00
// parse orm command line arguments.
2013-08-19 14:37:39 +00:00
func (d *commandSqlAll) Parse(args []string) {
var name string
flagSet := flag.NewFlagSet("orm command: sqlall", flag.ExitOnError)
flagSet.StringVar(&name, "db", "default", "DataBase alias name")
flagSet.Parse(args)
d.al = getDbAlias(name)
}
2014-01-17 09:04:15 +00:00
// run orm line command.
2013-08-27 04:33:27 +00:00
func (d *commandSqlAll) Run() error {
2013-08-25 03:31:07 +00:00
sqls, indexes := getDbCreateSql(d.al)
var all []string
for i, mi := range modelCache.allOrdered() {
queries := []string{sqls[i]}
2013-08-27 04:33:27 +00:00
for _, idx := range indexes[mi.table] {
queries = append(queries, idx.Sql)
}
2013-08-25 03:31:07 +00:00
sql := strings.Join(queries, "\n")
all = append(all, sql)
}
fmt.Println(strings.Join(all, "\n\n"))
2013-08-27 04:33:27 +00:00
return nil
2013-08-19 14:37:39 +00:00
}
func init() {
commands["syncdb"] = new(commandSyncDb)
commands["sqlall"] = new(commandSqlAll)
}
2013-08-27 04:33:27 +00:00
2014-01-17 09:04:15 +00:00
// run syncdb command line.
// name means table's alias name. default is "default".
// force means run next sql if the current is error.
// verbose means show all info when running command or not.
2013-08-27 04:33:27 +00:00
func RunSyncdb(name string, force bool, verbose bool) error {
BootStrap()
al := getDbAlias(name)
cmd := new(commandSyncDb)
cmd.al = al
cmd.force = force
cmd.noInfo = !verbose
cmd.verbose = verbose
cmd.rtOnError = true
return cmd.Run()
}