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.

context.go 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package db
  4. import (
  5. "context"
  6. "database/sql"
  7. "xorm.io/builder"
  8. "xorm.io/xorm"
  9. )
  10. // DefaultContext is the default context to run xorm queries in
  11. // will be overwritten by Init with HammerContext
  12. var DefaultContext context.Context
  13. // contextKey is a value for use with context.WithValue.
  14. type contextKey struct {
  15. name string
  16. }
  17. // enginedContextKey is a context key. It is used with context.Value() to get the current Engined for the context
  18. var (
  19. enginedContextKey = &contextKey{"engined"}
  20. _ Engined = &Context{}
  21. )
  22. // Context represents a db context
  23. type Context struct {
  24. context.Context
  25. e Engine
  26. transaction bool
  27. }
  28. func newContext(ctx context.Context, e Engine, transaction bool) *Context {
  29. return &Context{
  30. Context: ctx,
  31. e: e,
  32. transaction: transaction,
  33. }
  34. }
  35. // InTransaction if context is in a transaction
  36. func (ctx *Context) InTransaction() bool {
  37. return ctx.transaction
  38. }
  39. // Engine returns db engine
  40. func (ctx *Context) Engine() Engine {
  41. return ctx.e
  42. }
  43. // Value shadows Value for context.Context but allows us to get ourselves and an Engined object
  44. func (ctx *Context) Value(key any) any {
  45. if key == enginedContextKey {
  46. return ctx
  47. }
  48. return ctx.Context.Value(key)
  49. }
  50. // WithContext returns this engine tied to this context
  51. func (ctx *Context) WithContext(other context.Context) *Context {
  52. return newContext(ctx, ctx.e.Context(other), ctx.transaction)
  53. }
  54. // Engined structs provide an Engine
  55. type Engined interface {
  56. Engine() Engine
  57. }
  58. // GetEngine will get a db Engine from this context or return an Engine restricted to this context
  59. func GetEngine(ctx context.Context) Engine {
  60. if e := getEngine(ctx); e != nil {
  61. return e
  62. }
  63. return x.Context(ctx)
  64. }
  65. // getEngine will get a db Engine from this context or return nil
  66. func getEngine(ctx context.Context) Engine {
  67. if engined, ok := ctx.(Engined); ok {
  68. return engined.Engine()
  69. }
  70. enginedInterface := ctx.Value(enginedContextKey)
  71. if enginedInterface != nil {
  72. return enginedInterface.(Engined).Engine()
  73. }
  74. return nil
  75. }
  76. // Committer represents an interface to Commit or Close the Context
  77. type Committer interface {
  78. Commit() error
  79. Close() error
  80. }
  81. // halfCommitter is a wrapper of Committer.
  82. // It can be closed early, but can't be committed early, it is useful for reusing a transaction.
  83. type halfCommitter struct {
  84. committer Committer
  85. committed bool
  86. }
  87. func (c *halfCommitter) Commit() error {
  88. c.committed = true
  89. // should do nothing, and the parent committer will commit later
  90. return nil
  91. }
  92. func (c *halfCommitter) Close() error {
  93. if c.committed {
  94. // it's "commit and close", should do nothing, and the parent committer will commit later
  95. return nil
  96. }
  97. // it's "rollback and close", let the parent committer rollback right now
  98. return c.committer.Close()
  99. }
  100. // TxContext represents a transaction Context,
  101. // it will reuse the existing transaction in the parent context or create a new one.
  102. // Some tips to use:
  103. //
  104. // 1 It's always recommended to use `WithTx` in new code instead of `TxContext`, since `WithTx` will handle the transaction automatically.
  105. // 2. To maintain the old code which uses `TxContext`:
  106. // a. Always call `Close()` before returning regardless of whether `Commit()` has been called.
  107. // b. Always call `Commit()` before returning if there are no errors, even if the code did not change any data.
  108. // c. Remember the `Committer` will be a halfCommitter when a transaction is being reused.
  109. // So calling `Commit()` will do nothing, but calling `Close()` without calling `Commit()` will rollback the transaction.
  110. // And all operations submitted by the caller stack will be rollbacked as well, not only the operations in the current function.
  111. // d. It doesn't mean rollback is forbidden, but always do it only when there is an error, and you do want to rollback.
  112. func TxContext(parentCtx context.Context) (*Context, Committer, error) {
  113. if sess, ok := inTransaction(parentCtx); ok {
  114. return newContext(parentCtx, sess, true), &halfCommitter{committer: sess}, nil
  115. }
  116. sess := x.NewSession()
  117. if err := sess.Begin(); err != nil {
  118. sess.Close()
  119. return nil, nil, err
  120. }
  121. return newContext(DefaultContext, sess, true), sess, nil
  122. }
  123. // WithTx represents executing database operations on a transaction, if the transaction exist,
  124. // this function will reuse it otherwise will create a new one and close it when finished.
  125. func WithTx(parentCtx context.Context, f func(ctx context.Context) error) error {
  126. if sess, ok := inTransaction(parentCtx); ok {
  127. err := f(newContext(parentCtx, sess, true))
  128. if err != nil {
  129. // rollback immediately, in case the caller ignores returned error and tries to commit the transaction.
  130. _ = sess.Close()
  131. }
  132. return err
  133. }
  134. return txWithNoCheck(parentCtx, f)
  135. }
  136. func txWithNoCheck(parentCtx context.Context, f func(ctx context.Context) error) error {
  137. sess := x.NewSession()
  138. defer sess.Close()
  139. if err := sess.Begin(); err != nil {
  140. return err
  141. }
  142. if err := f(newContext(parentCtx, sess, true)); err != nil {
  143. return err
  144. }
  145. return sess.Commit()
  146. }
  147. // Insert inserts records into database
  148. func Insert(ctx context.Context, beans ...any) error {
  149. _, err := GetEngine(ctx).Insert(beans...)
  150. return err
  151. }
  152. // Exec executes a sql with args
  153. func Exec(ctx context.Context, sqlAndArgs ...any) (sql.Result, error) {
  154. return GetEngine(ctx).Exec(sqlAndArgs...)
  155. }
  156. // GetByBean filled empty fields of the bean according non-empty fields to query in database.
  157. func GetByBean(ctx context.Context, bean any) (bool, error) {
  158. return GetEngine(ctx).Get(bean)
  159. }
  160. func Exist[T any](ctx context.Context, cond builder.Cond) (bool, error) {
  161. if !cond.IsValid() {
  162. return false, ErrConditionRequired{}
  163. }
  164. var bean T
  165. return GetEngine(ctx).Where(cond).NoAutoCondition().Exist(&bean)
  166. }
  167. // DeleteByBean deletes all records according non-empty fields of the bean as conditions.
  168. func DeleteByBean(ctx context.Context, bean any) (int64, error) {
  169. return GetEngine(ctx).Delete(bean)
  170. }
  171. // DeleteByID deletes the given bean with the given ID
  172. func DeleteByID(ctx context.Context, id int64, bean any) (int64, error) {
  173. return GetEngine(ctx).ID(id).NoAutoCondition().NoAutoTime().Delete(bean)
  174. }
  175. // FindIDs finds the IDs for the given table name satisfying the given condition
  176. // By passing a different value than "id" for "idCol", you can query for foreign IDs, i.e. the repo IDs which satisfy the condition
  177. func FindIDs(ctx context.Context, tableName, idCol string, cond builder.Cond) ([]int64, error) {
  178. ids := make([]int64, 0, 10)
  179. if err := GetEngine(ctx).Table(tableName).
  180. Cols(idCol).
  181. Where(cond).
  182. Find(&ids); err != nil {
  183. return nil, err
  184. }
  185. return ids, nil
  186. }
  187. // DecrByIDs decreases the given column for entities of the "bean" type with one of the given ids by one
  188. // Timestamps of the entities won't be updated
  189. func DecrByIDs(ctx context.Context, ids []int64, decrCol string, bean any) error {
  190. _, err := GetEngine(ctx).Decr(decrCol).In("id", ids).NoAutoCondition().NoAutoTime().Update(bean)
  191. return err
  192. }
  193. // DeleteBeans deletes all given beans, beans must contain delete conditions.
  194. func DeleteBeans(ctx context.Context, beans ...any) (err error) {
  195. e := GetEngine(ctx)
  196. for i := range beans {
  197. if _, err = e.Delete(beans[i]); err != nil {
  198. return err
  199. }
  200. }
  201. return nil
  202. }
  203. // TruncateBeans deletes all given beans, beans may contain delete conditions.
  204. func TruncateBeans(ctx context.Context, beans ...any) (err error) {
  205. e := GetEngine(ctx)
  206. for i := range beans {
  207. if _, err = e.Truncate(beans[i]); err != nil {
  208. return err
  209. }
  210. }
  211. return nil
  212. }
  213. // CountByBean counts the number of database records according non-empty fields of the bean as conditions.
  214. func CountByBean(ctx context.Context, bean any) (int64, error) {
  215. return GetEngine(ctx).Count(bean)
  216. }
  217. // TableName returns the table name according a bean object
  218. func TableName(bean any) string {
  219. return x.TableName(bean)
  220. }
  221. // InTransaction returns true if the engine is in a transaction otherwise return false
  222. func InTransaction(ctx context.Context) bool {
  223. _, ok := inTransaction(ctx)
  224. return ok
  225. }
  226. func inTransaction(ctx context.Context) (*xorm.Session, bool) {
  227. e := getEngine(ctx)
  228. if e == nil {
  229. return nil, false
  230. }
  231. switch t := e.(type) {
  232. case *xorm.Engine:
  233. return nil, false
  234. case *xorm.Session:
  235. if t.IsInTx() {
  236. return t, true
  237. }
  238. return nil, false
  239. default:
  240. return nil, false
  241. }
  242. }