1
0
mirror of https://github.com/astaxie/beego.git synced 2024-12-18 18:10:49 +00:00
Beego/orm/db.go

1893 lines
45 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-07-30 12:32:38 +00:00
package orm
import (
"database/sql"
"errors"
"fmt"
"reflect"
"strings"
"time"
)
const (
formatTime = "15:04:05"
2015-09-12 13:46:43 +00:00
formatDate = "2006-01-02"
formatDateTime = "2006-01-02 15:04:05"
2013-07-30 12:32:38 +00:00
)
var (
2015-09-12 13:46:43 +00:00
// ErrMissPK missing pk error
ErrMissPK = errors.New("missed pk value")
2013-07-30 12:32:38 +00:00
)
var (
operators = map[string]bool{
"exact": true,
"iexact": true,
"contains": true,
"icontains": true,
// "regex": true,
// "iregex": true,
"gt": true,
"gte": true,
"lt": true,
"lte": true,
2015-06-09 02:18:21 +00:00
"eq": true,
"nq": true,
2017-03-17 17:24:45 +00:00
"ne": true,
2013-07-30 12:32:38 +00:00
"startswith": true,
"endswith": true,
"istartswith": true,
"iendswith": true,
"in": true,
2014-03-10 12:18:57 +00:00
"between": true,
2013-07-30 12:32:38 +00:00
// "year": true,
// "month": true,
// "day": true,
// "week_day": true,
"isnull": true,
// "search": true,
}
)
2014-01-17 09:04:15 +00:00
// an instance of dbBaser interface/
2013-07-30 12:32:38 +00:00
type dbBase struct {
ins dbBaser
}
2014-01-17 09:04:15 +00:00
// check dbBase implements dbBaser interface.
var _ dbBaser = new(dbBase)
2014-01-17 09:04:15 +00:00
// get struct columns values as interface slice.
2016-03-27 07:06:57 +00:00
func (d *dbBase) collectValues(mi *modelInfo, ind reflect.Value, cols []string, skipAuto bool, insert bool, names *[]string, tz *time.Location) (values []interface{}, autoFields []string, err error) {
if names == nil {
ns := make([]string, 0, len(cols))
names = &ns
2014-01-06 03:07:03 +00:00
}
values = make([]interface{}, 0, len(cols))
2014-01-06 03:07:03 +00:00
for _, column := range cols {
var fi *fieldInfo
if fi, _ = mi.fields.GetByAny(column); fi != nil {
column = fi.column
} else {
2013-10-09 03:37:16 +00:00
panic(fmt.Errorf("wrong db field/column name `%s` for model `%s`", column, mi.fullName))
}
2017-03-17 17:24:45 +00:00
if !fi.dbcol || fi.auto && skipAuto {
2013-07-30 12:32:38 +00:00
continue
}
value, err := d.collectFieldValue(mi, fi, ind, insert, tz)
if err != nil {
2016-03-27 07:06:57 +00:00
return nil, nil, err
}
2014-01-06 03:07:03 +00:00
// ignore empty value auto field
2016-03-27 07:06:57 +00:00
if insert && fi.auto {
if fi.fieldType&IsPositiveIntegerField > 0 {
if vu, ok := value.(uint64); !ok || vu == 0 {
continue
}
} else {
if vu, ok := value.(int64); !ok || vu == 0 {
continue
}
}
2016-03-27 07:06:57 +00:00
autoFields = append(autoFields, fi.column)
2014-01-06 03:07:03 +00:00
}
*names, values = append(*names, column), append(values, value)
2014-01-06 03:07:03 +00:00
}
return
}
2014-01-17 09:04:15 +00:00
// get one field value in struct column as interface.
func (d *dbBase) collectFieldValue(mi *modelInfo, fi *fieldInfo, ind reflect.Value, insert bool, tz *time.Location) (interface{}, error) {
var value interface{}
if fi.pk {
_, value, _ = getExistPk(mi, ind)
} else {
2016-02-24 10:46:14 +00:00
field := ind.FieldByIndex(fi.fieldIndex)
if fi.isFielder {
f := field.Addr().Interface().(Fielder)
value = f.RawValue()
2013-07-30 12:32:38 +00:00
} else {
switch fi.fieldType {
case TypeBooleanField:
if nb, ok := field.Interface().(sql.NullBool); ok {
value = nil
if nb.Valid {
value = nb.Bool
}
} else if field.Kind() == reflect.Ptr {
if field.IsNil() {
value = nil
} else {
value = field.Elem().Bool()
}
} else {
value = field.Bool()
}
2017-11-30 10:12:49 +00:00
case TypeVarCharField, TypeCharField, TypeTextField, TypeJSONField, TypeJsonbField:
if ns, ok := field.Interface().(sql.NullString); ok {
value = nil
if ns.Valid {
value = ns.String
}
} else if field.Kind() == reflect.Ptr {
if field.IsNil() {
value = nil
} else {
value = field.Elem().String()
}
} else {
value = field.String()
}
case TypeFloatField, TypeDecimalField:
if nf, ok := field.Interface().(sql.NullFloat64); ok {
value = nil
if nf.Valid {
value = nf.Float64
}
} else if field.Kind() == reflect.Ptr {
if field.IsNil() {
value = nil
} else {
value = field.Elem().Float()
}
} else {
vu := field.Interface()
if _, ok := vu.(float32); ok {
value, _ = StrTo(ToStr(vu)).Float64()
} else {
value = field.Float()
}
}
case TypeTimeField, TypeDateField, TypeDateTimeField:
value = field.Interface()
if t, ok := value.(time.Time); ok {
2013-11-01 16:51:53 +00:00
d.ins.TimeToDB(&t, tz)
2014-06-10 14:10:58 +00:00
if t.IsZero() {
value = nil
} else {
value = t
}
}
default:
switch {
2016-03-17 13:34:49 +00:00
case fi.fieldType&IsPositiveIntegerField > 0:
if field.Kind() == reflect.Ptr {
if field.IsNil() {
value = nil
} else {
value = field.Elem().Uint()
}
} else {
value = field.Uint()
}
case fi.fieldType&IsIntegerField > 0:
if ni, ok := field.Interface().(sql.NullInt64); ok {
value = nil
if ni.Valid {
value = ni.Int64
}
} else if field.Kind() == reflect.Ptr {
if field.IsNil() {
value = nil
} else {
value = field.Elem().Int()
}
} else {
value = field.Int()
}
case fi.fieldType&IsRelField > 0:
if field.IsNil() {
value = nil
} else {
if _, vu, ok := getExistPk(fi.relModelInfo, reflect.Indirect(field)); ok {
value = vu
} else {
2013-07-30 12:32:38 +00:00
value = nil
}
}
2017-03-17 17:24:45 +00:00
if !fi.null && value == nil {
2015-09-12 13:46:43 +00:00
return nil, fmt.Errorf("field `%s` cannot be NULL", fi.fullName)
}
2013-07-30 12:32:38 +00:00
}
}
}
switch fi.fieldType {
case TypeTimeField, TypeDateField, TypeDateTimeField:
2015-09-12 13:46:43 +00:00
if fi.autoNow || fi.autoNowAdd && insert {
if insert {
if t, ok := value.(time.Time); ok && !t.IsZero() {
break
}
}
tnow := time.Now()
2013-11-01 16:51:53 +00:00
d.ins.TimeToDB(&tnow, tz)
value = tnow
if fi.isFielder {
f := field.Addr().Interface().(Fielder)
f.SetRaw(tnow.In(DefaultTimeLoc))
} else if field.Kind() == reflect.Ptr {
v := tnow.In(DefaultTimeLoc)
field.Set(reflect.ValueOf(&v))
} else {
field.Set(reflect.ValueOf(tnow.In(DefaultTimeLoc)))
2013-07-30 12:32:38 +00:00
}
}
2016-04-09 02:22:40 +00:00
case TypeJSONField, TypeJsonbField:
2016-04-08 13:53:27 +00:00
if s, ok := value.(string); (ok && len(s) == 0) || value == nil {
if fi.colDefault && fi.initial.Exist() {
value = fi.initial.String()
} else {
value = nil
}
}
2013-07-30 12:32:38 +00:00
}
}
return value, nil
2013-07-30 12:32:38 +00:00
}
2014-01-17 09:04:15 +00:00
// create insert sql preparation statement object.
2013-08-09 05:20:19 +00:00
func (d *dbBase) PrepareInsert(q dbQuerier, mi *modelInfo) (stmtQuerier, string, error) {
Q := d.ins.TableQuote()
2013-07-30 12:32:38 +00:00
dbcols := make([]string, 0, len(mi.fields.dbcols))
marks := make([]string, 0, len(mi.fields.dbcols))
for _, fi := range mi.fields.fieldsDB {
2017-03-17 17:24:45 +00:00
if !fi.auto {
2013-07-30 12:32:38 +00:00
dbcols = append(dbcols, fi.column)
marks = append(marks, "?")
}
}
qmarks := strings.Join(marks, ", ")
sep := fmt.Sprintf("%s, %s", Q, Q)
columns := strings.Join(dbcols, sep)
query := fmt.Sprintf("INSERT INTO %s%s%s (%s%s%s) VALUES (%s)", Q, mi.table, Q, Q, columns, Q, qmarks)
d.ins.ReplaceMarks(&query)
2013-07-30 12:32:38 +00:00
2013-08-11 14:27:45 +00:00
d.ins.HasReturningID(mi, &query)
2013-08-09 05:20:19 +00:00
stmt, err := q.Prepare(query)
return stmt, query, err
2013-07-30 12:32:38 +00:00
}
2014-01-17 09:04:15 +00:00
// insert struct with prepared statement and given struct reflect value.
func (d *dbBase) InsertStmt(stmt stmtQuerier, mi *modelInfo, ind reflect.Value, tz *time.Location) (int64, error) {
2016-03-27 07:06:57 +00:00
values, _, err := d.collectValues(mi, ind, mi.fields.dbcols, true, true, nil, tz)
2013-07-30 12:32:38 +00:00
if err != nil {
return 0, err
}
2013-08-11 14:27:45 +00:00
if d.ins.HasReturningID(mi, nil) {
row := stmt.QueryRow(values...)
var id int64
err := row.Scan(&id)
return id, err
2013-07-30 12:32:38 +00:00
}
2015-09-12 13:46:43 +00:00
res, err := stmt.Exec(values...)
if err == nil {
return res.LastInsertId()
}
return 0, err
2013-07-30 12:32:38 +00:00
}
2014-01-17 09:04:15 +00:00
// query sql ,read records and persist in dbBaser.
func (d *dbBase) Read(q dbQuerier, mi *modelInfo, ind reflect.Value, tz *time.Location, cols []string, isForUpdate bool) error {
var whereCols []string
var args []interface{}
// if specify cols length > 0, then use it for where condition.
if len(cols) > 0 {
var err error
2014-01-06 03:07:03 +00:00
whereCols = make([]string, 0, len(cols))
2016-03-27 07:06:57 +00:00
args, _, err = d.collectValues(mi, ind, cols, false, false, &whereCols, tz)
if err != nil {
return err
}
} else {
// default use pk value as where condtion.
pkColumn, pkValue, ok := getExistPk(mi, ind)
2017-03-17 17:24:45 +00:00
if !ok {
return ErrMissPK
}
2014-01-06 03:07:03 +00:00
whereCols = []string{pkColumn}
args = append(args, pkValue)
2013-08-01 07:51:53 +00:00
}
Q := d.ins.TableQuote()
sep := fmt.Sprintf("%s, %s", Q, Q)
sels := strings.Join(mi.fields.dbcols, sep)
2013-08-01 07:51:53 +00:00
colsNum := len(mi.fields.dbcols)
sep = fmt.Sprintf("%s = ? AND %s", Q, Q)
wheres := strings.Join(whereCols, sep)
forUpdate := ""
if isForUpdate {
forUpdate = "FOR UPDATE"
}
query := fmt.Sprintf("SELECT %s%s%s FROM %s%s%s WHERE %s%s%s = ? %s", Q, sels, Q, Q, mi.table, Q, Q, wheres, Q, forUpdate)
2013-08-01 07:51:53 +00:00
refs := make([]interface{}, colsNum)
2015-03-20 05:29:01 +00:00
for i := range refs {
2013-08-01 07:51:53 +00:00
var ref interface{}
refs[i] = &ref
}
d.ins.ReplaceMarks(&query)
row := q.QueryRow(query, args...)
2013-08-01 07:51:53 +00:00
if err := row.Scan(refs...); err != nil {
2013-08-07 11:11:44 +00:00
if err == sql.ErrNoRows {
return ErrNoRows
}
2013-08-01 07:51:53 +00:00
return err
}
2015-09-12 13:46:43 +00:00
elm := reflect.New(mi.addrField.Elem().Type())
mind := reflect.Indirect(elm)
d.setColsValues(mi, &mind, mi.fields.dbcols, refs, tz)
ind.Set(mind)
2013-08-01 07:51:53 +00:00
return nil
}
2014-01-17 09:04:15 +00:00
// execute insert sql dbQuerier with given struct reflect.Value.
func (d *dbBase) Insert(q dbQuerier, mi *modelInfo, ind reflect.Value, tz *time.Location) (int64, error) {
names := make([]string, 0, len(mi.fields.dbcols))
2016-03-27 07:06:57 +00:00
values, autoFields, err := d.collectValues(mi, ind, mi.fields.dbcols, false, true, &names, tz)
if err != nil {
return 0, err
}
id, err := d.InsertValue(q, mi, false, names, values)
2013-07-30 12:32:38 +00:00
if err != nil {
return 0, err
}
2016-03-27 07:06:57 +00:00
if len(autoFields) > 0 {
err = d.ins.setval(q, mi, autoFields)
}
return id, err
}
2014-01-17 09:04:15 +00:00
// multi-insert sql with given slice struct reflect.Value.
2014-01-06 03:07:03 +00:00
func (d *dbBase) InsertMulti(q dbQuerier, mi *modelInfo, sind reflect.Value, bulk int, tz *time.Location) (int64, error) {
var (
cnt int64
nums int
values []interface{}
names []string
)
// typ := reflect.Indirect(mi.addrField).Type()
2016-03-27 07:06:57 +00:00
length, autoFields := sind.Len(), make([]string, 0, 1)
2014-01-06 03:07:03 +00:00
for i := 1; i <= length; i++ {
ind := reflect.Indirect(sind.Index(i - 1))
// Is this needed ?
// if !ind.Type().AssignableTo(typ) {
// return cnt, ErrArgs
// }
if i == 1 {
2016-03-27 07:06:57 +00:00
var (
vus []interface{}
err error
)
vus, autoFields, err = d.collectValues(mi, ind, mi.fields.dbcols, false, true, &names, tz)
2014-01-06 03:07:03 +00:00
if err != nil {
return cnt, err
}
values = make([]interface{}, bulk*len(vus))
nums += copy(values, vus)
} else {
2016-03-27 07:06:57 +00:00
vus, _, err := d.collectValues(mi, ind, mi.fields.dbcols, false, true, nil, tz)
2014-01-06 03:07:03 +00:00
if err != nil {
return cnt, err
}
if len(vus) != len(names) {
return cnt, ErrArgs
}
nums += copy(values[nums:], vus)
}
if i > 1 && i%bulk == 0 || length == i {
num, err := d.InsertValue(q, mi, true, names, values[:nums])
if err != nil {
return cnt, err
}
cnt += num
nums = 0
}
}
2016-03-27 07:06:57 +00:00
var err error
if len(autoFields) > 0 {
err = d.ins.setval(q, mi, autoFields)
}
return cnt, err
2014-01-06 03:07:03 +00:00
}
2014-01-17 09:04:15 +00:00
// execute insert sql with given struct and given values.
// insert the given values, not the field values in struct.
2014-01-06 03:07:03 +00:00
func (d *dbBase) InsertValue(q dbQuerier, mi *modelInfo, isMulti bool, names []string, values []interface{}) (int64, error) {
Q := d.ins.TableQuote()
2013-07-30 12:32:38 +00:00
marks := make([]string, len(names))
2015-03-20 05:29:01 +00:00
for i := range marks {
2013-07-30 12:32:38 +00:00
marks[i] = "?"
}
sep := fmt.Sprintf("%s, %s", Q, Q)
2013-07-30 12:32:38 +00:00
qmarks := strings.Join(marks, ", ")
columns := strings.Join(names, sep)
2014-01-06 03:07:03 +00:00
multi := len(values) / len(names)
if isMulti {
qmarks = strings.Repeat(qmarks+"), (", multi-1) + qmarks
}
query := fmt.Sprintf("INSERT INTO %s%s%s (%s%s%s) VALUES (%s)", Q, mi.table, Q, Q, columns, Q, qmarks)
2013-07-30 12:32:38 +00:00
d.ins.ReplaceMarks(&query)
2013-07-30 12:32:38 +00:00
2014-01-06 03:07:03 +00:00
if isMulti || !d.ins.HasReturningID(mi, &query) {
2015-09-12 13:46:43 +00:00
res, err := q.Exec(query, values...)
if err == nil {
2014-01-06 03:07:03 +00:00
if isMulti {
return res.RowsAffected()
}
2013-08-11 14:27:45 +00:00
return res.LastInsertId()
}
2015-09-12 13:46:43 +00:00
return 0, err
2013-07-30 12:32:38 +00:00
}
2015-09-12 13:46:43 +00:00
row := q.QueryRow(query, values...)
var id int64
err := row.Scan(&id)
return id, err
2013-07-30 12:32:38 +00:00
}
2016-07-21 07:49:55 +00:00
// InsertOrUpdate a row
// If your primary key or unique column conflict will update
// If no will insert
2016-07-22 04:25:30 +00:00
func (d *dbBase) InsertOrUpdate(q dbQuerier, mi *modelInfo, ind reflect.Value, a *alias, args ...string) (int64, error) {
2016-07-26 03:15:59 +00:00
args0 := ""
2016-07-20 06:37:05 +00:00
iouStr := ""
argsMap := map[string]string{}
2016-07-26 03:15:59 +00:00
switch a.Driver {
case DRMySQL:
2016-07-20 06:37:05 +00:00
iouStr = "ON DUPLICATE KEY UPDATE"
2016-07-26 03:15:59 +00:00
case DRPostgres:
if len(args) == 0 {
return 0, fmt.Errorf("`%s` use InsertOrUpdate must have a conflict column", a.DriverName)
2016-07-20 06:37:05 +00:00
}
2017-04-30 14:41:23 +00:00
args0 = strings.ToLower(args[0])
iouStr = fmt.Sprintf("ON CONFLICT (%s) DO UPDATE SET", args0)
2016-07-26 03:15:59 +00:00
default:
return 0, fmt.Errorf("`%s` nonsupport InsertOrUpdate in beego", a.DriverName)
2016-07-20 06:37:05 +00:00
}
2016-07-26 03:15:59 +00:00
2016-07-20 06:37:05 +00:00
//Get on the key-value pairs
for _, v := range args {
kv := strings.Split(v, "=")
if len(kv) == 2 {
2016-07-26 03:15:59 +00:00
argsMap[strings.ToLower(kv[0])] = kv[1]
2016-07-20 06:37:05 +00:00
}
}
isMulti := false
names := make([]string, 0, len(mi.fields.dbcols)-1)
Q := d.ins.TableQuote()
2016-07-22 04:25:30 +00:00
values, _, err := d.collectValues(mi, ind, mi.fields.dbcols, true, true, &names, a.TZ)
2016-07-20 06:37:05 +00:00
if err != nil {
return 0, err
}
marks := make([]string, len(names))
updateValues := make([]interface{}, 0)
updates := make([]string, len(names))
var conflitValue interface{}
for i, v := range names {
// identifier in database may not be case-sensitive, so quote it
v = fmt.Sprintf("%s%s%s", Q, v, Q)
2016-07-20 06:37:05 +00:00
marks[i] = "?"
2016-07-26 06:27:22 +00:00
valueStr := argsMap[strings.ToLower(v)]
2016-07-26 03:15:59 +00:00
if v == args0 {
2016-07-20 06:37:05 +00:00
conflitValue = values[i]
}
if valueStr != "" {
2016-07-26 03:15:59 +00:00
switch a.Driver {
case DRMySQL:
2016-07-20 06:37:05 +00:00
updates[i] = v + "=" + valueStr
2016-07-26 03:15:59 +00:00
case DRPostgres:
2016-07-20 06:37:05 +00:00
if conflitValue != nil {
//postgres ON CONFLICT DO UPDATE SET can`t use colu=colu+values
2016-07-20 08:26:02 +00:00
updates[i] = fmt.Sprintf("%s=(select %s from %s where %s = ? )", v, valueStr, mi.table, args0)
2016-07-20 06:37:05 +00:00
updateValues = append(updateValues, conflitValue)
} else {
2016-07-20 08:26:02 +00:00
return 0, fmt.Errorf("`%s` must be in front of `%s` in your struct", args0, v)
2016-07-20 06:37:05 +00:00
}
}
} else {
updates[i] = v + "=?"
updateValues = append(updateValues, values[i])
}
}
values = append(values, updateValues...)
sep := fmt.Sprintf("%s, %s", Q, Q)
qmarks := strings.Join(marks, ", ")
qupdates := strings.Join(updates, ", ")
columns := strings.Join(names, sep)
multi := len(values) / len(names)
if isMulti {
qmarks = strings.Repeat(qmarks+"), (", multi-1) + qmarks
}
//conflitValue maybe is a int,can`t use fmt.Sprintf
query := fmt.Sprintf("INSERT INTO %s%s%s (%s%s%s) VALUES (%s) %s "+qupdates, Q, mi.table, Q, Q, columns, Q, qmarks, iouStr)
d.ins.ReplaceMarks(&query)
if isMulti || !d.ins.HasReturningID(mi, &query) {
res, err := q.Exec(query, values...)
if err == nil {
if isMulti {
return res.RowsAffected()
}
return res.LastInsertId()
}
return 0, err
}
row := q.QueryRow(query, values...)
var id int64
err = row.Scan(&id)
2017-04-21 16:57:04 +00:00
if err != nil && err.Error() == `pq: syntax error at or near "ON"` {
2016-07-20 06:37:05 +00:00
err = fmt.Errorf("postgres version must 9.5 or higher")
}
return id, err
}
2014-01-17 09:04:15 +00:00
// execute update sql dbQuerier with given struct reflect.Value.
func (d *dbBase) Update(q dbQuerier, mi *modelInfo, ind reflect.Value, tz *time.Location, cols []string) (int64, error) {
2013-08-11 14:27:45 +00:00
pkName, pkValue, ok := getExistPk(mi, ind)
2017-03-17 17:24:45 +00:00
if !ok {
2013-07-30 12:32:38 +00:00
return 0, ErrMissPK
}
2014-01-06 03:07:03 +00:00
var setNames []string
// if specify cols length is zero, then commit all columns.
if len(cols) == 0 {
cols = mi.fields.dbcols
2014-01-06 03:07:03 +00:00
setNames = make([]string, 0, len(mi.fields.dbcols)-1)
} else {
setNames = make([]string, 0, len(cols))
}
2016-03-27 07:06:57 +00:00
setValues, _, err := d.collectValues(mi, ind, cols, true, false, &setNames, tz)
2013-07-30 12:32:38 +00:00
if err != nil {
return 0, err
}
2019-05-08 15:11:57 +00:00
var findAutoNowAdd, findAutoNow bool
var index int
for i, col := range setNames {
if mi.fields.GetByColumn(col).autoNowAdd {
index = i
2019-05-08 15:11:57 +00:00
findAutoNowAdd = true
}
if mi.fields.GetByColumn(col).autoNow {
findAutoNow = true
}
}
2019-05-08 15:11:57 +00:00
if findAutoNowAdd {
2019-03-22 16:33:26 +00:00
setNames = append(setNames[0:index], setNames[index+1:]...)
setValues = append(setValues[0:index], setValues[index+1:]...)
}
2019-05-08 15:11:57 +00:00
if !findAutoNow {
for col, info := range mi.fields.columns {
if info.autoNow {
setNames = append(setNames, col)
setValues = append(setValues, time.Now())
}
}
}
setValues = append(setValues, pkValue)
Q := d.ins.TableQuote()
2013-07-30 12:32:38 +00:00
sep := fmt.Sprintf("%s = ?, %s", Q, Q)
setColumns := strings.Join(setNames, sep)
2013-07-30 12:32:38 +00:00
query := fmt.Sprintf("UPDATE %s%s%s SET %s%s%s = ? WHERE %s%s%s = ?", Q, mi.table, Q, Q, setColumns, Q, Q, pkName, Q)
d.ins.ReplaceMarks(&query)
2013-07-30 12:32:38 +00:00
2015-09-28 12:07:35 +00:00
res, err := q.Exec(query, setValues...)
if err == nil {
2013-07-30 12:32:38 +00:00
return res.RowsAffected()
}
2015-09-12 13:46:43 +00:00
return 0, err
2013-07-30 12:32:38 +00:00
}
2014-01-17 09:04:15 +00:00
// execute delete sql dbQuerier with given struct reflect.Value.
// delete index is pk.
2016-09-12 13:13:21 +00:00
func (d *dbBase) Delete(q dbQuerier, mi *modelInfo, ind reflect.Value, tz *time.Location, cols []string) (int64, error) {
var whereCols []string
var args []interface{}
// if specify cols length > 0, then use it for where condition.
if len(cols) > 0 {
var err error
whereCols = make([]string, 0, len(cols))
args, _, err = d.collectValues(mi, ind, cols, false, false, &whereCols, tz)
if err != nil {
return 0, err
}
} else {
// default use pk value as where condtion.
pkColumn, pkValue, ok := getExistPk(mi, ind)
2017-03-17 17:24:45 +00:00
if !ok {
2016-09-12 13:13:21 +00:00
return 0, ErrMissPK
}
whereCols = []string{pkColumn}
args = append(args, pkValue)
2013-07-30 12:32:38 +00:00
}
Q := d.ins.TableQuote()
2016-09-12 13:13:21 +00:00
sep := fmt.Sprintf("%s = ? AND %s", Q, Q)
wheres := strings.Join(whereCols, sep)
query := fmt.Sprintf("DELETE FROM %s%s%s WHERE %s%s%s = ?", Q, mi.table, Q, Q, wheres, Q)
d.ins.ReplaceMarks(&query)
2016-09-12 13:13:21 +00:00
res, err := q.Exec(query, args...)
2015-09-12 13:46:43 +00:00
if err == nil {
2013-07-30 12:32:38 +00:00
num, err := res.RowsAffected()
if err != nil {
return 0, err
}
if num > 0 {
2013-08-07 11:11:44 +00:00
if mi.fields.pk.auto {
2016-03-17 13:34:49 +00:00
if mi.fields.pk.fieldType&IsPositiveIntegerField > 0 {
2016-02-24 10:46:14 +00:00
ind.FieldByIndex(mi.fields.pk.fieldIndex).SetUint(0)
2013-08-30 04:32:05 +00:00
} else {
2016-02-24 10:46:14 +00:00
ind.FieldByIndex(mi.fields.pk.fieldIndex).SetInt(0)
2013-08-30 04:32:05 +00:00
}
2013-07-30 12:32:38 +00:00
}
2016-09-12 13:13:21 +00:00
err := d.deleteRels(q, mi, args, tz)
2013-08-07 11:11:44 +00:00
if err != nil {
return num, err
2013-07-30 12:32:38 +00:00
}
}
return num, err
}
2015-09-12 13:46:43 +00:00
return 0, err
2013-07-30 12:32:38 +00:00
}
2014-01-17 09:04:15 +00:00
// update table-related record by querySet.
// need querySet not struct reflect.Value to update related records.
func (d *dbBase) UpdateBatch(q dbQuerier, qs *querySet, mi *modelInfo, cond *Condition, params Params, tz *time.Location) (int64, error) {
2013-07-30 12:32:38 +00:00
columns := make([]string, 0, len(params))
values := make([]interface{}, 0, len(params))
for col, val := range params {
2017-03-17 17:24:45 +00:00
if fi, ok := mi.fields.GetByAny(col); !ok || !fi.dbcol {
2013-10-09 03:37:16 +00:00
panic(fmt.Errorf("wrong field/column name `%s`", col))
2013-08-07 11:11:44 +00:00
} else {
columns = append(columns, fi.column)
values = append(values, val)
2013-07-30 12:32:38 +00:00
}
}
if len(columns) == 0 {
2013-10-09 03:37:16 +00:00
panic(fmt.Errorf("update params cannot empty"))
2013-07-30 12:32:38 +00:00
}
tables := newDbTables(mi, d.ins)
if qs != nil {
tables.parseRelated(qs.related, qs.relDepth)
}
2015-09-12 13:46:43 +00:00
where, args := tables.getCondSQL(cond, false, tz)
2013-07-30 12:32:38 +00:00
values = append(values, args...)
2015-09-12 13:46:43 +00:00
join := tables.getJoinSQL()
2013-07-30 12:32:38 +00:00
2013-11-01 10:32:03 +00:00
var query, T string
2013-07-30 12:32:38 +00:00
Q := d.ins.TableQuote()
if d.ins.SupportUpdateJoin() {
2013-10-09 12:28:54 +00:00
T = "T0."
}
2013-11-01 10:32:03 +00:00
cols := make([]string, 0, len(columns))
2013-10-09 12:28:54 +00:00
for i, v := range columns {
col := fmt.Sprintf("%s%s%s%s", T, Q, v, Q)
if c, ok := values[i].(colValue); ok {
switch c.opt {
2015-09-12 13:46:43 +00:00
case ColAdd:
2013-11-01 10:32:03 +00:00
cols = append(cols, col+" = "+col+" + ?")
2015-09-12 13:46:43 +00:00
case ColMinus:
2013-11-01 10:32:03 +00:00
cols = append(cols, col+" = "+col+" - ?")
2015-09-12 13:46:43 +00:00
case ColMultiply:
2013-11-01 10:32:03 +00:00
cols = append(cols, col+" = "+col+" * ?")
2015-09-12 13:46:43 +00:00
case ColExcept:
2013-11-01 10:32:03 +00:00
cols = append(cols, col+" = "+col+" / ?")
2013-10-09 12:28:54 +00:00
}
values[i] = c.value
} else {
2013-11-01 10:32:03 +00:00
cols = append(cols, col+" = ?")
2013-10-09 12:28:54 +00:00
}
}
2013-11-01 10:32:03 +00:00
sets := strings.Join(cols, ", ") + " "
2013-10-09 12:28:54 +00:00
if d.ins.SupportUpdateJoin() {
2013-11-01 10:32:03 +00:00
query = fmt.Sprintf("UPDATE %s%s%s T0 %sSET %s%s", Q, mi.table, Q, join, sets, where)
} else {
supQuery := fmt.Sprintf("SELECT T0.%s%s%s FROM %s%s%s T0 %s%s", Q, mi.fields.pk.column, Q, Q, mi.table, Q, join, where)
2013-11-01 10:32:03 +00:00
query = fmt.Sprintf("UPDATE %s%s%s SET %sWHERE %s%s%s IN ( %s )", Q, mi.table, Q, sets, Q, mi.fields.pk.column, Q, supQuery)
}
d.ins.ReplaceMarks(&query)
2018-11-18 13:54:25 +00:00
var err error
var res sql.Result
2018-11-19 15:42:56 +00:00
if qs != nil && qs.forContext {
2018-11-18 13:54:25 +00:00
res, err = q.ExecContext(qs.ctx, query, values...)
} else {
res, err = q.Exec(query, values...)
}
2015-09-12 13:46:43 +00:00
if err == nil {
2013-07-30 12:32:38 +00:00
return res.RowsAffected()
}
2015-09-12 13:46:43 +00:00
return 0, err
2013-07-30 12:32:38 +00:00
}
2014-01-17 09:04:15 +00:00
// delete related records.
// do UpdateBanch or DeleteBanch by condition of tables' relationship.
func (d *dbBase) deleteRels(q dbQuerier, mi *modelInfo, args []interface{}, tz *time.Location) error {
2013-07-30 12:32:38 +00:00
for _, fi := range mi.fields.fieldsReverse {
fi = fi.reverseFieldInfo
switch fi.onDelete {
2015-09-12 13:46:43 +00:00
case odCascade:
2013-08-07 11:11:44 +00:00
cond := NewCondition().And(fmt.Sprintf("%s__in", fi.name), args...)
_, err := d.DeleteBatch(q, nil, fi.mi, cond, tz)
2013-07-30 12:32:38 +00:00
if err != nil {
return err
}
2015-09-12 13:46:43 +00:00
case odSetDefault, odSetNULL:
2013-08-07 11:11:44 +00:00
cond := NewCondition().And(fmt.Sprintf("%s__in", fi.name), args...)
2013-07-30 12:32:38 +00:00
params := Params{fi.column: nil}
2015-09-12 13:46:43 +00:00
if fi.onDelete == odSetDefault {
2013-07-30 12:32:38 +00:00
params[fi.column] = fi.initial.String()
}
_, err := d.UpdateBatch(q, nil, fi.mi, cond, params, tz)
2013-07-30 12:32:38 +00:00
if err != nil {
return err
}
2015-09-12 13:46:43 +00:00
case odDoNothing:
2013-07-30 12:32:38 +00:00
}
}
return nil
}
2014-01-17 09:04:15 +00:00
// delete table-related records.
func (d *dbBase) DeleteBatch(q dbQuerier, qs *querySet, mi *modelInfo, cond *Condition, tz *time.Location) (int64, error) {
2013-07-30 12:32:38 +00:00
tables := newDbTables(mi, d.ins)
2014-01-03 16:04:15 +00:00
tables.skipEnd = true
2013-07-30 12:32:38 +00:00
if qs != nil {
tables.parseRelated(qs.related, qs.relDepth)
}
if cond == nil || cond.IsEmpty() {
2013-10-09 03:37:16 +00:00
panic(fmt.Errorf("delete operation cannot execute without condition"))
2013-07-30 12:32:38 +00:00
}
Q := d.ins.TableQuote()
2015-09-12 13:46:43 +00:00
where, args := tables.getCondSQL(cond, false, tz)
join := tables.getJoinSQL()
2013-07-30 12:32:38 +00:00
cols := fmt.Sprintf("T0.%s%s%s", Q, mi.fields.pk.column, Q)
query := fmt.Sprintf("SELECT %s FROM %s%s%s T0 %s%s", cols, Q, mi.table, Q, join, where)
d.ins.ReplaceMarks(&query)
2013-07-30 12:32:38 +00:00
var rs *sql.Rows
2015-09-12 13:46:43 +00:00
r, err := q.Query(query, args...)
if err != nil {
2013-07-30 12:32:38 +00:00
return 0, err
}
2015-09-12 13:46:43 +00:00
rs = r
2013-12-31 01:55:29 +00:00
defer rs.Close()
2013-08-07 11:11:44 +00:00
var ref interface{}
2013-07-30 12:32:38 +00:00
args = make([]interface{}, 0)
cnt := 0
for rs.Next() {
2013-08-07 11:11:44 +00:00
if err := rs.Scan(&ref); err != nil {
2013-07-30 12:32:38 +00:00
return 0, err
}
pkValue, err := d.convertValueFromDB(mi.fields.pk, reflect.ValueOf(ref).Interface(), tz)
if err != nil {
return 0, err
}
args = append(args, pkValue)
2013-07-30 12:32:38 +00:00
cnt++
}
if cnt == 0 {
return 0, nil
}
marks := make([]string, len(args))
2015-03-20 05:29:01 +00:00
for i := range marks {
marks[i] = "?"
}
2018-11-18 13:54:25 +00:00
sqlIn := fmt.Sprintf("IN (%s)", strings.Join(marks, ", "))
query = fmt.Sprintf("DELETE FROM %s%s%s WHERE %s%s%s %s", Q, mi.table, Q, Q, mi.fields.pk.column, Q, sqlIn)
d.ins.ReplaceMarks(&query)
2018-11-18 13:54:25 +00:00
var res sql.Result
2018-11-19 15:42:56 +00:00
if qs != nil && qs.forContext {
2018-11-18 13:54:25 +00:00
res, err = q.ExecContext(qs.ctx, query, args...)
} else {
res, err = q.Exec(query, args...)
}
2015-09-12 13:46:43 +00:00
if err == nil {
2013-07-30 12:32:38 +00:00
num, err := res.RowsAffected()
if err != nil {
return 0, err
}
2013-08-07 11:11:44 +00:00
if num > 0 {
err := d.deleteRels(q, mi, args, tz)
2013-07-30 12:32:38 +00:00
if err != nil {
return num, err
}
}
return num, nil
}
2015-09-12 13:46:43 +00:00
return 0, err
2013-07-30 12:32:38 +00:00
}
2014-01-17 09:04:15 +00:00
// read related records.
func (d *dbBase) ReadBatch(q dbQuerier, qs *querySet, mi *modelInfo, cond *Condition, container interface{}, tz *time.Location, cols []string) (int64, error) {
2013-07-30 12:32:38 +00:00
val := reflect.ValueOf(container)
ind := reflect.Indirect(val)
errTyp := true
one := true
isPtr := true
2013-07-30 12:32:38 +00:00
if val.Kind() == reflect.Ptr {
fn := ""
2013-07-30 12:32:38 +00:00
if ind.Kind() == reflect.Slice {
one = false
typ := ind.Type().Elem()
switch typ.Kind() {
case reflect.Ptr:
fn = getFullName(typ.Elem())
case reflect.Struct:
isPtr = false
fn = getFullName(typ)
2013-07-30 12:32:38 +00:00
}
} else {
fn = getFullName(ind.Type())
2013-07-30 12:32:38 +00:00
}
errTyp = fn != mi.fullName
2013-07-30 12:32:38 +00:00
}
if errTyp {
if one {
2013-10-09 03:37:16 +00:00
panic(fmt.Errorf("wrong object type `%s` for rows scan, need *%s", val.Type(), mi.fullName))
} else {
2013-10-09 03:37:16 +00:00
panic(fmt.Errorf("wrong object type `%s` for rows scan, need *[]*%s or *[]%s", val.Type(), mi.fullName, mi.fullName))
}
2013-07-30 12:32:38 +00:00
}
rlimit := qs.limit
offset := qs.offset
Q := d.ins.TableQuote()
var tCols []string
if len(cols) > 0 {
hasRel := len(qs.related) > 0 || qs.relDepth > 0
tCols = make([]string, 0, len(cols))
var maps map[string]bool
if hasRel {
maps = make(map[string]bool)
}
for _, col := range cols {
if fi, ok := mi.fields.GetByAny(col); ok {
tCols = append(tCols, fi.column)
if hasRel {
maps[fi.column] = true
}
} else {
2018-09-30 09:45:18 +00:00
return 0, fmt.Errorf("wrong field/column name `%s`", col)
}
}
if hasRel {
for _, fi := range mi.fields.fieldsDB {
if fi.fieldType&IsRelField > 0 {
2017-03-17 17:24:45 +00:00
if !maps[fi.column] {
tCols = append(tCols, fi.column)
}
}
}
}
} else {
tCols = mi.fields.dbcols
}
colsNum := len(tCols)
sep := fmt.Sprintf("%s, T0.%s", Q, Q)
sels := fmt.Sprintf("T0.%s%s%s", Q, strings.Join(tCols, sep), Q)
2013-07-30 12:32:38 +00:00
tables := newDbTables(mi, d.ins)
tables.parseRelated(qs.related, qs.relDepth)
2015-09-12 13:46:43 +00:00
where, args := tables.getCondSQL(cond, false, tz)
groupBy := tables.getGroupSQL(qs.groups)
orderBy := tables.getOrderSQL(qs.orders)
limit := tables.getLimitSQL(mi, offset, rlimit)
join := tables.getJoinSQL()
2013-07-30 12:32:38 +00:00
for _, tbl := range tables.tables {
if tbl.sel {
colsNum += len(tbl.mi.fields.dbcols)
sep := fmt.Sprintf("%s, %s.%s", Q, tbl.index, Q)
sels += fmt.Sprintf(", %s.%s%s%s", tbl.index, Q, strings.Join(tbl.mi.fields.dbcols, sep), Q)
2013-07-30 12:32:38 +00:00
}
}
2015-07-22 16:12:57 +00:00
sqlSelect := "SELECT"
if qs.distinct {
sqlSelect += " DISTINCT"
}
2015-09-02 16:45:09 +00:00
query := fmt.Sprintf("%s %s FROM %s%s%s T0 %s%s%s%s%s", sqlSelect, sels, Q, mi.table, Q, join, where, groupBy, orderBy, limit)
2018-06-23 14:25:05 +00:00
if qs.forupdate {
query += " FOR UPDATE"
}
d.ins.ReplaceMarks(&query)
2013-07-30 12:32:38 +00:00
var rs *sql.Rows
2018-11-18 13:54:25 +00:00
var err error
2018-11-19 15:42:56 +00:00
if qs != nil && qs.forContext {
2018-11-18 13:54:25 +00:00
rs, err = q.QueryContext(qs.ctx, query, args...)
if err != nil {
return 0, err
}
} else {
rs, err = q.Query(query, args...)
if err != nil {
return 0, err
}
2013-07-30 12:32:38 +00:00
}
refs := make([]interface{}, colsNum)
2015-03-20 05:29:01 +00:00
for i := range refs {
2013-07-31 14:11:22 +00:00
var ref interface{}
2013-07-30 12:32:38 +00:00
refs[i] = &ref
}
2013-12-31 01:55:29 +00:00
defer rs.Close()
2013-07-30 12:32:38 +00:00
slice := ind
var cnt int64
for rs.Next() {
2017-03-17 17:24:45 +00:00
if one && cnt == 0 || !one {
2013-07-30 12:32:38 +00:00
if err := rs.Scan(refs...); err != nil {
return 0, err
}
elm := reflect.New(mi.addrField.Elem().Type())
mind := reflect.Indirect(elm)
cacheV := make(map[string]*reflect.Value)
cacheM := make(map[string]*modelInfo)
trefs := refs
d.setColsValues(mi, &mind, tCols, refs[:len(tCols)], tz)
trefs = refs[len(tCols):]
2013-07-30 12:32:38 +00:00
for _, tbl := range tables.tables {
// loop selected tables
2013-07-30 12:32:38 +00:00
if tbl.sel {
last := mind
names := ""
mmi := mi
// loop cascade models
2013-07-30 12:32:38 +00:00
for _, name := range tbl.names {
names += name
if val, ok := cacheV[names]; ok {
last = *val
mmi = cacheM[names]
} else {
fi := mmi.fields.GetByName(name)
lastm := mmi
mmi = fi.relModelInfo
field := last
if last.Kind() != reflect.Invalid {
2016-02-24 10:46:14 +00:00
field = reflect.Indirect(last.FieldByIndex(fi.fieldIndex))
if field.IsValid() {
d.setColsValues(mmi, &field, mmi.fields.dbcols, trefs[:len(mmi.fields.dbcols)], tz)
for _, fi := range mmi.fields.fieldsReverse {
if fi.inModel && fi.reverseFieldInfo.mi == lastm {
if fi.reverseFieldInfo != nil {
2016-02-24 10:46:14 +00:00
f := field.FieldByIndex(fi.fieldIndex)
if f.Kind() == reflect.Ptr {
f.Set(last.Addr())
}
2013-09-22 11:20:40 +00:00
}
2013-07-31 14:11:22 +00:00
}
2013-07-30 12:32:38 +00:00
}
last = field
2013-07-30 12:32:38 +00:00
}
}
cacheV[names] = &field
cacheM[names] = mmi
2013-07-30 12:32:38 +00:00
}
}
trefs = trefs[len(mmi.fields.dbcols):]
2013-07-30 12:32:38 +00:00
}
}
if one {
ind.Set(mind)
} else {
if cnt == 0 {
2013-11-08 14:19:01 +00:00
// you can use a empty & caped container list
// orm will not replace it
if ind.Len() != 0 {
// if container is not empty
// create a new one
slice = reflect.New(ind.Type()).Elem()
}
}
if isPtr {
slice = reflect.Append(slice, mind.Addr())
} else {
slice = reflect.Append(slice, mind)
}
2013-07-30 12:32:38 +00:00
}
}
cnt++
}
2017-03-17 17:24:45 +00:00
if !one {
2013-11-08 14:19:01 +00:00
if cnt > 0 {
ind.Set(slice)
} else {
// when a result is empty and container is nil
// to set a empty container
if ind.IsNil() {
ind.Set(reflect.MakeSlice(ind.Type(), 0, 0))
}
}
2013-07-30 12:32:38 +00:00
}
return cnt, nil
}
2014-01-17 09:04:15 +00:00
// excute count sql and return count result int64.
func (d *dbBase) Count(q dbQuerier, qs *querySet, mi *modelInfo, cond *Condition, tz *time.Location) (cnt int64, err error) {
2013-07-30 12:32:38 +00:00
tables := newDbTables(mi, d.ins)
tables.parseRelated(qs.related, qs.relDepth)
2015-09-12 13:46:43 +00:00
where, args := tables.getCondSQL(cond, false, tz)
2016-05-27 06:34:22 +00:00
groupBy := tables.getGroupSQL(qs.groups)
2015-09-12 13:46:43 +00:00
tables.getOrderSQL(qs.orders)
join := tables.getJoinSQL()
2013-07-30 12:32:38 +00:00
Q := d.ins.TableQuote()
2016-05-27 06:34:22 +00:00
query := fmt.Sprintf("SELECT COUNT(*) FROM %s%s%s T0 %s%s%s", Q, mi.table, Q, join, where, groupBy)
if groupBy != "" {
query = fmt.Sprintf("SELECT COUNT(*) FROM (%s) AS T", query)
}
d.ins.ReplaceMarks(&query)
2013-07-30 12:32:38 +00:00
2018-11-18 13:54:25 +00:00
var row *sql.Row
2018-11-19 15:42:56 +00:00
if qs != nil && qs.forContext {
2018-11-18 13:54:25 +00:00
row = q.QueryRowContext(qs.ctx, query, args...)
} else {
row = q.QueryRow(query, args...)
}
2013-07-30 12:32:38 +00:00
err = row.Scan(&cnt)
return
}
2014-01-17 09:04:15 +00:00
// generate sql with replacing operator string placeholders and replaced values.
2015-09-12 13:46:43 +00:00
func (d *dbBase) GenerateOperatorSQL(mi *modelInfo, fi *fieldInfo, operator string, args []interface{}, tz *time.Location) (string, []interface{}) {
2017-04-28 14:36:28 +00:00
var sql string
params := getFlatParams(fi, args, tz)
2013-08-11 14:27:45 +00:00
if len(params) == 0 {
2013-10-09 03:37:16 +00:00
panic(fmt.Errorf("operator `%s` need at least one args", operator))
2013-07-30 12:32:38 +00:00
}
2013-08-11 14:27:45 +00:00
arg := params[0]
2014-03-10 12:18:57 +00:00
switch operator {
case "in":
2013-07-30 12:32:38 +00:00
marks := make([]string, len(params))
2015-03-20 05:29:01 +00:00
for i := range marks {
2013-07-30 12:32:38 +00:00
marks[i] = "?"
}
sql = fmt.Sprintf("IN (%s)", strings.Join(marks, ", "))
2014-03-10 12:18:57 +00:00
case "between":
if len(params) != 2 {
panic(fmt.Errorf("operator `%s` need 2 args not %d", operator, len(params)))
}
sql = "BETWEEN ? AND ?"
default:
2013-07-30 12:32:38 +00:00
if len(params) > 1 {
2013-10-09 03:37:16 +00:00
panic(fmt.Errorf("operator `%s` need 1 args not %d", operator, len(params)))
2013-07-30 12:32:38 +00:00
}
2015-09-12 13:46:43 +00:00
sql = d.ins.OperatorSQL(operator)
2013-07-30 12:32:38 +00:00
switch operator {
2013-07-31 14:11:22 +00:00
case "exact":
if arg == nil {
params[0] = "IS NULL"
}
2013-07-30 12:32:38 +00:00
case "iexact", "contains", "icontains", "startswith", "endswith", "istartswith", "iendswith":
param := strings.Replace(ToStr(arg), `%`, `\%`, -1)
switch operator {
2013-07-31 14:11:22 +00:00
case "iexact":
case "contains", "icontains":
2013-07-30 12:32:38 +00:00
param = fmt.Sprintf("%%%s%%", param)
case "startswith", "istartswith":
param = fmt.Sprintf("%s%%", param)
case "endswith", "iendswith":
param = fmt.Sprintf("%%%s", param)
}
params[0] = param
case "isnull":
if b, ok := arg.(bool); ok {
if b {
sql = "IS NULL"
} else {
sql = "IS NOT NULL"
}
params = nil
} else {
2013-10-09 03:37:16 +00:00
panic(fmt.Errorf("operator `%s` need a bool value not `%T`", operator, arg))
2013-07-30 12:32:38 +00:00
}
}
}
return sql, params
}
2014-01-17 09:25:17 +00:00
// gernerate sql string with inner function, such as UPPER(text).
func (d *dbBase) GenerateOperatorLeftCol(*fieldInfo, string, *string) {
// default not use
2013-08-11 14:27:45 +00:00
}
2014-01-17 09:04:15 +00:00
// set values to struct column.
func (d *dbBase) setColsValues(mi *modelInfo, ind *reflect.Value, cols []string, values []interface{}, tz *time.Location) {
2013-07-30 12:32:38 +00:00
for i, column := range cols {
val := reflect.Indirect(reflect.ValueOf(values[i])).Interface()
fi := mi.fields.GetByColumn(column)
2016-02-24 10:46:14 +00:00
field := ind.FieldByIndex(fi.fieldIndex)
2013-07-30 12:32:38 +00:00
value, err := d.convertValueFromDB(fi, val, tz)
2013-07-30 12:32:38 +00:00
if err != nil {
2013-10-09 03:37:16 +00:00
panic(fmt.Errorf("Raw value: `%v` %s", val, err.Error()))
2013-07-30 12:32:38 +00:00
}
_, err = d.setFieldValue(fi, value, field)
2013-07-30 12:32:38 +00:00
if err != nil {
2013-10-09 03:37:16 +00:00
panic(fmt.Errorf("Raw value: `%v` %s", val, err.Error()))
2013-07-30 12:32:38 +00:00
}
}
}
2014-01-17 09:04:15 +00:00
// convert value from database result to value following in field type.
func (d *dbBase) convertValueFromDB(fi *fieldInfo, val interface{}, tz *time.Location) (interface{}, error) {
2013-07-30 12:32:38 +00:00
if val == nil {
return nil, nil
}
var value interface{}
var tErr error
2013-07-30 12:32:38 +00:00
var str *StrTo
switch v := val.(type) {
case []byte:
s := StrTo(string(v))
str = &s
case string:
s := StrTo(v)
str = &s
}
fieldType := fi.fieldType
setValue:
switch {
case fieldType == TypeBooleanField:
if str == nil {
switch v := val.(type) {
case int64:
b := v == 1
value = b
default:
s := StrTo(ToStr(v))
str = &s
}
}
if str != nil {
b, err := str.Bool()
if err != nil {
tErr = err
goto end
2013-07-30 12:32:38 +00:00
}
value = b
}
2017-11-30 10:12:49 +00:00
case fieldType == TypeVarCharField || fieldType == TypeCharField || fieldType == TypeTextField || fieldType == TypeJSONField || fieldType == TypeJsonbField:
2013-07-30 12:32:38 +00:00
if str == nil {
value = ToStr(val)
} else {
value = str.String()
2013-07-30 12:32:38 +00:00
}
case fieldType == TypeTimeField || fieldType == TypeDateField || fieldType == TypeDateTimeField:
2013-07-30 12:32:38 +00:00
if str == nil {
switch t := val.(type) {
2013-07-30 12:32:38 +00:00
case time.Time:
d.ins.TimeFromDB(&t, tz)
value = t
2013-07-30 12:32:38 +00:00
default:
s := StrTo(ToStr(t))
2013-07-30 12:32:38 +00:00
str = &s
}
}
if str != nil {
s := str.String()
var (
t time.Time
err error
)
2013-11-01 16:51:53 +00:00
if len(s) >= 19 {
s = s[:19]
2015-09-12 13:46:43 +00:00
t, err = time.ParseInLocation(formatDateTime, s, tz)
} else if len(s) >= 10 {
if len(s) > 10 {
s = s[:10]
}
2015-09-12 13:46:43 +00:00
t, err = time.ParseInLocation(formatDate, s, tz)
} else if len(s) >= 8 {
if len(s) > 8 {
s = s[:8]
}
t, err = time.ParseInLocation(formatTime, s, tz)
2013-07-30 12:32:38 +00:00
}
2013-11-01 16:51:53 +00:00
t = t.In(DefaultTimeLoc)
if err != nil && s != "00:00:00" && s != "0000-00-00" && s != "0000-00-00 00:00:00" {
tErr = err
goto end
2013-07-30 12:32:38 +00:00
}
value = t
}
case fieldType&IsIntegerField > 0:
if str == nil {
s := StrTo(ToStr(val))
str = &s
}
if str != nil {
var err error
switch fieldType {
case TypeBitField:
_, err = str.Int8()
2013-07-30 12:32:38 +00:00
case TypeSmallIntegerField:
_, err = str.Int16()
case TypeIntegerField:
_, err = str.Int32()
case TypeBigIntegerField:
_, err = str.Int64()
2013-08-19 14:37:39 +00:00
case TypePositiveBitField:
_, err = str.Uint8()
2013-07-30 12:32:38 +00:00
case TypePositiveSmallIntegerField:
_, err = str.Uint16()
case TypePositiveIntegerField:
_, err = str.Uint32()
case TypePositiveBigIntegerField:
_, err = str.Uint64()
}
if err != nil {
tErr = err
goto end
2013-07-30 12:32:38 +00:00
}
2016-03-17 13:34:49 +00:00
if fieldType&IsPositiveIntegerField > 0 {
2013-07-30 12:32:38 +00:00
v, _ := str.Uint64()
value = v
} else {
v, _ := str.Int64()
value = v
}
}
case fieldType == TypeFloatField || fieldType == TypeDecimalField:
if str == nil {
switch v := val.(type) {
case float64:
value = v
default:
s := StrTo(ToStr(v))
str = &s
}
}
if str != nil {
v, err := str.Float64()
if err != nil {
tErr = err
goto end
2013-07-30 12:32:38 +00:00
}
value = v
}
case fieldType&IsRelField > 0:
fi = fi.relModelInfo.fields.pk
fieldType = fi.fieldType
2013-07-30 12:32:38 +00:00
goto setValue
}
end:
if tErr != nil {
err := fmt.Errorf("convert to `%s` failed, field: %s err: %s", fi.addrValue.Type(), fi.fullName, tErr)
return nil, err
}
2013-07-30 12:32:38 +00:00
return value, nil
}
2014-01-17 09:04:15 +00:00
// set one value to struct column field.
func (d *dbBase) setFieldValue(fi *fieldInfo, value interface{}, field reflect.Value) (interface{}, error) {
2013-07-30 12:32:38 +00:00
fieldType := fi.fieldType
2017-03-17 17:24:45 +00:00
isNative := !fi.isFielder
2013-07-30 12:32:38 +00:00
setValue:
switch {
case fieldType == TypeBooleanField:
if isNative {
if nb, ok := field.Interface().(sql.NullBool); ok {
if value == nil {
nb.Valid = false
} else {
nb.Bool = value.(bool)
nb.Valid = true
}
field.Set(reflect.ValueOf(nb))
} else if field.Kind() == reflect.Ptr {
if value != nil {
v := value.(bool)
field.Set(reflect.ValueOf(&v))
}
} else {
if value == nil {
value = false
}
field.SetBool(value.(bool))
2013-07-31 14:11:22 +00:00
}
2013-07-30 12:32:38 +00:00
}
2017-11-30 10:12:49 +00:00
case fieldType == TypeVarCharField || fieldType == TypeCharField || fieldType == TypeTextField || fieldType == TypeJSONField || fieldType == TypeJsonbField:
2013-07-30 12:32:38 +00:00
if isNative {
if ns, ok := field.Interface().(sql.NullString); ok {
if value == nil {
ns.Valid = false
} else {
ns.String = value.(string)
ns.Valid = true
}
field.Set(reflect.ValueOf(ns))
} else if field.Kind() == reflect.Ptr {
if value != nil {
v := value.(string)
field.Set(reflect.ValueOf(&v))
}
} else {
if value == nil {
value = ""
}
field.SetString(value.(string))
2013-07-31 14:11:22 +00:00
}
2013-07-30 12:32:38 +00:00
}
case fieldType == TypeTimeField || fieldType == TypeDateField || fieldType == TypeDateTimeField:
2013-07-30 12:32:38 +00:00
if isNative {
2013-07-31 14:11:22 +00:00
if value == nil {
value = time.Time{}
} else if field.Kind() == reflect.Ptr {
if value != nil {
v := value.(time.Time)
field.Set(reflect.ValueOf(&v))
}
} else {
field.Set(reflect.ValueOf(value))
2013-07-31 14:11:22 +00:00
}
2013-07-30 12:32:38 +00:00
}
case fieldType == TypePositiveBitField && field.Kind() == reflect.Ptr:
if value != nil {
v := uint8(value.(uint64))
field.Set(reflect.ValueOf(&v))
}
case fieldType == TypePositiveSmallIntegerField && field.Kind() == reflect.Ptr:
if value != nil {
v := uint16(value.(uint64))
field.Set(reflect.ValueOf(&v))
}
case fieldType == TypePositiveIntegerField && field.Kind() == reflect.Ptr:
if value != nil {
if field.Type() == reflect.TypeOf(new(uint)) {
v := uint(value.(uint64))
field.Set(reflect.ValueOf(&v))
} else {
v := uint32(value.(uint64))
field.Set(reflect.ValueOf(&v))
}
}
case fieldType == TypePositiveBigIntegerField && field.Kind() == reflect.Ptr:
if value != nil {
v := value.(uint64)
field.Set(reflect.ValueOf(&v))
}
case fieldType == TypeBitField && field.Kind() == reflect.Ptr:
if value != nil {
v := int8(value.(int64))
field.Set(reflect.ValueOf(&v))
}
case fieldType == TypeSmallIntegerField && field.Kind() == reflect.Ptr:
if value != nil {
v := int16(value.(int64))
field.Set(reflect.ValueOf(&v))
}
case fieldType == TypeIntegerField && field.Kind() == reflect.Ptr:
if value != nil {
if field.Type() == reflect.TypeOf(new(int)) {
v := int(value.(int64))
field.Set(reflect.ValueOf(&v))
} else {
v := int32(value.(int64))
field.Set(reflect.ValueOf(&v))
}
}
case fieldType == TypeBigIntegerField && field.Kind() == reflect.Ptr:
if value != nil {
v := value.(int64)
field.Set(reflect.ValueOf(&v))
}
2013-07-30 12:32:38 +00:00
case fieldType&IsIntegerField > 0:
2016-03-17 13:34:49 +00:00
if fieldType&IsPositiveIntegerField > 0 {
2013-07-30 12:32:38 +00:00
if isNative {
2013-07-31 14:11:22 +00:00
if value == nil {
value = uint64(0)
}
2013-07-30 12:32:38 +00:00
field.SetUint(value.(uint64))
}
} else {
if isNative {
if ni, ok := field.Interface().(sql.NullInt64); ok {
if value == nil {
ni.Valid = false
} else {
ni.Int64 = value.(int64)
ni.Valid = true
}
field.Set(reflect.ValueOf(ni))
} else {
if value == nil {
value = int64(0)
}
field.SetInt(value.(int64))
2013-07-31 14:11:22 +00:00
}
2013-07-30 12:32:38 +00:00
}
}
case fieldType == TypeFloatField || fieldType == TypeDecimalField:
if isNative {
if nf, ok := field.Interface().(sql.NullFloat64); ok {
if value == nil {
nf.Valid = false
} else {
nf.Float64 = value.(float64)
nf.Valid = true
}
field.Set(reflect.ValueOf(nf))
} else if field.Kind() == reflect.Ptr {
if value != nil {
if field.Type() == reflect.TypeOf(new(float32)) {
v := float32(value.(float64))
field.Set(reflect.ValueOf(&v))
} else {
v := value.(float64)
field.Set(reflect.ValueOf(&v))
}
}
} else {
if value == nil {
value = float64(0)
}
field.SetFloat(value.(float64))
2013-07-31 14:11:22 +00:00
}
2013-07-30 12:32:38 +00:00
}
case fieldType&IsRelField > 0:
2013-07-31 14:11:22 +00:00
if value != nil {
2013-08-07 11:11:44 +00:00
fieldType = fi.relModelInfo.fields.pk.fieldType
2013-07-31 14:11:22 +00:00
mf := reflect.New(fi.relModelInfo.addrField.Elem().Type())
field.Set(mf)
2016-02-24 10:46:14 +00:00
f := mf.Elem().FieldByIndex(fi.relModelInfo.fields.pk.fieldIndex)
field = f
2013-07-31 14:11:22 +00:00
goto setValue
2013-07-30 12:32:38 +00:00
}
}
2017-03-17 17:24:45 +00:00
if !isNative {
2013-07-30 12:32:38 +00:00
fd := field.Addr().Interface().(Fielder)
err := fd.SetRaw(value)
if err != nil {
err = fmt.Errorf("converted value `%v` set to Fielder `%s` failed, err: %s", value, fi.fullName, err)
2013-07-30 12:32:38 +00:00
return nil, err
}
}
return value, nil
}
2014-01-17 09:04:15 +00:00
// query sql, read values , save to *[]ParamList.
func (d *dbBase) ReadValues(q dbQuerier, qs *querySet, mi *modelInfo, cond *Condition, exprs []string, container interface{}, tz *time.Location) (int64, error) {
2013-07-30 12:32:38 +00:00
var (
maps []Params
lists []ParamsList
list ParamsList
)
typ := 0
2013-11-08 14:19:01 +00:00
switch v := container.(type) {
2013-07-30 12:32:38 +00:00
case *[]Params:
2013-11-08 14:19:01 +00:00
d := *v
if len(d) == 0 {
maps = d
}
2013-07-30 12:32:38 +00:00
typ = 1
case *[]ParamsList:
2013-11-08 14:19:01 +00:00
d := *v
if len(d) == 0 {
lists = d
}
2013-07-30 12:32:38 +00:00
typ = 2
case *ParamsList:
2013-11-08 14:19:01 +00:00
d := *v
if len(d) == 0 {
list = d
}
2013-07-30 12:32:38 +00:00
typ = 3
default:
2013-10-09 03:37:16 +00:00
panic(fmt.Errorf("unsupport read values type `%T`", container))
2013-07-30 12:32:38 +00:00
}
tables := newDbTables(mi, d.ins)
var (
cols []string
infos []*fieldInfo
)
hasExprs := len(exprs) > 0
Q := d.ins.TableQuote()
2013-07-30 12:32:38 +00:00
if hasExprs {
cols = make([]string, 0, len(exprs))
infos = make([]*fieldInfo, 0, len(exprs))
for _, ex := range exprs {
2013-08-11 14:27:45 +00:00
index, name, fi, suc := tables.parseExprs(mi, strings.Split(ex, ExprSep))
2017-03-17 17:24:45 +00:00
if !suc {
2013-07-30 12:32:38 +00:00
panic(fmt.Errorf("unknown field/column name `%s`", ex))
}
2013-08-11 14:27:45 +00:00
cols = append(cols, fmt.Sprintf("%s.%s%s%s %s%s%s", index, Q, fi.column, Q, Q, name, Q))
2013-07-30 12:32:38 +00:00
infos = append(infos, fi)
}
} else {
cols = make([]string, 0, len(mi.fields.dbcols))
infos = make([]*fieldInfo, 0, len(exprs))
for _, fi := range mi.fields.fieldsDB {
cols = append(cols, fmt.Sprintf("T0.%s%s%s %s%s%s", Q, fi.column, Q, Q, fi.name, Q))
2013-07-30 12:32:38 +00:00
infos = append(infos, fi)
}
}
2015-09-12 13:46:43 +00:00
where, args := tables.getCondSQL(cond, false, tz)
groupBy := tables.getGroupSQL(qs.groups)
orderBy := tables.getOrderSQL(qs.orders)
limit := tables.getLimitSQL(mi, qs.offset, qs.limit)
join := tables.getJoinSQL()
2013-07-30 12:32:38 +00:00
sels := strings.Join(cols, ", ")
2016-05-10 09:45:06 +00:00
sqlSelect := "SELECT"
if qs.distinct {
sqlSelect += " DISTINCT"
}
query := fmt.Sprintf("%s %s FROM %s%s%s T0 %s%s%s%s%s", sqlSelect, sels, Q, mi.table, Q, join, where, groupBy, orderBy, limit)
2013-07-30 12:32:38 +00:00
2013-12-17 08:46:14 +00:00
d.ins.ReplaceMarks(&query)
2015-09-12 13:46:43 +00:00
rs, err := q.Query(query, args...)
if err != nil {
2013-07-30 12:32:38 +00:00
return 0, err
}
refs := make([]interface{}, len(cols))
2015-03-20 05:29:01 +00:00
for i := range refs {
2013-07-31 14:11:22 +00:00
var ref interface{}
2013-07-30 12:32:38 +00:00
refs[i] = &ref
}
2013-12-31 01:55:29 +00:00
defer rs.Close()
2013-08-01 04:09:17 +00:00
var (
cnt int64
columns []string
)
2013-07-30 12:32:38 +00:00
for rs.Next() {
2013-08-01 04:09:17 +00:00
if cnt == 0 {
2015-09-12 13:46:43 +00:00
cols, err := rs.Columns()
if err != nil {
2013-08-01 04:09:17 +00:00
return 0, err
}
2015-09-12 13:46:43 +00:00
columns = cols
2013-08-01 04:09:17 +00:00
}
2013-07-30 12:32:38 +00:00
if err := rs.Scan(refs...); err != nil {
return 0, err
}
switch typ {
case 1:
params := make(Params, len(cols))
for i, ref := range refs {
fi := infos[i]
val := reflect.Indirect(reflect.ValueOf(ref)).Interface()
value, err := d.convertValueFromDB(fi, val, tz)
2013-07-30 12:32:38 +00:00
if err != nil {
2013-10-09 03:37:16 +00:00
panic(fmt.Errorf("db value convert failed `%v` %s", val, err.Error()))
2013-07-30 12:32:38 +00:00
}
2013-08-01 04:09:17 +00:00
params[columns[i]] = value
2013-07-30 12:32:38 +00:00
}
maps = append(maps, params)
case 2:
params := make(ParamsList, 0, len(cols))
for i, ref := range refs {
fi := infos[i]
val := reflect.Indirect(reflect.ValueOf(ref)).Interface()
value, err := d.convertValueFromDB(fi, val, tz)
2013-07-30 12:32:38 +00:00
if err != nil {
2013-10-09 03:37:16 +00:00
panic(fmt.Errorf("db value convert failed `%v` %s", val, err.Error()))
2013-07-30 12:32:38 +00:00
}
params = append(params, value)
}
lists = append(lists, params)
case 3:
for i, ref := range refs {
fi := infos[i]
val := reflect.Indirect(reflect.ValueOf(ref)).Interface()
value, err := d.convertValueFromDB(fi, val, tz)
2013-07-30 12:32:38 +00:00
if err != nil {
2013-10-09 03:37:16 +00:00
panic(fmt.Errorf("db value convert failed `%v` %s", val, err.Error()))
2013-07-30 12:32:38 +00:00
}
list = append(list, value)
}
}
cnt++
}
switch v := container.(type) {
case *[]Params:
*v = maps
case *[]ParamsList:
*v = lists
case *ParamsList:
*v = list
}
return cnt, nil
}
func (d *dbBase) RowsTo(dbQuerier, *querySet, *modelInfo, *Condition, interface{}, string, string, *time.Location) (int64, error) {
return 0, nil
}
2014-01-17 09:04:15 +00:00
// flag of update joined record.
func (d *dbBase) SupportUpdateJoin() bool {
return true
}
func (d *dbBase) MaxLimit() uint64 {
return 18446744073709551615
}
2014-01-17 09:04:15 +00:00
// return quote.
func (d *dbBase) TableQuote() string {
return "`"
}
2017-04-28 15:37:40 +00:00
// replace value placeholder in parametered sql string.
func (d *dbBase) ReplaceMarks(query *string) {
// default use `?` as mark, do nothing
}
2013-08-11 14:27:45 +00:00
2014-01-17 09:04:15 +00:00
// flag of RETURNING sql.
2013-08-11 14:27:45 +00:00
func (d *dbBase) HasReturningID(*modelInfo, *string) bool {
return false
}
2016-03-27 07:06:57 +00:00
// sync auto key
func (d *dbBase) setval(db dbQuerier, mi *modelInfo, autoFields []string) error {
return nil
}
2014-01-17 09:04:15 +00:00
// convert time from db.
func (d *dbBase) TimeFromDB(t *time.Time, tz *time.Location) {
*t = t.In(tz)
}
2014-01-17 09:04:15 +00:00
// convert time to db.
func (d *dbBase) TimeToDB(t *time.Time, tz *time.Location) {
*t = t.In(tz)
}
2013-08-19 14:37:39 +00:00
2014-01-17 09:04:15 +00:00
// get database types.
2013-08-19 14:37:39 +00:00
func (d *dbBase) DbTypes() map[string]string {
return nil
}
2013-08-27 04:33:27 +00:00
2014-01-17 09:04:15 +00:00
// gt all tables.
2013-08-27 04:33:27 +00:00
func (d *dbBase) GetTables(db dbQuerier) (map[string]bool, error) {
tables := make(map[string]bool)
query := d.ins.ShowTablesQuery()
rows, err := db.Query(query)
if err != nil {
return tables, err
}
2013-12-31 01:55:29 +00:00
defer rows.Close()
2013-08-27 04:33:27 +00:00
for rows.Next() {
var table string
err := rows.Scan(&table)
if err != nil {
return tables, err
}
if table != "" {
tables[table] = true
}
}
return tables, nil
}
2014-01-17 09:04:15 +00:00
// get all cloumns in table.
2013-08-27 04:33:27 +00:00
func (d *dbBase) GetColumns(db dbQuerier, table string) (map[string][3]string, error) {
columns := make(map[string][3]string)
query := d.ins.ShowColumnsQuery(table)
rows, err := db.Query(query)
if err != nil {
return columns, err
}
2013-12-31 01:55:29 +00:00
defer rows.Close()
2013-08-27 04:33:27 +00:00
for rows.Next() {
var (
name string
typ string
null string
)
err := rows.Scan(&name, &typ, &null)
if err != nil {
return columns, err
}
columns[name] = [3]string{name, typ, null}
}
return columns, nil
}
2014-01-17 09:04:15 +00:00
// not implement.
2015-09-12 13:46:43 +00:00
func (d *dbBase) OperatorSQL(operator string) string {
2013-11-18 05:21:19 +00:00
panic(ErrNotImplement)
}
2014-01-17 09:04:15 +00:00
// not implement.
2013-08-27 04:33:27 +00:00
func (d *dbBase) ShowTablesQuery() string {
panic(ErrNotImplement)
}
2014-01-17 09:04:15 +00:00
// not implement.
2013-08-27 04:33:27 +00:00
func (d *dbBase) ShowColumnsQuery(table string) string {
panic(ErrNotImplement)
}
2014-01-17 09:04:15 +00:00
// not implement.
2013-08-27 04:33:27 +00:00
func (d *dbBase) IndexExists(dbQuerier, string, string) bool {
panic(ErrNotImplement)
}