allow users to ignore some table when run orm commands

This commit is contained in:
Ming Deng 2020-09-07 21:40:20 +08:00
parent b86cf22fc4
commit 0f50b07a20
5 changed files with 59 additions and 1 deletions

View File

@ -142,6 +142,12 @@ func (d *commandSyncDb) Run() error {
}
for i, mi := range modelCache.allOrdered() {
if !isApplicableTableForDB(mi.addrField, d.al.Name) {
fmt.Printf("table `%s` is not applicable to database '%s'\n", mi.table, d.al.Name)
continue
}
if tables[mi.table] {
if !d.noInfo {
fmt.Printf("table `%s` already exists, skip\n", mi.table)

View File

@ -414,7 +414,7 @@ func (mc *_modelCache) getDbDropSQL(al *alias) (queries []string, err error) {
for _, mi := range modelCache.allOrdered() {
queries = append(queries, fmt.Sprintf(`DROP TABLE IF EXISTS %s%s%s`, Q, mi.table, Q))
}
return queries,nil
return queries, nil
}
//getDbCreateSQL get database scheme creation sql queries

View File

@ -107,6 +107,18 @@ func getTableUnique(val reflect.Value) [][]string {
return nil
}
// get whether the table needs to be created for the database alias
func isApplicableTableForDB(val reflect.Value, db string) bool {
fun := val.MethodByName("IsApplicableTableForDB")
if fun.IsValid() {
vals := fun.Call([]reflect.Value{reflect.ValueOf(db)})
if len(vals) > 0 && vals[0].Kind() == reflect.Bool {
return vals[0].Bool()
}
}
return true
}
// get snaked column name
func getColumnName(ft int, addrField reflect.Value, sf reflect.StructField, col string) string {
column := col

View File

@ -0,0 +1,35 @@
// Copyright 2020
//
// 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.
package orm
import (
"reflect"
"testing"
"github.com/stretchr/testify/assert"
)
type NotApplicableModel struct {
Id int
}
func (n *NotApplicableModel) IsApplicableTableForDB(db string) bool {
return db == "default"
}
func Test_IsApplicableTableForDB(t *testing.T) {
assert.False(t, isApplicableTableForDB(reflect.ValueOf(&NotApplicableModel{}), "defa"))
assert.True(t, isApplicableTableForDB(reflect.ValueOf(&NotApplicableModel{}), "default"))
}

View File

@ -75,6 +75,11 @@ type TableUniqueI interface {
TableUnique() [][]string
}
// IsApplicableTableForDB if return false, we won't create table to this db
type IsApplicableTableForDB interface {
IsApplicableTableForDB(db string) bool
}
// Driver define database driver
type Driver interface {
Name() string