marion преди 5 години
родител
ревизия
783a589beb
променени са 1 файла, в които са добавени 35 реда и са изтрити 7 реда
  1. 35 7
      utils/db_utils.go

+ 35 - 7
utils/db_utils.go

@@ -4,14 +4,23 @@ import (
 	"errors"
 	"github.com/go-xorm/xorm"
 	"reflect"
+	"strings"
 )
 
 // 分页插入数据库
 func Insert(db *xorm.Engine, beans ...interface{}) error {
-	return InsertWithSize(db, 500, beans...)
+	return InsertWithTableNameAndSize(db, "", 500, beans...)
+}
+
+func InsertWithTableName(db *xorm.Engine, tableName string, beans ...interface{}) error {
+	return InsertWithTableNameAndSize(db, tableName, 500, beans...)
 }
 
 func InsertWithSize(db *xorm.Engine, size int, beans ...interface{}) error {
+	return InsertWithTableNameAndSize(db, "", size, beans...)
+}
+
+func InsertWithTableNameAndSize(db *xorm.Engine, tableName string, size int, beans ...interface{}) error {
 	if nil == db {
 		return errors.New(`db can not be nil`)
 	}
@@ -24,7 +33,7 @@ func InsertWithSize(db *xorm.Engine, size int, beans ...interface{}) error {
 	defer trans.Close()
 	_ = trans.Begin()
 
-	err := TransInsertWithSize(trans, size, beans...)
+	err := TransInsertWithTableNameAndSize(trans, tableName, size, beans...)
 	if nil != err {
 		_ = trans.Rollback()
 		return err
@@ -34,10 +43,18 @@ func InsertWithSize(db *xorm.Engine, size int, beans ...interface{}) error {
 }
 
 func TransInsert(trans *xorm.Session, beans ...interface{}) error {
-	return TransInsertWithSize(trans, 500, beans...)
+	return TransInsertWithTableNameAndSize(trans, "", 500, beans...)
+}
+
+func TransInsertWithTableName(trans *xorm.Session, tableName string, beans ...interface{}) error {
+	return TransInsertWithTableNameAndSize(trans, tableName, 500, beans...)
 }
 
 func TransInsertWithSize(trans *xorm.Session, size int, beans ...interface{}) error {
+	return TransInsertWithTableNameAndSize(trans, "", size, beans...)
+}
+
+func TransInsertWithTableNameAndSize(trans *xorm.Session, tableName string, size int, beans ...interface{}) error {
 	if nil == trans {
 		return errors.New(`trans can not be nil`)
 	}
@@ -45,8 +62,9 @@ func TransInsertWithSize(trans *xorm.Session, size int, beans ...interface{}) er
 	if nil == beans || len(beans) == 0 {
 		return nil
 	}
+	tableName = strings.TrimSpace(tableName)
 
-	if size < 100 {
+	if size < 0 {
 		size = 500
 	}
 
@@ -88,9 +106,19 @@ func TransInsertWithSize(trans *xorm.Session, size int, beans ...interface{}) er
 		}
 	}
 
-	_, err := trans.Insert(objects...)
-	if nil != err {
-		return err
+	var err error
+	if tableName != "" {
+		for i := 0; i < len(objects); i++ {
+			_, err = trans.Table(tableName).Insert(objects[i])
+			if nil != err {
+				return err
+			}
+		}
+	} else {
+		_, err = trans.Insert(objects...)
+		if nil != err {
+			return err
+		}
 	}
 	return nil
 }