use submodule instead docs

This commit is contained in:
Lunny Xiao 2014-10-25 09:55:09 +08:00
parent 02b7db1334
commit 52e6a8fe38
27 changed files with 12 additions and 3466 deletions

6
.gitmodules vendored Normal file
View File

@ -0,0 +1,6 @@
[submodule "docs/manual-en-US"]
path = docs/manual-en-US
url = https://github.com/go-xorm/manual-en-US.git
[submodule "docs/manual-zh-CN"]
path = docs/manual-zh-CN
url = https://github.com/go-xorm/manual-zh-CN.git

View File

@ -1,27 +0,0 @@
Copyright (c) 2013 - 2014
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -1,19 +1,7 @@
# What is this?
# Xorm Manuals
An open source project for Xorm documentation.
Please visit [xorm.io/docs](http://xorm.io/docs)
## How to contribute?
# Contributing
Fork, update and submit a pull request. No matter how big or small, your changes are welcome!
## How does it work?
Xorm Web server checks for updates to this folder and updates the main documentation automatically.
## Note
Xorm documentation is written using standard markdown syntax. Please submit your changes using the same syntax.
## License
This project is under Apache v2 License. See the [LICENSE](LICENSE) file for the full license text.
If you have any suggestion about docs, please pull request.

View File

@ -1,27 +0,0 @@
# About
This manual documents aspects of Xorm.
### New to Xorm?
Read about the [Quick Start](docs/intro/quick_start.md).
### Can't find what you're looking for?
Search our [mailing list (xorm@googlegroups.com)](https://groups.google.com/forum/#!forum/xorm).
### Need help?
Send an email to the [xorm@googlegroups.com](mailto:xorm@googlegroups.com).
### Find a bug?
Open an [issue on github](https://github.com/go-xorm/xorm/issues).
### Want to be a contributor?
Fork the [documentation project](https://github.com/go-xorm/xorm/tree/master/docs), edit and pull request.
### Source code of this website?
Please visit [Xorm Web](https://github.com/go-xorm/website).

View File

@ -1,38 +0,0 @@
# Donation
<h4>
<b><font color="red">We will continue hard working with your huge support!</font></b>
</h4>
<h4>
<b>Donate by Paypal:</b>
<p>
<!--<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="encrypted" value="-----BEGIN PKCS7-----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-----END PKCS7-----
">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>-->
</p>
</h4>
### Your donation will be used as:
- Supports the development of Beego
- Supports maintaining the communities
- Upgrade to better server
- Award the outstanding contributors
- Holds community activities and lectures
### Donation Lists (descending by donating time)
| Donated at | Donator | Amount | Contact | Comments |
| ---------------- |:---------:| --------:|:---------:| ----------------------- |
|2014-7-8 | Steven Wang | 100¥ | easykooc@gmail.com | xorm目前做得最好的orm for golang |
|2014-7-8 | 韩天峰 | 20¥ | apolov@vip.qq.com | xorm是Golang里最好用的DB库 |
|2014-7-8 | sunhongjian | 100¥ | shongjiang@gmail.com |支持开源,支持美好的事物! |
|2014-7-8 | Jimmy Kuu | 200¥ | jimmy.kuu@gmail.com |再接再厉,持续发展 |
|2014-7-8 | 张仲东 | 100¥ | GoCMS作者 |支持XORM!! |
|2014-7-8 | wangwei | 100¥ | iamjcww@gmail.com |鄙视楼下 |
|2014-7-8 | Jazz | 2¥ | 1002376560@qq.com |这个沙发必须抢 |

View File

@ -1,70 +0,0 @@
---
name: AutoMap
sort: 100
---
When a struct auto mapping to a database's table, the below table describes how they change to each other:
<table>
<tr>
<td>go type's kind
</td>
<td>value method</td>
<td>xorm type
</td>
</tr>
<tr>
<td>implemented Conversion</td>
<td>Conversion.ToDB / Conversion.FromDB</td>
<td>Text</td>
</tr>
<tr>
<td>int, int8, int16, int32, uint, uint8, uint16, uint32</td>
<td></td>
<td> Int </td>
</tr>
<tr>
<td>int64, uint64</td><td></td><td>BigInt</td>
</tr>
<tr><td>float32</td><td></td><td>Float</td>
</tr>
<tr><td>float64</td><td></td><td>Double</td>
</tr>
<tr><td>complex64, complex128</td>
<td>json.Marshal / json.UnMarshal</td>
<td>Varchar(64)</td>
</tr>
<tr>
<td>[]uint8</td><td></td><td>Blob</td>
</tr>
<tr>
<td>array, slice, map except []uint8</td>
<td>json.Marshal / json.UnMarshal</td>
<td>Text</td>
</tr>
<tr>
<td>bool</td><td>1 or 0</td><td>Bool</td>
</tr>
<tr>
<td>string</td><td></td><td>Varchar(255)</td>
</tr>
<tr>
<td>time.Time</td><td></td><td>DateTime</td>
</tr>
<tr>
<td>cascade struct</td><td>primary key field value</td><td>BigInt</td>
</tr>
<tr>
<tr>
<td>struct</td><td>json.Marshal / json.UnMarshal</td><td>Text</td>
</tr>
<tr>
<td>
Others
</td>
<td></td>
<td>
Text
</td>
</tr>
</table>

View File

@ -1,443 +0,0 @@
---
name: ColumnType
sort: 110
---
<table>
<tr>
<td>xorm
</td>
<td>mysql
</td>
<td>sqlite3
</td>
<td>postgres
</td>
<td>remark</td>
</tr>
<tr>
<td>BIT
</td>
<td>BIT
</td>
<td>INTEGER
</td>
<td>BIT
</td>
<td></td>
</tr>
<tr>
<td>TINYINT
</td>
<td>TINYINT
</td>
<td>INTEGER
</td>
<td>SMALLINT
</td>
<td></td>
</tr>
<tr>
<td>SMALLINT
</td>
<td>SMALLINT
</td>
<td>INTEGER
</td>
<td>SMALLINT
</td>
<td></td>
</tr>
<tr>
<td>MEDIUMINT
</td>
<td>MEDIUMINT
</td>
<td>INTEGER
</td>
<td>INTEGER
</td>
<td></td>
</tr>
<tr>
<td>INT
</td>
<td>INT
</td>
<td>INTEGER
</td>
<td>INTEGER
</td>
<td></td>
</tr>
<tr>
<td>INTEGER
</td>
<td>INTEGER
</td>
<td>INTEGER
</td>
<td>INTEGER
</td>
<td></td>
</tr>
<tr>
<td>BIGINT
</td>
<td>BIGINT
</td>
<td>INTEGER
</td>
<td>BIGINT
</td>
<td></td>
</tr>
<tr><td cols="5"></td></tr>
<tr>
<td>CHAR
</td>
<td>CHAR
</td>
<td>TEXT
</td>
<td>CHAR
</td>
<td></td>
</tr>
<tr>
<td>VARCHAR
</td>
<td>VARCHAR
</td>
<td>TEXT
</td>
<td>VARCHAR
</td>
<td></td>
</tr>
<tr>
<td>TINYTEXT
</td>
<td>TINYTEXT
</td>
<td>TEXT
</td>
<td>TEXT
</td>
<td></td>
</tr>
<tr>
<td>TEXT
</td>
<td>TEXT
</td>
<td>TEXT
</td>
<td>TEXT
</td>
<td></td>
</tr>
<tr>
<td>MEDIUMTEXT
</td>
<td>MEDIUMTEXT
</td>
<td>TEXT
</td>
<td>TEXT
</td>
<td></td>
</tr>
<tr>
<td>LONGTEXT
</td>
<td>LONGTEXT
</td>
<td>TEXT
</td>
<td>TEXT
</td>
<td></td>
</tr>
<tr><td cols="5"></td></tr>
<tr>
<td>BINARY
</td>
<td>BINARY
</td>
<td>BLOB
</td>
<td>BYTEA
</td>
<td></td>
</tr>
<tr>
<td>VARBINARY
</td>
<td>VARBINARY
</td>
<td>BLOB
</td>
<td>BYTEA
</td>
<td></td>
</tr>
<tr><td cols="5"></td></tr>
<tr>
<td>DATE
</td>
<td>DATE
</td>
<td>NUMERIC
</td>
<td>DATE
</td>
<td></td>
</tr>
<tr>
<td>DATETIME
</td>
<td>DATETIME
</td>
<td>NUMERIC
</td>
<td>TIMESTAMP
</td>
<td></td>
</tr>
<tr>
<td>TIME
</td>
<td>TIME
</td>
<td>NUMERIC
</td>
<td>TIME
</td>
<td></td>
</tr>
<tr>
<td>TIMESTAMP
</td>
<td>TIMESTAMP
</td>
<td>NUMERIC
</td>
<td>TIMESTAMP
</td>
<td></td>
</tr>
<tr>
<td>TIMESTAMPZ
</td>
<td>TEXT
</td>
<td>TEXT
</td>
<td>TIMESTAMP with zone
</td>
<td>timestamp with zone info</td>
</tr>
<tr><td cols="5"></td></tr>
<tr>
<td>REAL
</td>
<td>REAL
</td>
<td>REAL
</td>
<td>REAL
</td>
<td></td>
</tr>
<tr>
<td>FLOAT
</td>
<td>FLOAT
</td>
<td>REAL
</td>
<td>REAL
</td>
<td></td>
</tr>
<tr>
<td>DOUBLE
</td>
<td>DOUBLE
</td>
<td>REAL
</td>
<td>DOUBLE PRECISION
</td>
<td></td>
</tr>
<tr><td cols="5"></td></tr>
<tr>
<td>DECIMAL
</td>
<td>DECIMAL
</td>
<td>NUMERIC
</td>
<td>DECIMAL
</td>
<td></td>
</tr>
<tr>
<td>NUMERIC
</td>
<td>NUMERIC
</td>
<td>NUMERIC
</td>
<td>NUMERIC
</td>
<td></td>
</tr>
<tr><td cols="5"></td></tr>
<tr>
<td>TINYBLOB
</td>
<td>TINYBLOB
</td>
<td>BLOB
</td>
<td>BYTEA
</td>
<td></td>
</tr>
<tr>
<td>BLOB
</td>
<td>BLOB
</td>
<td>BLOB
</td>
<td>BYTEA
</td>
<td></td>
</tr>
<tr>
<td>MEDIUMBLOB
</td>
<td>MEDIUMBLOB
</td>
<td>BLOB
</td>
<td>BYTEA
</td>
<td></td>
</tr>
<tr>
<td>LONGBLOB
</td>
<td>LONGBLOB
</td>
<td>BLOB
</td>
<td>BYTEA
</td>
<td></td>
</tr>
<tr>
<td>BYTEA
</td>
<td>BLOB
</td>
<td>BLOB
</td>
<td>BYTEA
</td>
<td></td>
</tr>
<tr><td cols="5"></td></tr>
<tr>
<td>BOOL
</td>
<td>TINYINT
</td>
<td>INTEGER
</td>
<td>BOOLEAN
</td>
<td></td>
</tr>
<tr>
<td>SERIAL
</td>
<td>INT
</td>
<td>INTEGER
</td>
<td>SERIAL
</td>
<td>auto increment</td>
</tr>
<tr>
<td>BIGSERIAL
</td>
<td>BIGINT
</td>
<td>INTEGER
</td>
<td>BIGSERIAL
</td>
<td>auto increment</td>
</tr>
</table>

View File

@ -1,143 +0,0 @@
---
root: true
name: Introduction
sort: 0
---
[中文](https://github.com/go-xorm/xorm/blob/master/README_CN.md)
Xorm is a simple and powerful ORM for Go.
[![Build Status](https://drone.io/github.com/go-xorm/tests/status.png)](https://drone.io/github.com/go-xorm/tests/latest) [![Go Walker](http://gowalker.org/api/v1/badge)](http://gowalker.org/github.com/go-xorm/xorm) [![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/lunny/xorm/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
# Features
* Struct <-> Table Mapping Support
* Chainable APIs
* Transaction Support
* Both ORM and raw SQL operation Support
* Sync database schema Support
* Query Cache speed up
* Database Reverse support, See [Xorm Tool README](https://github.com/go-xorm/cmd/blob/master/README.md)
* Simple cascade loading support
* Optimistic Locking support
# Drivers Support
Drivers for Go's sql package which currently support database/sql includes:
* Mysql: [github.com/go-sql-driver/mysql](https://github.com/go-sql-driver/mysql)
* MyMysql: [github.com/ziutek/mymysql/godrv](https://github.com/ziutek/mymysql/godrv)
* SQLite: [github.com/mattn/go-sqlite3](https://github.com/mattn/go-sqlite3)
* Postgres: [github.com/lib/pq](https://github.com/lib/pq)
* MsSql: [github.com/denisenkom/go-mssqldb](https://github.com/denisenkom/go-mssqldb)
* MsSql: [github.com/lunny/godbc](https://github.com/lunny/godbc)
# Changelog
* **v0.4.0 RC1**
Changes:
* moved xorm cmd to [github.com/go-xorm/cmd](github.com/go-xorm/cmd)
* refactored general DB operation a core lib at [github.com/go-xorm/core](https://github.com/go-xorm/core)
* moved tests to github.com/go-xorm/tests [github.com/go-xorm/tests](github.com/go-xorm/tests)
Improvements:
* Prepared statement cache
* Add Incr API
* Specify Timezone Location
* **v0.3.2**
Improvements:
* Add AllCols & MustCols function
* Add TableName for custom table name
Bug Fixes:
* #46
* #51
* #53
* #89
* #86
* #92
* **v0.3.1**
Features:
* Support MSSQL DB via ODBC driver ([github.com/lunny/godbc](https://github.com/lunny/godbc));
* Composite Key, using multiple pk xorm tag
* Added Row() API as alternative to Iterate() API for traversing result set, provide similar usages to sql.Rows type
* ORM struct allowed declaration of pointer builtin type as members to allow null DB fields
* Before and After Event processors
Improvements:
* Allowed int/int32/int64/uint/uint32/uint64/string as Primary Key type
* Performance improvement for Get()/Find()/Iterate()
[More changelogs ...](https://github.com/go-xorm/xorm/blob/master/docs/Changelog.md)
# Installation
If you have [gopm](https://github.com/gpmgo/gopm) installed,
gopm get github.com/go-xorm/xorm
Or
go get github.com/go-xorm/xorm
# Documents
* [GoDoc](http://godoc.org/github.com/go-xorm/xorm)
* [GoWalker](http://gowalker.org/github.com/go-xorm/xorm)
* [Quick Start](https://github.com/go-xorm/xorm/blob/master/docs/QuickStart.md)
# Cases
* [Gorevel](http://http://gorevel.cn/) - [github.com/goofcc/gorevel](http://github.com/goofcc/gorevel)
* [Gogs](http://try.gogits.org) - [github.com/gogits/gogs](http://github.com/gogits/gogs)
* [Gowalker](http://gowalker.org) - [github.com/Unknwon/gowalker](http://github.com/Unknwon/gowalker)
* [Gobuild.io](http://gobuild.io) - [github.com/shxsun/gobuild](http://github.com/shxsun/gobuild)
* [Sudo China](http://sudochina.com) - [github.com/insionng/toropress](http://github.com/insionng/toropress)
* [Godaily](http://godaily.org) - [github.com/govc/godaily](http://github.com/govc/godaily)
* [Very Hour](http://veryhour.com/)
* [GoCMS - github.com/zzboy/GoCMS](https://github.com/zzdboy/GoCMS)
* [GoBBS - gobbs.domolo.com](http://gobbs.domolo.com/)
# Discuss
Please visit [Xorm on Google Groups](https://groups.google.com/forum/#!forum/xorm)
# Contributing
If you want to pull request, please see [CONTRIBUTING](https://github.com/go-xorm/xorm/blob/master/CONTRIBUTING.md)
# LICENSE
BSD License
[http://creativecommons.org/licenses/BSD/](http://creativecommons.org/licenses/BSD/)

View File

@ -1,12 +0,0 @@
---
name: Cases
sort: 90
---
* [Gowalker](http://gowalker.org)source [github.com/Unknwon/gowalker](http://github.com/Unknwon/gowalker)
* [GoDaily](http://godaily.org)source [github.com/govc/godaily](http://github.com/govc/godaily)
* [Sudochina](http://sudochina.com) source [github.com/insionng/toropress](http://github.com/insionng/toropress)
* [VeryHour](http://veryhour.com)

View File

@ -1,60 +0,0 @@
---
name: Changelog
sort: 1
---
## Changelog
* **v0.4.0 RC1**
Changes:
* moved xorm cmd to [github.com/go-xorm/cmd](github.com/go-xorm/cmd)
* refactored general DB operation a core lib at [github.com/go-xorm/core](https://github.com/go-xorm/core)
* moved tests to github.com/go-xorm/tests [github.com/go-xorm/tests](github.com/go-xorm/tests)
Improvements:
* Prepared statement cache
* Add Incr API
* Specify Timezone Location
* **v0.3.2**
Improvements:
* Add AllCols & MustCols function
* Add TableName for custom table name
Bug Fixes:
* #46
* #51
* #53
* #89
* #86
* #92
* **v0.3.1**
Features:
* Support MSSQL DB via ODBC driver ([github.com/lunny/godbc](https://github.com/lunny/godbc));
* Composite Key, using multiple pk xorm tag
* Added Row() API as alternative to Iterate() API for traversing result set, provide similar usages to sql.Rows type
* ORM struct allowed declaration of pointer builtin type as members to allow null DB fields
* Before and After Event processors
Improvements:
* Allowed int/int32/int64/uint/uint32/uint64/string as Primary Key type
* Performance improvement for Get()/Find()/Iterate()
* **v0.2.3** : Improved documents; Optimistic Locking support; Timestamp with time zone support; Mapper change to tableMapper and columnMapper & added PrefixMapper & SuffixMapper support custom table or column name's prefix and suffix;Insert now return affected, err instead of id, err; Added UseBool & Distinct;
* **v0.2.2** : Postgres drivers now support lib/pq; Added method Iterate for record by record to handlerAdded SetMaxConns(go1.2+) support; some bugs fixed.
* **v0.2.1** : Added database reverse tool, now support generate go & c++ codes, see [Xorm Tool README](https://github.com/go-xorm/xorm/blob/master/xorm/README.md); some bug fixed.
* **v0.2.0** : Added Cache supported, select is speeder up 3~5x; Added SameMapper for same name between struct and table; Added Sync method for auto added tables, columns, indexes;
* **v0.1.9** : Added postgres and mymysql supported; Added ` and ? supported on Raw SQL even if postgres; Added Cols, StoreEngine, Charset function, Added many column data type supported, please see [Mapping Rules](#mapping).
* **v0.1.8** : Added union index and union unique supported, please see [Mapping Rules](#mapping).
* **v0.1.7** : Added IConnectPool interface and NoneConnectPool, SysConnectPool, SimpleConnectPool the three implements. You can choose one of them and the default is SysConnectPool. You can customrize your own connection pool. struct Engine added Close method, It should be invoked before system exit.
* **v0.1.6** : Added conversion interface support; added struct derive support; added single mapping support
* **v0.1.5** : Added multi threads support; added Sql() function for struct query; Get function changed return inteface; MakeSession and Create are instead with NewSession and NewEngine.
* **v0.1.4** : Added simple cascade load support; added more data type supports.
* **v0.1.3** : Find function now supports both slice and map; Add Table function for multi tables and temperory tables support
* **v0.1.2** : Insert function now supports both struct and slice pointer parameters, batch inserting and auto transaction
* **v0.1.1** : Add Id, In functions and improved README
* **v0.1.0** : Initial release.

View File

@ -1,51 +0,0 @@
---
name: FAQ
sort: 100
---
* How the xorm tag use both with json?
Use space.
```Go
type User struct {
Name string `json:"name" xorm:"name"`
}
```
* Does xorm support composite primary key?
Yes. You can use pk tag. All fields have tag will as one primary key by fields order on struct. When use, you can use xorm.PK{1, 2}. For example: `Id(xorm.PK{1, 2})`.
* How to use join
We can use Join() and extends tag to do join operation. For example:
type Userinfo struct {
Id int64
Name string
DetailId int64
}
type Userdetail struct {
Id int64
Gender int
}
type User struct {
Userinfo `xorm:"extends"`
Userdetail `xorm:"extends"`
}
var users = make([]User, 0)
err := engine.Table(&Userinfo{}).Join("LEFT", "userdetail", "userinfo.detail_id = userdetail.id").Find(&users)
//assert(User.Userinfo.Id != 0 && User.Userdetail.Id != 0)
Please notice that Userinfo field on User should be before Userdetail because of the order on join SQL stsatement. If the order is wrong, the same name field may be set a wrong value.
Of course, If join statment is very long, you could directly use Sql():
err := engine.Sql("select * from userinfo, userdetail where userinfo.detail_id = userdetail.id").Find(&users)
//assert(User.Userinfo.Id != 0 && User.Userdetail.Id != 0)

View File

@ -1,675 +0,0 @@
---
name: Quick Start
sort: 2
---
Quick Start
=====
* [1.Create ORM Engine](#10)
* [2.Define a struct](#20)
* [2.1.Name mapping rule](#21)
* [2.2.Use Table or Tag to change table or column name](#22)
* [2.3.Column define](#23)
* [3. database schema operation](#30)
* [3.1.Retrieve database schema infomation](#31)
* [3.2.Table Operation](#32)
* [3.3.Create indexes and uniques](#33)
* [3.4.Sync database schema](#34)
* [4.Insert records](#40)
* [5.Query and Count records](#60)
* [5.1.Query condition methods](#61)
* [5.2.Temporory methods](#62)
* [5.3.Get](#63)
* [5.4.Find](#64)
* [5.5.Iterate](#65)
* [5.6.Count](#66)
* [6.Update records](#70)
* [6.1.Optimistic Locking](#71)
* [7.Delete records](#80)
* [8.Execute SQL command](#90)
* [9.Execute SQL query](#100)
* [10.Transaction](#110)
* [11.Cache](#120)
* [13.Examples](#140)
<a name="10" id="10"></a>
## 1.Create ORM Engine
When using xorm, you can create multiple orm engines, an engine means a databse. So you can
```Go
import (
_ "github.com/go-sql-driver/mysql"
"github.com/go-xorm/xorm"
)
engine, err := xorm.NewEngine("mysql", "root:123@/test?charset=utf8")
defer engine.Close()
```
or
```Go
import (
_ "github.com/mattn/go-sqlite3"
"github.com/go-xorm/xorm"
)
engine, err = xorm.NewEngine("sqlite3", "./test.db")
defer engine.Close()
```
You can create many engines for different databases.Generally, you just need create only one engine. Engine supports run on go routines.
xorm supports four drivers now:
* Mysql: [github.com/Go-SQL-Driver/MySQL](https://github.com/Go-SQL-Driver/MySQL)
* MyMysql: [github.com/ziutek/mymysql](https://github.com/ziutek/mymysql)
* SQLite: [github.com/mattn/go-sqlite3](https://github.com/mattn/go-sqlite3)
* Postgres: [github.com/lib/pq](https://github.com/lib/pq)
* MsSql: [github.com/lunny/godbc](https://githubcom/lunny/godbc)
NewEngine's parameters are the same as `sql.Open`. So you should read the drivers' document for parameters' usage.
After engine created, you can do some settings.
1.Logs
* `engine.ShowSQL = true`, Show SQL statement on standard output;
* `engine.ShowDebug = true`, Show debug infomation on standard output;
* `engine.ShowError = true`, Show error infomation on standard output;
* `engine.ShowWarn = true`, Show warnning information on standard output;
2.If want to record infomation with another method: use `engine.Logger` as `io.Writer`:
```Go
f, err := os.Create("sql.log")
if err != nil {
println(err.Error())
return
}
engine.Logger = xorm.NewSimpleLogger(f)
```
3.Engine provide DB connection pool settings.
* Use `engine.SetMaxIdleConns()` to set idle connections.
* Use `engine.SetMaxOpenConns()` to set Max connections. This methods support only Go 1.2+.
<a name="20" id="20"></a>
## 2.Define struct
xorm maps a struct to a database table, the rule is below.
<a name="21" id="21"></a>
### 2.1.name mapping rule
use xorm.IMapper interface to implement. There are two IMapper implemented: `SnakeMapper` and `SameMapper`. SnakeMapper means struct name is word by word and table name or column name as 下划线. SameMapper means same name between struct and table.
SnakeMapper is the default.
```Go
engine.SetMapper(SameMapper{})
```
And you should notice:
* If you want to use other mapping rule, implement IMapper
* Tables's mapping rule could be different from Columns':
```Go
engine.SetTableMapper(SameMapper{})
engine.SetColumnMapper(SnakeMapper{})
```
<a name="22" id="22"></a>
### 2.2.Prefix mapping, Suffix Mapping and Cache Mapping
* `engine.NewPrefixMapper(SnakeMapper{}, "prefix")` can add prefix string when naming based on SnakeMapper or SameMapper, or you custom Mapper.
* `engine.NewPrefixMapper(SnakeMapper{}, "suffix")` can add suffix string when naming based on SnakeMapper or SameMapper, or you custom Mapper.
* `engine.NewCacheMapper(SnakeMapper{})` add naming Mapper for memory cache.
Of course, you can implement IMapper to make custom naming strategy.
<a name="22" id="22"></a>
### 2.3.Tag mapping
It's idealized of using IMapper for all naming. But if table or column is not in rule, we need new method to archive.
* If struct or pointer of struct has `TableName() string` method, the return value will be the struct's table name.
* `engine.Table()` can change the database table name for struct. The struct tag `xorm:"'table_name'"` can set column name for struct field. Use a pair of single quotes to prevent confusion for column's definition in struct tag. If not in confusion, ignore single quotes.
<a name="23" id="23"></a>
### 2.4.Column definition
Struct tag defines something for column as basic sql concepts, such as :
```
type User struct {
Id int64
Name string `xorm:"varchar(25) not null unique 'usr_name'"`
}
```
Data types are different in different DBMS. So xorm makes own data types definition to keep compatible. Details is in document [Column Types](https://github.com/go-xorm/xorm/blob/master/docs/COLUMNTYPE.md).
The following table is field mapping rules, the keyword is not case sensitive except column name
<table>
<tr>
<td>name or 'name'</td><td>Column Name, optional</td>
</tr>
<tr>
<td>pk</td><td>If column is Primary Key</td>
</tr>
<tr>
<td>support over 30 kinds of column types, details in [Column Types](https://github.com/go-xorm/xorm/blob/master/docs/COLUMNTYPE.md)</td><td>column type</td>
</tr>
<tr>
<td>autoincr</td><td>If autoincrement column</td>
</tr>
<tr>
<td>[not ]null | notnull</td><td>if column could be blank</td>
</tr>
<tr>
<td>unique/unique(uniquename)</td><td>column is Unique index; if add (uniquename), the column is used for combined unique index with the field that defining same uniquename.</td>
</tr>
<tr>
<td>index/index(indexname)</td><td>column is index. if add (indexname), the column is used for combined index with the field that defining same indexname.</td>
</tr>
<tr>
<td>extends</td><td>use for anonymous field, map the struct in anonymous field to database</td>
</tr>
<tr>
<td>-</td><td>This field will not be mapping</td>
</tr>
<tr>
<td>-></td><td>only write into database</td>
</tr>
<tr>
<td>&lt;-</td><td>only read from database</td>
</tr>
<tr>
<td>created</td><td>This field will be filled in current time on insert</td>
</tr>
<tr>
<td>updated</td><td>This field will be filled in current time on insert or update</td>
</tr>
<tr>
<td>version</td><td>This field will be filled 1 on insert and autoincrement on update</td>
</tr>
<tr>
<td>default 0 | default 'name'</td><td>column default value</td>
</tr>
</table>
Some default mapping rules
- 1. If field is name of `Id` and type of `int64`, xorm makes it as auto increment primary key. If another field, use struct tag `xorm:"pk"`.
- 2. String is corresponding to varchar(255).
- 3. Support custom type as `type MyString string`slice, map as field type. They are saving as Text column type and json-encode string. Support Blob column type with field type []byte or []uint8.
- 4. You can implement Conversion interface to define your custom mapping rule between field and database data.
```
type Conversion interface {
FromDB([]byte) error
ToDB() ([]byte, error)
}
```
- 5. If one struct has a Conversion field, so we need set an implementation to the field before get data from database. We can implement `BeforeSet(name string, cell xorm.Cell)` on struct to do this. For example: [testConversion](https://github.com/go-xorm/tests/blob/master/base.go#L1826)
<a name="30" id="30"></a>
## 3. database meta information
xorm provides methods to getting and setting table schema. For less schema changing production, `engine.Sync()` is enough.
<a name="31" id="31"></a>
## 3.1 retrieve database meta info
* DBMetas()
`engine.DBMetas()` returns all tables schema information.
<a name="31" id="31"></a>
## 3.2.directly table operation
* CreateTables()
`engine.CreateTables(struct)` creates table with struct or struct pointer.
`engine.Charset()` and `engine.StoreEngine()` can change charset or storage engine for **mysql** database.
* IsTableEmpty()
check table is empty or not.
* IsTableExist()
check table is existed or not.
* DropTables()
`engine.DropTables(struct)` drops table and indexes with struct or struct pointer. `engine.DropTables(string)` only drops table except indexes.
<a name="32" id="32"></a>
## 3.3.create indexes and uniques
* CreateIndexes
create indexes with struct.
* CreateUniques
create unique indexes with struct.
<a name="34" id="34"></a>
## 3.4.Synchronize database schema
xorm watches tables and indexes and sync schema:
1) use table name to create or drop table
2) use column name to alter column
3) use the indexes definition in struct field tag to create or drop indexes.
```Go
err := engine.Sync(new(User))
```
<a name="50" id="50"></a>
## 4.Insert data
Inserting records use Insert method.
* Insert one record
```Go
user := new(User)
user.Name = "myname"
affected, err := engine.Insert(user)
```
After inseted, `user.Id` will be filled with primary key column value.
```Go
fmt.Println(user.Id)
```
* Insert multiple records by Slice on one table
```Go
users := make([]User, 0)
users[0].Name = "name0"
...
affected, err := engine.Insert(&users)
```
* Insert multiple records by Slice of pointer on one table
```Go
users := make([]*User, 0)
users[0] = new(User)
users[0].Name = "name0"
...
affected, err := engine.Insert(&users)
```
* Insert one record on two table.
```Go
user := new(User)
user.Name = "myname"
question := new(Question)
question.Content = "whywhywhwy?"
affected, err := engine.Insert(user, question)
```
* Insert multiple records on multiple tables.
```Go
users := make([]User, 0)
users[0].Name = "name0"
...
questions := make([]Question, 0)
questions[0].Content = "whywhywhwy?"
affected, err := engine.Insert(&users, &questions)
```
* Insert one or multple records on multiple tables.
```Go
user := new(User)
user.Name = "myname"
...
questions := make([]Question, 0)
questions[0].Content = "whywhywhwy?"
affected, err := engine.Insert(user, &questions)
```
Notice: If you want to use transaction on inserting, you should use session.Begin() before calling Insert.
<a name="60" id="60"></a>
## 5. Chainable APIs
<a name="61" id="61"></a>
### 5.1. Chainable APIs for Queries, Execusions and Aggregations
Queries and Aggregations is basically formed by using `Get`, `Find`, `Count` methods, with conjunction of following chainable APIs to form conditions, grouping and ordering:
查询和统计主要使用`Get`, `Find`, `Count`三个方法。在进行查询时可以使用多个方法来形成查询条件,条件函数如下:
* Id([]interface{})
Primary Key lookup
* Where(string, …interface{})
As SQL conditional WHERE clause
* And(string, …interface{})
Conditional AND
* Or(string, …interface{})
Conditional OR
* Sql(string, …interface{})
Custom SQL query
* Asc(…string)
Ascending ordering on 1 or more fields
* Desc(…string)
Descending ordering on 1 or more fields
* OrderBy(string)
As SQL ORDER BY
* In(string, …interface{})
As SQL Conditional IN
* Cols(…string)
Explicity specify query or update columns. e.g.,:
```Go
engine.Cols("age", "name").Find(&users)
// SELECT age, name FROM user
engine.Cols("age", "name").Update(&user)
// UPDATE user SET age=? AND name=?
```
* Omit(...string)
Inverse function to Cols, to exclude specify query or update columns. Warning: Don't use with Cols()
```Go
engine.Omit("age").Update(&user)
// UPDATE user SET name = ? AND department = ?
```
* Distinct(…string)
As SQL DISTINCT
```Go
engine.Distinct("age", "department").Find(&users)
// SELECT DISTINCT age, department FROM user
```
Caution: this method will not lookup from caching store
* Table(nameOrStructPtr interface{})
Specify table name, or if struct pointer is passed into the name is extract from struct type name by IMapper conversion policy
* Limit(int, …int)
As SQL LIMIT with optional second param for OFFSET
* Top(int)
As SQL LIMIT
* Join(type, tableName, criteria string)
As SQL JOIN, support
type: either of these values [INNER, LEFT OUTER, CROSS] are supported now
tableName: joining table name
criteria: join criteria
* GroupBy(string)
As SQL GROUP BY
* Having(string)
As SQL HAVING
<a name="62" id="62"></a>
### 5.2. Override default behavior APIs
* NoAutoTime()
No auto timestamp for Created and Updated fields for INSERT and UPDATE
* NoCache()
Disable cache lookup
* UseBool(...string)
xorm's default behavior is fields with 0, "", nil, false, will not be used during query or update, use this method to explicit specify bool type fields for query or update
* Cascade(bool)
Do cascade lookup for associations
<a name="50" id="50"></a>
### 5.3.Get one record
Fetch a single object by user
```Go
var user = User{Id:27}
has, err := engine.Get(&user)
// or has, err := engine.Id(27).Get(&user)
var user = User{Name:"xlw"}
has, err := engine.Get(&user)
```
<a name="60" id="60"></a>
### 5.4.Find
Fetch multipe objects into a slice or a map, use Find
```Go
var everyone []Userinfo
err := engine.Find(&everyone)
users := make(map[int64]Userinfo)
err := engine.Find(&users)
```
* also you can use Where, Limit
```Go
var allusers []Userinfo
err := engine.Where("id > ?", "3").Limit(10,20).Find(&allusers) //Get id>3 limit 10 offset 20
```
* or you can use a struct query
```Go
var tenusers []Userinfo
err := engine.Limit(10).Find(&tenusers, &Userinfo{Name:"xlw"}) //Get All Name="xlw" limit 10 offset 0
```
* or In function
```Go
var tenusers []Userinfo
err := engine.In("id", 1, 3, 5).Find(&tenusers) //Get All id in (1, 3, 5)
```
* The default will query all columns of a table. Use Cols function if you want to select some columns
```Go
var tenusers []Userinfo
err := engine.Cols("id", "name").Find(&tenusers) //Find only id and name
```
<a name="70" id="70"></a>
### 5.5.Iterate records
Iterate, like find, but handle records one by one
```Go
err := engine.Where("age > ? or name=?)", 30, "xlw").Iterate(new(Userinfo), func(i int, bean interface{})error{
user := bean.(*Userinfo)
//do somthing use i and user
})
```
<a name="66" id="66"></a>
### 5.6.Count method usage
An ORM pointer struct is required for Count method in order to determine which table to retrieve from.
```Go
user := new(User)
total, err := engine.Where("id >?", 1).Count(user)
```
<a name="70" id="70"></a>
## 6.Update
更新数据使用`Update`方法Update方法的第一个参数为需要更新的内容可以为一个结构体指针或者一个Map[string]interface{}类型。当传入的为结构体指针时只有非空和0的field才会被作为更新的字段。当传入的为Map类型时key为数据库Column的名字value为要更新的内容。
```Go
user := new(User)
user.Name = "myname"
affected, err := engine.Id(id).Update(user)
```
这里需要注意Update会自动从user结构体中提取非0和非nil得值作为需要更新的内容因此如果需要更新一个值为0则此种方法将无法实现因此有两种选择
1. 通过添加Cols函数指定需要更新结构体中的哪些值未指定的将不更新指定了的即使为0也会更新。
```Go
affected, err := engine.Id(id).Cols("age").Update(&user)
```
2. 通过传入map[string]interface{}来进行更新但这时需要额外指定更新到哪个表因为通过map是无法自动检测更新哪个表的。
```Go
affected, err := engine.Table(new(User)).Id(id).Update(map[string]interface{}{"age":0})
```
### 6.1.Optimistic Lock
To enable object optimistic lock, add 'version' tag value:
```Go
type User struct {
Id int64
Name string
Version int `xorm:"version"`
}
```
The version starts with 1 when inserted to DB. For updating make sure originated version value is used for optimistic lock check.
```Go
var user User
engine.Id(1).Get(&user)
// SELECT * FROM user WHERE id = ?
engine.Id(1).Update(&user)
// UPDATE user SET ..., version = version + 1 WHERE id = ? AND version = ?
```
<a name="80" id="80"></a>
## 7.Delete one or more records
Delete one or more records
* delete by id
```Go
err := engine.Id(1).Delete(&User{})
```
* delete by other conditions
```Go
err := engine.Delete(&User{Name:"xlw"})
```
<a name="90" id="90"></a>
## 8.Execute SQL query
Of course, SQL execution is also provided.
If select then use Query
```Go
sql := "select * from userinfo"
results, err := engine.Query(sql)
```
<a name="100" id="100"></a>
## 9.Execute SQL command
If insert, update or delete then use Exec
```Go
sql = "update userinfo set username=? where id=?"
res, err := engine.Exec(sql, "xiaolun", 1)
```
<a name="110" id="110"></a>
## 10.Transaction
```Go
session := engine.NewSession()
defer session.Close()
// add Begin() before any action
err := session.Begin()
user1 := Userinfo{Username: "xiaoxiao", Departname: "dev", Alias: "lunny", Created: time.Now()}
_, err = session.Insert(&user1)
if err != nil {
session.Rollback()
return
}
user2 := Userinfo{Username: "yyy"}
_, err = session.Where("id = ?", 2).Update(&user2)
if err != nil {
session.Rollback()
return
}
_, err = session.Exec("delete from userinfo where username = ?", user2.Username)
if err != nil {
session.Rollback()
return
}
// add Commit() after all actions
err = session.Commit()
if err != nil {
return
}
```
<a name="120" id="120"></a>
## 11.Built-in LRU memory cache provider
1. Global Cache
Xorm implements cache support. Defaultly, it's disabled. If enable it, use below code.
```Go
cacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), 1000)
engine.SetDefaultCacher(cacher)
```
If disable some tables' cache, then:
```Go
engine.MapCacher(&user, nil)
```
2. Table's Cache
If only some tables need cache, then:
```Go
cacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), 1000)
engine.MapCacher(&user, cacher)
```
Caution:
1. When use Cols methods on cache enabled, the system still return all the columns.
2. When using Exec method, you should clear cache
```Go
engine.Exec("update user set name = ? where id = ?", "xlw", 1)
engine.ClearCache(new(User))
```
Cache implement theory below:
![cache design](https://raw.github.com/go-xorm/xorm/master/docs/cache_design.png)
<a name="140" id="140"></a>
## 13.Examples
Please visit [https://github.com/go-xorm/xorm/tree/master/examples](https://github.com/go-xorm/xorm/tree/master/examples)

View File

@ -1,109 +0,0 @@
---
root: false
name: Xorm Tools
sort: 3
---
# xorm tools
xorm tools is a set of tools for database operation.
## Binary Install
If you have [got](https://github.com/gobuild/got) installed, you can install by got
```
got go-xorm/cmd/xorm
```
or you can download from [gobuild](http://gobuild.io/download/github.com/lunny/got).
## Source Install
`go get github.com/go-xorm/cmd/xorm`
and you should install the depends below:
* github.com/go-xorm/xorm
* Mysql: [github.com/go-sql-driver/mysql](https://github.com/go-sql-driver/mysql)
* MyMysql: [github.com/ziutek/mymysql/godrv](https://github.com/ziutek/mymysql/godrv)
* Postgres: [github.com/lib/pq](https://github.com/lib/pq)
* SQLite: [github.com/mattn/go-sqlite3](https://github.com/mattn/go-sqlite3)
** For sqlite support, you need build via `go build -tags sqlite3` because of this driver ask cgo.
## Commands
All the commands below.
* **reverse** reverse a db to codes
* **shell** a general shell to operate all kinds of database
* **dump** dump database all table struct's and data to standard output
* **source** execute a sql from std in
* **driver** list all supported drivers
## Reverse
Reverse command is a tool to convert your database struct to all kinds languages of structs or classes. After you installed the tool, you can type
`xorm help reverse`
to get help
example:
sqlite:
`xorm reverse sqite3 test.db templates/goxorm`
mysql:
`xorm reverse mysql root:@/xorm_test?charset=utf8 templates/goxorm`
mymysql:
`xorm reverse mymysql xorm_test2/root/ templates/goxorm`
postgres:
`xorm reverse postgres "dbname=xorm_test sslmode=disable" templates/goxorm`
will generated go files in `./model` directory
### Template and Config
Now, xorm tool supports go and c++ two languages and have go, goxorm, c++ three of default templates. In template directory, we can put a config file to control how to generating.
````
lang=go
genJson=1
```
lang must be go or c++ now.
genJson can be 1 or 0, if 1 then the struct will have json tag.
## Shell
Shell command provides a tool to operate database. For example, you can create table, alter table, insert data, delete data and etc.
`xorm shell sqlite3 test.db` will connect to the sqlite3 database and you can type `help` to list all the shell commands.
## Dump
Dump command provides a tool to dump all database structs and data as SQL to your standard output.
`xorm dump sqlite3 test.db` could dump sqlite3 database test.db to standard output. If you want to save to file, just
type `xorm dump sqlite3 test.db > test.sql`.
## Source
`xorm source sqlite3 test.db < test.sql` will execute sql file on the test.db.
## Driver
List all supported drivers since default build will not include sqlite3.
## LICENSE
BSD License
[http://creativecommons.org/licenses/BSD/](http://creativecommons.org/licenses/BSD/)

View File

@ -1,22 +0,0 @@
# Developer Team
### Unknown
- Team role: Project manager, back-end developer.
- Social network: [Sina Weibo](http://weibo.com/Obahua) [GitHub](https://github.com/Unknwon) [Twitter](https://twitter.com/joe2010xtmf) [Google+](https://plus.google.com/u/0/+JiahuaChen)
### Lunny
- Team role: Back-end Git and database developer.
- Social network: [Sina Weibo](http://weibo.com/xiaolunwen) [GitHub](https://github.com/lunny) [Twitter](https://twitter.com/lunny)
### Fuxiaohei
- Team role: Front-end developer.
- Social network: [Sina Weibo](http://weibo.com/fuxiaohei) [GitHub](https://github.com/fuxiaohei)
### Slene
- Team role: Front and back-end developer.
- Social network: [Sina Weibo](http://weibo.com/slene) [GitHub](https://github.com/slene) [Twitter](https://twitter.com/slene)

1
docs/manual-en-US Submodule

@ -0,0 +1 @@
Subproject commit 8f77eedf2d6a187a7432e8887d1c4624abe08bc9

1
docs/manual-zh-CN Submodule

@ -0,0 +1 @@
Subproject commit 35220e001c82e7fb751aab775a3f2cdd0a045993

View File

@ -1,27 +0,0 @@
# 关于
本网站文档页面详细描述了 Xorm 的各个方面。
### 新手指导
如果您是首次了解 Xorm我们建议您先阅读 [快速入门](docs/intro/quick_start.md)。
### 其它资源
如果您无法找到相关问题的满意答案,可以在 [邮件列表 (xorm@googlegroups.com)](https://groups.google.com/forum/#!search/xorm) 中搜索。
### 寻求帮助
如果您遇到无法解决的问题,可以发送邮件到 [xorm@googlegroups.com](mailto:xorm@googlegroups.com) 提问。
### 问题提交
如果您在使用过程中发现 Xorm 有潜在的问题,请通过 [Xorm](https://github.com/go-xorm/xorm/issues) 上的问题列表提交。
### 完善文档
您可以通过派生 [文档项目](https://github.com/go-xorm/xorm/tree/master/docs)、编辑,然后提交合并请求。
### 网站源码
请移步 [Xorm Web](https://github.com/go-xorm/website)。

View File

@ -1,44 +0,0 @@
# 捐赠我们
<h4>
<b><font color="red">在您的支持与鼓励下Xorm 开发团队将会更加努力地开发出更好的产品!</font></b>
</h4>
<h4>
<b>支付宝捐赠</b>
</h4>
<img src="/img/alipay.png"/>
<h4>
<b>Paypal 捐赠</b>
<p>
<!--<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="encrypted" value="-----BEGIN PKCS7-----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-----END PKCS7-----
">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>-->
</p>
</h4>
### 您的捐赠将被用于:
- 持续和深入的开发
- 维护社区的运行稳定
- 租用更好的带宽
- 奖励团队的杰出贡献者
- 社区活动或讲座
### 捐赠列表(按照捐赠时间倒序)
| 捐赠时间 | 捐赠人 | 金额 | 联系方式 | 附言 |
| ---------------- |:---------:| --------:|:---------:| ----------------------- |
|2014-7-8 | Steven Wang | 100¥ | easykooc@gmail.com | xorm目前做得最好的orm for golang |
|2014-7-8 | 韩天峰 | 20¥ | apolov@vip.qq.com | xorm是Golang里最好用的DB库 |
|2014-7-8 | sunhongjian | 100¥ | shongjiang@gmail.com |支持开源,支持美好的事物! |
|2014-7-8 | Jimmy Kuu | 200¥ | jimmy.kuu@gmail.com |再接再厉,持续发展 |
|2014-7-8 | 张仲东 | 100¥ | GoCMS作者 |支持XORM!! |
|2014-7-8 | wangwei | 100¥ | iamjcww@gmail.com |鄙视楼下 |
|2014-7-8 | Jazz | 2¥ | 1002376560@qq.com |这个沙发必须抢 |

View File

@ -1,70 +0,0 @@
---
name: 自动映射
sort: 100
---
When a struct auto mapping to a database's table, the below table describes how they change to each other:
<table>
<tr>
<td>go type's kind
</td>
<td>value method</td>
<td>xorm type
</td>
</tr>
<tr>
<td>implemented Conversion</td>
<td>Conversion.ToDB / Conversion.FromDB</td>
<td>Text</td>
</tr>
<tr>
<td>int, int8, int16, int32, uint, uint8, uint16, uint32</td>
<td></td>
<td> Int </td>
</tr>
<tr>
<td>int64, uint64</td><td></td><td>BigInt</td>
</tr>
<tr><td>float32</td><td></td><td>Float</td>
</tr>
<tr><td>float64</td><td></td><td>Double</td>
</tr>
<tr><td>complex64, complex128</td>
<td>json.Marshal / json.UnMarshal</td>
<td>Varchar(64)</td>
</tr>
<tr>
<td>[]uint8</td><td></td><td>Blob</td>
</tr>
<tr>
<td>array, slice, map except []uint8</td>
<td>json.Marshal / json.UnMarshal</td>
<td>Text</td>
</tr>
<tr>
<td>bool</td><td>1 or 0</td><td>Bool</td>
</tr>
<tr>
<td>string</td><td></td><td>Varchar(255)</td>
</tr>
<tr>
<td>time.Time</td><td></td><td>DateTime</td>
</tr>
<tr>
<td>cascade struct</td><td>primary key field value</td><td>BigInt</td>
</tr>
<tr>
<tr>
<td>struct</td><td>json.Marshal / json.UnMarshal</td><td>Text</td>
</tr>
<tr>
<td>
Others
</td>
<td></td>
<td>
Text
</td>
</tr>
</table>

View File

@ -1,443 +0,0 @@
---
name: 标记字段类型
sort: 110
---
<table>
<tr>
<td>xorm
</td>
<td>mysql
</td>
<td>sqlite3
</td>
<td>postgres
</td>
<td>remark</td>
</tr>
<tr>
<td>BIT
</td>
<td>BIT
</td>
<td>INTEGER
</td>
<td>BIT
</td>
<td></td>
</tr>
<tr>
<td>TINYINT
</td>
<td>TINYINT
</td>
<td>INTEGER
</td>
<td>SMALLINT
</td>
<td></td>
</tr>
<tr>
<td>SMALLINT
</td>
<td>SMALLINT
</td>
<td>INTEGER
</td>
<td>SMALLINT
</td>
<td></td>
</tr>
<tr>
<td>MEDIUMINT
</td>
<td>MEDIUMINT
</td>
<td>INTEGER
</td>
<td>INTEGER
</td>
<td></td>
</tr>
<tr>
<td>INT
</td>
<td>INT
</td>
<td>INTEGER
</td>
<td>INTEGER
</td>
<td></td>
</tr>
<tr>
<td>INTEGER
</td>
<td>INTEGER
</td>
<td>INTEGER
</td>
<td>INTEGER
</td>
<td></td>
</tr>
<tr>
<td>BIGINT
</td>
<td>BIGINT
</td>
<td>INTEGER
</td>
<td>BIGINT
</td>
<td></td>
</tr>
<tr><td cols="5"></td></tr>
<tr>
<td>CHAR
</td>
<td>CHAR
</td>
<td>TEXT
</td>
<td>CHAR
</td>
<td></td>
</tr>
<tr>
<td>VARCHAR
</td>
<td>VARCHAR
</td>
<td>TEXT
</td>
<td>VARCHAR
</td>
<td></td>
</tr>
<tr>
<td>TINYTEXT
</td>
<td>TINYTEXT
</td>
<td>TEXT
</td>
<td>TEXT
</td>
<td></td>
</tr>
<tr>
<td>TEXT
</td>
<td>TEXT
</td>
<td>TEXT
</td>
<td>TEXT
</td>
<td></td>
</tr>
<tr>
<td>MEDIUMTEXT
</td>
<td>MEDIUMTEXT
</td>
<td>TEXT
</td>
<td>TEXT
</td>
<td></td>
</tr>
<tr>
<td>LONGTEXT
</td>
<td>LONGTEXT
</td>
<td>TEXT
</td>
<td>TEXT
</td>
<td></td>
</tr>
<tr><td cols="5"></td></tr>
<tr>
<td>BINARY
</td>
<td>BINARY
</td>
<td>BLOB
</td>
<td>BYTEA
</td>
<td></td>
</tr>
<tr>
<td>VARBINARY
</td>
<td>VARBINARY
</td>
<td>BLOB
</td>
<td>BYTEA
</td>
<td></td>
</tr>
<tr><td cols="5"></td></tr>
<tr>
<td>DATE
</td>
<td>DATE
</td>
<td>NUMERIC
</td>
<td>DATE
</td>
<td></td>
</tr>
<tr>
<td>DATETIME
</td>
<td>DATETIME
</td>
<td>NUMERIC
</td>
<td>TIMESTAMP
</td>
<td></td>
</tr>
<tr>
<td>TIME
</td>
<td>TIME
</td>
<td>NUMERIC
</td>
<td>TIME
</td>
<td></td>
</tr>
<tr>
<td>TIMESTAMP
</td>
<td>TIMESTAMP
</td>
<td>NUMERIC
</td>
<td>TIMESTAMP
</td>
<td></td>
</tr>
<tr>
<td>TIMESTAMPZ
</td>
<td>TEXT
</td>
<td>TEXT
</td>
<td>TIMESTAMP with zone
</td>
<td>timestamp with zone info</td>
</tr>
<tr><td cols="5"></td></tr>
<tr>
<td>REAL
</td>
<td>REAL
</td>
<td>REAL
</td>
<td>REAL
</td>
<td></td>
</tr>
<tr>
<td>FLOAT
</td>
<td>FLOAT
</td>
<td>REAL
</td>
<td>REAL
</td>
<td></td>
</tr>
<tr>
<td>DOUBLE
</td>
<td>DOUBLE
</td>
<td>REAL
</td>
<td>DOUBLE PRECISION
</td>
<td></td>
</tr>
<tr><td cols="5"></td></tr>
<tr>
<td>DECIMAL
</td>
<td>DECIMAL
</td>
<td>NUMERIC
</td>
<td>DECIMAL
</td>
<td></td>
</tr>
<tr>
<td>NUMERIC
</td>
<td>NUMERIC
</td>
<td>NUMERIC
</td>
<td>NUMERIC
</td>
<td></td>
</tr>
<tr><td cols="5"></td></tr>
<tr>
<td>TINYBLOB
</td>
<td>TINYBLOB
</td>
<td>BLOB
</td>
<td>BYTEA
</td>
<td></td>
</tr>
<tr>
<td>BLOB
</td>
<td>BLOB
</td>
<td>BLOB
</td>
<td>BYTEA
</td>
<td></td>
</tr>
<tr>
<td>MEDIUMBLOB
</td>
<td>MEDIUMBLOB
</td>
<td>BLOB
</td>
<td>BYTEA
</td>
<td></td>
</tr>
<tr>
<td>LONGBLOB
</td>
<td>LONGBLOB
</td>
<td>BLOB
</td>
<td>BYTEA
</td>
<td></td>
</tr>
<tr>
<td>BYTEA
</td>
<td>BLOB
</td>
<td>BLOB
</td>
<td>BYTEA
</td>
<td></td>
</tr>
<tr><td cols="5"></td></tr>
<tr>
<td>BOOL
</td>
<td>TINYINT
</td>
<td>INTEGER
</td>
<td>BOOLEAN
</td>
<td></td>
</tr>
<tr>
<td>SERIAL
</td>
<td>INT
</td>
<td>INTEGER
</td>
<td>SERIAL
</td>
<td>auto increment</td>
</tr>
<tr>
<td>BIGSERIAL
</td>
<td>BIGINT
</td>
<td>INTEGER
</td>
<td>BIGSERIAL
</td>
<td>auto increment</td>
</tr>
</table>

View File

@ -1,143 +0,0 @@
---
root: true
name: 简介
sort: 0
---
# xorm
[English](https://github.com/go-xorm/xorm/blob/master/README.md)
xorm是一个简单而强大的Go语言ORM库. 通过它可以使数据库操作非常简便。
[![Build Status](https://drone.io/github.com/go-xorm/tests/status.png)](https://drone.io/github.com/go-xorm/tests/latest) [![Go Walker](http://gowalker.org/api/v1/badge)](http://gowalker.org/github.com/go-xorm/xorm)
## 特性
* 支持Struct和数据库表之间的灵活映射并支持自动同步
* 事务支持
* 同时支持原始SQL语句和ORM操作的混合执行
* 使用连写来简化调用
* 支持使用Id, In, Where, Limit, Join, Having, Table, Sql, Cols等函数和结构体等方式作为条件
* 支持级联加载Struct
* 支持缓存
* 支持根据数据库自动生成xorm的结构体
* 支持记录版本(即乐观锁)
## 驱动支持
目前支持的Go数据库驱动和对应的数据库如下
* Mysql: [github.com/go-sql-driver/mysql](https://github.com/go-sql-driver/mysql)
* MyMysql: [github.com/ziutek/mymysql/godrv](https://github.com/ziutek/mymysql/godrv)
* SQLite: [github.com/mattn/go-sqlite3](https://github.com/mattn/go-sqlite3)
* Postgres: [github.com/lib/pq](https://github.com/lib/pq)
* MsSql: [github.com/denisenkom/go-mssqldb](https://github.com/denisenkom/go-mssqldb)
* MsSql: [github.com/lunny/godbc](https://github.com/lunny/godbc)
## 更新日志
* **v0.4.0 RC1**
新特性:
* 移动xorm cmd [github.com/go-xorm/cmd](github.com/go-xorm/cmd)
* 在重构一般DB操作核心库 [github.com/go-xorm/core](https://github.com/go-xorm/core)
* 移动测试github.com/复XORM/测试 [github.com/go-xorm/tests](github.com/go-xorm/tests)
改进:
* Prepared statement 缓存
* 添加 Incr API
* 指定时区位置
* **v0.3.2**
新特性:
* Add AllCols & MustCols function
* Add TableName for custom table name
Bug 修复:
* #46
* #51
* #53
* #89
* #86
* #92
* **v0.3.1**
新特性:
* 支持 MSSQL DB 通过 ODBC 驱动 ([github.com/lunny/godbc](https://github.com/lunny/godbc));
* 通过多个pk标记支持联合主键;
* 新增 Rows() API 用来遍历查询结果该函数提供了类似sql.Rows的相似用法可作为 Iterate() API 的可选替代;
* ORM 结构体现在允许内建类型的指针作为成员使得数据库为null成为可能
* Before 和 After 支持
改进:
* 允许 int/int32/int64/uint/uint32/uint64/string 作为主键类型
* 查询函数 Get()/Find()/Iterate() 在性能上的改进
[更多更新日志...](https://github.com/go-xorm/xorm/blob/master/docs/ChangelogCN.md)
## 安装
推荐使用 [gopm](https://github.com/gpmgo/gopm) 进行安装:
gopm get github.com/go-xorm/xorm
或者您也可以使用go工具进行安装
go get github.com/go-xorm/xorm
## 文档
* [快速开始](https://github.com/go-xorm/xorm/blob/master/docs/QuickStartCN.md)
* [GoWalker代码文档](http://gowalker.org/github.com/go-xorm/xorm)
* [Godoc代码文档](http://godoc.org/github.com/go-xorm/xorm)
## 案例
* [Gogs](http://try.gogits.org) - [github.com/gogits/gogs](http://github.com/gogits/gogs)
* [Gowalker](http://gowalker.org) - [github.com/Unknwon/gowalker](http://github.com/Unknwon/gowalker)
* [Gobuild.io](http://gobuild.io) - [github.com/shxsun/gobuild](http://github.com/shxsun/gobuild)
* [Sudo China](http://sudochina.com) - [github.com/insionng/toropress](http://github.com/insionng/toropress)
* [Godaily](http://godaily.org) - [github.com/govc/godaily](http://github.com/govc/godaily)
* [Very Hour](http://veryhour.com/)
* [GoCMS - github.com/zzboy/GoCMS](https://github.com/zzdboy/GoCMS)
* [GoBBS - gobbs.domolo.com](http://gobbs.domolo.com/)
## 讨论
请加入QQ群280360085 进行讨论。
## 贡献
如果您也想为Xorm贡献您的力量请查看 [CONTRIBUTING](https://github.com/go-xorm/xorm/blob/master/CONTRIBUTING.md)
## LICENSE
BSD License
[http://creativecommons.org/licenses/BSD/](http://creativecommons.org/licenses/BSD/)

View File

@ -1,13 +0,0 @@
---
name: 案例
sort: 90
---
* [Gowalker](http://gowalker.org),源代码 [github.com/Unknwon/gowalker](http://github.com/Unknwon/gowalker)
* [GoDaily Go语言学习网站](http://godaily.org),源代码 [github.com/govc/godaily](http://github.com/govc/godaily)
* [Sudochina](http://sudochina.com) 和对应的源代码[github.com/insionng/toropress](http://github.com/insionng/toropress)
* [VeryHour](http://veryhour.com)

View File

@ -1,58 +0,0 @@
---
name: 变更日志
sort: 1
---
## 更新日志
* **v0.4.0 RC1**
新特性:
* 移动xorm cmd [github.com/go-xorm/cmd](github.com/go-xorm/cmd)
* 在重构一般DB操作核心库 [github.com/go-xorm/core](https://github.com/go-xorm/core)
* 移动测试github.com/XORM/tests [github.com/go-xorm/tests](github.com/go-xorm/tests)
改进:
* Prepared statement 缓存
* 添加 Incr API
* 指定时区位置
* **v0.3.2**
改进:
* Add AllCols & MustCols function
* Add TableName for custom table name
Bug 修复:
* #46
* #51
* #53
* #89
* #86
* #92
* **v0.3.1**
新特性:
* 支持 MSSQL DB 通过 ODBC 驱动 ([github.com/lunny/godbc](https://github.com/lunny/godbc));
* 通过多个pk标记支持联合主键;
* 新增 Rows() API 用来遍历查询结果该函数提供了类似sql.Rows的相似用法可作为 Iterate() API 的可选替代;
* ORM 结构体现在允许内建类型的指针作为成员使得数据库为null成为可能
* Before 和 After 支持
改进:
* 允许 int/int32/int64/uint/uint32/uint64/string 作为主键类型
* 查询函数 Get()/Find()/Iterate() 在性能上的改进
* **v0.2.3** : 改善了文档提供了乐观锁支持添加了带时区时间字段支持Mapper现在分成表名Mapper和字段名Mapper同时实现了表或字段的自定义前缀后缀Insert方法的返回值含义从id, err更改为 affected, err请大家注意添加了UseBool 和 Distinct函数。
* **v0.2.2** : Postgres驱动新增了对lib/pq的支持新增了逐条遍历方法Iterate新增了SetMaxConns(go1.2+)支持修复了bug若干
* **v0.2.1** : 新增数据库反转工具当前支持go和c++代码的生成,详见 [Xorm Tool README](https://github.com/go-xorm/xorm/blob/master/xorm/README.md); 修复了一些bug.
* **v0.2.0** : 新增 [缓存](https://github.com/go-xorm/xorm/blob/master/docs/QuickStart.md#120)支持查询速度提升3-5倍 新增数据库表和Struct同名的映射方式 新增Sync同步表结构
* **v0.1.9** : 新增 postgres 和 mymysql 驱动支持; 在Postgres中支持原始SQL语句中使用 ` 和 ? 符号; 新增Cols, StoreEngine, Charset 函数SQL语句打印支持io.Writer接口默认打印到控制台新增更多的字段类型支持详见 [映射规则](https://github.com/go-xorm/xorm/blob/master/docs/QuickStartCn.md#21)删除废弃的MakeSession和Create函数。
* **v0.1.8** : 新增联合index联合unique支持请查看 [映射规则](https://github.com/go-xorm/xorm/blob/master/docs/QuickStartCn.md#21)。
* **v0.1.7** : 新增IConnectPool接口以及NoneConnectPool, SysConnectPool, SimpleConnectPool三种实现可以选择不使用连接池使用系统连接池和使用自带连接池三种实现默认为SysConnectPool即系统自带的连接池。同时支持自定义连接池。Engine新增Close方法在系统退出时应调用此方法。
* **v0.1.6** : 新增Conversion支持自定义类型到数据库类型的转换新增查询结构体自动检测匿名成员支持新增单向映射支持
* **v0.1.5** : 新增对多线程的支持新增Sql()函数支持任意sql语句的struct查询Get函数返回值变动MakeSession和Create函数被NewSession和NewEngine函数替代
* **v0.1.4** : Get函数和Find函数新增简单的级联载入功能对更多的数据库类型支持。
* **v0.1.3** : Find函数现在支持传入Slice或者Map当传入Map时key为id新增Table函数以为多表和临时表进行支持。
* **v0.1.2** : Insert函数支持混合struct和slice指针传入并根据数据库类型自动批量插入同时自动添加事务
* **v0.1.1** : 添加 Id, In 函数,改善 README 文档
* **v0.1.0** : 初始化工程

View File

@ -1,74 +0,0 @@
---
name: FAQ
sort: 100
---
* 怎么同时使用xorm的tag和json的tag
答:使用空格
```Go
type User struct {
Name string `json:"name" xorm:"name"`
}
```
* 我的struct里面包含bool类型为什么它不能作为条件也没法用Update更新
默认bool类型因为无法判断是否为空所以不会自动作为条件也不会作为Update的内容。可以使用UseBool函数也可以使用Cols函数
```Go
engine.Cols("bool_field").Update(&Struct{BoolField:true})
// UPDATE struct SET bool_field = true
```
* 我的struct里面包含float64和float32类型为什么用他们作为查询条件总是不正确
默认float32和float64映射到数据库中为float,real,double这几种类型这几种数据库类型数据库的实现一般都是非精确的。因此作为相等条件查询有可能不会返回正确的结果。如果一定要作为查询条件请将数据库中的类型定义为Numeric或者Decimal。
```Go
type account struct {
money float64 `xorm:"Numeric"`
}
```
* 为什么Update时Sqlite3返回的affected和其它数据库不一样
Sqlite3默认Update时返回的是update的查询条件的记录数条数不管记录是否真的有更新。而Mysql和Postgres默认情况下都是只返回记录中有字段改变的记录数。
* xorm有几种命名映射规则
目前支持SnakeMapper和SameMapper两种。SnakeMapper支持结构体和成员以驼峰式命名而数据库表和字段以下划线连接命名SameMapper支持结构体和数据库的命名保持一致的映射。
* xorm支持复合主键吗
支持。在定义时如果有多个字段标记了pk则这些字段自动成为复合主键顺序为在struct中出现的顺序。在使用Id方法时可以用`Id(xorm.PK{1, 2})`的方式来用。
* xorm如何使用Join
一般我们配合Join()和extends标记来进行比如我们要对两个表进行Join操作我们可以这样
type Userinfo struct {
Id int64
Name string
DetailId int64
}
type Userdetail struct {
Id int64
Gender int
}
type User struct {
Userinfo `xorm:"extends"`
Userdetail `xorm:"extends"`
}
var users = make([]User, 0)
err := engine.Table(&Userinfo{}).Join("LEFT", "userdetail", "userinfo.detail_id = userdetail.id").Find(&users)
请注意这里的Userinfo在User中的位置必须在Userdetail的前面因为他在join语句中的顺序在userdetail前面。如果顺序不对那么对于同名的列有可能会赋值出错。
当然如果Join语句比较复杂我们也可以直接用Sql函数
err := engine.Sql("select * from userinfo, userdetail where userinfo.detail_id = userdetail.id").Find(&users)

View File

@ -1,770 +0,0 @@
---
name: 快速开始
sort: 2
---
xorm 快速入门
=====
* [1.创建Orm引擎](#10)
* [2.定义表结构体](#20)
* [2.1.名称映射规则](#21)
* [2.2.前缀映射,后缀映射和缓存映射](#22)
* [2.3.使用Table和Tag改变名称映射](#23)
* [2.4.Column属性定义](#24)
* [2.5.Go与字段类型对应表](#25)
* [3.表结构操作](#30)
* [3.1 获取数据库信息](#31)
* [3.2 表操作](#32)
* [3.3 创建索引和唯一索引](#33)
* [3.4 同步数据库结构](#34)
* [4.插入数据](#50)
* [5.查询和统计数据](#60)
* [5.1.查询条件方法](#61)
* [5.2.临时开关方法](#62)
* [5.3.Get方法](#63)
* [5.4.Find方法](#64)
* [5.5.Iterate方法](#65)
* [5.6.Count方法](#66)
* [5.7.Rows方法](#67)
* [6.更新数据](#70)
* [6.1.乐观锁](#71)
* [7.删除数据](#80)
* [8.执行SQL查询](#90)
* [9.执行SQL命令](#100)
* [10.事务处理](#110)
* [11.缓存](#120)
* [12.事件](#125)
* [14.Examples](#140)
<a name="10" id="10"></a>
## 1.创建Orm引擎
在xorm里面可以同时存在多个Orm引擎一个Orm引擎称为Engine。因此在使用前必须调用NewEngine
```Go
import (
_ "github.com/go-sql-driver/mysql"
"github.com/go-xorm/xorm"
)
engine, err := xorm.NewEngine("mysql", "root:123@/test?charset=utf8")
defer engine.Close()
```
or
```Go
import (
_ "github.com/mattn/go-sqlite3"
"github.com/go-xorm/xorm"
)
engine, err = xorm.NewEngine("sqlite3", "./test.db")
defer engine.Close()
```
你可以创建一个或多个engine, 不过一般如果操作一个数据库只需要创建一个Engine即可。Engine支持在多GoRutine下使用。
xorm当前支持五种驱动四个数据库如下
* Mysql: [github.com/Go-SQL-Driver/MySQL](https://github.com/Go-SQL-Driver/MySQL)
* MyMysql: [github.com/ziutek/mymysql](https://github.com/ziutek/mymysql)
* SQLite: [github.com/mattn/go-sqlite3](https://github.com/mattn/go-sqlite3)
* Postgres: [github.com/lib/pq](https://github.com/lib/pq)
* MsSql: [github.com/lunny/godbc](https://githubcom/lunny/godbc)
NewEngine传入的参数和`sql.Open`传入的参数完全相同,因此,使用哪个驱动前,请查看此驱动中关于传入参数的说明文档。
在engine创建完成后可以进行一些设置
1.错误显示设置,默认如下均为`false`
* `engine.ShowSQL = true`则会在控制台打印出生成的SQL语句
* `engine.ShowDebug = true`,则会在控制台打印调试信息;
* `engine.ShowError = true`,则会在控制台打印错误信息;
* `engine.ShowWarn = true`,则会在控制台打印警告信息;
2.如果希望用其它方式记录,则可以`engine.Logger`赋值为一个`io.Writer`的实现。比如记录到Log文件则可以
```Go
f, err := os.Create("sql.log")
if err != nil {
println(err.Error())
return
}
engine.Logger = xorm.NewSimpleLogger(f)
```
3.engine内部支持连接池接口。
* 如果需要设置连接池的空闲数大小,可以使用`engine.SetMaxIdleConns()`来实现。
* 如果需要设置最大打开连接数,则可以使用`engine.SetMaxOpenConns()`来实现。
<a name="20" id="20"></a>
## 2.定义表结构体
xorm支持将一个struct映射为数据库中对应的一张表。映射规则如下
<a name="21" id="21"></a>
### 2.1.名称映射规则
名称映射规则主要负责结构体名称到表名和结构体field到表字段的名称映射。由xorm.IMapper接口的实现者来管理xorm内置了两种IMapper实现`SnakeMapper` 和 `SameMapper`。SnakeMapper支持struct为驼峰式命名表结构为下划线命名之间的转换SameMapper支持结构体名称和对应的表名称以及结构体field名称与对应的表字段名称相同的命名。
当前SnakeMapper为默认值如果需要改变时在engine创建完成后使用
```Go
engine.SetMapper(SameMapper{})
```
同时需要注意的是:
* 如果你使用了别的命名规则映射方案也可以自己实现一个IMapper。
* 表名称和字段名称的映射规则默认是相同的,当然也可以设置为不同,如:
```Go
engine.SetTableMapper(SameMapper{})
engine.SetColumnMapper(SnakeMapper{})
```
<a name="22" id="22"></a>
### 2.2.前缀映射,后缀映射和缓存映射
* 通过`engine.NewPrefixMapper(SnakeMapper{}, "prefix")`可以在SnakeMapper的基础上在命名中添加统一的前缀当然也可以把SnakeMapper{}换成SameMapper或者你自定义的Mapper。
* 通过`engine.NewSufffixMapper(SnakeMapper{}, "suffix")`可以在SnakeMapper的基础上在命名中添加统一的后缀当然也可以把SnakeMapper{}换成SameMapper或者你自定义的Mapper。
* 通过`eneing.NewCacheMapper(SnakeMapper{})`可以组合其它的映射规则,起到在内存中缓存曾经映射过的命名映射。
<a name="23" id="23"></a>
### 2.3.使用Table和Tag改变名称映射
如果所有的命名都是按照IMapper的映射来操作的那当然是最理想的。但是如果碰到某个表名或者某个字段名跟映射规则不匹配时我们就需要别的机制来改变。
* 如果struct拥有`TableName() string`的成员方法那么此方法的返回值即是该struct默认对应的数据库表名。
* 通过`engine.Table()`方法可以改变struct对应的数据库表的名称通过sturct中field对应的Tag中使用`xorm:"'column_name'"`可以使该field对应的Column名称为指定名称。这里使用两个单引号将Column名称括起来是为了防止名称冲突因为我们在Tag中还可以对这个Column进行更多的定义。如果名称不冲突的情况单引号也可以不使用。
<a name="23" id="23"></a>
### 2.4.Column属性定义
我们在field对应的Tag中对Column的一些属性进行定义定义的方法基本和我们写SQL定义表结构类似比如
```
type User struct {
Id int64
Name string `xorm:"varchar(25) not null unique 'usr_name'"`
}
```
对于不同的数据库系统数据类型其实是有些差异的。因此xorm中对数据类型有自己的定义基本的原则是尽量兼容各种数据库的字段类型具体的字段对应关系可以查看[字段类型对应表](https://github.com/go-xorm/xorm/blob/master/docs/COLUMNTYPE.md)。对于使用者,一般只要使用自己熟悉的数据库字段定义即可。
具体的映射规则如下另Tag中的关键字均不区分大小写字段名区分大小写
<table>
<tr>
<td>name</td><td>当前field对应的字段的名称可选如不写则自动根据field名字和转换规则命名如与其它关键字冲突请使用单引号括起来。</td>
</tr>
<tr>
<td>pk</td><td>是否是Primary Key如果在一个struct中有多个字段都使用了此标记则这多个字段构成了复合主键单主键当前支持int32,int,int64,uint32,uint,uint64,string这7种Go的数据类型复合主键支持这7种Go的数据类型的组合。</td>
</tr>
<tr>
<td>当前支持30多种字段类型详情参见 [字段类型](https://github.com/go-xorm/xorm/blob/master/docs/COLUMNTYPE.md)</td><td>字段类型</td>
</tr>
<tr>
<td>autoincr</td><td>是否是自增</td>
</tr>
<tr>
<td>[not ]null 或 notnull</td><td>是否可以为空</td>
</tr>
<tr>
<td>unique或unique(uniquename)</td><td>是否是唯一如不加括号则该字段不允许重复如加上括号则括号中为联合唯一索引的名字此时如果有另外一个或多个字段和本unique的uniquename相同则这些uniquename相同的字段组成联合唯一索引</td>
</tr>
<tr>
<td>index或index(indexname)</td><td>是否是索引如不加括号则该字段自身为索引如加上括号则括号中为联合索引的名字此时如果有另外一个或多个字段和本index的indexname相同则这些indexname相同的字段组成联合索引</td>
</tr>
<tr>
<td>extends</td><td>应用于一个匿名结构体之上,表示此匿名结构体的成员也映射到数据库中</td>
</tr>
<tr>
<td>-</td><td>这个Field将不进行字段映射</td>
</tr>
<tr>
<td>-></td><td>这个Field将只写入到数据库而不从数据库读取</td>
</tr>
<tr>
<td>&lt;-</td><td>这个Field将只从数据库读取而不写入到数据库</td>
</tr>
<tr>
<td>created</td><td>这个Field将在Insert时自动赋值为当前时间</td>
</tr>
<tr>
<td>updated</td><td>这个Field将在Insert或Update时自动赋值为当前时间</td>
</tr>
<tr>
<td>version</td><td>这个Field将会在insert时默认为1每次更新自动加1</td>
</tr>
<tr>
<td>default 0</td><td>设置默认值紧跟的内容如果是Varchar等需要加上单引号</td>
</tr>
</table>
另外有如下几条自动映射的规则:
- 1.如果field名称为`Id`而且类型为`int64`并且没有定义tag则会被xorm视为主键并且拥有自增属性。如果想用`Id`以外的名字或非int64类型做为主键名必须在对应的Tag上加上`xorm:"pk"`来定义主键,加上`xorm:"autoincr"`作为自增。这里需要注意的是,有些数据库并不允许非主键的自增属性。
- 2.string类型默认映射为varchar(255)如果需要不同的定义可以在tag中自定义
- 3.支持`type MyString string`等自定义的field支持Slice, Map等field成员这些成员默认存储为Text类型并且默认将使用Json格式来序列化和反序列化。也支持数据库字段类型为Blob类型如果是Blob类型则先使用Json格式序列化再转成[]byte格式。当然[]byte或者[]uint8默认为Blob类型并且都以二进制方式存储。具体参见 [go类型<->数据库类型对应表](https://github.com/go-xorm/xorm/blob/master/docs/AutoMap.md)
- 4.实现了Conversion接口的类型或者结构体将根据接口的转换方式在类型和数据库记录之间进行相互转换。
```Go
type Conversion interface {
FromDB([]byte) error
ToDB() ([]byte, error)
}
```
- 5.如果一个结构体包含一个Conversion的接口类型那么在获取数据时必须要预先设置一个实现此接口的struct或者struct的指针。此时可以在此struct中实现`BeforeSet(name string, cell xorm.Cell)`方法来进行预先给Conversion赋值。例子参见 [testConversion](https://github.com/go-xorm/tests/blob/master/base.go#L1826)
<a name="24" id="24"></a>
### 2.4.Go与字段类型对应表
如果不使用tag来定义field对应的数据库字段类型那么系统会自动给出一个默认的字段类型对应表如下
[go类型<->数据库类型对应表](https://github.com/go-xorm/xorm/blob/master/docs/AutoMap.md)
<a name="30" id="30"></a>
## 3.表结构操作
xorm提供了一些动态获取和修改表结构的方法。对于一般的应用很少动态修改表结构则只需调用Sync()同步下表结构即可。
<a name="31" id="31"></a>
## 3.1 获取数据库信息
* DBMetas()
xorm支持获取表结构信息通过调用`engine.DBMetas()`可以获取到所有的表,字段,索引的信息。
<a name="31" id="31"></a>
## 3.2.表操作
* CreateTables()
创建表使用`engine.CreateTables()`参数为一个或多个空的对应Struct的指针。同时可用的方法有Charset()和StoreEngine()如果对应的数据库支持这两个方法可以在创建表时指定表的字符编码和使用的引擎。当前仅支持Mysql数据库。
* IsTableEmpty()
判断表是否为空参数和CreateTables相同
* IsTableExist()
判断表是否存在
* DropTables()
删除表使用`engine.DropTables()`参数为一个或多个空的对应Struct的指针或者表的名字。如果为string传入则只删除对应的表如果传入的为Struct则删除表的同时还会删除对应的索引。
<a name="32" id="32"></a>
## 3.3.创建索引和唯一索引
* CreateIndexes
根据struct中的tag来创建索引
* CreateUniques
根据struct中的tag来创建唯一索引
<a name="34" id="34"></a>
## 3.4.同步数据库结构
同步能够部分智能的根据结构体的变动检测表结构的变动,并自动同步。目前能够实现:
* 1) 自动检测和创建表,这个检测是根据表的名字
* 2自动检测和新增表中的字段这个检测是根据字段名
* 3自动检测和创建索引和唯一索引这个检测是根据一个或多个字段名而不根据索引名称
调用方法如下:
```Go
err := engine.Sync(new(User))
```
<a name="50" id="50"></a>
## 4.插入数据
插入数据使用Insert方法Insert方法的参数可以是一个或多个Struct的指针一个或多个Struct的Slice的指针。
如果传入的是Slice并且当数据库支持批量插入时Insert会使用批量插入的方式进行插入。
* 插入一条数据
```Go
user := new(User)
user.Name = "myname"
affected, err := engine.Insert(user)
```
在插入单条数据成功后如果该结构体有自增字段则自增字段会被自动赋值为数据库中的id
```Go
fmt.Println(user.Id)
```
* 插入同一个表的多条数据
```Go
users := make([]User, 0)
users[0].Name = "name0"
...
affected, err := engine.Insert(&users)
```
* 使用指针Slice插入多条记录
```Go
users := make([]*User, 0)
users[0] = new(User)
users[0].Name = "name0"
...
affected, err := engine.Insert(&users)
```
* 插入不同表的一条记录
```Go
user := new(User)
user.Name = "myname"
question := new(Question)
question.Content = "whywhywhwy?"
affected, err := engine.Insert(user, question)
```
* 插入不同表的多条记录
```Go
users := make([]User, 0)
users[0].Name = "name0"
...
questions := make([]Question, 0)
questions[0].Content = "whywhywhwy?"
affected, err := engine.Insert(&users, &questions)
```
* 插入不同表的一条或多条记录
```Go
user := new(User)
user.Name = "myname"
...
questions := make([]Question, 0)
questions[0].Content = "whywhywhwy?"
affected, err := engine.Insert(user, &questions)
```
这里需要注意以下几点:
* 这里虽然支持同时插入,但这些插入并没有事务关系。因此有可能在中间插入出错后,后面的插入将不会继续。
* 多条插入会自动生成`Insert into table values (),(),()`的语句因此这样的语句有一个最大的记录数根据经验测算在150条左右。大于150条后生成的sql语句将太长可能导致执行失败。因此在插入大量数据时目前需要自行分割成每150条插入一次。
<a name="60" id="60"></a>
## 5.查询和统计数据
所有的查询条件不区分调用顺序但必须在调用GetFindCount, Iterate, Rows这几个函数之前调用。同时需要注意的一点是在调用的参数中如果采用默认的`SnakeMapper`所有的字符字段名均为映射后的数据库的字段名而不是field的名字。
<a name="61" id="61"></a>
### 5.1.查询条件方法
查询和统计主要使用`Get`, `Find`, `Count`, `Rows`, `Iterate`这几个方法。在进行查询时可以使用多个方法来形成查询条件,条件函数如下:
* Id(interface{})
传入一个PK字段的值作为查询条件如果是复合主键
`Id(xorm.PK{1, 2})`
传入的两个参数按照struct中pk标记字段出现的顺序赋值。
* Where(string, …interface{})
和SQL中Where语句中的条件基本相同作为条件
* And(string, …interface{})
和Where函数中的条件基本相同作为条件
* Or(string, …interface{})
和Where函数中的条件基本相同作为条件
* Sql(string, …interface{})
执行指定的Sql语句并把结果映射到结构体
* Asc(…string)
指定字段名正序排序
* Desc(…string)
指定字段名逆序排序
* OrderBy(string)
按照指定的顺序进行排序
* In(string, …interface{})
某字段在一些值中,这里需要注意必须是[]interface{}才可以展开由于Go语言的限制[]int64等均不可以展开。
* Cols(…string)
只查询或更新某些指定的字段默认是查询所有映射的字段或者根据Update的第一个参数来判断更新的字段。例如
```Go
engine.Cols("age", "name").Find(&users)
// SELECT age, name FROM user
engine.Cols("age", "name").Update(&user)
// UPDATE user SET age=? AND name=?
```
* AllCols()
查询或更新所有字段。
* MustCols(…string)
某些字段必须更新。
* Omit(...string)
和cols相反此函数指定排除某些指定的字段。注意此方法和Cols方法不可同时使用
```Go
engine.Omit("age").Update(&user)
// UPDATE user SET name = ? AND department = ?
```
* Distinct(…string)
按照参数中指定的字段归类结果
```Go
engine.Distinct("age", "department").Find(&users)
// SELECT DISTINCT age, department FROM user
```
注意当开启了缓存时此方法的调用将在当前查询中禁用缓存。因为缓存系统当前依赖Id而此时无法获得Id
* Table(nameOrStructPtr interface{})
传入表名称或者结构体指针如果传入的是结构体指针则按照IMapper的规则提取出表名
* Limit(int, …int)
限制获取的数目,第一个参数为条数,第二个参数为可选,表示开始位置
* Top(int)
相当于Limit(int, 0)
* Join(string,string,string)
第一个参数为连接类型当前支持INNER, LEFT OUTER, CROSS中的一个值第二个参数为表名第三个参数为连接条件
* GroupBy(string)
Groupby的参数字符串
* Having(string)
Having的参数字符串
<a name="62" id="62"></a>
### 5.2.临时开关方法
* NoAutoTime()
如果此方法执行则此次生成的语句中Created和Updated字段将不自动赋值为当前时间
* NoCache()
如果此方法执行,则此次生成的语句则在非缓存模式下执行
* UseBool(...string)
当从一个struct来生成查询条件或更新字段时xorm会判断struct的field是否为0,"",nil如果为以上则不当做查询条件或者更新内容。因为bool类型只有true和false两种值因此默认所有bool类型不会作为查询条件或者更新字段。如果可以使用此方法如果默认不传参数则所有的bool字段都将会被使用如果参数不为空则参数中指定的为字段名则这些字段对应的bool值将被使用。
* NoCascade()
是否自动关联查询field中的数据如果struct的field也是一个struct并且映射为某个Id则可以在查询时自动调用Get方法查询出对应的数据。
<a name="63" id="63"></a>
### 5.3.Get方法
查询单条数据使用`Get`方法在调用Get方法时需要传入一个对应结构体的指针同时结构体中的非空field自动成为查询的条件和前面的方法条件组合在一起查询。
如:
1) 根据Id来获得单条数据:
```Go
user := new(User)
has, err := engine.Id(id).Get(user)
// 复合主键的获取方法
// has, errr := engine.Id(xorm.PK{1,2}).Get(user)
```
2) 根据Where来获得单条数据
```Go
user := new(User)
has, err := engine.Where("name=?", "xlw").Get(user)
```
3) 根据user结构体中已有的非空数据来获得单条数据
```Go
user := &User{Id:1}
has, err := engine.Get(user)
```
或者其它条件
```Go
user := &User{Name:"xlw"}
has, err := engine.Get(user)
```
返回的结果为两个参数,一个`has`为该条记录是否存在,第二个参数`err`为是否有错误。不管err是否为nilhas都有可能为true或者false。
<a name="64" id="64"></a>
### 5.4.Find方法
查询多条数据使用`Find`方法Find方法的第一个参数为`slice`的指针或`Map`指针即为查询后返回的结果第二个参数可选为查询的条件struct的指针。
1) 传入Slice用于返回数据
```Go
everyone := make([]Userinfo, 0)
err := engine.Find(&everyone)
pEveryOne := make([]*Userinfo, 0)
err := engine.Find(&pEveryOne)
```
2) 传入Map用户返回数据map必须为`map[int64]Userinfo`的形式map的key为id因此对于复合主键无法使用这种方式。
```Go
users := make(map[int64]Userinfo)
err := engine.Find(&users)
pUsers := make(map[int64]*Userinfo)
err := engine.Find(&pUsers)
```
3) 也可以加入各种条件
```Go
users := make([]Userinfo, 0)
err := engine.Where("age > ? or name = ?", 30, "xlw").Limit(20, 10).Find(&users)
```
<a name="65" id="65"></a>
### 5.5.Iterate方法
Iterate方法提供逐条执行查询到的记录的方法他所能使用的条件和Find方法完全相同
```Go
err := engine.Where("age > ? or name=?)", 30, "xlw").Iterate(new(Userinfo), func(i int, bean interface{})error{
user := bean.(*Userinfo)
//do somthing use i and user
})
```
<a name="66" id="66"></a>
### 5.6.Count方法
统计数据使用`Count`方法Count方法的参数为struct的指针并且成为查询条件。
```Go
user := new(User)
total, err := engine.Where("id >?", 1).Count(user)
```
<a name="67" id="67"></a>
### 5.7.Rows方法
Rows方法和Iterate方法类似提供逐条执行查询到的记录的方法不过Rows更加灵活好用。
```Go
user := new(User)
rows, err := engine.Where("id >?", 1).Rows(user)
if err != nil {
}
defer rows.Close()
for rows.Next() {
err = rows.Scan(user)
//...
}
```
<a name="70" id="70"></a>
## 6.更新数据
更新数据使用`Update`方法Update方法的第一个参数为需要更新的内容可以为一个结构体指针或者一个Map[string]interface{}类型。当传入的为结构体指针时只有非空和0的field才会被作为更新的字段。当传入的为Map类型时key为数据库Column的名字value为要更新的内容。
```Go
user := new(User)
user.Name = "myname"
affected, err := engine.Id(id).Update(user)
```
这里需要注意Update会自动从user结构体中提取非0和非nil得值作为需要更新的内容因此如果需要更新一个值为0则此种方法将无法实现因此有两种选择
* 1.通过添加Cols函数指定需要更新结构体中的哪些值未指定的将不更新指定了的即使为0也会更新。
```Go
affected, err := engine.Id(id).Cols("age").Update(&user)
```
* 2.通过传入map[string]interface{}来进行更新但这时需要额外指定更新到哪个表因为通过map是无法自动检测更新哪个表的。
```Go
affected, err := engine.Table(new(User)).Id(id).Update(map[string]interface{}{"age":0})
```
<a name="71" id="71"></a>
### 6.1.乐观锁
要使用乐观锁需要使用version标记
type User struct {
Id int64
Name string
Version int `xorm:"version"`
}
在Insert时version标记的字段将会被设置为1在Update时Update的内容必须包含version原来的值。
```Go
var user User
engine.Id(1).Get(&user)
// SELECT * FROM user WHERE id = ?
engine.Id(1).Update(&user)
// UPDATE user SET ..., version = version + 1 WHERE id = ? AND version = ?
```
<a name="80" id="80"></a>
## 7.删除数据
删除数据`Delete`方法参数为struct的指针并且成为查询条件。
```Go
user := new(User)
affected, err := engine.Id(id).Delete(user)
```
`Delete`的返回值第一个参数为删除的记录数,第二个参数为错误。
注意当删除时如果user中包含有bool,float64或者float32类型有可能会使删除失败。具体请查看 <a href="#160">FAQ</a>
<a name="90" id="90"></a>
## 8.执行SQL查询
也可以直接执行一个SQL查询即Select命令。在Postgres中支持原始SQL语句中使用 ` 和 ? 符号。
```Go
sql := "select * from userinfo"
results, err := engine.Query(sql)
```
当调用`Query`时,第一个返回值`results`为`[]map[string][]byte`的形式。
<a name="100" id="100"></a>
## 9.执行SQL命令
也可以直接执行一个SQL命令即执行Insert Update Delete 等操作。此时不管数据库是何种类型,都可以使用 ` 和 ? 符号。
```Go
sql = "update `userinfo` set username=? where id=?"
res, err := engine.Exec(sql, "xiaolun", 1)
```
<a name="110" id="110"></a>
## 10.事务处理
当使用事务处理时需要创建Session对象。在进行事物处理时可以混用ORM方法和RAW方法如下代码所示
```Go
session := engine.NewSession()
defer session.Close()
// add Begin() before any action
err := session.Begin()
user1 := Userinfo{Username: "xiaoxiao", Departname: "dev", Alias: "lunny", Created: time.Now()}
_, err = session.Insert(&user1)
if err != nil {
session.Rollback()
return
}
user2 := Userinfo{Username: "yyy"}
_, err = session.Where("id = ?", 2).Update(&user2)
if err != nil {
session.Rollback()
return
}
_, err = session.Exec("delete from userinfo where username = ?", user2.Username)
if err != nil {
session.Rollback()
return
}
// add Commit() after all actions
err = session.Commit()
if err != nil {
return
}
```
* 注意如果您使用的是mysql数据库引擎为innodb事务才有效myisam引擎是不支持事务的。
<a name="120" id="120"></a>
## 11.缓存
xorm内置了一致性缓存支持不过默认并没有开启。要开启缓存需要在engine创建完后进行配置
启用一个全局的内存缓存
```Go
cacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), 1000)
engine.SetDefaultCacher(cacher)
```
上述代码采用了LRU算法的一个缓存缓存方式是存放到内存中缓存struct的记录数为1000条缓存针对的范围是所有具有主键的表没有主键的表中的数据将不会被缓存。
如果只想针对部分表,则:
```Go
cacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), 1000)
engine.MapCacher(&user, cacher)
```
如果要禁用某个表的缓存,则:
```Go
engine.MapCacher(&user, nil)
```
设置完之后,其它代码基本上就不需要改动了,缓存系统已经在后台运行。
当前实现了内存存储的CacheStore接口MemoryStore如果需要采用其它设备存储可以实现CacheStore接口。
不过需要特别注意不适用缓存或者需要手动编码的地方:
1. 当使用了`Distinct`,`Having`,`GroupBy`方法将不会使用缓存
2. 在`Get`或者`Find`时使用了`Cols`,`Omit`方法,则在开启缓存后此方法无效,系统仍旧会取出这个表中的所有字段。
3. 在使用Exec方法执行了方法之后可能会导致缓存与数据库不一致的地方。因此如果启用缓存尽量避免使用Exec。如果必须使用则需要在使用了Exec之后调用ClearCache手动做缓存清除的工作。比如
```Go
engine.Exec("update user set name = ? where id = ?", "xlw", 1)
engine.ClearCache(new(User))
```
缓存的实现原理如下图所示:
![cache design](https://raw.github.com/go-xorm/xorm/master/docs/cache_design.png)
<a name="125" id="125"></a>
## 12.事件
xorm支持两种方式的事件一种是在Struct中的特定方法来作为事件的方法一种是在执行语句的过程中执行事件。
在Struct中作为成员方法的事件如下
* BeforeInsert()
* BeforeUpdate()
* BeforeDelete()
* AfterInsert()
* AfterUpdate()
* AfterDelete()
在语句执行过程中的事件方法为:
* Before(beforeFunc interface{})
* After(afterFunc interface{})
其中beforeFunc和afterFunc的原型为func(bean interface{}).
<a name="140" id="140"></a>
## 14.Examples
请访问[https://github.com/go-xorm/xorm/tree/master/examples](https://github.com/go-xorm/xorm/tree/master/examples)

View File

@ -1,109 +0,0 @@
---
root: false
name: xorm 工具
sort: 3
---
# xorm 工具
xorm 是一组数据库操作命令行工具。
## 二进制安装
如果你安装了 [got](https://github.com/gobuild/got),你可以输入如下命令安装:
```
got go-xorm/cmd/xorm
```
或者你可以从 [gobuild](http://gobuild.io/download/github.com/lunny/got) 下载后解压到可执行路径。
## 源码安装
`go get github.com/go-xorm/cmd/xorm`
同时你需要安装如下依赖:
* github.com/go-xorm/xorm
* Mysql: [github.com/go-sql-driver/mysql](https://github.com/go-sql-driver/mysql)
* MyMysql: [github.com/ziutek/mymysql/godrv](https://github.com/ziutek/mymysql/godrv)
* Postgres: [github.com/lib/pq](https://github.com/lib/pq)
* SQLite: [github.com/mattn/go-sqlite3](https://github.com/mattn/go-sqlite3)
** 对于sqlite3的支持你需要自己进行编译 `go build -tags sqlite3` 因为sqlite3需要cgo的支持。
## 命令列表
有如下可用的命令:
* **reverse** 反转一个数据库结构,生成代码
* **shell** 通用的数据库操作客户端,可对数据库结构和数据操作
* **dump** Dump数据库中所有结构和数据到标准输出
* **source** 从标注输入中执行SQL文件
* **driver** 列出所有支持的数据库驱动
## reverse
Reverse command is a tool to convert your database struct to all kinds languages of structs or classes. After you installed the tool, you can type
`xorm help reverse`
to get help
example:
sqlite:
`xorm reverse sqite3 test.db templates/goxorm`
mysql:
`xorm reverse mysql root:@/xorm_test?charset=utf8 templates/goxorm`
mymysql:
`xorm reverse mymysql xorm_test2/root/ templates/goxorm`
postgres:
`xorm reverse postgres "dbname=xorm_test sslmode=disable" templates/goxorm`
will generated go files in `./model` directory
### Template and Config
Now, xorm tool supports go and c++ two languages and have go, goxorm, c++ three of default templates. In template directory, we can put a config file to control how to generating.
````
lang=go
genJson=1
```
lang must be go or c++ now.
genJson can be 1 or 0, if 1 then the struct will have json tag.
## Shell
Shell command provides a tool to operate database. For example, you can create table, alter table, insert data, delete data and etc.
`xorm shell sqlite3 test.db` will connect to the sqlite3 database and you can type `help` to list all the shell commands.
## Dump
Dump command provides a tool to dump all database structs and data as SQL to your standard output.
`xorm dump sqlite3 test.db` could dump sqlite3 database test.db to standard output. If you want to save to file, just
type `xorm dump sqlite3 test.db > test.sql`.
## Source
`xorm source sqlite3 test.db < test.sql` will execute sql file on the test.db.
## Driver
List all supported drivers since default build will not include sqlite3.
## LICENSE
BSD License
[http://creativecommons.org/licenses/BSD/](http://creativecommons.org/licenses/BSD/)

View File

@ -1,22 +0,0 @@
# 开发者团队
### 无闻
- 团队角色:项目管理员,后端开发者
- 社交网络:[新浪微博](http://weibo.com/Obahua) [GitHub](https://github.com/Unknwon) [Twitter](https://twitter.com/joe2010xtmf) [Google+](https://plus.google.com/u/0/+JiahuaChen)
### Lunny
- 团队角色:后端 Git 和数据库部分开发者
- 社交网络:[新浪微博](http://weibo.com/xiaolunwen) [GitHub](https://github.com/lunny) [Twitter](https://twitter.com/lunny)
### 傅小黑
- 团队角色:前端开发者
- 社交网络:[新浪微博](http://weibo.com/fuxiaohei) [GitHub](https://github.com/fuxiaohei)
### Slene
- 团队角色:前、后端开发者
- 社交网络:[新浪微博](http://weibo.com/slene) [GitHub](https://github.com/slene) [Twitter](https://twitter.com/slene)