Skip to content
Projects
Groups
Snippets
Help
Loading...
Sign in
Toggle navigation
B
beego
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Commits
Issue Boards
Open sidebar
go
beego
Commits
68ec133a
Commit
68ec133a
authored
Sep 12, 2015
by
astaxie
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
golint orm
parent
542e143e
Expand all
Hide whitespace changes
Inline
Side-by-side
Showing
25 changed files
with
313 additions
and
284 deletions
+313
-284
cmd.go
orm/cmd.go
+12
-12
cmd_utils.go
orm/cmd_utils.go
+18
-19
db.go
orm/db.go
+0
-0
db_alias.go
orm/db_alias.go
+27
-25
db_mysql.go
orm/db_mysql.go
+1
-1
db_postgres.go
orm/db_postgres.go
+3
-3
db_sqlite.go
orm/db_sqlite.go
+1
-1
db_tables.go
orm/db_tables.go
+12
-12
db_utils.go
orm/db_utils.go
+7
-8
models.go
orm/models.go
+5
-5
models_boot.go
orm/models_boot.go
+10
-13
models_fields.go
orm/models_fields.go
+0
-0
models_info_f.go
orm/models_info_f.go
+8
-8
models_info_m.go
orm/models_info_m.go
+2
-3
models_test.go
orm/models_test.go
+33
-33
orm.go
orm/orm.go
+10
-5
orm_conds.go
orm/orm_conds.go
+11
-10
orm_log.go
orm/orm_log.go
+3
-2
orm_queryset.go
orm/orm_queryset.go
+21
-20
orm_raw.go
orm/orm_raw.go
+56
-60
orm_test.go
orm/orm_test.go
+0
-0
qb.go
orm/qb.go
+5
-3
qb_mysql.go
orm/qb_mysql.go
+37
-11
types.go
orm/types.go
+11
-11
utils.go
orm/utils.go
+20
-19
No files found.
orm/cmd.go
View file @
68ec133a
...
...
@@ -46,7 +46,7 @@ func printHelp(errs ...string) {
os
.
Exit
(
2
)
}
// listen for orm command and then run it if command arguments passed.
//
RunCommand
listen for orm command and then run it if command arguments passed.
func
RunCommand
()
{
if
len
(
os
.
Args
)
<
2
||
os
.
Args
[
1
]
!=
"orm"
{
return
...
...
@@ -100,7 +100,7 @@ func (d *commandSyncDb) Parse(args []string) {
func
(
d
*
commandSyncDb
)
Run
()
error
{
var
drops
[]
string
if
d
.
force
{
drops
=
getDbDropS
ql
(
d
.
al
)
drops
=
getDbDropS
QL
(
d
.
al
)
}
db
:=
d
.
al
.
DB
...
...
@@ -124,7 +124,7 @@ func (d *commandSyncDb) Run() error {
}
}
sqls
,
indexes
:=
getDbCreateS
ql
(
d
.
al
)
sqls
,
indexes
:=
getDbCreateS
QL
(
d
.
al
)
tables
,
err
:=
d
.
al
.
DbBaser
.
GetTables
(
db
)
if
err
!=
nil
{
...
...
@@ -180,7 +180,7 @@ func (d *commandSyncDb) Run() error {
fmt
.
Printf
(
"create index `%s` for table `%s`
\n
"
,
idx
.
Name
,
idx
.
Table
)
}
query
:=
idx
.
S
ql
query
:=
idx
.
S
QL
_
,
err
:=
db
.
Exec
(
query
)
if
d
.
verbose
{
fmt
.
Printf
(
" %s
\n
"
,
query
)
...
...
@@ -203,7 +203,7 @@ func (d *commandSyncDb) Run() error {
queries
:=
[]
string
{
sqls
[
i
]}
for
_
,
idx
:=
range
indexes
[
mi
.
table
]
{
queries
=
append
(
queries
,
idx
.
S
ql
)
queries
=
append
(
queries
,
idx
.
S
QL
)
}
for
_
,
query
:=
range
queries
{
...
...
@@ -228,12 +228,12 @@ func (d *commandSyncDb) Run() error {
}
// database creation commander interface implement.
type
commandS
ql
All
struct
{
type
commandS
QL
All
struct
{
al
*
alias
}
// parse orm command line arguments.
func
(
d
*
commandS
ql
All
)
Parse
(
args
[]
string
)
{
func
(
d
*
commandS
QL
All
)
Parse
(
args
[]
string
)
{
var
name
string
flagSet
:=
flag
.
NewFlagSet
(
"orm command: sqlall"
,
flag
.
ExitOnError
)
...
...
@@ -244,13 +244,13 @@ func (d *commandSqlAll) Parse(args []string) {
}
// run orm line command.
func
(
d
*
commandS
ql
All
)
Run
()
error
{
sqls
,
indexes
:=
getDbCreateS
ql
(
d
.
al
)
func
(
d
*
commandS
QL
All
)
Run
()
error
{
sqls
,
indexes
:=
getDbCreateS
QL
(
d
.
al
)
var
all
[]
string
for
i
,
mi
:=
range
modelCache
.
allOrdered
()
{
queries
:=
[]
string
{
sqls
[
i
]}
for
_
,
idx
:=
range
indexes
[
mi
.
table
]
{
queries
=
append
(
queries
,
idx
.
S
ql
)
queries
=
append
(
queries
,
idx
.
S
QL
)
}
sql
:=
strings
.
Join
(
queries
,
"
\n
"
)
all
=
append
(
all
,
sql
)
...
...
@@ -262,10 +262,10 @@ func (d *commandSqlAll) Run() error {
func
init
()
{
commands
[
"syncdb"
]
=
new
(
commandSyncDb
)
commands
[
"sqlall"
]
=
new
(
commandS
ql
All
)
commands
[
"sqlall"
]
=
new
(
commandS
QL
All
)
}
// run syncdb command line.
//
RunSyncdb
run syncdb command line.
// name means table's alias name. default is "default".
// force means run next sql if the current is error.
// verbose means show all info when running command or not.
...
...
orm/cmd_utils.go
View file @
68ec133a
...
...
@@ -23,11 +23,11 @@ import (
type
dbIndex
struct
{
Table
string
Name
string
S
ql
string
S
QL
string
}
// create database drop sql.
func
getDbDropS
ql
(
al
*
alias
)
(
sqls
[]
string
)
{
func
getDbDropS
QL
(
al
*
alias
)
(
sqls
[]
string
)
{
if
len
(
modelCache
.
cache
)
==
0
{
fmt
.
Println
(
"no Model found, need register your model"
)
os
.
Exit
(
2
)
...
...
@@ -65,7 +65,7 @@ checkColumn:
case
TypeIntegerField
:
col
=
T
[
"int32"
]
case
TypeBigIntegerField
:
if
al
.
Driver
==
DR
_
Sqlite
{
if
al
.
Driver
==
DRSqlite
{
fieldType
=
TypeIntegerField
goto
checkColumn
}
...
...
@@ -104,15 +104,15 @@ func getColumnAddQuery(al *alias, fi *fieldInfo) string {
typ
+=
" "
+
"NOT NULL"
}
return
fmt
.
Sprintf
(
"ALTER TABLE %s%s%s ADD COLUMN %s%s%s %s %s"
,
Q
,
fi
.
mi
.
table
,
Q
,
Q
,
fi
.
column
,
Q
,
return
fmt
.
Sprintf
(
"ALTER TABLE %s%s%s ADD COLUMN %s%s%s %s %s"
,
Q
,
fi
.
mi
.
table
,
Q
,
Q
,
fi
.
column
,
Q
,
typ
,
getColumnDefault
(
fi
),
)
}
// create database creation string.
func
getDbCreateS
ql
(
al
*
alias
)
(
sqls
[]
string
,
tableIndexes
map
[
string
][]
dbIndex
)
{
func
getDbCreateS
QL
(
al
*
alias
)
(
sqls
[]
string
,
tableIndexes
map
[
string
][]
dbIndex
)
{
if
len
(
modelCache
.
cache
)
==
0
{
fmt
.
Println
(
"no Model found, need register your model"
)
os
.
Exit
(
2
)
...
...
@@ -142,7 +142,7 @@ func getDbCreateSql(al *alias) (sqls []string, tableIndexes map[string][]dbIndex
if
fi
.
auto
{
switch
al
.
Driver
{
case
DR
_Sqlite
,
DR_
Postgres
:
case
DR
Sqlite
,
DR
Postgres
:
column
+=
T
[
"auto"
]
default
:
column
+=
col
+
" "
+
T
[
"auto"
]
...
...
@@ -159,7 +159,7 @@ func getDbCreateSql(al *alias) (sqls []string, tableIndexes map[string][]dbIndex
//if fi.initial.String() != "" {
// column += " DEFAULT " + fi.initial.String()
//}
// Append attribute DEFAULT
column
+=
getColumnDefault
(
fi
)
...
...
@@ -201,7 +201,7 @@ func getDbCreateSql(al *alias) (sqls []string, tableIndexes map[string][]dbIndex
sql
+=
strings
.
Join
(
columns
,
",
\n
"
)
sql
+=
"
\n
)"
if
al
.
Driver
==
DR
_
MySQL
{
if
al
.
Driver
==
DRMySQL
{
var
engine
string
if
mi
.
model
!=
nil
{
engine
=
getTableEngine
(
mi
.
addrField
)
...
...
@@ -237,7 +237,7 @@ func getDbCreateSql(al *alias) (sqls []string, tableIndexes map[string][]dbIndex
index
:=
dbIndex
{}
index
.
Table
=
mi
.
table
index
.
Name
=
name
index
.
S
ql
=
sql
index
.
S
QL
=
sql
tableIndexes
[
mi
.
table
]
=
append
(
tableIndexes
[
mi
.
table
],
index
)
}
...
...
@@ -247,7 +247,6 @@ func getDbCreateSql(al *alias) (sqls []string, tableIndexes map[string][]dbIndex
return
}
// Get string value for the attribute "DEFAULT" for the CREATE, ALTER commands
func
getColumnDefault
(
fi
*
fieldInfo
)
string
{
var
(
...
...
@@ -263,16 +262,16 @@ func getColumnDefault(fi *fieldInfo) string {
// These defaults will be useful if there no config value orm:"default" and NOT NULL is on
switch
fi
.
fieldType
{
case
TypeDateField
,
TypeDateTimeField
:
return
v
;
case
TypeBooleanField
,
TypeBitField
,
TypeSmallIntegerField
,
TypeIntegerField
,
TypeBigIntegerField
,
TypePositiveBitField
,
TypePositiveSmallIntegerField
,
case
TypeDateField
,
TypeDateTimeField
:
return
v
case
TypeBooleanField
,
TypeBitField
,
TypeSmallIntegerField
,
TypeIntegerField
,
TypeBigIntegerField
,
TypePositiveBitField
,
TypePositiveSmallIntegerField
,
TypePositiveIntegerField
,
TypePositiveBigIntegerField
,
TypeFloatField
,
TypeDecimalField
:
d
=
"0"
d
=
"0"
}
if
fi
.
colDefault
{
if
!
fi
.
initial
.
Exist
()
{
v
=
fmt
.
Sprintf
(
t
,
""
)
...
...
orm/db.go
View file @
68ec133a
This diff is collapsed.
Click to expand it.
orm/db_alias.go
View file @
68ec133a
...
...
@@ -22,15 +22,16 @@ import (
"time"
)
// database driver constant int.
//
DriverType
database driver constant int.
type
DriverType
int
// Enum the Database driver
const
(
_
DriverType
=
iota
// int enum type
DR
_
MySQL
// mysql
DR
_
Sqlite
// sqlite
DR
_
Oracle
// oracle
DR
_
Postgres
// pgsql
_
DriverType
=
iota
// int enum type
DRMySQL
// mysql
DRSqlite
// sqlite
DROracle
// oracle
DRPostgres
// pgsql
)
// database driver string.
...
...
@@ -53,15 +54,15 @@ var _ Driver = new(driver)
var
(
dataBaseCache
=
&
_dbCache
{
cache
:
make
(
map
[
string
]
*
alias
)}
drivers
=
map
[
string
]
DriverType
{
"mysql"
:
DR
_
MySQL
,
"postgres"
:
DR
_
Postgres
,
"sqlite3"
:
DR
_
Sqlite
,
"mysql"
:
DRMySQL
,
"postgres"
:
DRPostgres
,
"sqlite3"
:
DRSqlite
,
}
dbBasers
=
map
[
DriverType
]
dbBaser
{
DR
_
MySQL
:
newdbBaseMysql
(),
DR
_
Sqlite
:
newdbBaseSqlite
(),
DR
_
Oracle
:
newdbBaseMysql
(),
DR
_
Postgres
:
newdbBasePostgres
(),
DRMySQL
:
newdbBaseMysql
(),
DRSqlite
:
newdbBaseSqlite
(),
DROracle
:
newdbBaseMysql
(),
DRPostgres
:
newdbBasePostgres
(),
}
)
...
...
@@ -119,7 +120,7 @@ func detectTZ(al *alias) {
}
switch
al
.
Driver
{
case
DR
_
MySQL
:
case
DRMySQL
:
row
:=
al
.
DB
.
QueryRow
(
"SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP)"
)
var
tz
string
row
.
Scan
(
&
tz
)
...
...
@@ -147,10 +148,10 @@ func detectTZ(al *alias) {
al
.
Engine
=
"INNODB"
}
case
DR
_
Sqlite
:
case
DRSqlite
:
al
.
TZ
=
time
.
UTC
case
DR
_
Postgres
:
case
DRPostgres
:
row
:=
al
.
DB
.
QueryRow
(
"SELECT current_setting('TIMEZONE')"
)
var
tz
string
row
.
Scan
(
&
tz
)
...
...
@@ -188,12 +189,13 @@ func addAliasWthDB(aliasName, driverName string, db *sql.DB) (*alias, error) {
return
al
,
nil
}
// AddAliasWthDB add a aliasName for the drivename
func
AddAliasWthDB
(
aliasName
,
driverName
string
,
db
*
sql
.
DB
)
error
{
_
,
err
:=
addAliasWthDB
(
aliasName
,
driverName
,
db
)
return
err
}
// Setting the database connect params. Use the database driver self dataSource args.
//
RegisterDataBase
Setting the database connect params. Use the database driver self dataSource args.
func
RegisterDataBase
(
aliasName
,
driverName
,
dataSource
string
,
params
...
int
)
error
{
var
(
err
error
...
...
@@ -236,7 +238,7 @@ end:
return
err
}
// Register a database driver use specify driver name, this can be definition the driver is which database type.
// Register
Driver Register
a database driver use specify driver name, this can be definition the driver is which database type.
func
RegisterDriver
(
driverName
string
,
typ
DriverType
)
error
{
if
t
,
ok
:=
drivers
[
driverName
];
ok
==
false
{
drivers
[
driverName
]
=
typ
...
...
@@ -248,7 +250,7 @@ func RegisterDriver(driverName string, typ DriverType) error {
return
nil
}
// Change the database default used timezone
//
SetDataBaseTZ
Change the database default used timezone
func
SetDataBaseTZ
(
aliasName
string
,
tz
*
time
.
Location
)
error
{
if
al
,
ok
:=
dataBaseCache
.
get
(
aliasName
);
ok
{
al
.
TZ
=
tz
...
...
@@ -258,14 +260,14 @@ func SetDataBaseTZ(aliasName string, tz *time.Location) error {
return
nil
}
// Change the max idle conns for *sql.DB, use specify database alias name
//
SetMaxIdleConns
Change the max idle conns for *sql.DB, use specify database alias name
func
SetMaxIdleConns
(
aliasName
string
,
maxIdleConns
int
)
{
al
:=
getDbAlias
(
aliasName
)
al
.
MaxIdleConns
=
maxIdleConns
al
.
DB
.
SetMaxIdleConns
(
maxIdleConns
)
}
// Change the max open conns for *sql.DB, use specify database alias name
//
SetMaxOpenConns
Change the max open conns for *sql.DB, use specify database alias name
func
SetMaxOpenConns
(
aliasName
string
,
maxOpenConns
int
)
{
al
:=
getDbAlias
(
aliasName
)
al
.
MaxOpenConns
=
maxOpenConns
...
...
@@ -275,7 +277,7 @@ func SetMaxOpenConns(aliasName string, maxOpenConns int) {
}
}
// Get *sql.DB from registered database by db alias name.
// Get
DB Get
*sql.DB from registered database by db alias name.
// Use "default" as alias name if you not set.
func
GetDB
(
aliasNames
...
string
)
(
*
sql
.
DB
,
error
)
{
var
name
string
...
...
@@ -284,9 +286,9 @@ func GetDB(aliasNames ...string) (*sql.DB, error) {
}
else
{
name
=
"default"
}
if
al
,
ok
:=
dataBaseCache
.
get
(
name
);
ok
{
al
,
ok
:=
dataBaseCache
.
get
(
name
)
if
ok
{
return
al
.
DB
,
nil
}
else
{
return
nil
,
fmt
.
Errorf
(
"DataBase of alias name `%s` not found
\n
"
,
name
)
}
return
nil
,
fmt
.
Errorf
(
"DataBase of alias name `%s` not found
\n
"
,
name
)
}
orm/db_mysql.go
View file @
68ec133a
...
...
@@ -67,7 +67,7 @@ type dbBaseMysql struct {
var
_
dbBaser
=
new
(
dbBaseMysql
)
// get mysql operator.
func
(
d
*
dbBaseMysql
)
OperatorS
ql
(
operator
string
)
string
{
func
(
d
*
dbBaseMysql
)
OperatorS
QL
(
operator
string
)
string
{
return
mysqlOperators
[
operator
]
}
...
...
orm/db_postgres.go
View file @
68ec133a
...
...
@@ -66,7 +66,7 @@ type dbBasePostgres struct {
var
_
dbBaser
=
new
(
dbBasePostgres
)
// get postgresql operator.
func
(
d
*
dbBasePostgres
)
OperatorS
ql
(
operator
string
)
string
{
func
(
d
*
dbBasePostgres
)
OperatorS
QL
(
operator
string
)
string
{
return
postgresOperators
[
operator
]
}
...
...
@@ -101,7 +101,7 @@ func (d *dbBasePostgres) ReplaceMarks(query *string) {
num
:=
0
for
_
,
c
:=
range
q
{
if
c
==
'?'
{
num
+=
1
num
++
}
}
if
num
==
0
{
...
...
@@ -114,7 +114,7 @@ func (d *dbBasePostgres) ReplaceMarks(query *string) {
if
c
==
'?'
{
data
=
append
(
data
,
'$'
)
data
=
append
(
data
,
[]
byte
(
strconv
.
Itoa
(
num
))
...
)
num
+=
1
num
++
}
else
{
data
=
append
(
data
,
c
)
}
...
...
orm/db_sqlite.go
View file @
68ec133a
...
...
@@ -66,7 +66,7 @@ type dbBaseSqlite struct {
var
_
dbBaser
=
new
(
dbBaseSqlite
)
// get sqlite operator.
func
(
d
*
dbBaseSqlite
)
OperatorS
ql
(
operator
string
)
string
{
func
(
d
*
dbBaseSqlite
)
OperatorS
QL
(
operator
string
)
string
{
return
sqliteOperators
[
operator
]
}
...
...
orm/db_tables.go
View file @
68ec133a
...
...
@@ -164,7 +164,7 @@ func (t *dbTables) parseRelated(rels []string, depth int) {
}
// generate join string.
func
(
t
*
dbTables
)
getJoinS
ql
()
(
join
string
)
{
func
(
t
*
dbTables
)
getJoinS
QL
()
(
join
string
)
{
Q
:=
t
.
base
.
TableQuote
()
for
_
,
jt
:=
range
t
.
tables
{
...
...
@@ -220,7 +220,7 @@ func (t *dbTables) parseExprs(mi *modelInfo, exprs []string) (index, name string
)
num
:=
len
(
exprs
)
-
1
names
:=
make
([]
string
,
0
)
var
names
[]
string
inner
:=
true
...
...
@@ -326,7 +326,7 @@ loopFor:
}
// generate condition sql.
func
(
t
*
dbTables
)
getCondS
ql
(
cond
*
Condition
,
sub
bool
,
tz
*
time
.
Location
)
(
where
string
,
params
[]
interface
{})
{
func
(
t
*
dbTables
)
getCondS
QL
(
cond
*
Condition
,
sub
bool
,
tz
*
time
.
Location
)
(
where
string
,
params
[]
interface
{})
{
if
cond
==
nil
||
cond
.
IsEmpty
()
{
return
}
...
...
@@ -347,7 +347,7 @@ func (t *dbTables) getCondSql(cond *Condition, sub bool, tz *time.Location) (whe
where
+=
"NOT "
}
if
p
.
isCond
{
w
,
ps
:=
t
.
getCondS
ql
(
p
.
cond
,
true
,
tz
)
w
,
ps
:=
t
.
getCondS
QL
(
p
.
cond
,
true
,
tz
)
if
w
!=
""
{
w
=
fmt
.
Sprintf
(
"( %s) "
,
w
)
}
...
...
@@ -372,12 +372,12 @@ func (t *dbTables) getCondSql(cond *Condition, sub bool, tz *time.Location) (whe
operator
=
"exact"
}
operS
ql
,
args
:=
t
.
base
.
GenerateOperatorSql
(
mi
,
fi
,
operator
,
p
.
args
,
tz
)
operS
QL
,
args
:=
t
.
base
.
GenerateOperatorSQL
(
mi
,
fi
,
operator
,
p
.
args
,
tz
)
leftCol
:=
fmt
.
Sprintf
(
"%s.%s%s%s"
,
index
,
Q
,
fi
.
column
,
Q
)
t
.
base
.
GenerateOperatorLeftCol
(
fi
,
operator
,
&
leftCol
)
where
+=
fmt
.
Sprintf
(
"%s %s "
,
leftCol
,
operS
ql
)
where
+=
fmt
.
Sprintf
(
"%s %s "
,
leftCol
,
operS
QL
)
params
=
append
(
params
,
args
...
)
}
...
...
@@ -391,8 +391,8 @@ func (t *dbTables) getCondSql(cond *Condition, sub bool, tz *time.Location) (whe
}
// generate group sql.
func
(
t
*
dbTables
)
getGroupS
ql
(
groups
[]
string
)
(
groupSql
string
)
{
if
len
(
groups
)
==
0
{
func
(
t
*
dbTables
)
getGroupS
QL
(
groups
[]
string
)
(
groupSQL
string
)
{
if
len
(
groups
)
==
0
{
return
}
...
...
@@ -410,12 +410,12 @@ func (t *dbTables) getGroupSql(groups []string) (groupSql string) {
groupSqls
=
append
(
groupSqls
,
fmt
.
Sprintf
(
"%s.%s%s%s"
,
index
,
Q
,
fi
.
column
,
Q
))
}
groupS
ql
=
fmt
.
Sprintf
(
"GROUP BY %s "
,
strings
.
Join
(
groupSqls
,
", "
))
groupS
QL
=
fmt
.
Sprintf
(
"GROUP BY %s "
,
strings
.
Join
(
groupSqls
,
", "
))
return
}
// generate order sql.
func
(
t
*
dbTables
)
getOrderS
ql
(
orders
[]
string
)
(
orderSql
string
)
{
func
(
t
*
dbTables
)
getOrderS
QL
(
orders
[]
string
)
(
orderSQL
string
)
{
if
len
(
orders
)
==
0
{
return
}
...
...
@@ -439,12 +439,12 @@ func (t *dbTables) getOrderSql(orders []string) (orderSql string) {
orderSqls
=
append
(
orderSqls
,
fmt
.
Sprintf
(
"%s.%s%s%s %s"
,
index
,
Q
,
fi
.
column
,
Q
,
asc
))
}
orderS
ql
=
fmt
.
Sprintf
(
"ORDER BY %s "
,
strings
.
Join
(
orderSqls
,
", "
))
orderS
QL
=
fmt
.
Sprintf
(
"ORDER BY %s "
,
strings
.
Join
(
orderSqls
,
", "
))
return
}
// generate limit sql.
func
(
t
*
dbTables
)
getLimitS
ql
(
mi
*
modelInfo
,
offset
int64
,
limit
int64
)
(
limits
string
)
{
func
(
t
*
dbTables
)
getLimitS
QL
(
mi
*
modelInfo
,
offset
int64
,
limit
int64
)
(
limits
string
)
{
if
limit
==
0
{
limit
=
int64
(
DefaultRowsLimit
)
}
...
...
orm/db_utils.go
View file @
68ec133a
...
...
@@ -24,9 +24,8 @@ import (
func
getDbAlias
(
name
string
)
*
alias
{
if
al
,
ok
:=
dataBaseCache
.
get
(
name
);
ok
{
return
al
}
else
{
panic
(
fmt
.
Errorf
(
"unknown DataBase alias name %s"
,
name
))
}
panic
(
fmt
.
Errorf
(
"unknown DataBase alias name %s"
,
name
))
}
// get pk column info.
...
...
@@ -80,19 +79,19 @@ outFor:
var
err
error
if
len
(
v
)
>=
19
{
s
:=
v
[
:
19
]
t
,
err
=
time
.
ParseInLocation
(
format
_
DateTime
,
s
,
DefaultTimeLoc
)
t
,
err
=
time
.
ParseInLocation
(
formatDateTime
,
s
,
DefaultTimeLoc
)
}
else
{
s
:=
v
if
len
(
v
)
>
10
{
s
=
v
[
:
10
]
}
t
,
err
=
time
.
ParseInLocation
(
format
_
Date
,
s
,
tz
)
t
,
err
=
time
.
ParseInLocation
(
formatDate
,
s
,
tz
)
}
if
err
==
nil
{
if
fi
.
fieldType
==
TypeDateField
{
v
=
t
.
In
(
tz
)
.
Format
(
format
_
Date
)
v
=
t
.
In
(
tz
)
.
Format
(
formatDate
)
}
else
{
v
=
t
.
In
(
tz
)
.
Format
(
format
_
DateTime
)
v
=
t
.
In
(
tz
)
.
Format
(
formatDateTime
)
}
}
}
...
...
@@ -137,9 +136,9 @@ outFor:
case
reflect
.
Struct
:
if
v
,
ok
:=
arg
.
(
time
.
Time
);
ok
{
if
fi
!=
nil
&&
fi
.
fieldType
==
TypeDateField
{
arg
=
v
.
In
(
tz
)
.
Format
(
format
_
Date
)
arg
=
v
.
In
(
tz
)
.
Format
(
formatDate
)
}
else
{
arg
=
v
.
In
(
tz
)
.
Format
(
format
_
DateTime
)
arg
=
v
.
In
(
tz
)
.
Format
(
formatDateTime
)
}
}
else
{
typ
:=
val
.
Type
()
...
...
orm/models.go
View file @
68ec133a
...
...
@@ -19,10 +19,10 @@ import (
)
const
(
od
_CASCADE
=
"cascade"
od
_SET_NULL
=
"set_null"
od
_SET_DEFAULT
=
"set_default"
od
_DO_NOTHING
=
"do_nothing"
od
Cascade
=
"cascade"
od
SetNULL
=
"set_null"
od
SetDefault
=
"set_default"
od
DoNothing
=
"do_nothing"
defaultStructTagName
=
"orm"
defaultStructTagDelim
=
";"
)
...
...
@@ -113,7 +113,7 @@ func (mc *_modelCache) clean() {
mc
.
done
=
false
}
// Clean model cache. Then you can re-RegisterModel.
//
ResetModelCache
Clean model cache. Then you can re-RegisterModel.
// Common use this api for test case.
func
ResetModelCache
()
{
modelCache
.
clean
()
...
...
orm/models_boot.go
View file @
68ec133a
...
...
@@ -51,19 +51,16 @@ func registerModel(prefix string, model interface{}) {
}
info
:=
newModelInfo
(
val
)
if
info
.
fields
.
pk
==
nil
{
outFor
:
for
_
,
fi
:=
range
info
.
fields
.
fieldsDB
{
if
fi
.
name
==
"Id"
{
if
fi
.
sf
.
Tag
.
Get
(
defaultStructTagName
)
==
""
{
switch
fi
.
addrValue
.
Elem
()
.
Kind
()
{
case
reflect
.
Int
,
reflect
.
Int32
,
reflect
.
Int64
,
reflect
.
Uint
,
reflect
.
Uint32
,
reflect
.
Uint64
:
fi
.
auto
=
true
fi
.
pk
=
true
info
.
fields
.
pk
=
fi
break
outFor
}
if
strings
.
ToLower
(
fi
.
name
)
==
"id"
{
switch
fi
.
addrValue
.
Elem
()
.
Kind
()
{
case
reflect
.
Int
,
reflect
.
Int32
,
reflect
.
Int64
,
reflect
.
Uint
,
reflect
.
Uint32
,
reflect
.
Uint64
:
fi
.
auto
=
true
fi
.
pk
=
true
info
.
fields
.
pk
=
fi
break
outFor
}
}
}
...
...
@@ -298,12 +295,12 @@ end:
}
}
// register models
//
RegisterModel
register models
func
RegisterModel
(
models
...
interface
{})
{
RegisterModelWithPrefix
(
""
,
models
...
)
}
// register models with a prefix
//
RegisterModelWithPrefix
register models with a prefix
func
RegisterModelWithPrefix
(
prefix
string
,
models
...
interface
{})
{
if
modelCache
.
done
{
panic
(
fmt
.
Errorf
(
"RegisterModel must be run before BootStrap"
))
...
...
@@ -314,7 +311,7 @@ func RegisterModelWithPrefix(prefix string, models ...interface{}) {
}
}
// bootrap models.
//
BootStrap
bootrap models.
// make all model parsed and can not add more models
func
BootStrap
()
{
if
modelCache
.
done
{
...
...
orm/models_fields.go
View file @
68ec133a
This diff is collapsed.
Click to expand it.
orm/models_info_f.go
View file @
68ec133a
...
...
@@ -119,8 +119,8 @@ type fieldInfo struct {
colDefault
bool
initial
StrTo
size
int
auto
_now
bool
auto
_now_add
bool
auto
Now
bool
auto
NowAdd
bool
rel
bool
reverse
bool
reverseField
string
...
...
@@ -309,20 +309,20 @@ checkType:
if
fi
.
rel
&&
fi
.
dbcol
{
switch
onDelete
{
case
od
_CASCADE
,
od_DO_NOTHING
:
case
od
_SET_DEFAULT
:
case
od
Cascade
,
odDoNothing
:
case
od
SetDefault
:
if
initial
.
Exist
()
==
false
{
err
=
errors
.
New
(
"on_delete: set_default need set field a default value"
)
goto
end
}
case
od
_SET_
NULL
:
case
od
Set
NULL
:
if
fi
.
null
==
false
{
err
=
errors
.
New
(
"on_delete: set_null need set field null"
)
goto
end
}
default
:
if
onDelete
==
""
{
onDelete
=
od
_CASCADE
onDelete
=
od
Cascade
}
else
{
err
=
fmt
.
Errorf
(
"on_delete value expected choice in `cascade,set_null,set_default,do_nothing`, unknown `%s`"
,
onDelete
)
goto
end
...
...
@@ -350,9 +350,9 @@ checkType:
fi
.
unique
=
false
case
TypeDateField
,
TypeDateTimeField
:
if
attrs
[
"auto_now"
]
{
fi
.
auto
_n
ow
=
true
fi
.
auto
N
ow
=
true
}
else
if
attrs
[
"auto_now_add"
]
{
fi
.
auto
_now_a
dd
=
true
fi
.
auto
NowA
dd
=
true
}
case
TypeFloatField
:
case
TypeDecimalField
:
...
...
orm/models_info_m.go
View file @
68ec133a
...
...
@@ -15,7 +15,6 @@
package
orm
import
(
"errors"
"fmt"
"os"
"reflect"
...
...
@@ -72,13 +71,13 @@ func newModelInfo(val reflect.Value) (info *modelInfo) {
added
:=
info
.
fields
.
Add
(
fi
)
if
added
==
false
{
err
=
errors
.
New
(
fmt
.
Sprintf
(
"duplicate column name: %s"
,
fi
.
column
)
)
err
=
fmt
.
Errorf
(
"duplicate column name: %s"
,
fi
.
column
)
break
}
if
fi
.
pk
{
if
info
.
fields
.
pk
!=
nil
{
err
=
errors
.
New
(
fmt
.
Sprintf
(
"one model must have one pk field only"
)
)
err
=
fmt
.
Errorf
(
"one model must have one pk field only"
)
break
}
else
{
info
.
fields
.
pk
=
fi
...
...
orm/models_test.go
View file @
68ec133a
...
...
@@ -76,21 +76,21 @@ func (e *SliceStringField) RawValue() interface{} {
var
_
Fielder
=
new
(
SliceStringField
)
// A json field.
type
J
son
Field
struct
{
type
J
SON
Field
struct
{
Name
string
Data
string
}
func
(
e
*
J
son
Field
)
String
()
string
{
func
(
e
*
J
SON
Field
)
String
()
string
{
data
,
_
:=
json
.
Marshal
(
e
)
return
string
(
data
)
}
func
(
e
*
J
son
Field
)
FieldType
()
int
{
func
(
e
*
J
SON
Field
)
FieldType
()
int
{
return
TypeTextField
}
func
(
e
*
J
son
Field
)
SetRaw
(
value
interface
{})
error
{
func
(
e
*
J
SON
Field
)
SetRaw
(
value
interface
{})
error
{
switch
d
:=
value
.
(
type
)
{
case
string
:
return
json
.
Unmarshal
([]
byte
(
d
),
e
)
...
...
@@ -99,14 +99,14 @@ func (e *JsonField) SetRaw(value interface{}) error {
}
}
func
(
e
*
J
son
Field
)
RawValue
()
interface
{}
{
func
(
e
*
J
SON
Field
)
RawValue
()
interface
{}
{
return
e
.
String
()
}
var
_
Fielder
=
new
(
J
son
Field
)
var
_
Fielder
=
new
(
J
SON
Field
)
type
Data
struct
{
I
d
int
I
D
int
`orm:"column(id)"`
Boolean
bool
Char
string
`orm:"size(50)"`
Text
string
`orm:"type(text)"`
...
...
@@ -130,7 +130,7 @@ type Data struct {
}
type
DataNull
struct
{
I
d
int
I
D
int
`orm:"column(id)"`
Boolean
bool
`orm:"null"`
Char
string
`orm:"null;size(50)"`
Text
string
`orm:"null;type(text)"`
...
...
@@ -193,7 +193,7 @@ type Float32 float64
type
Float64
float64
type
DataCustom
struct
{
I
d
int
I
D
int
`orm:"column(id)"`
Boolean
Boolean
Char
string
`orm:"size(50)"`
Text
string
`orm:"type(text)"`
...
...
@@ -216,28 +216,28 @@ type DataCustom struct {
// only for mysql
type
UserBig
struct
{
I
d
uint64
I
D
uint64
`orm:"column(id)"`
Name
string
}
type
User
struct
{
I
d
int
UserName
string
`orm:"size(30);unique"`
Email
string
`orm:"size(100)"`
Password
string
`orm:"size(100)"`
Status
int16
`orm:"column(Status)"`
IsStaff
bool
IsActive
bool
`orm:"default(1)"`
Created
time
.
Time
`orm:"auto_now_add;type(date)"`
Updated
time
.
Time
`orm:"auto_now"`
Profile
*
Profile
`orm:"null;rel(one);on_delete(set_null)"`
Posts
[]
*
Post
`orm:"reverse(many)" json:"-"`
ShouldSkip
string
`orm:"-"`
Nums
int
Langs
SliceStringField
`orm:"size(100)"`
Extra
Json
Field
`orm:"type(text)"`
unexport
bool
`orm:"-"`
unexport
_
bool
I
D
int
`orm:"column(id)"`
UserName
string
`orm:"size(30);unique"`
Email
string
`orm:"size(100)"`
Password
string
`orm:"size(100)"`
Status
int16
`orm:"column(Status)"`
IsStaff
bool
IsActive
bool
`orm:"default(1)"`
Created
time
.
Time
`orm:"auto_now_add;type(date)"`
Updated
time
.
Time
`orm:"auto_now"`
Profile
*
Profile
`orm:"null;rel(one);on_delete(set_null)"`
Posts
[]
*
Post
`orm:"reverse(many)" json:"-"`
ShouldSkip
string
`orm:"-"`
Nums
int
Langs
SliceStringField
`orm:"size(100)"`
Extra
JSON
Field
`orm:"type(text)"`
unexport
bool
`orm:"-"`
unexport
Bool
bool
}
func
(
u
*
User
)
TableIndex
()
[][]
string
{
...
...
@@ -259,7 +259,7 @@ func NewUser() *User {
}
type
Profile
struct
{
I
d
int
I
D
int
`orm:"column(id)"`
Age
int16
Money
float64
User
*
User
`orm:"reverse(one)" json:"-"`
...
...
@@ -276,7 +276,7 @@ func NewProfile() *Profile {
}
type
Post
struct
{
I
d
int
I
D
int
`orm:"column(id)"`
User
*
User
`orm:"rel(fk)"`
Title
string
`orm:"size(60)"`
Content
string
`orm:"type(text)"`
...
...
@@ -297,7 +297,7 @@ func NewPost() *Post {
}
type
Tag
struct
{
I
d
int
I
D
int
`orm:"column(id)"`
Name
string
`orm:"size(30)"`
BestPost
*
Post
`orm:"rel(one);null"`
Posts
[]
*
Post
`orm:"reverse(many)" json:"-"`
...
...
@@ -309,7 +309,7 @@ func NewTag() *Tag {
}
type
PostTags
struct
{
I
d
int
I
D
int
`orm:"column(id)"`
Post
*
Post
`orm:"rel(fk)"`
Tag
*
Tag
`orm:"rel(fk)"`
}
...
...
@@ -319,7 +319,7 @@ func (m *PostTags) TableName() string {
}
type
Comment
struct
{
I
d
int
I
D
int
`orm:"column(id)"`
Post
*
Post
`orm:"rel(fk);column(post)"`
Content
string
`orm:"type(text)"`
Parent
*
Comment
`orm:"null;rel(fk)"`
...
...
@@ -397,7 +397,7 @@ go test -v github.com/astaxie/beego/orm
RegisterDataBase
(
"default"
,
DBARGS
.
Driver
,
DBARGS
.
Source
,
20
)
alias
:=
getDbAlias
(
"default"
)
if
alias
.
Driver
==
DR
_
MySQL
{
if
alias
.
Driver
==
DRMySQL
{
alias
.
Engine
=
"INNODB"
}
...
...
orm/orm.go
View file @
68ec133a
...
...
@@ -12,6 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
// Package orm provide ORM for MySQL/PostgreSQL/sqlite
// Simple Usage
//
// package main
...
...
@@ -59,12 +60,13 @@ import (
"time"
)
// DebugQueries define the debug
const
(
Debug
_
Queries
=
iota
DebugQueries
=
iota
)
// Define common vars
var
(
// DebugLevel = Debug_Queries
Debug
=
false
DebugLog
=
NewLog
(
os
.
Stderr
)
DefaultRowsLimit
=
1000
...
...
@@ -79,7 +81,10 @@ var (
ErrNotImplement
=
errors
.
New
(
"have not implement"
)
)
// Params stores the Params
type
Params
map
[
string
]
interface
{}
// ParamsList stores paramslist
type
ParamsList
[]
interface
{}
type
orm
struct
{
...
...
@@ -188,7 +193,7 @@ func (o *orm) InsertMulti(bulk int, mds interface{}) (int64, error) {
o
.
setPk
(
mi
,
ind
,
id
)
cnt
+=
1
cnt
++
}
}
else
{
mi
,
_
:=
o
.
getMiInd
(
sind
.
Index
(
0
)
.
Interface
(),
false
)
...
...
@@ -489,7 +494,7 @@ func (o *orm) Driver() Driver {
return
driver
(
o
.
alias
.
Name
)
}
// create new orm
//
NewOrm
create new orm
func
NewOrm
()
Ormer
{
BootStrap
()
// execute only once
...
...
@@ -501,7 +506,7 @@ func NewOrm() Ormer {
return
o
}
// create a new ormer object with specify *sql.DB for query
//
NewOrmWithDB
create a new ormer object with specify *sql.DB for query
func
NewOrmWithDB
(
driverName
,
aliasName
string
,
db
*
sql
.
DB
)
(
Ormer
,
error
)
{
var
al
*
alias
...
...
orm/orm_conds.go
View file @
68ec133a
...
...
@@ -19,6 +19,7 @@ import (
"strings"
)
// ExprSep define the expression seperation
const
(
ExprSep
=
"__"
)
...
...
@@ -32,19 +33,19 @@ type condValue struct {
isCond
bool
}
//
c
ondition struct.
//
C
ondition struct.
// work for WHERE conditions.
type
Condition
struct
{
params
[]
condValue
}
// return new condition struct
//
NewCondition
return new condition struct
func
NewCondition
()
*
Condition
{
c
:=
&
Condition
{}
return
c
}
// add expression to condition
//
And
add expression to condition
func
(
c
Condition
)
And
(
expr
string
,
args
...
interface
{})
*
Condition
{
if
expr
==
""
||
len
(
args
)
==
0
{
panic
(
fmt
.
Errorf
(
"<Condition.And> args cannot empty"
))
...
...
@@ -53,7 +54,7 @@ func (c Condition) And(expr string, args ...interface{}) *Condition {
return
&
c
}
// add NOT expression to condition
//
AndNot
add NOT expression to condition
func
(
c
Condition
)
AndNot
(
expr
string
,
args
...
interface
{})
*
Condition
{
if
expr
==
""
||
len
(
args
)
==
0
{
panic
(
fmt
.
Errorf
(
"<Condition.AndNot> args cannot empty"
))
...
...
@@ -62,7 +63,7 @@ func (c Condition) AndNot(expr string, args ...interface{}) *Condition {
return
&
c
}
// combine a condition to current condition
//
AndCond
combine a condition to current condition
func
(
c
*
Condition
)
AndCond
(
cond
*
Condition
)
*
Condition
{
c
=
c
.
clone
()
if
c
==
cond
{
...
...
@@ -74,7 +75,7 @@ func (c *Condition) AndCond(cond *Condition) *Condition {
return
c
}
// add OR expression to condition
//
Or
add OR expression to condition
func
(
c
Condition
)
Or
(
expr
string
,
args
...
interface
{})
*
Condition
{
if
expr
==
""
||
len
(
args
)
==
0
{
panic
(
fmt
.
Errorf
(
"<Condition.Or> args cannot empty"
))
...
...
@@ -83,7 +84,7 @@ func (c Condition) Or(expr string, args ...interface{}) *Condition {
return
&
c
}
// add OR NOT expression to condition
//
OrNot
add OR NOT expression to condition
func
(
c
Condition
)
OrNot
(
expr
string
,
args
...
interface
{})
*
Condition
{
if
expr
==
""
||
len
(
args
)
==
0
{
panic
(
fmt
.
Errorf
(
"<Condition.OrNot> args cannot empty"
))
...
...
@@ -92,7 +93,7 @@ func (c Condition) OrNot(expr string, args ...interface{}) *Condition {
return
&
c
}
// combine a OR condition to current condition
//
OrCond
combine a OR condition to current condition
func
(
c
*
Condition
)
OrCond
(
cond
*
Condition
)
*
Condition
{
c
=
c
.
clone
()
if
c
==
cond
{
...
...
@@ -104,12 +105,12 @@ func (c *Condition) OrCond(cond *Condition) *Condition {
return
c
}
// check the condition arguments are empty or not.
//
IsEmpty
check the condition arguments are empty or not.
func
(
c
*
Condition
)
IsEmpty
()
bool
{
return
len
(
c
.
params
)
==
0
}
// clone a condition
// clone
clone
a condition
func
(
c
Condition
)
clone
()
*
Condition
{
return
&
c
}
orm/orm_log.go
View file @
68ec133a
...
...
@@ -23,11 +23,12 @@ import (
"time"
)
// Log implement the log.Logger
type
Log
struct
{
*
log
.
Logger
}
// set io.Writer to create a Logger.
//
NewLog
set io.Writer to create a Logger.
func
NewLog
(
out
io
.
Writer
)
*
Log
{
d
:=
new
(
Log
)
d
.
Logger
=
log
.
New
(
out
,
"[ORM]"
,
1e9
)
...
...
@@ -41,7 +42,7 @@ func debugLogQueies(alias *alias, operaton, query string, t time.Time, err error
if
err
!=
nil
{
flag
=
"FAIL"
}
con
:=
fmt
.
Sprintf
(
" - %s - [Queries/%s] - [%s / %11s / %7.1fms] - [%s]"
,
t
.
Format
(
format
_
DateTime
),
alias
.
Name
,
flag
,
operaton
,
elsp
,
query
)
con
:=
fmt
.
Sprintf
(
" - %s - [Queries/%s] - [%s / %11s / %7.1fms] - [%s]"
,
t
.
Format
(
formatDateTime
),
alias
.
Name
,
flag
,
operaton
,
elsp
,
query
)
cons
:=
make
([]
string
,
0
,
len
(
args
))
for
_
,
arg
:=
range
args
{
cons
=
append
(
cons
,
fmt
.
Sprintf
(
"%v"
,
arg
))
...
...
orm/orm_queryset.go
View file @
68ec133a
...
...
@@ -25,11 +25,12 @@ type colValue struct {
type
operator
int
// define Col operations
const
(
Col
_
Add
operator
=
iota
Col
_
Minus
Col
_
Multiply
Col
_
Except
ColAdd
operator
=
iota
ColMinus
ColMultiply
ColExcept
)
// ColValue do the field raw changes. e.g Nums = Nums + 10. usage:
...
...
@@ -38,7 +39,7 @@ const (
// }
func
ColValue
(
opt
operator
,
value
interface
{})
interface
{}
{
switch
opt
{
case
Col
_Add
,
Col_Minus
,
Col_Multiply
,
Col_
Except
:
case
Col
Add
,
ColMinus
,
ColMultiply
,
Col
Except
:
default
:
panic
(
fmt
.
Errorf
(
"orm.ColValue wrong operator"
))
}
...
...
@@ -129,21 +130,21 @@ func (o querySet) Distinct() QuerySeter {
// set relation model to query together.
// it will query relation models and assign to parent model.
func
(
o
querySet
)
RelatedSel
(
params
...
interface
{})
QuerySeter
{
if
len
(
params
)
==
0
{
o
.
relDepth
=
DefaultRelsDepth
}
else
{
for
_
,
p
:=
range
params
{
switch
val
:=
p
.
(
type
)
{
case
string
:
o
.
related
=
append
(
o
.
related
,
val
)
case
int
:
o
.
relDepth
=
val
default
:
panic
(
fmt
.
Errorf
(
"<QuerySeter.RelatedSel> wrong param kind: %v"
,
val
))
}
}
}
return
&
o
if
len
(
params
)
==
0
{
o
.
relDepth
=
DefaultRelsDepth
}
else
{
for
_
,
p
:=
range
params
{
switch
val
:=
p
.
(
type
)
{
case
string
:
o
.
related
=
append
(
o
.
related
,
val
)
case
int
:
o
.
relDepth
=
val
default
:
panic
(
fmt
.
Errorf
(
"<QuerySeter.RelatedSel> wrong param kind: %v"
,
val
))
}
}
}
return
&
o
}
// set condition to QuerySeter.
...
...
orm/orm_raw.go
View file @
68ec133a
...
...
@@ -165,14 +165,14 @@ func (o *rawSet) setFieldValue(ind reflect.Value, value interface{}) {
if
str
!=
""
{
if
len
(
str
)
>=
19
{
str
=
str
[
:
19
]
t
,
err
:=
time
.
ParseInLocation
(
format
_
DateTime
,
str
,
o
.
orm
.
alias
.
TZ
)
t
,
err
:=
time
.
ParseInLocation
(
formatDateTime
,
str
,
o
.
orm
.
alias
.
TZ
)
if
err
==
nil
{
t
=
t
.
In
(
DefaultTimeLoc
)
ind
.
Set
(
reflect
.
ValueOf
(
t
))
}
}
else
if
len
(
str
)
>=
10
{
str
=
str
[
:
10
]
t
,
err
:=
time
.
ParseInLocation
(
format
_
Date
,
str
,
DefaultTimeLoc
)
t
,
err
:=
time
.
ParseInLocation
(
formatDate
,
str
,
DefaultTimeLoc
)
if
err
==
nil
{
ind
.
Set
(
reflect
.
ValueOf
(
t
))
}
...
...
@@ -255,12 +255,13 @@ func (o *rawSet) loopSetRefs(refs []interface{}, sInds []reflect.Value, nIndsPtr
// query data and map to container
func
(
o
*
rawSet
)
QueryRow
(
containers
...
interface
{})
error
{
refs
:=
make
([]
interface
{},
0
,
len
(
containers
))
sInds
:=
make
([]
reflect
.
Value
,
0
)
eTyps
:=
make
([]
reflect
.
Type
,
0
)
var
(
refs
=
make
([]
interface
{},
0
,
len
(
containers
))
sInds
[]
reflect
.
Value
eTyps
[]
reflect
.
Type
sMi
*
modelInfo
)
structMode
:=
false
var
sMi
*
modelInfo
for
_
,
container
:=
range
containers
{
val
:=
reflect
.
ValueOf
(
container
)
ind
:=
reflect
.
Indirect
(
val
)
...
...
@@ -385,12 +386,13 @@ func (o *rawSet) QueryRow(containers ...interface{}) error {
// query data rows and map to container
func
(
o
*
rawSet
)
QueryRows
(
containers
...
interface
{})
(
int64
,
error
)
{
refs
:=
make
([]
interface
{},
0
,
len
(
containers
))
sInds
:=
make
([]
reflect
.
Value
,
0
)
eTyps
:=
make
([]
reflect
.
Type
,
0
)
var
(
refs
=
make
([]
interface
{},
0
,
len
(
containers
))
sInds
[]
reflect
.
Value
eTyps
[]
reflect
.
Type
sMi
*
modelInfo
)
structMode
:=
false
var
sMi
*
modelInfo
for
_
,
container
:=
range
containers
{
val
:=
reflect
.
ValueOf
(
container
)
sInd
:=
reflect
.
Indirect
(
val
)
...
...
@@ -557,10 +559,9 @@ func (o *rawSet) readValues(container interface{}, needCols []string) (int64, er
args
:=
getFlatParams
(
nil
,
o
.
args
,
o
.
orm
.
alias
.
TZ
)
var
rs
*
sql
.
Rows
if
r
,
err
:=
o
.
orm
.
db
.
Query
(
query
,
args
...
);
err
!=
nil
{
rs
,
err
:=
o
.
orm
.
db
.
Query
(
query
,
args
...
)
if
err
!=
nil
{
return
0
,
err
}
else
{
rs
=
r
}
defer
rs
.
Close
()
...
...
@@ -574,30 +575,30 @@ func (o *rawSet) readValues(container interface{}, needCols []string) (int64, er
for
rs
.
Next
()
{
if
cnt
==
0
{
if
columns
,
err
:=
rs
.
Columns
();
err
!=
nil
{
columns
,
err
:=
rs
.
Columns
()
if
err
!=
nil
{
return
0
,
err
}
if
len
(
needCols
)
>
0
{
indexs
=
make
([]
int
,
0
,
len
(
needCols
))
}
else
{
if
len
(
needCols
)
>
0
{
indexs
=
make
([]
int
,
0
,
len
(
needCols
))
}
else
{
indexs
=
make
([]
int
,
0
,
len
(
columns
))
}
indexs
=
make
([]
int
,
0
,
len
(
columns
))
}
cols
=
columns
refs
=
make
([]
interface
{},
len
(
cols
))
for
i
:=
range
refs
{
var
ref
sql
.
NullString
refs
[
i
]
=
&
ref
cols
=
columns
refs
=
make
([]
interface
{},
len
(
cols
))
for
i
:=
range
refs
{
var
ref
sql
.
NullString
refs
[
i
]
=
&
ref
if
len
(
needCols
)
>
0
{
for
_
,
c
:=
range
needCols
{
if
c
==
cols
[
i
]
{
indexs
=
append
(
indexs
,
i
)
}
if
len
(
needCols
)
>
0
{
for
_
,
c
:=
range
needCols
{
if
c
==
cols
[
i
]
{
indexs
=
append
(
indexs
,
i
)
}
}
else
{
indexs
=
append
(
indexs
,
i
)
}
}
else
{
indexs
=
append
(
indexs
,
i
)
}
}
}
...
...
@@ -684,11 +685,9 @@ func (o *rawSet) queryRowsTo(container interface{}, keyCol, valueCol string) (in
args
:=
getFlatParams
(
nil
,
o
.
args
,
o
.
orm
.
alias
.
TZ
)
var
rs
*
sql
.
Rows
if
r
,
err
:=
o
.
orm
.
db
.
Query
(
query
,
args
...
);
err
!=
nil
{
rs
,
err
:=
o
.
orm
.
db
.
Query
(
query
,
args
...
)
if
err
!=
nil
{
return
0
,
err
}
else
{
rs
=
r
}
defer
rs
.
Close
()
...
...
@@ -706,32 +705,29 @@ func (o *rawSet) queryRowsTo(container interface{}, keyCol, valueCol string) (in
for
rs
.
Next
()
{
if
cnt
==
0
{
if
columns
,
err
:=
rs
.
Columns
();
err
!=
nil
{
columns
,
err
:=
rs
.
Columns
()
if
err
!=
nil
{
return
0
,
err
}
else
{
cols
=
columns
refs
=
make
([]
interface
{},
len
(
cols
))
for
i
:=
range
refs
{
if
keyCol
==
cols
[
i
]
{
keyIndex
=
i
}
if
typ
==
1
||
keyIndex
==
i
{
var
ref
sql
.
NullString
refs
[
i
]
=
&
ref
}
else
{
var
ref
interface
{}
refs
[
i
]
=
&
ref
}
if
valueCol
==
cols
[
i
]
{
valueIndex
=
i
}
}
cols
=
columns
refs
=
make
([]
interface
{},
len
(
cols
))
for
i
:=
range
refs
{
if
keyCol
==
cols
[
i
]
{
keyIndex
=
i
}
if
keyIndex
==
-
1
||
valueIndex
==
-
1
{
panic
(
fmt
.
Errorf
(
"<RawSeter> RowsTo unknown key, value column name `%s: %s`"
,
keyCol
,
valueCol
))
if
typ
==
1
||
keyIndex
==
i
{
var
ref
sql
.
NullString
refs
[
i
]
=
&
ref
}
else
{
var
ref
interface
{}
refs
[
i
]
=
&
ref
}
if
valueCol
==
cols
[
i
]
{
valueIndex
=
i
}
}
if
keyIndex
==
-
1
||
valueIndex
==
-
1
{
panic
(
fmt
.
Errorf
(
"<RawSeter> RowsTo unknown key, value column name `%s: %s`"
,
keyCol
,
valueCol
))
}
}
...
...
orm/orm_test.go
View file @
68ec133a
This diff is collapsed.
Click to expand it.
orm/qb.go
View file @
68ec133a
...
...
@@ -16,6 +16,7 @@ package orm
import
"errors"
// QueryBuilder is the Query builder interface
type
QueryBuilder
interface
{
Select
(
fields
...
string
)
QueryBuilder
From
(
tables
...
string
)
QueryBuilder
...
...
@@ -43,15 +44,16 @@ type QueryBuilder interface {
String
()
string
}
// NewQueryBuilder return the QueryBuilder
func
NewQueryBuilder
(
driver
string
)
(
qb
QueryBuilder
,
err
error
)
{
if
driver
==
"mysql"
{
qb
=
new
(
MySQLQueryBuilder
)
}
else
if
driver
==
"postgres"
{
err
=
errors
.
New
(
"postgres query builder is not supported yet
!
"
)
err
=
errors
.
New
(
"postgres query builder is not supported yet"
)
}
else
if
driver
==
"sqlite"
{
err
=
errors
.
New
(
"sqlite query builder is not supported yet
!
"
)
err
=
errors
.
New
(
"sqlite query builder is not supported yet"
)
}
else
{
err
=
errors
.
New
(
"unknown driver for query builder
!
"
)
err
=
errors
.
New
(
"unknown driver for query builder"
)
}
return
}
orm/qb_mysql.go
View file @
68ec133a
...
...
@@ -20,134 +20,160 @@ import (
"strings"
)
const
COMMA_SPACE
=
", "
// CommaSpace is the seperation
const
CommaSpace
=
", "
// MySQLQueryBuilder is the SQL build
type
MySQLQueryBuilder
struct
{
Tokens
[]
string
}
// Select will join the fields
func
(
qb
*
MySQLQueryBuilder
)
Select
(
fields
...
string
)
QueryBuilder
{
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"SELECT"
,
strings
.
Join
(
fields
,
C
OMMA_SPACE
))
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"SELECT"
,
strings
.
Join
(
fields
,
C
ommaSpace
))
return
qb
}
// From join the tables
func
(
qb
*
MySQLQueryBuilder
)
From
(
tables
...
string
)
QueryBuilder
{
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"FROM"
,
strings
.
Join
(
tables
,
C
OMMA_SPACE
))
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"FROM"
,
strings
.
Join
(
tables
,
C
ommaSpace
))
return
qb
}
// InnerJoin INNER JOIN the table
func
(
qb
*
MySQLQueryBuilder
)
InnerJoin
(
table
string
)
QueryBuilder
{
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"INNER JOIN"
,
table
)
return
qb
}
// LeftJoin LEFT JOIN the table
func
(
qb
*
MySQLQueryBuilder
)
LeftJoin
(
table
string
)
QueryBuilder
{
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"LEFT JOIN"
,
table
)
return
qb
}
// RightJoin RIGHT JOIN the table
func
(
qb
*
MySQLQueryBuilder
)
RightJoin
(
table
string
)
QueryBuilder
{
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"RIGHT JOIN"
,
table
)
return
qb
}
// On join with on cond
func
(
qb
*
MySQLQueryBuilder
)
On
(
cond
string
)
QueryBuilder
{
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"ON"
,
cond
)
return
qb
}
// Where join the Where cond
func
(
qb
*
MySQLQueryBuilder
)
Where
(
cond
string
)
QueryBuilder
{
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"WHERE"
,
cond
)
return
qb
}
// And join the and cond
func
(
qb
*
MySQLQueryBuilder
)
And
(
cond
string
)
QueryBuilder
{
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"AND"
,
cond
)
return
qb
}
// Or join the or cond
func
(
qb
*
MySQLQueryBuilder
)
Or
(
cond
string
)
QueryBuilder
{
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"OR"
,
cond
)
return
qb
}
// In join the IN (vals)
func
(
qb
*
MySQLQueryBuilder
)
In
(
vals
...
string
)
QueryBuilder
{
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"IN"
,
"("
,
strings
.
Join
(
vals
,
C
OMMA_SPACE
),
")"
)
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"IN"
,
"("
,
strings
.
Join
(
vals
,
C
ommaSpace
),
")"
)
return
qb
}
// OrderBy join the Order by fields
func
(
qb
*
MySQLQueryBuilder
)
OrderBy
(
fields
...
string
)
QueryBuilder
{
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"ORDER BY"
,
strings
.
Join
(
fields
,
C
OMMA_SPACE
))
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"ORDER BY"
,
strings
.
Join
(
fields
,
C
ommaSpace
))
return
qb
}
// Asc join the asc
func
(
qb
*
MySQLQueryBuilder
)
Asc
()
QueryBuilder
{
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"ASC"
)
return
qb
}
// Desc join the desc
func
(
qb
*
MySQLQueryBuilder
)
Desc
()
QueryBuilder
{
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"DESC"
)
return
qb
}
// Limit join the limit num
func
(
qb
*
MySQLQueryBuilder
)
Limit
(
limit
int
)
QueryBuilder
{
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"LIMIT"
,
strconv
.
Itoa
(
limit
))
return
qb
}
// Offset join the offset num
func
(
qb
*
MySQLQueryBuilder
)
Offset
(
offset
int
)
QueryBuilder
{
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"OFFSET"
,
strconv
.
Itoa
(
offset
))
return
qb
}
// GroupBy join the Group by fields
func
(
qb
*
MySQLQueryBuilder
)
GroupBy
(
fields
...
string
)
QueryBuilder
{
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"GROUP BY"
,
strings
.
Join
(
fields
,
C
OMMA_SPACE
))
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"GROUP BY"
,
strings
.
Join
(
fields
,
C
ommaSpace
))
return
qb
}
// Having join the Having cond
func
(
qb
*
MySQLQueryBuilder
)
Having
(
cond
string
)
QueryBuilder
{
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"HAVING"
,
cond
)
return
qb
}
// Update join the update table
func
(
qb
*
MySQLQueryBuilder
)
Update
(
tables
...
string
)
QueryBuilder
{
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"UPDATE"
,
strings
.
Join
(
tables
,
C
OMMA_SPACE
))
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"UPDATE"
,
strings
.
Join
(
tables
,
C
ommaSpace
))
return
qb
}
// Set join the set kv
func
(
qb
*
MySQLQueryBuilder
)
Set
(
kv
...
string
)
QueryBuilder
{
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"SET"
,
strings
.
Join
(
kv
,
C
OMMA_SPACE
))
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"SET"
,
strings
.
Join
(
kv
,
C
ommaSpace
))
return
qb
}
// Delete join the Delete tables
func
(
qb
*
MySQLQueryBuilder
)
Delete
(
tables
...
string
)
QueryBuilder
{
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"DELETE"
)
if
len
(
tables
)
!=
0
{
qb
.
Tokens
=
append
(
qb
.
Tokens
,
strings
.
Join
(
tables
,
C
OMMA_SPACE
))
qb
.
Tokens
=
append
(
qb
.
Tokens
,
strings
.
Join
(
tables
,
C
ommaSpace
))
}
return
qb
}
// InsertInto join the insert SQL
func
(
qb
*
MySQLQueryBuilder
)
InsertInto
(
table
string
,
fields
...
string
)
QueryBuilder
{
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"INSERT INTO"
,
table
)
if
len
(
fields
)
!=
0
{
fieldsStr
:=
strings
.
Join
(
fields
,
C
OMMA_SPACE
)
fieldsStr
:=
strings
.
Join
(
fields
,
C
ommaSpace
)
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"("
,
fieldsStr
,
")"
)
}
return
qb
}
// Values join the Values(vals)
func
(
qb
*
MySQLQueryBuilder
)
Values
(
vals
...
string
)
QueryBuilder
{
valsStr
:=
strings
.
Join
(
vals
,
C
OMMA_SPACE
)
valsStr
:=
strings
.
Join
(
vals
,
C
ommaSpace
)
qb
.
Tokens
=
append
(
qb
.
Tokens
,
"VALUES"
,
"("
,
valsStr
,
")"
)
return
qb
}
// Subquery join the sub as alias
func
(
qb
*
MySQLQueryBuilder
)
Subquery
(
sub
string
,
alias
string
)
string
{
return
fmt
.
Sprintf
(
"(%s) AS %s"
,
sub
,
alias
)
}
// String join all Tokens
func
(
qb
*
MySQLQueryBuilder
)
String
()
string
{
return
strings
.
Join
(
qb
.
Tokens
,
" "
)
}
orm/types.go
View file @
68ec133a
...
...
@@ -20,13 +20,13 @@ import (
"time"
)
// database driver
//
Driver define
database driver
type
Driver
interface
{
Name
()
string
Type
()
DriverType
}
// field info
//
Fielder define
field info
type
Fielder
interface
{
String
()
string
FieldType
()
int
...
...
@@ -34,7 +34,7 @@ type Fielder interface {
RawValue
()
interface
{}
}
//
orm struct
//
Ormer define the orm interface
type
Ormer
interface
{
Read
(
interface
{},
...
string
)
error
ReadOrCreate
(
interface
{},
string
,
...
string
)
(
bool
,
int64
,
error
)
...
...
@@ -53,13 +53,13 @@ type Ormer interface {
Driver
()
Driver
}
// insert prepared statement
//
Inserter
insert prepared statement
type
Inserter
interface
{
Insert
(
interface
{})
(
int64
,
error
)
Close
()
error
}
// query seter
//
QuerySeter
query seter
type
QuerySeter
interface
{
Filter
(
string
,
...
interface
{})
QuerySeter
Exclude
(
string
,
...
interface
{})
QuerySeter
...
...
@@ -84,7 +84,7 @@ type QuerySeter interface {
RowsToStruct
(
interface
{},
string
,
string
)
(
int64
,
error
)
}
// model to model query struct
//
QueryM2Mer
model to model query struct
type
QueryM2Mer
interface
{
Add
(
...
interface
{})
(
int64
,
error
)
Remove
(
...
interface
{})
(
int64
,
error
)
...
...
@@ -93,13 +93,13 @@ type QueryM2Mer interface {
Count
()
(
int64
,
error
)
}
// raw query statement
//
RawPreparer
raw query statement
type
RawPreparer
interface
{
Exec
(
...
interface
{})
(
sql
.
Result
,
error
)
Close
()
error
}
// raw query seter
//
RawSeter
raw query seter
type
RawSeter
interface
{
Exec
()
(
sql
.
Result
,
error
)
QueryRow
(
...
interface
{})
error
...
...
@@ -113,7 +113,7 @@ type RawSeter interface {
Prepare
()
(
RawPreparer
,
error
)
}
// statement querier
// st
mtQuerier st
atement querier
type
stmtQuerier
interface
{
Close
()
error
Exec
(
args
...
interface
{})
(
sql
.
Result
,
error
)
...
...
@@ -162,8 +162,8 @@ type dbBaser interface {
UpdateBatch
(
dbQuerier
,
*
querySet
,
*
modelInfo
,
*
Condition
,
Params
,
*
time
.
Location
)
(
int64
,
error
)
DeleteBatch
(
dbQuerier
,
*
querySet
,
*
modelInfo
,
*
Condition
,
*
time
.
Location
)
(
int64
,
error
)
Count
(
dbQuerier
,
*
querySet
,
*
modelInfo
,
*
Condition
,
*
time
.
Location
)
(
int64
,
error
)
OperatorS
ql
(
string
)
string
GenerateOperatorS
ql
(
*
modelInfo
,
*
fieldInfo
,
string
,
[]
interface
{},
*
time
.
Location
)
(
string
,
[]
interface
{})
OperatorS
QL
(
string
)
string
GenerateOperatorS
QL
(
*
modelInfo
,
*
fieldInfo
,
string
,
[]
interface
{},
*
time
.
Location
)
(
string
,
[]
interface
{})
GenerateOperatorLeftCol
(
*
fieldInfo
,
string
,
*
string
)
PrepareInsert
(
dbQuerier
,
*
modelInfo
)
(
stmtQuerier
,
string
,
error
)
ReadValues
(
dbQuerier
,
*
querySet
,
*
modelInfo
,
*
Condition
,
[]
string
,
interface
{},
*
time
.
Location
)
(
int64
,
error
)
...
...
orm/utils.go
View file @
68ec133a
...
...
@@ -22,9 +22,10 @@ import (
"time"
)
// StrTo is the target string
type
StrTo
string
//
s
et string
//
S
et string
func
(
f
*
StrTo
)
Set
(
v
string
)
{
if
v
!=
""
{
*
f
=
StrTo
(
v
)
...
...
@@ -33,93 +34,93 @@ func (f *StrTo) Set(v string) {
}
}
//
clean
string
//
Clear
string
func
(
f
*
StrTo
)
Clear
()
{
*
f
=
StrTo
(
0x1E
)
}
// check string exist
//
Exist
check string exist
func
(
f
StrTo
)
Exist
()
bool
{
return
string
(
f
)
!=
string
(
0x1E
)
}
// string to bool
//
Bool
string to bool
func
(
f
StrTo
)
Bool
()
(
bool
,
error
)
{
return
strconv
.
ParseBool
(
f
.
String
())
}
// string to float32
//
Float32
string to float32
func
(
f
StrTo
)
Float32
()
(
float32
,
error
)
{
v
,
err
:=
strconv
.
ParseFloat
(
f
.
String
(),
32
)
return
float32
(
v
),
err
}
// string to float64
//
Float64
string to float64
func
(
f
StrTo
)
Float64
()
(
float64
,
error
)
{
return
strconv
.
ParseFloat
(
f
.
String
(),
64
)
}
// string to int
//
Int
string to int
func
(
f
StrTo
)
Int
()
(
int
,
error
)
{
v
,
err
:=
strconv
.
ParseInt
(
f
.
String
(),
10
,
32
)
return
int
(
v
),
err
}
// string to int8
//
Int8
string to int8
func
(
f
StrTo
)
Int8
()
(
int8
,
error
)
{
v
,
err
:=
strconv
.
ParseInt
(
f
.
String
(),
10
,
8
)
return
int8
(
v
),
err
}
// string to int16
//
Int16
string to int16
func
(
f
StrTo
)
Int16
()
(
int16
,
error
)
{
v
,
err
:=
strconv
.
ParseInt
(
f
.
String
(),
10
,
16
)
return
int16
(
v
),
err
}
// string to int32
//
Int32
string to int32
func
(
f
StrTo
)
Int32
()
(
int32
,
error
)
{
v
,
err
:=
strconv
.
ParseInt
(
f
.
String
(),
10
,
32
)
return
int32
(
v
),
err
}
// string to int64
//
Int64
string to int64
func
(
f
StrTo
)
Int64
()
(
int64
,
error
)
{
v
,
err
:=
strconv
.
ParseInt
(
f
.
String
(),
10
,
64
)
return
int64
(
v
),
err
}
// string to uint
//
Uint
string to uint
func
(
f
StrTo
)
Uint
()
(
uint
,
error
)
{
v
,
err
:=
strconv
.
ParseUint
(
f
.
String
(),
10
,
32
)
return
uint
(
v
),
err
}
// string to uint8
//
Uint8
string to uint8
func
(
f
StrTo
)
Uint8
()
(
uint8
,
error
)
{
v
,
err
:=
strconv
.
ParseUint
(
f
.
String
(),
10
,
8
)
return
uint8
(
v
),
err
}
// string to uint16
//
Uint16
string to uint16
func
(
f
StrTo
)
Uint16
()
(
uint16
,
error
)
{
v
,
err
:=
strconv
.
ParseUint
(
f
.
String
(),
10
,
16
)
return
uint16
(
v
),
err
}
// string to uint31
//
Uint32
string to uint31
func
(
f
StrTo
)
Uint32
()
(
uint32
,
error
)
{
v
,
err
:=
strconv
.
ParseUint
(
f
.
String
(),
10
,
32
)
return
uint32
(
v
),
err
}
// string to uint64
//
Uint64
string to uint64
func
(
f
StrTo
)
Uint64
()
(
uint64
,
error
)
{
v
,
err
:=
strconv
.
ParseUint
(
f
.
String
(),
10
,
64
)
return
uint64
(
v
),
err
}
// string to string
//
String
string to string
func
(
f
StrTo
)
String
()
string
{
if
f
.
Exist
()
{
return
string
(
f
)
...
...
@@ -127,7 +128,7 @@ func (f StrTo) String() string {
return
""
}
// interface to string
//
ToStr
interface to string
func
ToStr
(
value
interface
{},
args
...
int
)
(
s
string
)
{
switch
v
:=
value
.
(
type
)
{
case
bool
:
...
...
@@ -166,7 +167,7 @@ func ToStr(value interface{}, args ...int) (s string) {
return
s
}
// interface to int64
//
ToInt64
interface to int64
func
ToInt64
(
value
interface
{})
(
d
int64
)
{
val
:=
reflect
.
ValueOf
(
value
)
switch
value
.
(
type
)
{
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment