github.com/masterhung0112/hk_server/v5@v5.0.0-20220302090640-ec71aef15e1c/shared/driver/conn.go (about) 1 // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. 2 // See LICENSE.txt for license information. 3 4 package driver 5 6 import ( 7 "context" 8 "database/sql/driver" 9 "github.com/masterhung0112/hk_server/v5/plugin" 10 ) 11 12 // Conn is a DB driver conn implementation 13 // which executes queries using the Plugin DB API. 14 type Conn struct { 15 id string 16 api plugin.Driver 17 } 18 19 // driverConn is a super-interface combining the basic 20 // driver.Conn interface with some new additions later. 21 type driverConn interface { 22 driver.Conn 23 driver.ConnBeginTx 24 driver.ConnPrepareContext 25 driver.ExecerContext 26 driver.QueryerContext 27 driver.Pinger 28 } 29 30 var ( 31 // Compile-time check to ensure Conn implements the interface. 32 _ driverConn = &Conn{} 33 ) 34 35 func (c *Conn) Begin() (tx driver.Tx, err error) { 36 txID, err := c.api.Tx(c.id, driver.TxOptions{}) 37 if err != nil { 38 return nil, err 39 } 40 41 t := &wrapperTx{ 42 id: txID, 43 api: c.api, 44 } 45 return t, nil 46 } 47 48 func (c *Conn) BeginTx(_ context.Context, opts driver.TxOptions) (driver.Tx, error) { 49 txID, err := c.api.Tx(c.id, opts) 50 if err != nil { 51 return nil, err 52 } 53 54 t := &wrapperTx{ 55 id: txID, 56 api: c.api, 57 } 58 return t, nil 59 } 60 61 func (c *Conn) Prepare(q string) (driver.Stmt, error) { 62 stID, err := c.api.Stmt(c.id, q) 63 if err != nil { 64 return nil, err 65 } 66 67 st := &wrapperStmt{ 68 id: stID, 69 api: c.api, 70 } 71 return st, nil 72 } 73 74 func (c *Conn) PrepareContext(_ context.Context, q string) (driver.Stmt, error) { 75 stID, err := c.api.Stmt(c.id, q) 76 if err != nil { 77 return nil, err 78 } 79 st := &wrapperStmt{ 80 id: stID, 81 api: c.api, 82 } 83 return st, nil 84 } 85 86 func (c *Conn) ExecContext(_ context.Context, q string, args []driver.NamedValue) (driver.Result, error) { 87 resultContainer, err := c.api.ConnExec(c.id, q, args) 88 if err != nil { 89 return nil, err 90 } 91 res := &wrapperResult{ 92 res: resultContainer, 93 } 94 return res, nil 95 } 96 97 func (c *Conn) QueryContext(_ context.Context, q string, args []driver.NamedValue) (driver.Rows, error) { 98 rowsID, err := c.api.ConnQuery(c.id, q, args) 99 if err != nil { 100 return nil, err 101 } 102 103 rows := &wrapperRows{ 104 id: rowsID, 105 api: c.api, 106 } 107 return rows, nil 108 } 109 110 func (c *Conn) Ping(_ context.Context) error { 111 return c.api.ConnPing(c.id) 112 } 113 114 func (c *Conn) Close() error { 115 return c.api.ConnClose(c.id) 116 }