You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

503 lines
14 KiB

  1. # xorm
  2. [中文](https://gitea.com/xorm/xorm/src/branch/master/README_CN.md)
  3. Xorm is a simple and powerful ORM for Go.
  4. [![Build Status](https://drone.gitea.com/api/badges/xorm/xorm/status.svg)](https://drone.gitea.com/xorm/xorm) [![](http://gocover.io/_badge/xorm.io/xorm)](https://gocover.io/xorm.io/xorm)
  5. [![](https://goreportcard.com/badge/xorm.io/xorm)](https://goreportcard.com/report/xorm.io/xorm)
  6. [![Join the chat at https://img.shields.io/discord/323460943201959939.svg](https://img.shields.io/discord/323460943201959939.svg)](https://discord.gg/HuR2CF3)
  7. ## Features
  8. * Struct <-> Table Mapping Support
  9. * Chainable APIs
  10. * Transaction Support
  11. * Both ORM and raw SQL operation Support
  12. * Sync database schema Support
  13. * Query Cache speed up
  14. * Database Reverse support, See [Xorm Tool README](https://github.com/go-xorm/cmd/blob/master/README.md)
  15. * Simple cascade loading support
  16. * Optimistic Locking support
  17. * SQL Builder support via [xorm.io/builder](https://xorm.io/builder)
  18. * Automatical Read/Write seperatelly
  19. * Postgres schema support
  20. * Context Cache support
  21. ## Drivers Support
  22. Drivers for Go's sql package which currently support database/sql includes:
  23. * Mysql: [github.com/go-sql-driver/mysql](https://github.com/go-sql-driver/mysql)
  24. * MyMysql: [github.com/ziutek/mymysql/godrv](https://github.com/ziutek/mymysql/tree/master/godrv)
  25. * Postgres: [github.com/lib/pq](https://github.com/lib/pq)
  26. * Tidb: [github.com/pingcap/tidb](https://github.com/pingcap/tidb)
  27. * SQLite: [github.com/mattn/go-sqlite3](https://github.com/mattn/go-sqlite3)
  28. * MsSql: [github.com/denisenkom/go-mssqldb](https://github.com/denisenkom/go-mssqldb)
  29. * Oracle: [github.com/mattn/go-oci8](https://github.com/mattn/go-oci8) (experiment)
  30. ## Installation
  31. go get xorm.io/xorm
  32. ## Documents
  33. * [Manual](http://xorm.io/docs)
  34. * [GoDoc](http://godoc.org/xorm.io/xorm)
  35. ## Quick Start
  36. * Create Engine
  37. ```Go
  38. engine, err := xorm.NewEngine(driverName, dataSourceName)
  39. ```
  40. * Define a struct and Sync2 table struct to database
  41. ```Go
  42. type User struct {
  43. Id int64
  44. Name string
  45. Salt string
  46. Age int
  47. Passwd string `xorm:"varchar(200)"`
  48. Created time.Time `xorm:"created"`
  49. Updated time.Time `xorm:"updated"`
  50. }
  51. err := engine.Sync2(new(User))
  52. ```
  53. * Create Engine Group
  54. ```Go
  55. dataSourceNameSlice := []string{masterDataSourceName, slave1DataSourceName, slave2DataSourceName}
  56. engineGroup, err := xorm.NewEngineGroup(driverName, dataSourceNameSlice)
  57. ```
  58. ```Go
  59. masterEngine, err := xorm.NewEngine(driverName, masterDataSourceName)
  60. slave1Engine, err := xorm.NewEngine(driverName, slave1DataSourceName)
  61. slave2Engine, err := xorm.NewEngine(driverName, slave2DataSourceName)
  62. engineGroup, err := xorm.NewEngineGroup(masterEngine, []*Engine{slave1Engine, slave2Engine})
  63. ```
  64. Then all place where `engine` you can just use `engineGroup`.
  65. * `Query` runs a SQL string, the returned results is `[]map[string][]byte`, `QueryString` returns `[]map[string]string`, `QueryInterface` returns `[]map[string]interface{}`.
  66. ```Go
  67. results, err := engine.Query("select * from user")
  68. results, err := engine.Where("a = 1").Query()
  69. results, err := engine.QueryString("select * from user")
  70. results, err := engine.Where("a = 1").QueryString()
  71. results, err := engine.QueryInterface("select * from user")
  72. results, err := engine.Where("a = 1").QueryInterface()
  73. ```
  74. * `Exec` runs a SQL string, it returns `affected` and `error`
  75. ```Go
  76. affected, err := engine.Exec("update user set age = ? where name = ?", age, name)
  77. ```
  78. * `Insert` one or multiple records to database
  79. ```Go
  80. affected, err := engine.Insert(&user)
  81. // INSERT INTO struct () values ()
  82. affected, err := engine.Insert(&user1, &user2)
  83. // INSERT INTO struct1 () values ()
  84. // INSERT INTO struct2 () values ()
  85. affected, err := engine.Insert(&users)
  86. // INSERT INTO struct () values (),(),()
  87. affected, err := engine.Insert(&user1, &users)
  88. // INSERT INTO struct1 () values ()
  89. // INSERT INTO struct2 () values (),(),()
  90. ```
  91. * `Get` query one record from database
  92. ```Go
  93. has, err := engine.Get(&user)
  94. // SELECT * FROM user LIMIT 1
  95. has, err := engine.Where("name = ?", name).Desc("id").Get(&user)
  96. // SELECT * FROM user WHERE name = ? ORDER BY id DESC LIMIT 1
  97. var name string
  98. has, err := engine.Table(&user).Where("id = ?", id).Cols("name").Get(&name)
  99. // SELECT name FROM user WHERE id = ?
  100. var id int64
  101. has, err := engine.Table(&user).Where("name = ?", name).Cols("id").Get(&id)
  102. has, err := engine.SQL("select id from user").Get(&id)
  103. // SELECT id FROM user WHERE name = ?
  104. var valuesMap = make(map[string]string)
  105. has, err := engine.Table(&user).Where("id = ?", id).Get(&valuesMap)
  106. // SELECT * FROM user WHERE id = ?
  107. var valuesSlice = make([]interface{}, len(cols))
  108. has, err := engine.Table(&user).Where("id = ?", id).Cols(cols...).Get(&valuesSlice)
  109. // SELECT col1, col2, col3 FROM user WHERE id = ?
  110. ```
  111. * `Exist` check if one record exist on table
  112. ```Go
  113. has, err := testEngine.Exist(new(RecordExist))
  114. // SELECT * FROM record_exist LIMIT 1
  115. has, err = testEngine.Exist(&RecordExist{
  116. Name: "test1",
  117. })
  118. // SELECT * FROM record_exist WHERE name = ? LIMIT 1
  119. has, err = testEngine.Where("name = ?", "test1").Exist(&RecordExist{})
  120. // SELECT * FROM record_exist WHERE name = ? LIMIT 1
  121. has, err = testEngine.SQL("select * from record_exist where name = ?", "test1").Exist()
  122. // select * from record_exist where name = ?
  123. has, err = testEngine.Table("record_exist").Exist()
  124. // SELECT * FROM record_exist LIMIT 1
  125. has, err = testEngine.Table("record_exist").Where("name = ?", "test1").Exist()
  126. // SELECT * FROM record_exist WHERE name = ? LIMIT 1
  127. ```
  128. * `Find` query multiple records from database, also you can use join and extends
  129. ```Go
  130. var users []User
  131. err := engine.Where("name = ?", name).And("age > 10").Limit(10, 0).Find(&users)
  132. // SELECT * FROM user WHERE name = ? AND age > 10 limit 10 offset 0
  133. type Detail struct {
  134. Id int64
  135. UserId int64 `xorm:"index"`
  136. }
  137. type UserDetail struct {
  138. User `xorm:"extends"`
  139. Detail `xorm:"extends"`
  140. }
  141. var users []UserDetail
  142. err := engine.Table("user").Select("user.*, detail.*").
  143. Join("INNER", "detail", "detail.user_id = user.id").
  144. Where("user.name = ?", name).Limit(10, 0).
  145. Find(&users)
  146. // SELECT user.*, detail.* FROM user INNER JOIN detail WHERE user.name = ? limit 10 offset 0
  147. ```
  148. * `Iterate` and `Rows` query multiple records and record by record handle, there are two methods Iterate and Rows
  149. ```Go
  150. err := engine.Iterate(&User{Name:name}, func(idx int, bean interface{}) error {
  151. user := bean.(*User)
  152. return nil
  153. })
  154. // SELECT * FROM user
  155. err := engine.BufferSize(100).Iterate(&User{Name:name}, func(idx int, bean interface{}) error {
  156. user := bean.(*User)
  157. return nil
  158. })
  159. // SELECT * FROM user Limit 0, 100
  160. // SELECT * FROM user Limit 101, 100
  161. rows, err := engine.Rows(&User{Name:name})
  162. // SELECT * FROM user
  163. defer rows.Close()
  164. bean := new(Struct)
  165. for rows.Next() {
  166. err = rows.Scan(bean)
  167. }
  168. ```
  169. * `Update` update one or more records, default will update non-empty and non-zero fields except when you use Cols, AllCols and so on.
  170. ```Go
  171. affected, err := engine.ID(1).Update(&user)
  172. // UPDATE user SET ... Where id = ?
  173. affected, err := engine.Update(&user, &User{Name:name})
  174. // UPDATE user SET ... Where name = ?
  175. var ids = []int64{1, 2, 3}
  176. affected, err := engine.In("id", ids).Update(&user)
  177. // UPDATE user SET ... Where id IN (?, ?, ?)
  178. // force update indicated columns by Cols
  179. affected, err := engine.ID(1).Cols("age").Update(&User{Name:name, Age: 12})
  180. // UPDATE user SET age = ?, updated=? Where id = ?
  181. // force NOT update indicated columns by Omit
  182. affected, err := engine.ID(1).Omit("name").Update(&User{Name:name, Age: 12})
  183. // UPDATE user SET age = ?, updated=? Where id = ?
  184. affected, err := engine.ID(1).AllCols().Update(&user)
  185. // UPDATE user SET name=?,age=?,salt=?,passwd=?,updated=? Where id = ?
  186. ```
  187. * `Delete` delete one or more records, Delete MUST have condition
  188. ```Go
  189. affected, err := engine.Where(...).Delete(&user)
  190. // DELETE FROM user Where ...
  191. affected, err := engine.ID(2).Delete(&user)
  192. // DELETE FROM user Where id = ?
  193. ```
  194. * `Count` count records
  195. ```Go
  196. counts, err := engine.Count(&user)
  197. // SELECT count(*) AS total FROM user
  198. ```
  199. * `FindAndCount` combines function `Find` with `Count` which is usually used in query by page
  200. ```Go
  201. var users []User
  202. counts, err := engine.FindAndCount(&users)
  203. ```
  204. * `Sum` sum functions
  205. ```Go
  206. agesFloat64, err := engine.Sum(&user, "age")
  207. // SELECT sum(age) AS total FROM user
  208. agesInt64, err := engine.SumInt(&user, "age")
  209. // SELECT sum(age) AS total FROM user
  210. sumFloat64Slice, err := engine.Sums(&user, "age", "score")
  211. // SELECT sum(age), sum(score) FROM user
  212. sumInt64Slice, err := engine.SumsInt(&user, "age", "score")
  213. // SELECT sum(age), sum(score) FROM user
  214. ```
  215. * Query conditions builder
  216. ```Go
  217. err := engine.Where(builder.NotIn("a", 1, 2).And(builder.In("b", "c", "d", "e"))).Find(&users)
  218. // SELECT id, name ... FROM user WHERE a NOT IN (?, ?) AND b IN (?, ?, ?)
  219. ```
  220. * Multiple operations in one go routine, no transation here but resue session memory
  221. ```Go
  222. session := engine.NewSession()
  223. defer session.Close()
  224. user1 := Userinfo{Username: "xiaoxiao", Departname: "dev", Alias: "lunny", Created: time.Now()}
  225. if _, err := session.Insert(&user1); err != nil {
  226. return err
  227. }
  228. user2 := Userinfo{Username: "yyy"}
  229. if _, err := session.Where("id = ?", 2).Update(&user2); err != nil {
  230. return err
  231. }
  232. if _, err := session.Exec("delete from userinfo where username = ?", user2.Username); err != nil {
  233. return err
  234. }
  235. return nil
  236. ```
  237. * Transation should be on one go routine. There is transaction and resue session memory
  238. ```Go
  239. session := engine.NewSession()
  240. defer session.Close()
  241. // add Begin() before any action
  242. if err := session.Begin(); err != nil {
  243. // if returned then will rollback automatically
  244. return err
  245. }
  246. user1 := Userinfo{Username: "xiaoxiao", Departname: "dev", Alias: "lunny", Created: time.Now()}
  247. if _, err := session.Insert(&user1); err != nil {
  248. return err
  249. }
  250. user2 := Userinfo{Username: "yyy"}
  251. if _, err := session.Where("id = ?", 2).Update(&user2); err != nil {
  252. return err
  253. }
  254. if _, err := session.Exec("delete from userinfo where username = ?", user2.Username); err != nil {
  255. return err
  256. }
  257. // add Commit() after all actions
  258. return session.Commit()
  259. ```
  260. * Or you can use `Transaction` to replace above codes.
  261. ```Go
  262. res, err := engine.Transaction(func(session *xorm.Session) (interface{}, error) {
  263. user1 := Userinfo{Username: "xiaoxiao", Departname: "dev", Alias: "lunny", Created: time.Now()}
  264. if _, err := session.Insert(&user1); err != nil {
  265. return nil, err
  266. }
  267. user2 := Userinfo{Username: "yyy"}
  268. if _, err := session.Where("id = ?", 2).Update(&user2); err != nil {
  269. return nil, err
  270. }
  271. if _, err := session.Exec("delete from userinfo where username = ?", user2.Username); err != nil {
  272. return nil, err
  273. }
  274. return nil, nil
  275. })
  276. ```
  277. * Context Cache, if enabled, current query result will be cached on session and be used by next same statement on the same session.
  278. ```Go
  279. sess := engine.NewSession()
  280. defer sess.Close()
  281. var context = xorm.NewMemoryContextCache()
  282. var c2 ContextGetStruct
  283. has, err := sess.ID(1).ContextCache(context).Get(&c2)
  284. assert.NoError(t, err)
  285. assert.True(t, has)
  286. assert.EqualValues(t, 1, c2.Id)
  287. assert.EqualValues(t, "1", c2.Name)
  288. sql, args := sess.LastSQL()
  289. assert.True(t, len(sql) > 0)
  290. assert.True(t, len(args) > 0)
  291. var c3 ContextGetStruct
  292. has, err = sess.ID(1).ContextCache(context).Get(&c3)
  293. assert.NoError(t, err)
  294. assert.True(t, has)
  295. assert.EqualValues(t, 1, c3.Id)
  296. assert.EqualValues(t, "1", c3.Name)
  297. sql, args = sess.LastSQL()
  298. assert.True(t, len(sql) == 0)
  299. assert.True(t, len(args) == 0)
  300. ```
  301. ## Contributing
  302. If you want to pull request, please see [CONTRIBUTING](https://gitea.com/xorm/xorm/src/branch/master/CONTRIBUTING.md). And we also provide [Xorm on Google Groups](https://groups.google.com/forum/#!forum/xorm) to discuss.
  303. ## Credits
  304. ### Contributors
  305. This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)].
  306. <a href="graphs/contributors"><img src="https://opencollective.com/xorm/contributors.svg?width=890&button=false" /></a>
  307. ### Backers
  308. Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/xorm#backer)]
  309. <a href="https://opencollective.com/xorm#backers" target="_blank"><img src="https://opencollective.com/xorm/backers.svg?width=890"></a>
  310. ### Sponsors
  311. Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/xorm#sponsor)]
  312. ## Changelog
  313. * **v0.7.0**
  314. * Some bugs fixed
  315. * **v0.6.6**
  316. * Some bugs fixed
  317. * **v0.6.5**
  318. * Postgres schema support
  319. * vgo support
  320. * Add FindAndCount
  321. * Database special params support via NewEngineWithParams
  322. * Some bugs fixed
  323. * **v0.6.4**
  324. * Automatical Read/Write seperatelly
  325. * Query/QueryString/QueryInterface and action with Where/And
  326. * Get support non-struct variables
  327. * BufferSize on Iterate
  328. * fix some other bugs.
  329. [More changes ...](https://github.com/go-xorm/manual-en-US/tree/master/chapter-16)
  330. ## Cases
  331. * [studygolang](http://studygolang.com/) - [github.com/studygolang/studygolang](https://github.com/studygolang/studygolang)
  332. * [Gitea](http://gitea.io) - [github.com/go-gitea/gitea](http://github.com/go-gitea/gitea)
  333. * [Gogs](http://try.gogits.org) - [github.com/gogits/gogs](http://github.com/gogits/gogs)
  334. * [grafana](https://grafana.com/) - [github.com/grafana/grafana](http://github.com/grafana/grafana)
  335. * [github.com/m3ng9i/qreader](https://github.com/m3ng9i/qreader)
  336. * [Wego](http://github.com/go-tango/wego)
  337. * [Docker.cn](https://docker.cn/)
  338. * [Xorm Adapter](https://github.com/casbin/xorm-adapter) for [Casbin](https://github.com/casbin/casbin) - [github.com/casbin/xorm-adapter](https://github.com/casbin/xorm-adapter)
  339. * [Gorevel](http://gorevel.cn/) - [github.com/goofcc/gorevel](http://github.com/goofcc/gorevel)
  340. * [Gowalker](http://gowalker.org) - [github.com/Unknwon/gowalker](http://github.com/Unknwon/gowalker)
  341. * [Gobuild.io](http://gobuild.io) - [github.com/shxsun/gobuild](http://github.com/shxsun/gobuild)
  342. * [Sudo China](http://sudochina.com) - [github.com/insionng/toropress](http://github.com/insionng/toropress)
  343. * [Godaily](http://godaily.org) - [github.com/govc/godaily](http://github.com/govc/godaily)
  344. * [YouGam](http://www.yougam.com/)
  345. * [GoCMS - github.com/zzboy/GoCMS](https://github.com/zzdboy/GoCMS)
  346. * [GoBBS - gobbs.domolo.com](http://gobbs.domolo.com/)
  347. * [go-blog](http://wangcheng.me) - [github.com/easykoo/go-blog](https://github.com/easykoo/go-blog)
  348. ## LICENSE
  349. BSD License [http://creativecommons.org/licenses/BSD/](http://creativecommons.org/licenses/BSD/)