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

README.md 15 kB

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