1
0
mirror of https://github.com/astaxie/beego.git synced 2024-12-23 16:10:50 +00:00
Beego/orm/cmd.go

284 lines
5.8 KiB
Go
Raw Normal View History

2014-08-18 08:41:43 +00:00
// Copyright 2014 beego Author. All Rights Reserved.
2014-07-03 15:40:21 +00:00
//
2014-08-18 08:41:43 +00:00
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
2014-07-03 15:40:21 +00:00
//
2014-08-18 08:41:43 +00:00
// http://www.apache.org/licenses/LICENSE-2.0
2014-07-03 15:40:21 +00:00
//
2014-08-18 08:41:43 +00:00
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
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)
}
2015-09-12 13:46:43 +00:00
// RunCommand 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 {
2015-09-12 13:46:43 +00:00
drops = getDbDropSQL(d.al)
2013-08-19 14:37:39 +00:00
}
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
}
}
2015-09-12 13:46:43 +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 {
2017-03-17 17:24:45 +00:00
if _, ok := columns[fi.column]; !ok {
2013-08-27 04:33:27 +00:00
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] {
2017-03-17 17:24:45 +00:00
if !d.al.DbBaser.IndexExists(db, idx.Table, idx.Name) {
2013-08-27 04:33:27 +00:00
if !d.noInfo {
fmt.Printf("create index `%s` for table `%s`\n", idx.Name, idx.Table)
}
2015-09-12 13:46:43 +00:00
query := idx.SQL
2013-08-27 04:33:27 +00:00
_, 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] {
2015-09-12 13:46:43 +00:00
queries = append(queries, idx.SQL)
2013-08-27 04:33:27 +00:00
}
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.
2015-09-12 13:46:43 +00:00
type commandSQLAll struct {
2013-08-19 14:37:39 +00:00
al *alias
}
2014-01-17 09:04:15 +00:00
// parse orm command line arguments.
2015-09-12 13:46:43 +00:00
func (d *commandSQLAll) Parse(args []string) {
2013-08-19 14:37:39 +00:00
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.
2015-09-12 13:46:43 +00:00
func (d *commandSQLAll) Run() error {
sqls, indexes := getDbCreateSQL(d.al)
2013-08-25 03:31:07 +00:00
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] {
2015-09-12 13:46:43 +00:00
queries = append(queries, idx.SQL)
2013-08-27 04:33:27 +00:00
}
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)
2015-09-12 13:46:43 +00:00
commands["sqlall"] = new(commandSQLAll)
2013-08-19 14:37:39 +00:00
}
2013-08-27 04:33:27 +00:00
2015-09-12 13:46:43 +00:00
// RunSyncdb run syncdb command line.
2014-01-17 09:04:15 +00:00
// 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()
}