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.

conn.go 6.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. package sql
  18. import (
  19. "context"
  20. "database/sql/driver"
  21. "seata.apache.org/seata-go/pkg/datasource/sql/exec"
  22. "seata.apache.org/seata-go/pkg/datasource/sql/types"
  23. "seata.apache.org/seata-go/pkg/datasource/sql/util"
  24. )
  25. // Conn is a connection to a database. It is not used concurrently
  26. // by multiple goroutines.
  27. //
  28. // Conn is assumed to be stateful.
  29. type Conn struct {
  30. res *DBResource
  31. txCtx *types.TransactionContext
  32. targetConn driver.Conn
  33. autoCommit bool
  34. dbName string
  35. dbType types.DBType
  36. }
  37. // ResetSession is called prior to executing a query on the connection
  38. // if the connection has been used before. If the driver returns ErrBadConn
  39. // the connection is discarded.
  40. func (c *Conn) ResetSession(ctx context.Context) error {
  41. conn, ok := c.targetConn.(driver.SessionResetter)
  42. if !ok {
  43. return driver.ErrSkip
  44. }
  45. c.autoCommit = true
  46. c.txCtx = types.NewTxCtx()
  47. return conn.ResetSession(ctx)
  48. }
  49. // Prepare returns a prepared statement, bound to this connection.
  50. func (c *Conn) Prepare(query string) (driver.Stmt, error) {
  51. s, err := c.targetConn.Prepare(query)
  52. if err != nil {
  53. return nil, err
  54. }
  55. return &Stmt{
  56. conn: c,
  57. stmt: s,
  58. query: query,
  59. res: c.res,
  60. txCtx: c.txCtx,
  61. }, nil
  62. }
  63. // PrepareContext
  64. func (c *Conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
  65. conn, ok := c.targetConn.(driver.ConnPrepareContext)
  66. if !ok {
  67. stmt, err := c.targetConn.Prepare(query)
  68. if err != nil {
  69. return nil, err
  70. }
  71. return &Stmt{stmt: stmt, query: query, res: c.res, txCtx: c.txCtx}, nil
  72. }
  73. s, err := conn.PrepareContext(ctx, query)
  74. if err != nil {
  75. return nil, err
  76. }
  77. return &Stmt{
  78. conn: c,
  79. stmt: s,
  80. query: query,
  81. res: c.res,
  82. txCtx: c.txCtx,
  83. }, nil
  84. }
  85. // Exec warning: if you want to use global transaction, please use ExecContext function
  86. func (c *Conn) Exec(query string, args []driver.Value) (driver.Result, error) {
  87. conn, ok := c.targetConn.(driver.Execer)
  88. if !ok {
  89. return nil, driver.ErrSkip
  90. }
  91. ret, err := conn.Exec(query, args)
  92. if err != nil {
  93. return nil, err
  94. }
  95. return types.NewResult(types.WithResult(ret)).GetResult(), nil
  96. }
  97. // ExecContext
  98. func (c *Conn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) {
  99. targetConn, ok := c.targetConn.(driver.ExecerContext)
  100. if !ok {
  101. values := make([]driver.Value, 0, len(args))
  102. for i := range args {
  103. values = append(values, args[i].Value)
  104. }
  105. return c.Exec(query, values)
  106. }
  107. ret, err := targetConn.ExecContext(ctx, query, args)
  108. if err != nil {
  109. return nil, err
  110. }
  111. return types.NewResult(types.WithResult(ret)).GetResult(), nil
  112. }
  113. // Query
  114. func (c *Conn) Query(query string, args []driver.Value) (driver.Rows, error) {
  115. conn, ok := c.targetConn.(driver.Queryer)
  116. if !ok {
  117. return nil, driver.ErrSkip
  118. }
  119. executor, err := exec.BuildExecutor(c.res.dbType, c.txCtx.TransactionMode, query)
  120. if err != nil {
  121. return nil, err
  122. }
  123. execCtx := &types.ExecContext{
  124. TxCtx: c.txCtx,
  125. Query: query,
  126. Values: args,
  127. }
  128. ret, err := executor.ExecWithValue(context.Background(), execCtx,
  129. func(ctx context.Context, query string, args []driver.NamedValue) (types.ExecResult, error) {
  130. ret, err := conn.Query(query, util.NamedValueToValue(args))
  131. if err != nil {
  132. return nil, err
  133. }
  134. return types.NewResult(types.WithRows(ret)), nil
  135. })
  136. if err != nil {
  137. return nil, err
  138. }
  139. return ret.GetRows(), nil
  140. }
  141. // QueryContext
  142. func (c *Conn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) {
  143. conn, ok := c.targetConn.(driver.QueryerContext)
  144. if !ok {
  145. values := make([]driver.Value, 0, len(args))
  146. for i := range args {
  147. values = append(values, args[i].Value)
  148. }
  149. return c.Query(query, values)
  150. }
  151. ret, err := conn.QueryContext(ctx, query, args)
  152. if err != nil {
  153. return nil, err
  154. }
  155. return types.NewResult(types.WithRows(ret)).GetRows(), nil
  156. }
  157. // Begin starts and returns a new transaction.
  158. //
  159. // Deprecated: Drivers should implement ConnBeginTx instead (or additionally).
  160. func (c *Conn) Begin() (driver.Tx, error) {
  161. c.autoCommit = false
  162. tx, err := c.targetConn.Begin()
  163. if err != nil {
  164. return nil, err
  165. }
  166. if c.txCtx == nil {
  167. c.txCtx = types.NewTxCtx()
  168. c.txCtx.DBType = c.res.dbType
  169. c.txCtx.TxOpt = driver.TxOptions{}
  170. }
  171. return newTx(
  172. withDriverConn(c),
  173. withTxCtx(c.txCtx),
  174. withOriginTx(tx),
  175. )
  176. }
  177. // BeginTx Open a transaction and judge whether the current transaction needs to open a
  178. //
  179. // global transaction according to tranCtx. If so, it needs to be included in the transaction management of seata
  180. func (c *Conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) {
  181. if c.txCtx.TransactionMode == types.XAMode {
  182. c.autoCommit = false
  183. return newTx(
  184. withDriverConn(c),
  185. withTxCtx(c.txCtx),
  186. withOriginTx(nil),
  187. )
  188. }
  189. if conn, ok := c.targetConn.(driver.ConnBeginTx); ok {
  190. tx, err := conn.BeginTx(ctx, opts)
  191. if err != nil {
  192. return nil, err
  193. }
  194. return newTx(
  195. withDriverConn(c),
  196. withTxCtx(c.txCtx),
  197. withOriginTx(tx),
  198. )
  199. }
  200. txi, err := c.Begin()
  201. if err != nil {
  202. return nil, err
  203. }
  204. return newTx(
  205. withDriverConn(c),
  206. withTxCtx(c.txCtx),
  207. withOriginTx(txi),
  208. )
  209. }
  210. func (c *Conn) GetAutoCommit() bool {
  211. return c.autoCommit
  212. }
  213. func (c *Conn) GetDbVersion() string {
  214. if c.res == nil {
  215. return ""
  216. }
  217. return c.res.GetDbVersion()
  218. }
  219. // Close invalidates and potentially stops any current
  220. // prepared statements and transactions, marking this
  221. // connection as no longer in use.
  222. //
  223. // Because the sql package maintains a free pool of
  224. // connections and only calls Close when there's a surplus of
  225. // idle connections, it shouldn't be necessary for drivers to
  226. // do their own connection caching.
  227. //
  228. // Drivers must ensure all network calls made by Close
  229. // do not block indefinitely (e.g. apply a timeout).
  230. func (c *Conn) Close() error {
  231. c.txCtx = types.NewTxCtx()
  232. return c.targetConn.Close()
  233. }