2014-08-01 10:35:28 +00:00
|
|
|
// Copyright 2013 bee authors
|
|
|
|
//
|
|
|
|
// 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
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// 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.
|
|
|
|
|
2017-03-06 23:58:53 +00:00
|
|
|
package generate
|
2014-07-31 10:46:03 +00:00
|
|
|
|
|
|
|
import (
|
2020-06-25 14:29:27 +00:00
|
|
|
"bufio"
|
2014-07-31 10:46:03 +00:00
|
|
|
"database/sql"
|
|
|
|
"fmt"
|
2020-06-25 14:29:27 +00:00
|
|
|
"io"
|
2014-07-31 10:46:03 +00:00
|
|
|
"os"
|
2014-08-01 06:49:30 +00:00
|
|
|
"path"
|
2014-08-19 09:00:37 +00:00
|
|
|
"path/filepath"
|
2014-07-31 10:46:03 +00:00
|
|
|
"regexp"
|
|
|
|
"strings"
|
2016-08-01 15:50:02 +00:00
|
|
|
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger "github.com/beego/bee/logger"
|
|
|
|
"github.com/beego/bee/logger/colors"
|
|
|
|
"github.com/beego/bee/utils"
|
2016-08-01 15:50:02 +00:00
|
|
|
_ "github.com/go-sql-driver/mysql"
|
|
|
|
_ "github.com/lib/pq"
|
2014-07-31 10:46:03 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2016-07-22 23:05:01 +00:00
|
|
|
OModel byte = 1 << iota
|
|
|
|
OController
|
|
|
|
ORouter
|
2014-07-31 10:46:03 +00:00
|
|
|
)
|
|
|
|
|
2014-08-22 07:50:13 +00:00
|
|
|
// DbTransformer has method to reverse engineer a database schema to restful api code
|
|
|
|
type DbTransformer interface {
|
|
|
|
GetTableNames(conn *sql.DB) []string
|
|
|
|
GetConstraints(conn *sql.DB, table *Table, blackList map[string]bool)
|
|
|
|
GetColumns(conn *sql.DB, table *Table, blackList map[string]bool)
|
2016-11-13 14:14:48 +00:00
|
|
|
GetGoDataType(sqlType string) (string, error)
|
2014-08-22 07:50:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// MysqlDB is the MySQL version of DbTransformer
|
|
|
|
type MysqlDB struct {
|
|
|
|
}
|
|
|
|
|
|
|
|
// PostgresDB is the PostgreSQL version of DbTransformer
|
|
|
|
type PostgresDB struct {
|
|
|
|
}
|
|
|
|
|
|
|
|
// dbDriver maps a DBMS name to its version of DbTransformer
|
|
|
|
var dbDriver = map[string]DbTransformer{
|
|
|
|
"mysql": &MysqlDB{},
|
|
|
|
"postgres": &PostgresDB{},
|
|
|
|
}
|
|
|
|
|
2014-08-01 06:49:30 +00:00
|
|
|
type MvcPath struct {
|
|
|
|
ModelPath string
|
|
|
|
ControllerPath string
|
|
|
|
RouterPath string
|
|
|
|
}
|
2014-07-31 10:46:03 +00:00
|
|
|
|
2014-08-21 03:53:12 +00:00
|
|
|
// typeMapping maps SQL data type to corresponding Go data type
|
2014-08-21 03:55:54 +00:00
|
|
|
var typeMappingMysql = map[string]string{
|
2014-07-31 10:46:03 +00:00
|
|
|
"int": "int", // int signed
|
|
|
|
"integer": "int",
|
|
|
|
"tinyint": "int8",
|
|
|
|
"smallint": "int16",
|
|
|
|
"mediumint": "int32",
|
|
|
|
"bigint": "int64",
|
|
|
|
"int unsigned": "uint", // int unsigned
|
|
|
|
"integer unsigned": "uint",
|
|
|
|
"tinyint unsigned": "uint8",
|
|
|
|
"smallint unsigned": "uint16",
|
|
|
|
"mediumint unsigned": "uint32",
|
|
|
|
"bigint unsigned": "uint64",
|
2014-08-27 03:08:32 +00:00
|
|
|
"bit": "uint64",
|
2014-07-31 10:46:03 +00:00
|
|
|
"bool": "bool", // boolean
|
|
|
|
"enum": "string", // enum
|
|
|
|
"set": "string", // set
|
|
|
|
"varchar": "string", // string & text
|
|
|
|
"char": "string",
|
|
|
|
"tinytext": "string",
|
|
|
|
"mediumtext": "string",
|
|
|
|
"text": "string",
|
|
|
|
"longtext": "string",
|
|
|
|
"blob": "string", // blob
|
2014-08-27 03:41:31 +00:00
|
|
|
"tinyblob": "string",
|
|
|
|
"mediumblob": "string",
|
2014-07-31 10:46:03 +00:00
|
|
|
"longblob": "string",
|
|
|
|
"date": "time.Time", // time
|
|
|
|
"datetime": "time.Time",
|
|
|
|
"timestamp": "time.Time",
|
2014-08-27 04:01:13 +00:00
|
|
|
"time": "time.Time",
|
2014-07-31 10:46:03 +00:00
|
|
|
"float": "float32", // float & decimal
|
|
|
|
"double": "float64",
|
|
|
|
"decimal": "float64",
|
2014-08-19 10:04:22 +00:00
|
|
|
"binary": "string", // binary
|
|
|
|
"varbinary": "string",
|
2017-05-29 18:48:57 +00:00
|
|
|
"year": "int16",
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
|
2014-08-21 03:53:12 +00:00
|
|
|
// typeMappingPostgres maps SQL data type to corresponding Go data type
|
|
|
|
var typeMappingPostgres = map[string]string{
|
2014-08-22 07:50:13 +00:00
|
|
|
"serial": "int", // serial
|
|
|
|
"big serial": "int64",
|
|
|
|
"smallint": "int16", // int
|
|
|
|
"integer": "int",
|
|
|
|
"bigint": "int64",
|
|
|
|
"boolean": "bool", // bool
|
|
|
|
"char": "string", // string
|
|
|
|
"character": "string",
|
|
|
|
"character varying": "string",
|
|
|
|
"varchar": "string",
|
|
|
|
"text": "string",
|
|
|
|
"date": "time.Time", // time
|
|
|
|
"time": "time.Time",
|
|
|
|
"timestamp": "time.Time",
|
|
|
|
"timestamp without time zone": "time.Time",
|
2015-06-09 19:29:43 +00:00
|
|
|
"timestamp with time zone": "time.Time",
|
2014-09-04 02:53:29 +00:00
|
|
|
"interval": "string", // time interval, string for now
|
|
|
|
"real": "float32", // float & decimal
|
|
|
|
"double precision": "float64",
|
|
|
|
"decimal": "float64",
|
|
|
|
"numeric": "float64",
|
|
|
|
"money": "float64", // money
|
|
|
|
"bytea": "string", // binary
|
|
|
|
"tsvector": "string", // fulltext
|
|
|
|
"ARRAY": "string", // array
|
|
|
|
"USER-DEFINED": "string", // user defined
|
|
|
|
"uuid": "string", // uuid
|
2014-09-05 02:03:21 +00:00
|
|
|
"json": "string", // json
|
2016-12-12 20:34:13 +00:00
|
|
|
"jsonb": "string", // jsonb
|
|
|
|
"inet": "string", // ip address
|
2014-08-21 03:53:12 +00:00
|
|
|
}
|
|
|
|
|
2014-07-31 10:46:03 +00:00
|
|
|
// Table represent a table in a database
|
|
|
|
type Table struct {
|
2014-08-19 09:00:37 +00:00
|
|
|
Name string
|
|
|
|
Pk string
|
|
|
|
Uk []string
|
|
|
|
Fk map[string]*ForeignKey
|
|
|
|
Columns []*Column
|
|
|
|
ImportTimePkg bool
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Column reprsents a column for a table
|
|
|
|
type Column struct {
|
|
|
|
Name string
|
|
|
|
Type string
|
|
|
|
Tag *OrmTag
|
|
|
|
}
|
|
|
|
|
|
|
|
// ForeignKey represents a foreign key column for a table
|
|
|
|
type ForeignKey struct {
|
|
|
|
Name string
|
|
|
|
RefSchema string
|
|
|
|
RefTable string
|
|
|
|
RefColumn string
|
|
|
|
}
|
|
|
|
|
|
|
|
// OrmTag contains Beego ORM tag information for a column
|
|
|
|
type OrmTag struct {
|
|
|
|
Auto bool
|
|
|
|
Pk bool
|
|
|
|
Null bool
|
|
|
|
Index bool
|
|
|
|
Unique bool
|
|
|
|
Column string
|
|
|
|
Size string
|
|
|
|
Decimals string
|
|
|
|
Digits string
|
|
|
|
AutoNow bool
|
|
|
|
AutoNowAdd bool
|
|
|
|
Type string
|
|
|
|
Default string
|
|
|
|
RelOne bool
|
|
|
|
ReverseOne bool
|
|
|
|
RelFk bool
|
|
|
|
ReverseMany bool
|
|
|
|
RelM2M bool
|
2017-05-30 08:21:45 +00:00
|
|
|
Comment string //column comment
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// String returns the source code string for the Table struct
|
|
|
|
func (tb *Table) String() string {
|
2017-03-06 23:58:53 +00:00
|
|
|
rv := fmt.Sprintf("type %s struct {\n", utils.CamelCase(tb.Name))
|
2014-07-31 10:46:03 +00:00
|
|
|
for _, v := range tb.Columns {
|
|
|
|
rv += v.String() + "\n"
|
|
|
|
}
|
|
|
|
rv += "}\n"
|
|
|
|
return rv
|
|
|
|
}
|
|
|
|
|
|
|
|
// String returns the source code string of a field in Table struct
|
|
|
|
// It maps to a column in database table. e.g. Id int `orm:"column(id);auto"`
|
|
|
|
func (col *Column) String() string {
|
|
|
|
return fmt.Sprintf("%s %s %s", col.Name, col.Type, col.Tag.String())
|
|
|
|
}
|
|
|
|
|
|
|
|
// String returns the ORM tag string for a column
|
|
|
|
func (tag *OrmTag) String() string {
|
|
|
|
var ormOptions []string
|
|
|
|
if tag.Column != "" {
|
|
|
|
ormOptions = append(ormOptions, fmt.Sprintf("column(%s)", tag.Column))
|
|
|
|
}
|
|
|
|
if tag.Auto {
|
|
|
|
ormOptions = append(ormOptions, "auto")
|
|
|
|
}
|
|
|
|
if tag.Size != "" {
|
|
|
|
ormOptions = append(ormOptions, fmt.Sprintf("size(%s)", tag.Size))
|
|
|
|
}
|
|
|
|
if tag.Type != "" {
|
|
|
|
ormOptions = append(ormOptions, fmt.Sprintf("type(%s)", tag.Type))
|
|
|
|
}
|
|
|
|
if tag.Null {
|
|
|
|
ormOptions = append(ormOptions, "null")
|
|
|
|
}
|
|
|
|
if tag.AutoNow {
|
|
|
|
ormOptions = append(ormOptions, "auto_now")
|
|
|
|
}
|
|
|
|
if tag.AutoNowAdd {
|
|
|
|
ormOptions = append(ormOptions, "auto_now_add")
|
|
|
|
}
|
|
|
|
if tag.Decimals != "" {
|
|
|
|
ormOptions = append(ormOptions, fmt.Sprintf("digits(%s);decimals(%s)", tag.Digits, tag.Decimals))
|
|
|
|
}
|
|
|
|
if tag.RelFk {
|
|
|
|
ormOptions = append(ormOptions, "rel(fk)")
|
|
|
|
}
|
|
|
|
if tag.RelOne {
|
|
|
|
ormOptions = append(ormOptions, "rel(one)")
|
|
|
|
}
|
|
|
|
if tag.ReverseOne {
|
|
|
|
ormOptions = append(ormOptions, "reverse(one)")
|
|
|
|
}
|
|
|
|
if tag.ReverseMany {
|
|
|
|
ormOptions = append(ormOptions, "reverse(many)")
|
|
|
|
}
|
|
|
|
if tag.RelM2M {
|
|
|
|
ormOptions = append(ormOptions, "rel(m2m)")
|
|
|
|
}
|
|
|
|
if tag.Pk {
|
|
|
|
ormOptions = append(ormOptions, "pk")
|
|
|
|
}
|
|
|
|
if tag.Unique {
|
|
|
|
ormOptions = append(ormOptions, "unique")
|
|
|
|
}
|
|
|
|
if tag.Default != "" {
|
|
|
|
ormOptions = append(ormOptions, fmt.Sprintf("default(%s)", tag.Default))
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(ormOptions) == 0 {
|
|
|
|
return ""
|
|
|
|
}
|
2017-05-30 11:43:40 +00:00
|
|
|
if tag.Comment != "" {
|
|
|
|
return fmt.Sprintf("`orm:\"%s\" description:\"%s\"`", strings.Join(ormOptions, ";"), tag.Comment)
|
|
|
|
}
|
2014-07-31 10:46:03 +00:00
|
|
|
return fmt.Sprintf("`orm:\"%s\"`", strings.Join(ormOptions, ";"))
|
|
|
|
}
|
|
|
|
|
2017-03-06 23:58:53 +00:00
|
|
|
func GenerateAppcode(driver, connStr, level, tables, currpath string) {
|
2014-08-01 07:52:25 +00:00
|
|
|
var mode byte
|
2014-08-21 02:45:52 +00:00
|
|
|
switch level {
|
|
|
|
case "1":
|
2016-07-22 23:05:01 +00:00
|
|
|
mode = OModel
|
2014-08-21 02:45:52 +00:00
|
|
|
case "2":
|
2016-07-22 23:05:01 +00:00
|
|
|
mode = OModel | OController
|
2014-08-21 02:45:52 +00:00
|
|
|
case "3":
|
2016-07-22 23:05:01 +00:00
|
|
|
mode = OModel | OController | ORouter
|
2014-08-21 02:45:52 +00:00
|
|
|
default:
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatal("Invalid level value. Must be either \"1\", \"2\", or \"3\"")
|
2014-08-01 07:52:25 +00:00
|
|
|
}
|
2014-08-07 08:39:28 +00:00
|
|
|
var selectedTables map[string]bool
|
|
|
|
if tables != "" {
|
|
|
|
selectedTables = make(map[string]bool)
|
|
|
|
for _, v := range strings.Split(tables, ",") {
|
|
|
|
selectedTables[v] = true
|
|
|
|
}
|
|
|
|
}
|
2014-08-21 02:45:52 +00:00
|
|
|
switch driver {
|
|
|
|
case "mysql":
|
|
|
|
case "postgres":
|
|
|
|
case "sqlite":
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatal("Generating app code from SQLite database is not supported yet.")
|
2014-08-21 02:45:52 +00:00
|
|
|
default:
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatal("Unknown database driver. Must be either \"mysql\", \"postgres\" or \"sqlite\"")
|
2014-08-21 02:45:52 +00:00
|
|
|
}
|
2014-08-07 08:39:28 +00:00
|
|
|
gen(driver, connStr, mode, selectedTables, currpath)
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Generate takes table, column and foreign key information from database connection
|
|
|
|
// and generate corresponding golang source files
|
2016-05-26 16:17:24 +00:00
|
|
|
func gen(dbms, connStr string, mode byte, selectedTableNames map[string]bool, apppath string) {
|
2014-07-31 10:46:03 +00:00
|
|
|
db, err := sql.Open(dbms, connStr)
|
|
|
|
if err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatalf("Could not connect to '%s' database using '%s': %s", dbms, connStr, err)
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
defer db.Close()
|
2014-08-22 07:50:13 +00:00
|
|
|
if trans, ok := dbDriver[dbms]; ok {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Info("Analyzing database tables...")
|
2017-05-20 05:06:25 +00:00
|
|
|
var tableNames []string
|
|
|
|
if len(selectedTableNames) != 0 {
|
|
|
|
for tableName := range selectedTableNames {
|
|
|
|
tableNames = append(tableNames, tableName)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
tableNames = trans.GetTableNames(db)
|
|
|
|
}
|
2014-08-22 07:50:13 +00:00
|
|
|
tables := getTableObjects(tableNames, db, trans)
|
|
|
|
mvcPath := new(MvcPath)
|
2016-05-26 16:17:24 +00:00
|
|
|
mvcPath.ModelPath = path.Join(apppath, "models")
|
|
|
|
mvcPath.ControllerPath = path.Join(apppath, "controllers")
|
|
|
|
mvcPath.RouterPath = path.Join(apppath, "routers")
|
2014-08-22 07:50:13 +00:00
|
|
|
createPaths(mode, mvcPath)
|
2016-05-26 16:17:24 +00:00
|
|
|
pkgPath := getPackagePath(apppath)
|
2017-10-18 04:06:42 +00:00
|
|
|
writeSourceFiles(pkgPath, tables, mode, mvcPath)
|
2014-08-22 07:50:13 +00:00
|
|
|
} else {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatalf("Generating app code from '%s' database is not supported yet.", dbms)
|
2014-08-22 07:50:13 +00:00
|
|
|
}
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
|
2016-11-13 14:14:48 +00:00
|
|
|
// GetTableNames returns a slice of table names in the current database
|
2014-08-22 07:50:13 +00:00
|
|
|
func (*MysqlDB) GetTableNames(db *sql.DB) (tables []string) {
|
2014-08-01 09:42:04 +00:00
|
|
|
rows, err := db.Query("SHOW TABLES")
|
|
|
|
if err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatalf("Could not show tables: %s", err)
|
2014-08-01 09:42:04 +00:00
|
|
|
}
|
2014-07-31 10:46:03 +00:00
|
|
|
defer rows.Close()
|
|
|
|
for rows.Next() {
|
|
|
|
var name string
|
|
|
|
if err := rows.Scan(&name); err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatalf("Could not show tables: %s", err)
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
tables = append(tables, name)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// getTableObjects process each table name
|
2014-08-22 07:50:13 +00:00
|
|
|
func getTableObjects(tableNames []string, db *sql.DB, dbTransformer DbTransformer) (tables []*Table) {
|
2014-07-31 10:46:03 +00:00
|
|
|
// if a table has a composite pk or doesn't have pk, we can't use it yet
|
|
|
|
// these tables will be put into blacklist so that other struct will not
|
|
|
|
// reference it.
|
|
|
|
blackList := make(map[string]bool)
|
|
|
|
// process constraints information for each table, also gather blacklisted table names
|
|
|
|
for _, tableName := range tableNames {
|
|
|
|
// create a table struct
|
|
|
|
tb := new(Table)
|
|
|
|
tb.Name = tableName
|
|
|
|
tb.Fk = make(map[string]*ForeignKey)
|
2014-08-22 07:50:13 +00:00
|
|
|
dbTransformer.GetConstraints(db, tb, blackList)
|
2014-07-31 10:46:03 +00:00
|
|
|
tables = append(tables, tb)
|
|
|
|
}
|
|
|
|
// process columns, ignoring blacklisted tables
|
|
|
|
for _, tb := range tables {
|
2014-08-22 07:50:13 +00:00
|
|
|
dbTransformer.GetColumns(db, tb, blackList)
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-11-13 14:14:48 +00:00
|
|
|
// GetConstraints gets primary key, unique key and foreign keys of a table from
|
|
|
|
// information_schema and fill in the Table struct
|
2014-08-22 07:50:13 +00:00
|
|
|
func (*MysqlDB) GetConstraints(db *sql.DB, table *Table, blackList map[string]bool) {
|
2014-07-31 10:46:03 +00:00
|
|
|
rows, err := db.Query(
|
2015-10-16 15:44:11 +00:00
|
|
|
`SELECT
|
2014-07-31 10:46:03 +00:00
|
|
|
c.constraint_type, u.column_name, u.referenced_table_schema, u.referenced_table_name, referenced_column_name, u.ordinal_position
|
|
|
|
FROM
|
2015-10-16 15:44:11 +00:00
|
|
|
information_schema.table_constraints c
|
2014-07-31 10:46:03 +00:00
|
|
|
INNER JOIN
|
2015-10-16 15:44:11 +00:00
|
|
|
information_schema.key_column_usage u ON c.constraint_name = u.constraint_name
|
2014-07-31 10:46:03 +00:00
|
|
|
WHERE
|
|
|
|
c.table_schema = database() AND c.table_name = ? AND u.table_schema = database() AND u.table_name = ?`,
|
|
|
|
table.Name, table.Name) // u.position_in_unique_constraint,
|
|
|
|
if err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatal("Could not query INFORMATION_SCHEMA for PK/UK/FK information")
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
for rows.Next() {
|
|
|
|
var constraintTypeBytes, columnNameBytes, refTableSchemaBytes, refTableNameBytes, refColumnNameBytes, refOrdinalPosBytes []byte
|
|
|
|
if err := rows.Scan(&constraintTypeBytes, &columnNameBytes, &refTableSchemaBytes, &refTableNameBytes, &refColumnNameBytes, &refOrdinalPosBytes); err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatal("Could not read INFORMATION_SCHEMA for PK/UK/FK information")
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
constraintType, columnName, refTableSchema, refTableName, refColumnName, refOrdinalPos :=
|
|
|
|
string(constraintTypeBytes), string(columnNameBytes), string(refTableSchemaBytes),
|
|
|
|
string(refTableNameBytes), string(refColumnNameBytes), string(refOrdinalPosBytes)
|
|
|
|
if constraintType == "PRIMARY KEY" {
|
|
|
|
if refOrdinalPos == "1" {
|
|
|
|
table.Pk = columnName
|
|
|
|
} else {
|
|
|
|
table.Pk = ""
|
2016-11-13 14:14:48 +00:00
|
|
|
// Add table to blacklist so that other struct will not reference it, because we are not
|
2014-07-31 10:46:03 +00:00
|
|
|
// registering blacklisted tables
|
|
|
|
blackList[table.Name] = true
|
|
|
|
}
|
|
|
|
} else if constraintType == "UNIQUE" {
|
|
|
|
table.Uk = append(table.Uk, columnName)
|
|
|
|
} else if constraintType == "FOREIGN KEY" {
|
|
|
|
fk := new(ForeignKey)
|
|
|
|
fk.Name = columnName
|
|
|
|
fk.RefSchema = refTableSchema
|
|
|
|
fk.RefTable = refTableName
|
|
|
|
fk.RefColumn = refColumnName
|
|
|
|
table.Fk[columnName] = fk
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-11-13 14:14:48 +00:00
|
|
|
// GetColumns retrieves columns details from
|
|
|
|
// information_schema and fill in the Column struct
|
2014-08-22 07:50:13 +00:00
|
|
|
func (mysqlDB *MysqlDB) GetColumns(db *sql.DB, table *Table, blackList map[string]bool) {
|
2014-07-31 10:46:03 +00:00
|
|
|
// retrieve columns
|
2016-11-13 14:14:48 +00:00
|
|
|
colDefRows, err := db.Query(
|
2014-07-31 10:46:03 +00:00
|
|
|
`SELECT
|
2017-05-26 05:30:28 +00:00
|
|
|
column_name, data_type, column_type, is_nullable, column_default, extra, column_comment
|
2014-07-31 10:46:03 +00:00
|
|
|
FROM
|
2015-10-16 15:44:11 +00:00
|
|
|
information_schema.columns
|
2014-07-31 10:46:03 +00:00
|
|
|
WHERE
|
|
|
|
table_schema = database() AND table_name = ?`,
|
|
|
|
table.Name)
|
2016-11-13 14:14:48 +00:00
|
|
|
if err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatalf("Could not query the database: %s", err)
|
2016-11-13 14:14:48 +00:00
|
|
|
}
|
2014-07-31 10:46:03 +00:00
|
|
|
defer colDefRows.Close()
|
2016-11-13 14:14:48 +00:00
|
|
|
|
2014-07-31 10:46:03 +00:00
|
|
|
for colDefRows.Next() {
|
|
|
|
// datatype as bytes so that SQL <null> values can be retrieved
|
2017-05-26 05:30:28 +00:00
|
|
|
var colNameBytes, dataTypeBytes, columnTypeBytes, isNullableBytes, columnDefaultBytes, extraBytes, columnCommentBytes []byte
|
|
|
|
if err := colDefRows.Scan(&colNameBytes, &dataTypeBytes, &columnTypeBytes, &isNullableBytes, &columnDefaultBytes, &extraBytes, &columnCommentBytes); err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatal("Could not query INFORMATION_SCHEMA for column information")
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
2017-05-26 05:30:28 +00:00
|
|
|
colName, dataType, columnType, isNullable, columnDefault, extra, columnComment :=
|
|
|
|
string(colNameBytes), string(dataTypeBytes), string(columnTypeBytes), string(isNullableBytes), string(columnDefaultBytes), string(extraBytes), string(columnCommentBytes)
|
2016-11-13 14:14:48 +00:00
|
|
|
|
2014-07-31 10:46:03 +00:00
|
|
|
// create a column
|
|
|
|
col := new(Column)
|
2017-03-06 23:58:53 +00:00
|
|
|
col.Name = utils.CamelCase(colName)
|
2016-11-13 14:14:48 +00:00
|
|
|
col.Type, err = mysqlDB.GetGoDataType(dataType)
|
|
|
|
if err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatalf("%s", err)
|
2016-11-13 14:14:48 +00:00
|
|
|
}
|
|
|
|
|
2014-07-31 10:46:03 +00:00
|
|
|
// Tag info
|
|
|
|
tag := new(OrmTag)
|
|
|
|
tag.Column = colName
|
2017-05-26 05:30:28 +00:00
|
|
|
tag.Comment = columnComment
|
2014-07-31 10:46:03 +00:00
|
|
|
if table.Pk == colName {
|
|
|
|
col.Name = "Id"
|
|
|
|
col.Type = "int"
|
|
|
|
if extra == "auto_increment" {
|
|
|
|
tag.Auto = true
|
|
|
|
} else {
|
|
|
|
tag.Pk = true
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
fkCol, isFk := table.Fk[colName]
|
|
|
|
isBl := false
|
|
|
|
if isFk {
|
|
|
|
_, isBl = blackList[fkCol.RefTable]
|
|
|
|
}
|
|
|
|
// check if the current column is a foreign key
|
|
|
|
if isFk && !isBl {
|
|
|
|
tag.RelFk = true
|
|
|
|
refStructName := fkCol.RefTable
|
2017-03-06 23:58:53 +00:00
|
|
|
col.Name = utils.CamelCase(colName)
|
|
|
|
col.Type = "*" + utils.CamelCase(refStructName)
|
2014-07-31 10:46:03 +00:00
|
|
|
} else {
|
|
|
|
// if the name of column is Id, and it's not primary key
|
|
|
|
if colName == "id" {
|
|
|
|
col.Name = "Id_RENAME"
|
|
|
|
}
|
|
|
|
if isNullable == "YES" {
|
|
|
|
tag.Null = true
|
|
|
|
}
|
|
|
|
if isSQLSignedIntType(dataType) {
|
|
|
|
sign := extractIntSignness(columnType)
|
|
|
|
if sign == "unsigned" && extra != "auto_increment" {
|
2016-11-13 14:14:48 +00:00
|
|
|
col.Type, err = mysqlDB.GetGoDataType(dataType + " " + sign)
|
|
|
|
if err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatalf("%s", err)
|
2016-11-13 14:14:48 +00:00
|
|
|
}
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
if isSQLStringType(dataType) {
|
|
|
|
tag.Size = extractColSize(columnType)
|
|
|
|
}
|
|
|
|
if isSQLTemporalType(dataType) {
|
|
|
|
tag.Type = dataType
|
|
|
|
//check auto_now, auto_now_add
|
|
|
|
if columnDefault == "CURRENT_TIMESTAMP" && extra == "on update CURRENT_TIMESTAMP" {
|
|
|
|
tag.AutoNow = true
|
|
|
|
} else if columnDefault == "CURRENT_TIMESTAMP" {
|
|
|
|
tag.AutoNowAdd = true
|
|
|
|
}
|
2014-08-19 09:00:37 +00:00
|
|
|
// need to import time package
|
|
|
|
table.ImportTimePkg = true
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
if isSQLDecimal(dataType) {
|
|
|
|
tag.Digits, tag.Decimals = extractDecimal(columnType)
|
|
|
|
}
|
2014-08-19 10:04:22 +00:00
|
|
|
if isSQLBinaryType(dataType) {
|
|
|
|
tag.Size = extractColSize(columnType)
|
|
|
|
}
|
2014-08-27 03:08:32 +00:00
|
|
|
if isSQLBitType(dataType) {
|
|
|
|
tag.Size = extractColSize(columnType)
|
|
|
|
}
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
col.Tag = tag
|
|
|
|
table.Columns = append(table.Columns, col)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-07-31 21:30:35 +00:00
|
|
|
// GetGoDataType maps an SQL data type to Golang data type
|
2016-11-13 14:14:48 +00:00
|
|
|
func (*MysqlDB) GetGoDataType(sqlType string) (string, error) {
|
2017-04-28 14:53:38 +00:00
|
|
|
if v, ok := typeMappingMysql[sqlType]; ok {
|
2016-11-13 14:14:48 +00:00
|
|
|
return v, nil
|
2014-08-22 07:50:13 +00:00
|
|
|
}
|
2016-11-13 14:14:48 +00:00
|
|
|
return "", fmt.Errorf("data type '%s' not found", sqlType)
|
2014-08-22 07:50:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// GetTableNames for PostgreSQL
|
|
|
|
func (*PostgresDB) GetTableNames(db *sql.DB) (tables []string) {
|
|
|
|
rows, err := db.Query(`
|
|
|
|
SELECT table_name FROM information_schema.tables
|
2016-03-11 15:39:17 +00:00
|
|
|
WHERE table_catalog = current_database() AND
|
|
|
|
table_type = 'BASE TABLE' AND
|
|
|
|
table_schema NOT IN ('pg_catalog', 'information_schema')`)
|
2014-08-22 07:50:13 +00:00
|
|
|
if err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatalf("Could not show tables: %s", err)
|
2014-08-22 07:50:13 +00:00
|
|
|
}
|
|
|
|
defer rows.Close()
|
2016-11-13 14:14:48 +00:00
|
|
|
|
2014-08-22 07:50:13 +00:00
|
|
|
for rows.Next() {
|
|
|
|
var name string
|
|
|
|
if err := rows.Scan(&name); err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatalf("Could not show tables: %s", err)
|
2014-08-22 07:50:13 +00:00
|
|
|
}
|
|
|
|
tables = append(tables, name)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetConstraints for PostgreSQL
|
|
|
|
func (*PostgresDB) GetConstraints(db *sql.DB, table *Table, blackList map[string]bool) {
|
|
|
|
rows, err := db.Query(
|
2015-10-16 15:44:11 +00:00
|
|
|
`SELECT
|
2014-08-22 07:50:13 +00:00
|
|
|
c.constraint_type,
|
|
|
|
u.column_name,
|
|
|
|
cu.table_catalog AS referenced_table_catalog,
|
|
|
|
cu.table_name AS referenced_table_name,
|
|
|
|
cu.column_name AS referenced_column_name,
|
|
|
|
u.ordinal_position
|
|
|
|
FROM
|
2015-10-16 15:44:11 +00:00
|
|
|
information_schema.table_constraints c
|
2014-08-22 07:50:13 +00:00
|
|
|
INNER JOIN
|
|
|
|
information_schema.key_column_usage u ON c.constraint_name = u.constraint_name
|
|
|
|
INNER JOIN
|
|
|
|
information_schema.constraint_column_usage cu ON cu.constraint_name = c.constraint_name
|
|
|
|
WHERE
|
2016-03-11 15:39:17 +00:00
|
|
|
c.table_catalog = current_database() AND c.table_schema NOT IN ('pg_catalog', 'information_schema')
|
|
|
|
AND c.table_name = $1
|
|
|
|
AND u.table_catalog = current_database() AND u.table_schema NOT IN ('pg_catalog', 'information_schema')
|
|
|
|
AND u.table_name = $2`,
|
2014-08-22 07:50:13 +00:00
|
|
|
table.Name, table.Name) // u.position_in_unique_constraint,
|
|
|
|
if err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatalf("Could not query INFORMATION_SCHEMA for PK/UK/FK information: %s", err)
|
2014-08-22 07:50:13 +00:00
|
|
|
}
|
2016-11-13 14:14:48 +00:00
|
|
|
|
2014-08-22 07:50:13 +00:00
|
|
|
for rows.Next() {
|
|
|
|
var constraintTypeBytes, columnNameBytes, refTableSchemaBytes, refTableNameBytes, refColumnNameBytes, refOrdinalPosBytes []byte
|
|
|
|
if err := rows.Scan(&constraintTypeBytes, &columnNameBytes, &refTableSchemaBytes, &refTableNameBytes, &refColumnNameBytes, &refOrdinalPosBytes); err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatalf("Could not read INFORMATION_SCHEMA for PK/UK/FK information: %s", err)
|
2014-08-22 07:50:13 +00:00
|
|
|
}
|
|
|
|
constraintType, columnName, refTableSchema, refTableName, refColumnName, refOrdinalPos :=
|
|
|
|
string(constraintTypeBytes), string(columnNameBytes), string(refTableSchemaBytes),
|
|
|
|
string(refTableNameBytes), string(refColumnNameBytes), string(refOrdinalPosBytes)
|
|
|
|
if constraintType == "PRIMARY KEY" {
|
|
|
|
if refOrdinalPos == "1" {
|
|
|
|
table.Pk = columnName
|
|
|
|
} else {
|
|
|
|
table.Pk = ""
|
|
|
|
// add table to blacklist so that other struct will not reference it, because we are not
|
|
|
|
// registering blacklisted tables
|
|
|
|
blackList[table.Name] = true
|
|
|
|
}
|
|
|
|
} else if constraintType == "UNIQUE" {
|
|
|
|
table.Uk = append(table.Uk, columnName)
|
|
|
|
} else if constraintType == "FOREIGN KEY" {
|
|
|
|
fk := new(ForeignKey)
|
|
|
|
fk.Name = columnName
|
|
|
|
fk.RefSchema = refTableSchema
|
|
|
|
fk.RefTable = refTableName
|
|
|
|
fk.RefColumn = refColumnName
|
|
|
|
table.Fk[columnName] = fk
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetColumns for PostgreSQL
|
|
|
|
func (postgresDB *PostgresDB) GetColumns(db *sql.DB, table *Table, blackList map[string]bool) {
|
|
|
|
// retrieve columns
|
2016-11-13 14:14:48 +00:00
|
|
|
colDefRows, err := db.Query(
|
2014-08-22 07:50:13 +00:00
|
|
|
`SELECT
|
|
|
|
column_name,
|
|
|
|
data_type,
|
|
|
|
data_type ||
|
|
|
|
CASE
|
|
|
|
WHEN data_type = 'character' THEN '('||character_maximum_length||')'
|
|
|
|
WHEN data_type = 'numeric' THEN '(' || numeric_precision || ',' || numeric_scale ||')'
|
|
|
|
ELSE ''
|
|
|
|
END AS column_type,
|
|
|
|
is_nullable,
|
|
|
|
column_default,
|
|
|
|
'' AS extra
|
|
|
|
FROM
|
2015-10-16 15:44:11 +00:00
|
|
|
information_schema.columns
|
2014-08-22 07:50:13 +00:00
|
|
|
WHERE
|
2016-03-11 15:39:17 +00:00
|
|
|
table_catalog = current_database() AND table_schema NOT IN ('pg_catalog', 'information_schema')
|
|
|
|
AND table_name = $1`,
|
2014-08-22 07:50:13 +00:00
|
|
|
table.Name)
|
2016-11-13 14:14:48 +00:00
|
|
|
if err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatalf("Could not query INFORMATION_SCHEMA for column information: %s", err)
|
2016-11-13 14:14:48 +00:00
|
|
|
}
|
2014-08-22 07:50:13 +00:00
|
|
|
defer colDefRows.Close()
|
2016-11-13 14:14:48 +00:00
|
|
|
|
2014-08-22 07:50:13 +00:00
|
|
|
for colDefRows.Next() {
|
|
|
|
// datatype as bytes so that SQL <null> values can be retrieved
|
|
|
|
var colNameBytes, dataTypeBytes, columnTypeBytes, isNullableBytes, columnDefaultBytes, extraBytes []byte
|
|
|
|
if err := colDefRows.Scan(&colNameBytes, &dataTypeBytes, &columnTypeBytes, &isNullableBytes, &columnDefaultBytes, &extraBytes); err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatalf("Could not query INFORMATION_SCHEMA for column information: %s", err)
|
2014-08-22 07:50:13 +00:00
|
|
|
}
|
|
|
|
colName, dataType, columnType, isNullable, columnDefault, extra :=
|
|
|
|
string(colNameBytes), string(dataTypeBytes), string(columnTypeBytes), string(isNullableBytes), string(columnDefaultBytes), string(extraBytes)
|
2016-11-13 14:14:48 +00:00
|
|
|
// Create a column
|
2014-08-22 07:50:13 +00:00
|
|
|
col := new(Column)
|
2017-03-06 23:58:53 +00:00
|
|
|
col.Name = utils.CamelCase(colName)
|
2016-11-13 14:14:48 +00:00
|
|
|
col.Type, err = postgresDB.GetGoDataType(dataType)
|
|
|
|
if err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatalf("%s", err)
|
2016-11-13 14:14:48 +00:00
|
|
|
}
|
|
|
|
|
2014-08-22 07:50:13 +00:00
|
|
|
// Tag info
|
|
|
|
tag := new(OrmTag)
|
|
|
|
tag.Column = colName
|
|
|
|
if table.Pk == colName {
|
|
|
|
col.Name = "Id"
|
|
|
|
col.Type = "int"
|
|
|
|
if extra == "auto_increment" {
|
|
|
|
tag.Auto = true
|
|
|
|
} else {
|
|
|
|
tag.Pk = true
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
fkCol, isFk := table.Fk[colName]
|
|
|
|
isBl := false
|
|
|
|
if isFk {
|
|
|
|
_, isBl = blackList[fkCol.RefTable]
|
|
|
|
}
|
|
|
|
// check if the current column is a foreign key
|
|
|
|
if isFk && !isBl {
|
|
|
|
tag.RelFk = true
|
|
|
|
refStructName := fkCol.RefTable
|
2017-03-06 23:58:53 +00:00
|
|
|
col.Name = utils.CamelCase(colName)
|
|
|
|
col.Type = "*" + utils.CamelCase(refStructName)
|
2014-08-22 07:50:13 +00:00
|
|
|
} else {
|
|
|
|
// if the name of column is Id, and it's not primary key
|
|
|
|
if colName == "id" {
|
|
|
|
col.Name = "Id_RENAME"
|
|
|
|
}
|
|
|
|
if isNullable == "YES" {
|
|
|
|
tag.Null = true
|
|
|
|
}
|
|
|
|
if isSQLStringType(dataType) {
|
|
|
|
tag.Size = extractColSize(columnType)
|
|
|
|
}
|
|
|
|
if isSQLTemporalType(dataType) || strings.HasPrefix(dataType, "timestamp") {
|
|
|
|
tag.Type = dataType
|
|
|
|
//check auto_now, auto_now_add
|
|
|
|
if columnDefault == "CURRENT_TIMESTAMP" && extra == "on update CURRENT_TIMESTAMP" {
|
|
|
|
tag.AutoNow = true
|
|
|
|
} else if columnDefault == "CURRENT_TIMESTAMP" {
|
|
|
|
tag.AutoNowAdd = true
|
|
|
|
}
|
|
|
|
// need to import time package
|
|
|
|
table.ImportTimePkg = true
|
|
|
|
}
|
|
|
|
if isSQLDecimal(dataType) {
|
|
|
|
tag.Digits, tag.Decimals = extractDecimal(columnType)
|
|
|
|
}
|
|
|
|
if isSQLBinaryType(dataType) {
|
|
|
|
tag.Size = extractColSize(columnType)
|
|
|
|
}
|
2014-09-04 02:53:29 +00:00
|
|
|
if isSQLStrangeType(dataType) {
|
|
|
|
tag.Type = dataType
|
|
|
|
}
|
2014-08-22 07:50:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
col.Tag = tag
|
|
|
|
table.Columns = append(table.Columns, col)
|
|
|
|
}
|
|
|
|
}
|
2016-07-31 21:30:35 +00:00
|
|
|
|
|
|
|
// GetGoDataType returns the Go type from the mapped Postgres type
|
2016-11-13 14:14:48 +00:00
|
|
|
func (*PostgresDB) GetGoDataType(sqlType string) (string, error) {
|
2014-08-22 07:50:13 +00:00
|
|
|
if v, ok := typeMappingPostgres[sqlType]; ok {
|
2016-11-13 14:14:48 +00:00
|
|
|
return v, nil
|
2014-08-22 07:50:13 +00:00
|
|
|
}
|
2016-11-13 14:14:48 +00:00
|
|
|
return "", fmt.Errorf("data type '%s' not found", sqlType)
|
2014-08-22 07:50:13 +00:00
|
|
|
}
|
|
|
|
|
2014-07-31 10:46:03 +00:00
|
|
|
// deleteAndRecreatePaths removes several directories completely
|
2014-08-01 10:38:32 +00:00
|
|
|
func createPaths(mode byte, paths *MvcPath) {
|
2016-07-22 23:05:01 +00:00
|
|
|
if (mode & OModel) == OModel {
|
2014-08-22 08:04:07 +00:00
|
|
|
os.Mkdir(paths.ModelPath, 0777)
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
2016-07-22 23:05:01 +00:00
|
|
|
if (mode & OController) == OController {
|
2014-08-01 06:49:30 +00:00
|
|
|
os.Mkdir(paths.ControllerPath, 0777)
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
2016-07-22 23:05:01 +00:00
|
|
|
if (mode & ORouter) == ORouter {
|
2014-08-01 06:49:30 +00:00
|
|
|
os.Mkdir(paths.RouterPath, 0777)
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// writeSourceFiles generates source files for model/controller/router
|
|
|
|
// It will wipe the following directories and recreate them:./models, ./controllers, ./routers
|
|
|
|
// Newly geneated files will be inside these folders.
|
2017-10-18 04:06:42 +00:00
|
|
|
func writeSourceFiles(pkgPath string, tables []*Table, mode byte, paths *MvcPath) {
|
2016-07-22 23:05:01 +00:00
|
|
|
if (OModel & mode) == OModel {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Info("Creating model files...")
|
2017-10-18 04:06:42 +00:00
|
|
|
writeModelFiles(tables, paths.ModelPath)
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
2016-07-22 23:05:01 +00:00
|
|
|
if (OController & mode) == OController {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Info("Creating controller files...")
|
2017-10-18 04:06:42 +00:00
|
|
|
writeControllerFiles(tables, paths.ControllerPath, pkgPath)
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
2016-07-22 23:05:01 +00:00
|
|
|
if (ORouter & mode) == ORouter {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Info("Creating router files...")
|
2017-10-18 04:06:42 +00:00
|
|
|
writeRouterFile(tables, paths.RouterPath, pkgPath)
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// writeModelFiles generates model files
|
2017-10-18 04:06:42 +00:00
|
|
|
func writeModelFiles(tables []*Table, mPath string) {
|
2017-03-06 23:58:53 +00:00
|
|
|
w := colors.NewColorWriter(os.Stdout)
|
2016-07-31 21:30:35 +00:00
|
|
|
|
2014-07-31 10:46:03 +00:00
|
|
|
for _, tb := range tables {
|
|
|
|
filename := getFileName(tb.Name)
|
2014-08-01 06:49:30 +00:00
|
|
|
fpath := path.Join(mPath, filename+".go")
|
2014-08-09 03:14:00 +00:00
|
|
|
var f *os.File
|
|
|
|
var err error
|
2017-03-06 23:58:53 +00:00
|
|
|
if utils.IsExist(fpath) {
|
|
|
|
beeLogger.Log.Warnf("'%s' already exists. Do you want to overwrite it? [Yes|No] ", fpath)
|
|
|
|
if utils.AskForConfirmation() {
|
2014-08-28 09:31:37 +00:00
|
|
|
f, err = os.OpenFile(fpath, os.O_RDWR|os.O_TRUNC, 0666)
|
2014-08-09 03:14:00 +00:00
|
|
|
if err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Warnf("%s", err)
|
2014-08-09 03:14:00 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
} else {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Warnf("Skipped create file '%s'", fpath)
|
2014-08-09 03:14:00 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
} else {
|
2014-08-12 03:13:48 +00:00
|
|
|
f, err = os.OpenFile(fpath, os.O_CREATE|os.O_RDWR, 0666)
|
2014-08-09 03:14:00 +00:00
|
|
|
if err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Warnf("%s", err)
|
2014-08-09 03:14:00 +00:00
|
|
|
continue
|
|
|
|
}
|
2014-08-01 10:48:49 +00:00
|
|
|
}
|
2017-04-28 14:53:38 +00:00
|
|
|
var template string
|
2014-07-31 10:46:03 +00:00
|
|
|
if tb.Pk == "" {
|
2016-07-22 23:05:01 +00:00
|
|
|
template = StructModelTPL
|
2014-07-31 10:46:03 +00:00
|
|
|
} else {
|
2016-07-22 23:05:01 +00:00
|
|
|
template = ModelTPL
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
fileStr := strings.Replace(template, "{{modelStruct}}", tb.String(), 1)
|
2017-03-06 23:58:53 +00:00
|
|
|
fileStr = strings.Replace(fileStr, "{{modelName}}", utils.CamelCase(tb.Name), -1)
|
2015-03-03 15:35:46 +00:00
|
|
|
fileStr = strings.Replace(fileStr, "{{tableName}}", tb.Name, -1)
|
2016-11-13 14:14:48 +00:00
|
|
|
|
|
|
|
// If table contains time field, import time.Time package
|
2014-08-19 09:00:37 +00:00
|
|
|
timePkg := ""
|
2014-08-19 09:43:08 +00:00
|
|
|
importTimePkg := ""
|
2014-08-19 09:00:37 +00:00
|
|
|
if tb.ImportTimePkg {
|
|
|
|
timePkg = "\"time\"\n"
|
2014-08-19 09:43:08 +00:00
|
|
|
importTimePkg = "import \"time\"\n"
|
2014-08-19 09:00:37 +00:00
|
|
|
}
|
|
|
|
fileStr = strings.Replace(fileStr, "{{timePkg}}", timePkg, -1)
|
2014-08-19 09:43:08 +00:00
|
|
|
fileStr = strings.Replace(fileStr, "{{importTimePkg}}", importTimePkg, -1)
|
2014-07-31 10:46:03 +00:00
|
|
|
if _, err := f.WriteString(fileStr); err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatalf("Could not write model file to '%s': %s", fpath, err)
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
2017-03-06 23:58:53 +00:00
|
|
|
utils.CloseFile(f)
|
2016-07-31 21:30:35 +00:00
|
|
|
fmt.Fprintf(w, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", fpath, "\x1b[0m")
|
2017-03-06 23:58:53 +00:00
|
|
|
utils.FormatSourceCode(fpath)
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// writeControllerFiles generates controller files
|
2017-10-18 04:06:42 +00:00
|
|
|
func writeControllerFiles(tables []*Table, cPath string, pkgPath string) {
|
2017-03-06 23:58:53 +00:00
|
|
|
w := colors.NewColorWriter(os.Stdout)
|
2016-07-31 21:30:35 +00:00
|
|
|
|
2014-07-31 10:46:03 +00:00
|
|
|
for _, tb := range tables {
|
|
|
|
if tb.Pk == "" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
filename := getFileName(tb.Name)
|
2014-08-01 06:49:30 +00:00
|
|
|
fpath := path.Join(cPath, filename+".go")
|
2014-08-09 03:14:00 +00:00
|
|
|
var f *os.File
|
|
|
|
var err error
|
2017-03-06 23:58:53 +00:00
|
|
|
if utils.IsExist(fpath) {
|
|
|
|
beeLogger.Log.Warnf("'%s' already exists. Do you want to overwrite it? [Yes|No] ", fpath)
|
|
|
|
if utils.AskForConfirmation() {
|
2014-08-28 09:31:37 +00:00
|
|
|
f, err = os.OpenFile(fpath, os.O_RDWR|os.O_TRUNC, 0666)
|
2014-08-09 03:14:00 +00:00
|
|
|
if err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Warnf("%s", err)
|
2014-08-09 03:14:00 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
} else {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Warnf("Skipped create file '%s'", fpath)
|
2014-08-09 03:14:00 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
} else {
|
2014-08-12 03:13:48 +00:00
|
|
|
f, err = os.OpenFile(fpath, os.O_CREATE|os.O_RDWR, 0666)
|
2014-08-09 03:14:00 +00:00
|
|
|
if err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Warnf("%s", err)
|
2014-08-09 03:14:00 +00:00
|
|
|
continue
|
|
|
|
}
|
2014-08-01 10:48:49 +00:00
|
|
|
}
|
2017-03-06 23:58:53 +00:00
|
|
|
fileStr := strings.Replace(CtrlTPL, "{{ctrlName}}", utils.CamelCase(tb.Name), -1)
|
2014-08-19 09:00:37 +00:00
|
|
|
fileStr = strings.Replace(fileStr, "{{pkgPath}}", pkgPath, -1)
|
2014-07-31 10:46:03 +00:00
|
|
|
if _, err := f.WriteString(fileStr); err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatalf("Could not write controller file to '%s': %s", fpath, err)
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
2017-03-06 23:58:53 +00:00
|
|
|
utils.CloseFile(f)
|
2016-07-31 21:30:35 +00:00
|
|
|
fmt.Fprintf(w, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", fpath, "\x1b[0m")
|
2017-03-06 23:58:53 +00:00
|
|
|
utils.FormatSourceCode(fpath)
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// writeRouterFile generates router file
|
2017-10-18 04:06:42 +00:00
|
|
|
func writeRouterFile(tables []*Table, rPath string, pkgPath string) {
|
2017-03-06 23:58:53 +00:00
|
|
|
w := colors.NewColorWriter(os.Stdout)
|
2016-07-31 21:30:35 +00:00
|
|
|
|
2014-07-31 10:46:03 +00:00
|
|
|
var nameSpaces []string
|
|
|
|
for _, tb := range tables {
|
|
|
|
if tb.Pk == "" {
|
|
|
|
continue
|
|
|
|
}
|
2016-11-13 14:14:48 +00:00
|
|
|
// Add namespaces
|
2016-07-22 23:05:01 +00:00
|
|
|
nameSpace := strings.Replace(NamespaceTPL, "{{nameSpace}}", tb.Name, -1)
|
2017-03-06 23:58:53 +00:00
|
|
|
nameSpace = strings.Replace(nameSpace, "{{ctrlName}}", utils.CamelCase(tb.Name), -1)
|
2014-07-31 10:46:03 +00:00
|
|
|
nameSpaces = append(nameSpaces, nameSpace)
|
|
|
|
}
|
2016-11-13 14:14:48 +00:00
|
|
|
// Add export controller
|
2017-04-24 13:06:31 +00:00
|
|
|
fpath := filepath.Join(rPath, "router.go")
|
2016-07-22 23:05:01 +00:00
|
|
|
routerStr := strings.Replace(RouterTPL, "{{nameSpaces}}", strings.Join(nameSpaces, ""), 1)
|
2014-08-19 09:00:37 +00:00
|
|
|
routerStr = strings.Replace(routerStr, "{{pkgPath}}", pkgPath, 1)
|
2014-08-09 03:14:00 +00:00
|
|
|
var f *os.File
|
|
|
|
var err error
|
2017-03-06 23:58:53 +00:00
|
|
|
if utils.IsExist(fpath) {
|
|
|
|
beeLogger.Log.Warnf("'%s' already exists. Do you want to overwrite it? [Yes|No] ", fpath)
|
|
|
|
if utils.AskForConfirmation() {
|
2014-08-28 09:31:37 +00:00
|
|
|
f, err = os.OpenFile(fpath, os.O_RDWR|os.O_TRUNC, 0666)
|
2014-08-09 03:14:00 +00:00
|
|
|
if err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Warnf("%s", err)
|
2014-08-09 03:14:00 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
} else {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Warnf("Skipped create file '%s'", fpath)
|
2014-08-09 03:14:00 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
} else {
|
2014-08-12 03:13:48 +00:00
|
|
|
f, err = os.OpenFile(fpath, os.O_CREATE|os.O_RDWR, 0666)
|
2014-08-09 03:14:00 +00:00
|
|
|
if err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Warnf("%s", err)
|
2014-08-09 03:14:00 +00:00
|
|
|
return
|
|
|
|
}
|
2014-08-01 10:48:49 +00:00
|
|
|
}
|
2014-07-31 10:46:03 +00:00
|
|
|
if _, err := f.WriteString(routerStr); err != nil {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatalf("Could not write router file to '%s': %s", fpath, err)
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
2017-03-06 23:58:53 +00:00
|
|
|
utils.CloseFile(f)
|
2016-07-31 21:30:35 +00:00
|
|
|
fmt.Fprintf(w, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", fpath, "\x1b[0m")
|
2017-03-06 23:58:53 +00:00
|
|
|
utils.FormatSourceCode(fpath)
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func isSQLTemporalType(t string) bool {
|
2014-08-28 09:11:56 +00:00
|
|
|
return t == "date" || t == "datetime" || t == "timestamp" || t == "time"
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func isSQLStringType(t string) bool {
|
|
|
|
return t == "char" || t == "varchar"
|
|
|
|
}
|
|
|
|
|
|
|
|
func isSQLSignedIntType(t string) bool {
|
|
|
|
return t == "int" || t == "tinyint" || t == "smallint" || t == "mediumint" || t == "bigint"
|
|
|
|
}
|
|
|
|
|
|
|
|
func isSQLDecimal(t string) bool {
|
|
|
|
return t == "decimal"
|
|
|
|
}
|
|
|
|
|
2014-08-19 10:04:22 +00:00
|
|
|
func isSQLBinaryType(t string) bool {
|
|
|
|
return t == "binary" || t == "varbinary"
|
|
|
|
}
|
|
|
|
|
2014-08-27 03:08:32 +00:00
|
|
|
func isSQLBitType(t string) bool {
|
|
|
|
return t == "bit"
|
|
|
|
}
|
2014-09-04 02:53:29 +00:00
|
|
|
func isSQLStrangeType(t string) bool {
|
2014-09-05 02:03:21 +00:00
|
|
|
return t == "interval" || t == "uuid" || t == "json"
|
2014-09-04 02:53:29 +00:00
|
|
|
}
|
2014-08-27 03:08:32 +00:00
|
|
|
|
2014-07-31 10:46:03 +00:00
|
|
|
// extractColSize extracts field size: e.g. varchar(255) => 255
|
|
|
|
func extractColSize(colType string) string {
|
|
|
|
regex := regexp.MustCompile(`^[a-z]+\(([0-9]+)\)$`)
|
|
|
|
size := regex.FindStringSubmatch(colType)
|
|
|
|
return size[1]
|
|
|
|
}
|
|
|
|
|
|
|
|
func extractIntSignness(colType string) string {
|
|
|
|
regex := regexp.MustCompile(`(int|smallint|mediumint|bigint)\([0-9]+\)(.*)`)
|
|
|
|
signRegex := regex.FindStringSubmatch(colType)
|
|
|
|
return strings.Trim(signRegex[2], " ")
|
|
|
|
}
|
|
|
|
|
|
|
|
func extractDecimal(colType string) (digits string, decimals string) {
|
|
|
|
decimalRegex := regexp.MustCompile(`decimal\(([0-9]+),([0-9]+)\)`)
|
|
|
|
decimal := decimalRegex.FindStringSubmatch(colType)
|
|
|
|
digits, decimals = decimal[1], decimal[2]
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func getFileName(tbName string) (filename string) {
|
|
|
|
// avoid test file
|
|
|
|
filename = tbName
|
|
|
|
for strings.HasSuffix(filename, "_test") {
|
|
|
|
pos := strings.LastIndex(filename, "_")
|
|
|
|
filename = filename[:pos] + filename[pos+1:]
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2014-08-19 09:00:37 +00:00
|
|
|
func getPackagePath(curpath string) (packpath string) {
|
|
|
|
gopath := os.Getenv("GOPATH")
|
|
|
|
if gopath == "" {
|
2020-06-25 14:29:27 +00:00
|
|
|
info := "GOPATH environment variable is not set or empty"
|
|
|
|
gomodpath := filepath.Join(curpath, `go.mod`)
|
|
|
|
re, err := regexp.Compile(`^module\s+(.+)$`)
|
|
|
|
if err != nil {
|
|
|
|
beeLogger.Log.Error(info)
|
|
|
|
beeLogger.Log.Fatalf("try `go.mod` generate regexp error:%s", err)
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
fd, err := os.Open(gomodpath)
|
|
|
|
if err != nil {
|
|
|
|
beeLogger.Log.Error(info)
|
|
|
|
beeLogger.Log.Fatalf("try `go.mod` Error while reading 'go.mod',%s", gomodpath)
|
|
|
|
}
|
|
|
|
reader := bufio.NewReader(fd)
|
|
|
|
for {
|
|
|
|
byteLine, _, er := reader.ReadLine()
|
|
|
|
if er != nil && er != io.EOF {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
if er == io.EOF {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
line := string(byteLine)
|
|
|
|
s := re.FindStringSubmatch(line)
|
|
|
|
if len(s) >= 2 {
|
|
|
|
return s[1]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
beeLogger.Log.Error(info)
|
|
|
|
beeLogger.Log.Fatalf("try `go.mod` Error while parse 'go.mod',%s", gomodpath)
|
|
|
|
} else {
|
|
|
|
beeLogger.Log.Debugf("GOPATH: %s", utils.FILE(), utils.LINE(), gopath)
|
2014-08-19 09:00:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
appsrcpath := ""
|
|
|
|
haspath := false
|
|
|
|
wgopath := filepath.SplitList(gopath)
|
|
|
|
|
|
|
|
for _, wg := range wgopath {
|
2017-04-19 15:51:12 +00:00
|
|
|
wg, _ = filepath.EvalSymlinks(filepath.Join(wg, "src"))
|
2017-04-19 15:02:57 +00:00
|
|
|
if strings.HasPrefix(strings.ToLower(curpath), strings.ToLower(wg)) {
|
2014-08-19 09:00:37 +00:00
|
|
|
haspath = true
|
|
|
|
appsrcpath = wg
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if !haspath {
|
2017-04-19 15:51:12 +00:00
|
|
|
beeLogger.Log.Fatalf("Cannot generate application code outside of GOPATH '%s' compare with CWD '%s'", gopath, curpath)
|
2014-08-19 09:00:37 +00:00
|
|
|
}
|
2016-03-11 15:39:17 +00:00
|
|
|
|
Fix bug that execute the cmd not in application catalog
2015/12/31 10:02:34 [INFO] Using matching model 'Post'
panic: runtime error: slice bounds out of range
goroutine 1 [running]:
main.getPackagePath(0xc082005b60, 0xf, 0x0, 0x0)
E:/ossbuild/src/bee/g_appcode.go:988 +0x5f7
main.generateController(0xc0820022b0, 0x4, 0xc082005b60, 0xf)
E:/ossbuild/src/bee/g_controllers.go:52 +0xadc
main.generateScaffold(0xc0820022b0, 0x4, 0xc0821150c0, 0x16,
0xc082005b60, 0xf,
0xc082118040, 0x5, 0xc0821150e0, 0x1e)
E:/ossbuild/src/bee/g_scaffold.go:18 +0x2d7
main.generateCode(0xc0de40, 0xc08200c1b0, 0x3, 0x3, 0x0)
E:/ossbuild/src/bee/g.go:123 +0x16c9
main.main()
E:/ossbuild/src/bee/bee.go:114 +0x37d
2016-01-07 03:51:31 +00:00
|
|
|
if curpath == appsrcpath {
|
2017-03-06 23:58:53 +00:00
|
|
|
beeLogger.Log.Fatal("Cannot generate application code outside of application path")
|
Fix bug that execute the cmd not in application catalog
2015/12/31 10:02:34 [INFO] Using matching model 'Post'
panic: runtime error: slice bounds out of range
goroutine 1 [running]:
main.getPackagePath(0xc082005b60, 0xf, 0x0, 0x0)
E:/ossbuild/src/bee/g_appcode.go:988 +0x5f7
main.generateController(0xc0820022b0, 0x4, 0xc082005b60, 0xf)
E:/ossbuild/src/bee/g_controllers.go:52 +0xadc
main.generateScaffold(0xc0820022b0, 0x4, 0xc0821150c0, 0x16,
0xc082005b60, 0xf,
0xc082118040, 0x5, 0xc0821150e0, 0x1e)
E:/ossbuild/src/bee/g_scaffold.go:18 +0x2d7
main.generateCode(0xc0de40, 0xc08200c1b0, 0x3, 0x3, 0x0)
E:/ossbuild/src/bee/g.go:123 +0x16c9
main.main()
E:/ossbuild/src/bee/bee.go:114 +0x37d
2016-01-07 03:51:31 +00:00
|
|
|
}
|
2016-03-11 15:39:17 +00:00
|
|
|
|
2014-08-19 09:00:37 +00:00
|
|
|
packpath = strings.Join(strings.Split(curpath[len(appsrcpath)+1:], string(filepath.Separator)), "/")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2014-07-31 10:46:03 +00:00
|
|
|
const (
|
2016-07-22 23:05:01 +00:00
|
|
|
StructModelTPL = `package models
|
2014-08-19 09:43:08 +00:00
|
|
|
{{importTimePkg}}
|
2014-07-31 10:46:03 +00:00
|
|
|
{{modelStruct}}
|
|
|
|
`
|
|
|
|
|
2016-07-22 23:05:01 +00:00
|
|
|
ModelTPL = `package models
|
2014-07-31 10:46:03 +00:00
|
|
|
|
2014-08-19 09:00:37 +00:00
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"reflect"
|
|
|
|
"strings"
|
|
|
|
{{timePkg}}
|
|
|
|
"github.com/astaxie/beego/orm"
|
|
|
|
)
|
|
|
|
|
2014-07-31 10:46:03 +00:00
|
|
|
{{modelStruct}}
|
|
|
|
|
2015-03-03 15:35:46 +00:00
|
|
|
func (t *{{modelName}}) TableName() string {
|
|
|
|
return "{{tableName}}"
|
|
|
|
}
|
|
|
|
|
2014-07-31 10:46:03 +00:00
|
|
|
func init() {
|
|
|
|
orm.RegisterModel(new({{modelName}}))
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add{{modelName}} insert a new {{modelName}} into database and returns
|
|
|
|
// last inserted Id on success.
|
|
|
|
func Add{{modelName}}(m *{{modelName}}) (id int64, err error) {
|
|
|
|
o := orm.NewOrm()
|
|
|
|
id, err = o.Insert(m)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get{{modelName}}ById retrieves {{modelName}} by Id. Returns error if
|
|
|
|
// Id doesn't exist
|
|
|
|
func Get{{modelName}}ById(id int) (v *{{modelName}}, err error) {
|
|
|
|
o := orm.NewOrm()
|
|
|
|
v = &{{modelName}}{Id: id}
|
2017-04-19 15:02:57 +00:00
|
|
|
if err = o.Read(v); err == nil {
|
2014-07-31 10:46:03 +00:00
|
|
|
return v, nil
|
|
|
|
}
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2014-08-04 07:46:46 +00:00
|
|
|
// GetAll{{modelName}} retrieves all {{modelName}} matches certain condition. Returns empty list if
|
|
|
|
// no records exist
|
2014-08-05 06:31:19 +00:00
|
|
|
func GetAll{{modelName}}(query map[string]string, fields []string, sortby []string, order []string,
|
2014-08-05 09:49:36 +00:00
|
|
|
offset int64, limit int64) (ml []interface{}, err error) {
|
2014-08-04 07:46:46 +00:00
|
|
|
o := orm.NewOrm()
|
2014-08-05 06:31:19 +00:00
|
|
|
qs := o.QueryTable(new({{modelName}}))
|
|
|
|
// query k=v
|
|
|
|
for k, v := range query {
|
2014-08-05 07:27:05 +00:00
|
|
|
// rewrite dot-notation to Object__Attribute
|
|
|
|
k = strings.Replace(k, ".", "__", -1)
|
2016-11-16 20:39:54 +00:00
|
|
|
if strings.Contains(k, "isnull") {
|
|
|
|
qs = qs.Filter(k, (v == "true" || v == "1"))
|
|
|
|
} else {
|
|
|
|
qs = qs.Filter(k, v)
|
|
|
|
}
|
2014-08-05 06:31:19 +00:00
|
|
|
}
|
|
|
|
// order by:
|
|
|
|
var sortFields []string
|
|
|
|
if len(sortby) != 0 {
|
|
|
|
if len(sortby) == len(order) {
|
|
|
|
// 1) for each sort field, there is an associated order
|
|
|
|
for i, v := range sortby {
|
|
|
|
orderby := ""
|
|
|
|
if order[i] == "desc" {
|
|
|
|
orderby = "-" + v
|
|
|
|
} else if order[i] == "asc" {
|
|
|
|
orderby = v
|
|
|
|
} else {
|
|
|
|
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
|
|
|
|
}
|
|
|
|
sortFields = append(sortFields, orderby)
|
|
|
|
}
|
|
|
|
qs = qs.OrderBy(sortFields...)
|
|
|
|
} else if len(sortby) != len(order) && len(order) == 1 {
|
|
|
|
// 2) there is exactly one order, all the sorted fields will be sorted by this order
|
|
|
|
for _, v := range sortby {
|
|
|
|
orderby := ""
|
|
|
|
if order[0] == "desc" {
|
|
|
|
orderby = "-" + v
|
|
|
|
} else if order[0] == "asc" {
|
|
|
|
orderby = v
|
|
|
|
} else {
|
|
|
|
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
|
|
|
|
}
|
|
|
|
sortFields = append(sortFields, orderby)
|
|
|
|
}
|
|
|
|
} else if len(sortby) != len(order) && len(order) != 1 {
|
|
|
|
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if len(order) != 0 {
|
|
|
|
return nil, errors.New("Error: unused 'order' fields")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-08-05 09:49:36 +00:00
|
|
|
var l []{{modelName}}
|
2014-08-05 06:31:19 +00:00
|
|
|
qs = qs.OrderBy(sortFields...)
|
2017-04-19 15:02:57 +00:00
|
|
|
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
|
2014-08-06 02:26:54 +00:00
|
|
|
if len(fields) == 0 {
|
|
|
|
for _, v := range l {
|
|
|
|
ml = append(ml, v)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// trim unused fields
|
|
|
|
for _, v := range l {
|
|
|
|
m := make(map[string]interface{})
|
2014-08-06 02:49:26 +00:00
|
|
|
val := reflect.ValueOf(v)
|
|
|
|
for _, fname := range fields {
|
|
|
|
m[fname] = val.FieldByName(fname).Interface()
|
2014-08-05 09:49:36 +00:00
|
|
|
}
|
2014-08-06 02:26:54 +00:00
|
|
|
ml = append(ml, m)
|
2014-08-05 09:49:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return ml, nil
|
2014-08-04 07:46:46 +00:00
|
|
|
}
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2014-07-31 10:46:03 +00:00
|
|
|
// Update{{modelName}} updates {{modelName}} by Id and returns error if
|
|
|
|
// the record to be updated doesn't exist
|
|
|
|
func Update{{modelName}}ById(m *{{modelName}}) (err error) {
|
|
|
|
o := orm.NewOrm()
|
|
|
|
v := {{modelName}}{Id: m.Id}
|
|
|
|
// ascertain id exists in the database
|
|
|
|
if err = o.Read(&v); err == nil {
|
|
|
|
var num int64
|
|
|
|
if num, err = o.Update(m); err == nil {
|
|
|
|
fmt.Println("Number of records updated in database:", num)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Delete{{modelName}} deletes {{modelName}} by Id and returns error if
|
|
|
|
// the record to be deleted doesn't exist
|
|
|
|
func Delete{{modelName}}(id int) (err error) {
|
|
|
|
o := orm.NewOrm()
|
|
|
|
v := {{modelName}}{Id: id}
|
|
|
|
// ascertain id exists in the database
|
|
|
|
if err = o.Read(&v); err == nil {
|
|
|
|
var num int64
|
|
|
|
if num, err = o.Delete(&{{modelName}}{Id: id}); err == nil {
|
|
|
|
fmt.Println("Number of records deleted in database:", num)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
`
|
2016-07-22 23:05:01 +00:00
|
|
|
CtrlTPL = `package controllers
|
2014-08-19 09:00:37 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"{{pkgPath}}/models"
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/astaxie/beego"
|
|
|
|
)
|
2014-07-31 10:46:03 +00:00
|
|
|
|
2016-12-12 20:34:13 +00:00
|
|
|
// {{ctrlName}}Controller operations for {{ctrlName}}
|
2014-07-31 10:46:03 +00:00
|
|
|
type {{ctrlName}}Controller struct {
|
|
|
|
beego.Controller
|
|
|
|
}
|
|
|
|
|
2016-09-09 07:20:59 +00:00
|
|
|
// URLMapping ...
|
2014-11-05 14:48:09 +00:00
|
|
|
func (c *{{ctrlName}}Controller) URLMapping() {
|
|
|
|
c.Mapping("Post", c.Post)
|
|
|
|
c.Mapping("GetOne", c.GetOne)
|
|
|
|
c.Mapping("GetAll", c.GetAll)
|
|
|
|
c.Mapping("Put", c.Put)
|
|
|
|
c.Mapping("Delete", c.Delete)
|
2014-08-18 04:21:21 +00:00
|
|
|
}
|
|
|
|
|
2016-09-09 07:20:59 +00:00
|
|
|
// Post ...
|
2014-07-31 10:46:03 +00:00
|
|
|
// @Title Post
|
|
|
|
// @Description create {{ctrlName}}
|
|
|
|
// @Param body body models.{{ctrlName}} true "body for {{ctrlName}} content"
|
2015-10-16 15:44:11 +00:00
|
|
|
// @Success 201 {int} models.{{ctrlName}}
|
2014-07-31 10:46:03 +00:00
|
|
|
// @Failure 403 body is empty
|
|
|
|
// @router / [post]
|
2014-11-05 14:48:09 +00:00
|
|
|
func (c *{{ctrlName}}Controller) Post() {
|
2014-07-31 10:46:03 +00:00
|
|
|
var v models.{{ctrlName}}
|
2015-11-25 14:24:10 +00:00
|
|
|
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err == nil {
|
|
|
|
if _, err := models.Add{{ctrlName}}(&v); err == nil {
|
|
|
|
c.Ctx.Output.SetStatus(201)
|
|
|
|
c.Data["json"] = v
|
|
|
|
} else {
|
|
|
|
c.Data["json"] = err.Error()
|
|
|
|
}
|
2014-07-31 10:46:03 +00:00
|
|
|
} else {
|
2014-11-05 14:48:09 +00:00
|
|
|
c.Data["json"] = err.Error()
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
2015-10-22 03:32:21 +00:00
|
|
|
c.ServeJSON()
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
|
2016-09-09 07:27:36 +00:00
|
|
|
// GetOne ...
|
|
|
|
// @Title Get One
|
2014-07-31 10:46:03 +00:00
|
|
|
// @Description get {{ctrlName}} by id
|
|
|
|
// @Param id path string true "The key for staticblock"
|
|
|
|
// @Success 200 {object} models.{{ctrlName}}
|
|
|
|
// @Failure 403 :id is empty
|
|
|
|
// @router /:id [get]
|
2014-11-05 14:48:09 +00:00
|
|
|
func (c *{{ctrlName}}Controller) GetOne() {
|
2016-01-06 03:55:56 +00:00
|
|
|
idStr := c.Ctx.Input.Param(":id")
|
2014-07-31 10:46:03 +00:00
|
|
|
id, _ := strconv.Atoi(idStr)
|
|
|
|
v, err := models.Get{{ctrlName}}ById(id)
|
|
|
|
if err != nil {
|
2014-11-05 14:48:09 +00:00
|
|
|
c.Data["json"] = err.Error()
|
2014-07-31 10:46:03 +00:00
|
|
|
} else {
|
2014-11-05 14:48:09 +00:00
|
|
|
c.Data["json"] = v
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
2015-10-22 03:32:21 +00:00
|
|
|
c.ServeJSON()
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
|
2016-09-09 07:20:59 +00:00
|
|
|
// GetAll ...
|
2014-08-04 07:46:46 +00:00
|
|
|
// @Title Get All
|
|
|
|
// @Description get {{ctrlName}}
|
2014-08-05 08:13:40 +00:00
|
|
|
// @Param query query string false "Filter. e.g. col1:v1,col2:v2 ..."
|
|
|
|
// @Param fields query string false "Fields returned. e.g. col1,col2 ..."
|
|
|
|
// @Param sortby query string false "Sorted-by fields. e.g. col1,col2 ..."
|
|
|
|
// @Param order query string false "Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
|
|
|
|
// @Param limit query string false "Limit the size of result set. Must be an integer"
|
|
|
|
// @Param offset query string false "Start position of result set. Must be an integer"
|
2014-08-04 07:46:46 +00:00
|
|
|
// @Success 200 {object} models.{{ctrlName}}
|
2015-10-16 15:44:11 +00:00
|
|
|
// @Failure 403
|
2014-08-04 07:46:46 +00:00
|
|
|
// @router / [get]
|
2014-11-05 14:48:09 +00:00
|
|
|
func (c *{{ctrlName}}Controller) GetAll() {
|
2014-08-05 06:31:19 +00:00
|
|
|
var fields []string
|
|
|
|
var sortby []string
|
|
|
|
var order []string
|
2016-09-09 07:38:44 +00:00
|
|
|
var query = make(map[string]string)
|
2014-08-05 06:31:19 +00:00
|
|
|
var limit int64 = 10
|
2016-09-09 07:38:44 +00:00
|
|
|
var offset int64
|
2014-08-05 06:31:19 +00:00
|
|
|
|
|
|
|
// fields: col1,col2,entity.col3
|
2014-11-05 14:48:09 +00:00
|
|
|
if v := c.GetString("fields"); v != "" {
|
2014-08-05 06:31:19 +00:00
|
|
|
fields = strings.Split(v, ",")
|
|
|
|
}
|
|
|
|
// limit: 10 (default is 10)
|
2014-11-05 14:48:09 +00:00
|
|
|
if v, err := c.GetInt64("limit"); err == nil {
|
2014-08-05 06:31:19 +00:00
|
|
|
limit = v
|
|
|
|
}
|
|
|
|
// offset: 0 (default is 0)
|
2014-11-05 14:48:09 +00:00
|
|
|
if v, err := c.GetInt64("offset"); err == nil {
|
2014-08-05 06:31:19 +00:00
|
|
|
offset = v
|
|
|
|
}
|
|
|
|
// sortby: col1,col2
|
2014-11-05 14:48:09 +00:00
|
|
|
if v := c.GetString("sortby"); v != "" {
|
2014-08-05 06:31:19 +00:00
|
|
|
sortby = strings.Split(v, ",")
|
|
|
|
}
|
|
|
|
// order: desc,asc
|
2014-11-05 14:48:09 +00:00
|
|
|
if v := c.GetString("order"); v != "" {
|
2014-08-05 06:31:19 +00:00
|
|
|
order = strings.Split(v, ",")
|
|
|
|
}
|
|
|
|
// query: k:v,k:v
|
2014-11-05 14:48:09 +00:00
|
|
|
if v := c.GetString("query"); v != "" {
|
2014-08-05 06:31:19 +00:00
|
|
|
for _, cond := range strings.Split(v, ",") {
|
2016-08-18 15:25:18 +00:00
|
|
|
kv := strings.SplitN(cond, ":", 2)
|
2014-08-05 06:31:19 +00:00
|
|
|
if len(kv) != 2 {
|
2014-11-05 14:48:09 +00:00
|
|
|
c.Data["json"] = errors.New("Error: invalid query key/value pair")
|
2015-10-22 03:32:21 +00:00
|
|
|
c.ServeJSON()
|
2014-08-05 06:31:19 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
k, v := kv[0], kv[1]
|
|
|
|
query[k] = v
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
l, err := models.GetAll{{ctrlName}}(query, fields, sortby, order, offset, limit)
|
2014-08-04 07:46:46 +00:00
|
|
|
if err != nil {
|
2014-11-05 14:48:09 +00:00
|
|
|
c.Data["json"] = err.Error()
|
2014-08-04 07:46:46 +00:00
|
|
|
} else {
|
2014-11-05 14:48:09 +00:00
|
|
|
c.Data["json"] = l
|
2014-08-04 07:46:46 +00:00
|
|
|
}
|
2015-10-22 03:32:21 +00:00
|
|
|
c.ServeJSON()
|
2014-08-04 07:46:46 +00:00
|
|
|
}
|
|
|
|
|
2016-09-09 07:27:36 +00:00
|
|
|
// Put ...
|
|
|
|
// @Title Put
|
2014-07-31 10:46:03 +00:00
|
|
|
// @Description update the {{ctrlName}}
|
|
|
|
// @Param id path string true "The id you want to update"
|
|
|
|
// @Param body body models.{{ctrlName}} true "body for {{ctrlName}} content"
|
|
|
|
// @Success 200 {object} models.{{ctrlName}}
|
|
|
|
// @Failure 403 :id is not int
|
|
|
|
// @router /:id [put]
|
2014-11-05 14:48:09 +00:00
|
|
|
func (c *{{ctrlName}}Controller) Put() {
|
2016-01-06 03:55:56 +00:00
|
|
|
idStr := c.Ctx.Input.Param(":id")
|
2014-07-31 10:46:03 +00:00
|
|
|
id, _ := strconv.Atoi(idStr)
|
|
|
|
v := models.{{ctrlName}}{Id: id}
|
2015-11-25 14:24:10 +00:00
|
|
|
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err == nil {
|
|
|
|
if err := models.Update{{ctrlName}}ById(&v); err == nil {
|
|
|
|
c.Data["json"] = "OK"
|
|
|
|
} else {
|
|
|
|
c.Data["json"] = err.Error()
|
|
|
|
}
|
2014-07-31 10:46:03 +00:00
|
|
|
} else {
|
2014-11-05 14:48:09 +00:00
|
|
|
c.Data["json"] = err.Error()
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
2015-10-22 03:32:21 +00:00
|
|
|
c.ServeJSON()
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
|
2016-09-09 07:20:59 +00:00
|
|
|
// Delete ...
|
2014-08-04 07:46:46 +00:00
|
|
|
// @Title Delete
|
2014-07-31 10:46:03 +00:00
|
|
|
// @Description delete the {{ctrlName}}
|
|
|
|
// @Param id path string true "The id you want to delete"
|
|
|
|
// @Success 200 {string} delete success!
|
|
|
|
// @Failure 403 id is empty
|
|
|
|
// @router /:id [delete]
|
2014-11-05 14:48:09 +00:00
|
|
|
func (c *{{ctrlName}}Controller) Delete() {
|
2016-01-06 03:55:56 +00:00
|
|
|
idStr := c.Ctx.Input.Param(":id")
|
2014-07-31 10:46:03 +00:00
|
|
|
id, _ := strconv.Atoi(idStr)
|
|
|
|
if err := models.Delete{{ctrlName}}(id); err == nil {
|
2014-11-05 14:48:09 +00:00
|
|
|
c.Data["json"] = "OK"
|
2014-07-31 10:46:03 +00:00
|
|
|
} else {
|
2014-11-05 14:48:09 +00:00
|
|
|
c.Data["json"] = err.Error()
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
2015-10-22 03:32:21 +00:00
|
|
|
c.ServeJSON()
|
2014-07-31 10:46:03 +00:00
|
|
|
}
|
|
|
|
`
|
2016-07-22 23:05:01 +00:00
|
|
|
RouterTPL = `// @APIVersion 1.0.0
|
2014-07-31 10:46:03 +00:00
|
|
|
// @Title beego Test API
|
|
|
|
// @Description beego has a very cool tools to autogenerate documents for your API
|
|
|
|
// @Contact astaxie@gmail.com
|
|
|
|
// @TermsOfServiceUrl http://beego.me/
|
|
|
|
// @License Apache 2.0
|
|
|
|
// @LicenseUrl http://www.apache.org/licenses/LICENSE-2.0.html
|
|
|
|
package routers
|
|
|
|
|
|
|
|
import (
|
2014-08-19 09:00:37 +00:00
|
|
|
"{{pkgPath}}/controllers"
|
|
|
|
|
2014-07-31 10:46:03 +00:00
|
|
|
"github.com/astaxie/beego"
|
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
ns := beego.NewNamespace("/v1",
|
|
|
|
{{nameSpaces}}
|
|
|
|
)
|
|
|
|
beego.AddNamespace(ns)
|
|
|
|
}
|
|
|
|
`
|
2016-07-22 23:05:01 +00:00
|
|
|
NamespaceTPL = `
|
2014-08-19 09:00:37 +00:00
|
|
|
beego.NSNamespace("/{{nameSpace}}",
|
|
|
|
beego.NSInclude(
|
|
|
|
&controllers.{{ctrlName}}Controller{},
|
|
|
|
),
|
|
|
|
),
|
2014-07-31 10:46:03 +00:00
|
|
|
`
|
|
|
|
)
|