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 7.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. func TxContext(parentCtx context.Context) (*Context, Committer, error) {
  103. if sess, ok := inTransaction(parentCtx); ok {
  104. return newContext(parentCtx, sess, true), &halfCommitter{committer: sess}, nil
  105. }
  106. sess := x.NewSession()
  107. if err := sess.Begin(); err != nil {
  108. sess.Close()
  109. return nil, nil, err
  110. }
  111. return newContext(DefaultContext, sess, true), sess, nil
  112. }
  113. // WithTx represents executing database operations on a transaction, if the transaction exist,
  114. // this function will reuse it otherwise will create a new one and close it when finished.
  115. func WithTx(parentCtx context.Context, f func(ctx context.Context) error) error {
  116. if sess, ok := inTransaction(parentCtx); ok {
  117. err := f(newContext(parentCtx, sess, true))
  118. if err != nil {
  119. // rollback immediately, in case the caller ignores returned error and tries to commit the transaction.
  120. _ = sess.Close()
  121. }
  122. return err
  123. }
  124. return txWithNoCheck(parentCtx, f)
  125. }
  126. func txWithNoCheck(parentCtx context.Context, f func(ctx context.Context) error) error {
  127. sess := x.NewSession()
  128. defer sess.Close()
  129. if err := sess.Begin(); err != nil {
  130. return err
  131. }
  132. if err := f(newContext(parentCtx, sess, true)); err != nil {
  133. return err
  134. }
  135. return sess.Commit()
  136. }
  137. // Insert inserts records into database
  138. func Insert(ctx context.Context, beans ...any) error {
  139. _, err := GetEngine(ctx).Insert(beans...)
  140. return err
  141. }
  142. // Exec executes a sql with args
  143. func Exec(ctx context.Context, sqlAndArgs ...any) (sql.Result, error) {
  144. return GetEngine(ctx).Exec(sqlAndArgs...)
  145. }
  146. // GetByBean filled empty fields of the bean according non-empty fields to query in database.
  147. func GetByBean(ctx context.Context, bean any) (bool, error) {
  148. return GetEngine(ctx).Get(bean)
  149. }
  150. func Exist[T any](ctx context.Context, cond builder.Cond) (bool, error) {
  151. if !cond.IsValid() {
  152. return false, ErrConditionRequired{}
  153. }
  154. var bean T
  155. return GetEngine(ctx).Where(cond).NoAutoCondition().Exist(&bean)
  156. }
  157. // DeleteByBean deletes all records according non-empty fields of the bean as conditions.
  158. func DeleteByBean(ctx context.Context, bean any) (int64, error) {
  159. return GetEngine(ctx).Delete(bean)
  160. }
  161. // DeleteByID deletes the given bean with the given ID
  162. func DeleteByID(ctx context.Context, id int64, bean any) (int64, error) {
  163. return GetEngine(ctx).ID(id).NoAutoCondition().NoAutoTime().Delete(bean)
  164. }
  165. // FindIDs finds the IDs for the given table name satisfying the given condition
  166. // By passing a different value than "id" for "idCol", you can query for foreign IDs, i.e. the repo IDs which satisfy the condition
  167. func FindIDs(ctx context.Context, tableName, idCol string, cond builder.Cond) ([]int64, error) {
  168. ids := make([]int64, 0, 10)
  169. if err := GetEngine(ctx).Table(tableName).
  170. Cols(idCol).
  171. Where(cond).
  172. Find(&ids); err != nil {
  173. return nil, err
  174. }
  175. return ids, nil
  176. }
  177. // DecrByIDs decreases the given column for entities of the "bean" type with one of the given ids by one
  178. // Timestamps of the entities won't be updated
  179. func DecrByIDs(ctx context.Context, ids []int64, decrCol string, bean any) error {
  180. _, err := GetEngine(ctx).Decr(decrCol).In("id", ids).NoAutoCondition().NoAutoTime().Update(bean)
  181. return err
  182. }
  183. // DeleteBeans deletes all given beans, beans must contain delete conditions.
  184. func DeleteBeans(ctx context.Context, beans ...any) (err error) {
  185. e := GetEngine(ctx)
  186. for i := range beans {
  187. if _, err = e.Delete(beans[i]); err != nil {
  188. return err
  189. }
  190. }
  191. return nil
  192. }
  193. // TruncateBeans deletes all given beans, beans may contain delete conditions.
  194. func TruncateBeans(ctx context.Context, beans ...any) (err error) {
  195. e := GetEngine(ctx)
  196. for i := range beans {
  197. if _, err = e.Truncate(beans[i]); err != nil {
  198. return err
  199. }
  200. }
  201. return nil
  202. }
  203. // CountByBean counts the number of database records according non-empty fields of the bean as conditions.
  204. func CountByBean(ctx context.Context, bean any) (int64, error) {
  205. return GetEngine(ctx).Count(bean)
  206. }
  207. // TableName returns the table name according a bean object
  208. func TableName(bean any) string {
  209. return x.TableName(bean)
  210. }
  211. // InTransaction returns true if the engine is in a transaction otherwise return false
  212. func InTransaction(ctx context.Context) bool {
  213. _, ok := inTransaction(ctx)
  214. return ok
  215. }
  216. func inTransaction(ctx context.Context) (*xorm.Session, bool) {
  217. e := getEngine(ctx)
  218. if e == nil {
  219. return nil, false
  220. }
  221. switch t := e.(type) {
  222. case *xorm.Engine:
  223. return nil, false
  224. case *xorm.Session:
  225. if t.IsInTx() {
  226. return t, true
  227. }
  228. return nil, false
  229. default:
  230. return nil, false
  231. }
  232. }