├── .travis.yml ├── LICENSE ├── Makefile ├── README.md ├── driver.go ├── driver_go1.09.go ├── driver_go1.10.go ├── driver_test.go ├── go.mod ├── go.sum ├── options.go └── tests ├── docker-compose.yml └── integration_test.go /.travis.yml: -------------------------------------------------------------------------------- 1 | services: 2 | - docker 3 | 4 | sudo: false 5 | language: go 6 | go: 7 | - 1.10.x 8 | - 1.11.x 9 | - 1.12.x 10 | - 1.13.x 11 | - 1.14.x 12 | - master 13 | 14 | env: 15 | - GO111MODULE=on 16 | 17 | before_script: 18 | - go get -u golang.org/x/lint/golint 19 | 20 | install: 21 | - go get -d -t ./... 22 | 23 | script: 24 | - make ci 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 The OpenZipkin Authors 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | vet: 2 | go vet ./... 3 | 4 | lint: 5 | golint ./.. 6 | 7 | test: unit-test acceptance-test 8 | 9 | unit-test: 10 | go test --count=1 -v . 11 | 12 | acceptance-test: 13 | docker-compose -f tests/docker-compose.yml build --no-cache 14 | docker-compose -f tests/docker-compose.yml up -d 15 | go test --count=1 -v ./tests || (sleep 2; docker-compose -f tests/docker-compose.yml logs; docker-compose -f tests/docker-compose.yml stop; exit 1) 16 | docker-compose -f tests/docker-compose.yml stop 17 | 18 | ci: vet lint test 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Zipkin instrumentation SQL 2 | 3 | [![Build Status](https://travis-ci.org/openzipkin-contrib/zipkin-go-sql.svg?branch=master)](https://travis-ci.org/openzipkin-contrib/zipkin-go-sql) 4 | [![Go Report Card](https://goreportcard.com/badge/github.com/openzipkin-contrib/zipkin-go-sql)](https://goreportcard.com/report/github.com/openzipkin-contrib/zipkin-go-sql) 5 | [![GoDoc](https://godoc.org/github.com/openzipkin-contrib/zipkin-go-sql?status.svg)](https://godoc.org/github.com/openzipkin-contrib/zipkin-go-sql) 6 | 7 | A SQL wrapper including Zipkin instrumentation 8 | 9 | ## Usage 10 | 11 | ```go 12 | import ( 13 | _ "github.com/go-sql-driver/mysql" 14 | zipkinsql "github.com/openzipkin-contrib/zipkin-go-sql" 15 | zipkin "github.com/openzipkin/zipkin-go" 16 | ) 17 | 18 | var ( 19 | driverName string 20 | err error 21 | db *sql.DB 22 | tracer *zipkin.Tracer 23 | ) 24 | 25 | // Register our zipkinsql wrapper for the provided MySQL driver. 26 | driverName, err = zipkinsql.Register("mysql", tracer, zipkinsql.WithAllTraceOptions()) 27 | if err != nil { 28 | log.Fatalf("unable to register zipkin driver: %v\n", err) 29 | } 30 | 31 | // Connect to a MySQL database using the zipkinsql driver wrapper. 32 | db, err = sql.Open(driverName, "mysql://user:pass@127.0.0.1:3306/db") 33 | ``` 34 | 35 | You can also wrap your own driver with zipkin instrumentation as follows: 36 | 37 | ```go 38 | 39 | import ( 40 | mysql "github.com/go-sql-driver/mysql" 41 | zipkinsql "github.com/openzipkin-contrib/zipkin-go-sql" 42 | zipkinmodel "github.com/openzipkin/zipkin-go/model" 43 | ) 44 | 45 | var ( 46 | driver driver.Driver 47 | err error 48 | db *sql.DB 49 | tracer *zipkin.Tracer 50 | ) 51 | 52 | // Explicitly wrap the MySQL driver with zipkinsql 53 | driver = zipkinsql.Wrap( 54 | &mysql.MySQLDriver{}, 55 | tracer, 56 | zipkinsql.WithRemoteEndpoint(zipkinmodel.Endpoint{ 57 | ServiceName: "resultsdb", 58 | Port: 5432 59 | }), 60 | ) 61 | 62 | // Register our zipkinsql wrapper as a database driver 63 | sql.Register("zipkinsql-mysql", driver) 64 | 65 | // Connect to a MySQL database using the zipkinsql driver wrapper 66 | db, err = sql.Open("zipkinsql-mysql", "mysql://user:pass@127.0.0.1:3306/db") 67 | ``` 68 | 69 | Projects providing their own abstractions on top of database/sql/driver can also wrap an existing driver.Conn interface directly with zipkinsql. 70 | 71 | ```go 72 | import zipkinsql "github.com/openzipkin-contrib/zipkin-go-sql" 73 | 74 | func initializeConn(...) driver.Conn { 75 | // create custom driver.Conn 76 | conn := Connect(...) 77 | 78 | // wrap with zipkinsql 79 | return zipkinsql.WrapConn(conn, tracer, zipkinsql.WithAllTraceOptions()) 80 | } 81 | ``` 82 | 83 | Go 1.10+ provides a new driver.Connector interface that can be 84 | wrapped directly by zipkinsql without the need for zipkinsql to 85 | register a driver.Driver. 86 | 87 | Example: 88 | 89 | ```go 90 | import( 91 | zipkinsql "github.com/openzipkin-contrib/zipkin-go-sql" 92 | "github.com/lib/pq" 93 | ) 94 | var ( 95 | connector driver.Connector 96 | err error 97 | db *sql.DB 98 | tracer *zipkin.Tracer 99 | ) 100 | 101 | connector, err = pq.NewConnector("postgres://user:pass@host:5432/db") 102 | if err != nil { 103 | log.Fatalf("unable to create postgres connector: %v\n", err) 104 | } 105 | // Wrap the driver.Connector with zipkinsql. 106 | connector = zipkinsql.WrapConnector(connector, tracer, zipkinsql.WithAllTraceOptions()) 107 | // Use the wrapped driver.Connector. 108 | db = sql.OpenDB(connector) 109 | ``` 110 | 111 | ## Using jmoiron/sqlx 112 | 113 | If using the `sqlx` library with named queries you will need to use the 114 | `sqlx.NewDb` function to wrap an existing `*sql.DB` connection. `sqlx.Open` and `sqlx.Connect` methods won't work. 115 | 116 | First create a `*sql.DB` connection and then create a `*sqlx.DB` connection by wrapping the former and **keeping the same driver name** e.g.: 117 | 118 | ```go 119 | driverName, err := zipkinsql.Register("postgres", zipkinsql.WithAllTraceOptions()) 120 | if err != nil { ... } 121 | 122 | db, err := sql.Open(driverName, "postgres://localhost:5432/my_database") 123 | if err != nil { ... } 124 | 125 | // Keep the driver name! 126 | dbx := sqlx.NewDb(db, "postgres") 127 | ``` 128 | 129 | ## Usage of *Context methods 130 | 131 | Instrumentation is possible if the context is being passed downstream in methods. 132 | This is not only for instrumentation purposes but also a [good practice](https://medium.com/@cep21/how-to-correctly-use-context-context-in-go-1-7-8f2c0fafdf39) in go programming. `database/sql` package exposes already a set of methods that receive the context as first paramenter: 133 | 134 | - `*DB.Begin` -> `*DB.BeginTx` 135 | - `*DB.Exec` -> `*DB.ExecContext` 136 | - `*DB.Ping` -> `*DB.PingContext` 137 | - `*DB.Prepare` -> `*DB.PrepareContext` 138 | - `*DB.Query` -> `*DB.QueryContext` 139 | - `*DB.QueryRow` -> `*DB.QueryRowContext` 140 | - `*Stmt.Exec` -> `*Stmt.ExecContext` 141 | - `*Stmt.Query` -> `*Stmt.QueryContext` 142 | - `*Stmt.QueryRow` -> `*Stmt.QueryRowContext` 143 | - `*Tx.Exec` -> `*Tx.ExecContext` 144 | - `*Tx.Prepare` -> `*Tx.PrepareContext` 145 | - `*Tx.Query` -> `*Tx.QueryContext` 146 | - `*Tx.QueryRow` -> `*Tx.QueryRowContext` 147 | -------------------------------------------------------------------------------- /driver.go: -------------------------------------------------------------------------------- 1 | package zipkinsql 2 | 3 | import ( 4 | "context" 5 | "database/sql" 6 | "database/sql/driver" 7 | "fmt" 8 | "strconv" 9 | "sync" 10 | "time" 11 | 12 | zipkin "github.com/openzipkin/zipkin-go" 13 | zipkinmodel "github.com/openzipkin/zipkin-go/model" 14 | ) 15 | 16 | type conn interface { 17 | driver.Pinger 18 | driver.Execer 19 | driver.ExecerContext 20 | driver.Queryer 21 | driver.QueryerContext 22 | driver.Conn 23 | driver.ConnPrepareContext 24 | driver.ConnBeginTx 25 | } 26 | 27 | var ( 28 | // Type assertions 29 | _ driver.Driver = &zDriver{} 30 | _ conn = &zConn{} 31 | _ driver.Result = &zResult{} 32 | _ driver.Stmt = &zStmt{} 33 | _ driver.StmtExecContext = &zStmt{} 34 | _ driver.StmtQueryContext = &zStmt{} 35 | ) 36 | 37 | var ( 38 | regMu sync.Mutex 39 | ) 40 | 41 | // Register initializes and registers our zipkinsql wrapped database driver 42 | // identified by its driverName and using provided TraceOptions. On success it 43 | // returns the generated driverName to use when calling sql.Open. 44 | // It is possible to register multiple wrappers for the same database driver if 45 | // needing different TraceOptions for different connections. 46 | func Register(driverName string, tracer *zipkin.Tracer, options ...TraceOption) (string, error) { 47 | // retrieve the driver implementation we need to wrap with instrumentation 48 | db, err := sql.Open(driverName, "") 49 | if err != nil { 50 | return "", err 51 | } 52 | dri := db.Driver() 53 | if err = db.Close(); err != nil { 54 | return "", err 55 | } 56 | 57 | regMu.Lock() 58 | defer regMu.Unlock() 59 | registerName := fmt.Sprintf("%s-zipkinsql-%d", driverName, len(sql.Drivers())) 60 | sql.Register(registerName, Wrap(dri, tracer, options...)) 61 | 62 | return registerName, nil 63 | } 64 | 65 | // Wrap takes a SQL driver and wraps it with Zipkin instrumentation. 66 | func Wrap(d driver.Driver, t *zipkin.Tracer, options ...TraceOption) driver.Driver { 67 | o := TraceOptions{} 68 | for _, option := range options { 69 | option(&o) 70 | } 71 | if o.TagQueryParams && !o.TagQuery { 72 | o.TagQueryParams = false 73 | } 74 | 75 | return wrapDriver(d, t, o) 76 | } 77 | 78 | func (d zDriver) Open(name string) (driver.Conn, error) { 79 | c, err := d.parent.Open(name) 80 | if err != nil { 81 | return nil, err 82 | } 83 | return wrapConn(c, d.tracer, d.options), nil 84 | } 85 | 86 | // WrapConn allows an existing driver.Conn to be wrapped by zipkinsql. 87 | func WrapConn(c driver.Conn, t *zipkin.Tracer, options ...TraceOption) driver.Conn { 88 | o := TraceOptions{} 89 | for _, option := range options { 90 | option(&o) 91 | } 92 | return wrapConn(c, t, o) 93 | } 94 | 95 | // zConn implements driver.Conn 96 | type zConn struct { 97 | parent driver.Conn 98 | tracer *zipkin.Tracer 99 | options TraceOptions 100 | } 101 | 102 | func (c zConn) Ping(ctx context.Context) (err error) { 103 | if pinger, ok := c.parent.(driver.Pinger); ok { 104 | err = pinger.Ping(ctx) 105 | } 106 | return 107 | } 108 | 109 | func (c zConn) Exec(query string, args []driver.Value) (res driver.Result, err error) { 110 | if exec, ok := c.parent.(driver.Execer); ok { 111 | return exec.Exec(query, args) 112 | } 113 | 114 | return nil, driver.ErrSkip 115 | } 116 | 117 | func (c zConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (res driver.Result, err error) { 118 | if execCtx, ok := c.parent.(driver.ExecerContext); ok { 119 | parentSpan := zipkin.SpanFromContext(ctx) 120 | if parentSpan == nil && !c.options.AllowRootSpan { 121 | return execCtx.ExecContext(ctx, query, args) 122 | } 123 | 124 | var ( 125 | startTime time.Time 126 | ) 127 | 128 | defer func() { 129 | if err == nil || err != driver.ErrSkip { 130 | var span zipkin.Span 131 | span, _ = c.tracer.StartSpanFromContext( 132 | ctx, 133 | "sql/exec", 134 | zipkin.Kind(zipkinmodel.Client), 135 | zipkin.StartTime(startTime), 136 | zipkin.RemoteEndpoint(c.options.RemoteEndpoint), 137 | ) 138 | 139 | if c.options.TagQuery { 140 | span.Tag("sql.query", query) 141 | if c.options.TagQueryParams { 142 | addNamedParamsTags(span, args) 143 | } 144 | } 145 | setSpanDefaultTags(span, c.options.DefaultTags) 146 | 147 | setSpanError(span, err) 148 | span.Finish() 149 | } 150 | }() 151 | 152 | startTime = time.Now() 153 | if res, err = execCtx.ExecContext(ctx, query, args); err != nil { 154 | return nil, err 155 | } 156 | 157 | return zResult{parent: res, tracer: c.tracer, ctx: ctx, options: c.options}, nil 158 | } 159 | 160 | return nil, driver.ErrSkip 161 | } 162 | 163 | func (c zConn) Query(query string, args []driver.Value) (rows driver.Rows, err error) { 164 | if queryer, ok := c.parent.(driver.Queryer); ok { 165 | return queryer.Query(query, args) 166 | } 167 | 168 | return nil, driver.ErrSkip 169 | } 170 | 171 | func (c zConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (rows driver.Rows, err error) { 172 | if queryerCtx, ok := c.parent.(driver.QueryerContext); ok { 173 | parentSpan := zipkin.SpanFromContext(ctx) 174 | if parentSpan == nil && !c.options.AllowRootSpan { 175 | return queryerCtx.QueryContext(ctx, query, args) 176 | } 177 | 178 | var ( 179 | startTime time.Time 180 | ) 181 | 182 | defer func() { 183 | if err == nil || err != driver.ErrSkip { 184 | var span zipkin.Span 185 | span, _ = c.tracer.StartSpanFromContext( 186 | ctx, 187 | "sql/query", 188 | zipkin.Kind(zipkinmodel.Client), 189 | zipkin.StartTime(startTime), 190 | zipkin.RemoteEndpoint(c.options.RemoteEndpoint), 191 | ) 192 | 193 | if c.options.TagQuery { 194 | span.Tag("sql.query", query) 195 | if c.options.TagQueryParams { 196 | addNamedParamsTags(span, args) 197 | } 198 | } 199 | setSpanDefaultTags(span, c.options.DefaultTags) 200 | 201 | setSpanError(span, err) 202 | span.Finish() 203 | } 204 | }() 205 | 206 | startTime = time.Now() 207 | if rows, err = queryerCtx.QueryContext(ctx, query, args); err != nil { 208 | return nil, err 209 | } 210 | 211 | return rows, nil 212 | } 213 | 214 | return nil, driver.ErrSkip 215 | } 216 | 217 | func (c zConn) Prepare(query string) (stmt driver.Stmt, err error) { 218 | if c.options.AllowRootSpan { 219 | span := c.tracer.StartSpan( 220 | "sql/prepare", 221 | zipkin.Kind(zipkinmodel.Client), 222 | zipkin.RemoteEndpoint(c.options.RemoteEndpoint), 223 | ) 224 | 225 | if c.options.TagQuery { 226 | span.Tag("sql.query", query) 227 | } 228 | setSpanDefaultTags(span, c.options.DefaultTags) 229 | defer func() { 230 | setSpanError(span, err) 231 | span.Finish() 232 | }() 233 | } 234 | 235 | stmt, err = c.parent.Prepare(query) 236 | if err != nil { 237 | return nil, err 238 | } 239 | 240 | stmt = wrapStmt(stmt, query, c.tracer, c.options) 241 | return 242 | } 243 | 244 | func (c *zConn) Close() error { 245 | return c.parent.Close() 246 | } 247 | 248 | func (c *zConn) Begin() (driver.Tx, error) { 249 | return c.Begin() 250 | } 251 | 252 | func (c *zConn) PrepareContext(ctx context.Context, query string) (stmt driver.Stmt, err error) { 253 | var span zipkin.Span 254 | setSpanDefaultTags(span, c.options.DefaultTags) 255 | if c.options.AllowRootSpan || zipkin.SpanFromContext(ctx) != nil { 256 | span, ctx = c.tracer.StartSpanFromContext( 257 | ctx, 258 | "sql/prepare", 259 | zipkin.Kind(zipkinmodel.Client), 260 | zipkin.RemoteEndpoint(c.options.RemoteEndpoint), 261 | ) 262 | if c.options.TagQuery { 263 | span.Tag("sql.query", query) 264 | } 265 | 266 | defer func() { 267 | setSpanError(span, err) 268 | span.Finish() 269 | }() 270 | } 271 | 272 | if prepCtx, ok := c.parent.(driver.ConnPrepareContext); ok { 273 | stmt, err = prepCtx.PrepareContext(ctx, query) 274 | } else { 275 | stmt, err = c.parent.Prepare(query) 276 | } 277 | 278 | if err != nil { 279 | return nil, err 280 | } 281 | 282 | stmt = wrapStmt(stmt, query, c.tracer, c.options) 283 | return 284 | } 285 | 286 | func (c *zConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { 287 | if zipkin.SpanFromContext(ctx) == nil && !c.options.AllowRootSpan { 288 | if connBeginTx, ok := c.parent.(driver.ConnBeginTx); ok { 289 | return connBeginTx.BeginTx(ctx, opts) 290 | } 291 | 292 | return c.parent.Begin() 293 | } 294 | 295 | span, _ := c.tracer.StartSpanFromContext( 296 | ctx, 297 | "sql/begin_transaction", 298 | zipkin.Kind(zipkinmodel.Client), 299 | zipkin.RemoteEndpoint(c.options.RemoteEndpoint), 300 | ) 301 | defer span.Finish() 302 | 303 | setSpanDefaultTags(span, c.options.DefaultTags) 304 | 305 | if connBeginTx, ok := c.parent.(driver.ConnBeginTx); ok { 306 | tx, err := connBeginTx.BeginTx(ctx, opts) 307 | setSpanError(span, err) 308 | if err != nil { 309 | return nil, err 310 | } 311 | return zTx{parent: tx, ctx: ctx, tracer: c.tracer, options: c.options}, nil 312 | } 313 | 314 | tx, err := c.parent.Begin() 315 | setSpanError(span, err) 316 | if err != nil { 317 | return nil, err 318 | } 319 | 320 | return zTx{parent: tx, ctx: ctx, tracer: c.tracer, options: c.options}, nil 321 | } 322 | 323 | // zResult implements driver.Result 324 | type zResult struct { 325 | parent driver.Result 326 | ctx context.Context 327 | tracer *zipkin.Tracer 328 | options TraceOptions 329 | } 330 | 331 | func (r zResult) LastInsertId() (int64, error) { 332 | if !r.options.LastInsertIDSpan { 333 | return r.parent.LastInsertId() 334 | } 335 | 336 | span, _ := r.tracer.StartSpanFromContext( 337 | r.ctx, 338 | "sql/last_insert_id", 339 | zipkin.Kind(zipkinmodel.Client), 340 | zipkin.RemoteEndpoint(r.options.RemoteEndpoint), 341 | ) 342 | defer span.Finish() 343 | 344 | setSpanDefaultTags(span, r.options.DefaultTags) 345 | 346 | id, err := r.parent.LastInsertId() 347 | setSpanError(span, err) 348 | 349 | return id, err 350 | } 351 | 352 | func (r zResult) RowsAffected() (cnt int64, err error) { 353 | zipkin.SpanFromContext(r.ctx) 354 | if r.options.RowsAffectedSpan && (r.options.AllowRootSpan || zipkin.SpanFromContext(r.ctx) != nil) { 355 | span, _ := r.tracer.StartSpanFromContext( 356 | r.ctx, 357 | "sql/rows_affected", 358 | ) 359 | setSpanDefaultTags(span, r.options.DefaultTags) 360 | defer func() { 361 | span.Tag("sql.affected_rows", fmt.Sprintf("%d", cnt)) 362 | setSpanError(span, err) 363 | span.Finish() 364 | }() 365 | } 366 | 367 | cnt, err = r.parent.RowsAffected() 368 | return 369 | } 370 | 371 | // zStmt implements driver.Stmt 372 | type zStmt struct { 373 | parent driver.Stmt 374 | query string 375 | tracer *zipkin.Tracer 376 | options TraceOptions 377 | } 378 | 379 | func (s zStmt) Exec(args []driver.Value) (res driver.Result, err error) { 380 | if !s.options.AllowRootSpan { 381 | return s.parent.Exec(args) 382 | } 383 | 384 | span, ctx := s.tracer.StartSpanFromContext( 385 | context.Background(), 386 | "sql:exec", 387 | zipkin.Kind(zipkinmodel.Client), 388 | zipkin.RemoteEndpoint(s.options.RemoteEndpoint), 389 | ) 390 | setSpanDefaultTags(span, s.options.DefaultTags) 391 | 392 | if s.options.TagQuery { 393 | span.Tag("sql.query", s.query) 394 | if s.options.TagQueryParams { 395 | addParamsTags(span, args) 396 | } 397 | } 398 | 399 | defer func() { 400 | setSpanError(span, err) 401 | span.Finish() 402 | }() 403 | 404 | res, err = s.parent.Exec(args) 405 | if err != nil { 406 | return nil, err 407 | } 408 | if s.options.TagAffectedRows { 409 | if affectedRows, aRErr := res.RowsAffected(); aRErr != nil { 410 | span.Tag("sql.affected_rows", fmt.Sprintf("%d", affectedRows)) 411 | } 412 | } 413 | 414 | res, err = zResult{parent: res, ctx: ctx, tracer: s.tracer, options: s.options}, nil 415 | 416 | return 417 | } 418 | 419 | func (s zStmt) Close() error { 420 | return s.parent.Close() 421 | } 422 | 423 | func (s zStmt) NumInput() int { 424 | return s.parent.NumInput() 425 | } 426 | 427 | func (s zStmt) Query(args []driver.Value) (rows driver.Rows, err error) { 428 | if !s.options.AllowRootSpan { 429 | return s.parent.Query(args) 430 | } 431 | 432 | span, _ := s.tracer.StartSpanFromContext( 433 | context.Background(), 434 | "sql:query", 435 | zipkin.Kind(zipkinmodel.Client), 436 | zipkin.RemoteEndpoint(s.options.RemoteEndpoint), 437 | ) 438 | setSpanDefaultTags(span, s.options.DefaultTags) 439 | 440 | if s.options.TagQuery { 441 | span.Tag("sql.query", s.query) 442 | if s.options.TagQueryParams { 443 | addParamsTags(span, args) 444 | } 445 | } 446 | 447 | defer func() { 448 | setSpanError(span, err) 449 | span.Finish() 450 | }() 451 | 452 | rows, err = s.parent.Query(args) 453 | if err != nil { 454 | return nil, err 455 | } 456 | 457 | return 458 | } 459 | 460 | func (s zStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (res driver.Result, err error) { 461 | if zipkin.SpanFromContext(ctx) == nil && !s.options.AllowRootSpan { 462 | return s.parent.(driver.StmtExecContext).ExecContext(ctx, args) 463 | } 464 | 465 | span, ctx := s.tracer.StartSpanFromContext( 466 | ctx, 467 | "sql/exec", 468 | zipkin.Kind(zipkinmodel.Client), 469 | zipkin.RemoteEndpoint(s.options.RemoteEndpoint), 470 | ) 471 | defer func() { 472 | setSpanError(span, err) 473 | span.Finish() 474 | }() 475 | 476 | if s.options.TagQuery { 477 | span.Tag("sql.query", s.query) 478 | if s.options.TagQueryParams { 479 | addNamedParamsTags(span, args) 480 | } 481 | } 482 | 483 | setSpanDefaultTags(span, s.options.DefaultTags) 484 | 485 | execContext := s.parent.(driver.StmtExecContext) 486 | res, err = execContext.ExecContext(ctx, args) 487 | if err != nil { 488 | return nil, err 489 | } 490 | if s.options.TagAffectedRows { 491 | if affectedRows, aRErr := res.RowsAffected(); aRErr != nil { 492 | span.Tag("sql.affected_rows", fmt.Sprintf("%d", affectedRows)) 493 | } 494 | } 495 | 496 | res, err = zResult{parent: res, tracer: s.tracer, ctx: ctx, options: s.options}, nil 497 | return 498 | } 499 | 500 | func (s zStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (rows driver.Rows, err error) { 501 | if zipkin.SpanFromContext(ctx) == nil && !s.options.AllowRootSpan { 502 | return s.parent.(driver.StmtQueryContext).QueryContext(ctx, args) 503 | } 504 | 505 | span, ctx := s.tracer.StartSpanFromContext( 506 | ctx, 507 | "sql/query", 508 | zipkin.Kind(zipkinmodel.Client), 509 | zipkin.RemoteEndpoint(s.options.RemoteEndpoint), 510 | ) 511 | defer func() { 512 | setSpanError(span, err) 513 | span.Finish() 514 | }() 515 | 516 | if s.options.TagQuery { 517 | span.Tag("sql.query", s.query) 518 | if s.options.TagQueryParams { 519 | addNamedParamsTags(span, args) 520 | } 521 | } 522 | 523 | setSpanDefaultTags(span, s.options.DefaultTags) 524 | 525 | defer func() { 526 | setSpanError(span, err) 527 | span.Finish() 528 | }() 529 | 530 | // we already tested driver to implement StmtQueryContext 531 | queryContext := s.parent.(driver.StmtQueryContext) 532 | rows, err = queryContext.QueryContext(ctx, args) 533 | if err != nil { 534 | return nil, err 535 | } 536 | 537 | return 538 | } 539 | 540 | // zTx implemens driver.Tx 541 | type zTx struct { 542 | parent driver.Tx 543 | ctx context.Context 544 | tracer *zipkin.Tracer 545 | options TraceOptions 546 | } 547 | 548 | func (t zTx) Commit() (err error) { 549 | if zipkin.SpanFromContext(t.ctx) != nil || t.options.AllowRootSpan { 550 | span, _ := t.tracer.StartSpanFromContext( 551 | t.ctx, 552 | "sql/commit", 553 | zipkin.Kind(zipkinmodel.Client), 554 | zipkin.RemoteEndpoint(t.options.RemoteEndpoint), 555 | ) 556 | defer func() { 557 | setSpanDefaultTags(span, t.options.DefaultTags) 558 | setSpanError(span, err) 559 | span.Finish() 560 | }() 561 | } 562 | err = t.parent.Commit() 563 | return 564 | } 565 | 566 | func (t zTx) Rollback() (err error) { 567 | if zipkin.SpanFromContext(t.ctx) != nil || t.options.AllowRootSpan { 568 | span, _ := t.tracer.StartSpanFromContext( 569 | t.ctx, 570 | "sql/rollback", 571 | zipkin.Kind(zipkinmodel.Client), 572 | zipkin.RemoteEndpoint(t.options.RemoteEndpoint), 573 | ) 574 | defer func() { 575 | setSpanDefaultTags(span, t.options.DefaultTags) 576 | setSpanError(span, err) 577 | span.Finish() 578 | }() 579 | } 580 | err = t.parent.Rollback() 581 | return 582 | } 583 | 584 | func addParamsTags(span zipkin.Span, args []driver.Value) { 585 | for i, arg := range args { 586 | key := "sql.arg" + strconv.Itoa(i) 587 | span.Tag(key, argToTagValue(arg)) 588 | } 589 | } 590 | 591 | func addNamedParamsTags(span zipkin.Span, args []driver.NamedValue) { 592 | for _, arg := range args { 593 | var key string 594 | if arg.Name != "" { 595 | key = arg.Name 596 | } else { 597 | key = "sql.arg." + strconv.Itoa(arg.Ordinal) 598 | } 599 | span.Tag(key, argToTagValue(arg.Value)) 600 | } 601 | } 602 | 603 | func argToTagValue(val interface{}) string { 604 | switch v := val.(type) { 605 | case nil: 606 | return "NULL" 607 | case int64: 608 | return fmt.Sprintf("%d", v) 609 | case float64: 610 | return fmt.Sprintf("%f", v) 611 | case bool: 612 | if v { 613 | return "true" 614 | } 615 | return "false" 616 | case []byte: 617 | if len(v) > 256 { 618 | v = v[0:256] 619 | } 620 | return fmt.Sprintf("%s", v) 621 | default: 622 | s := fmt.Sprintf("%v", v) 623 | if len(s) > 256 { 624 | s = s[0:256] 625 | } 626 | return s 627 | } 628 | } 629 | 630 | func setSpanError(span zipkin.Span, err error) { 631 | if err != nil { 632 | zipkin.TagError.Set(span, err.Error()) 633 | } 634 | } 635 | 636 | func setSpanDefaultTags(span zipkin.Span, tags map[string]string) { 637 | for key, value := range tags { 638 | span.Tag(key, value) 639 | } 640 | } 641 | -------------------------------------------------------------------------------- /driver_go1.09.go: -------------------------------------------------------------------------------- 1 | // +build go1.9,!go1.10 2 | 3 | package zipkinsql 4 | 5 | import ( 6 | "database/sql" 7 | "database/sql/driver" 8 | 9 | zipkin "github.com/openzipkin/zipkin-go" 10 | ) 11 | 12 | var errConnDone = sql.ErrConnDone 13 | 14 | // zDriver implements driver.Driver 15 | type zDriver struct { 16 | parent driver.Driver 17 | tracer *zipkin.Tracer 18 | options TraceOptions 19 | } 20 | 21 | func wrapDriver(d driver.Driver, t *zipkin.Tracer, o TraceOptions) driver.Driver { 22 | return zDriver{parent: d, tracer: t, options: o} 23 | } 24 | 25 | func wrapConn(parent driver.Conn, t *zipkin.Tracer, options TraceOptions) driver.Conn { 26 | var ( 27 | n, hasNameValueChecker = parent.(driver.NamedValueChecker) 28 | ) 29 | c := &zConn{parent: parent, tracer: t, options: options} 30 | if hasNameValueChecker { 31 | return struct { 32 | conn 33 | driver.NamedValueChecker 34 | }{c, n} 35 | } 36 | return c 37 | } 38 | 39 | func wrapStmt(stmt driver.Stmt, query string, tracer *zipkin.Tracer, options TraceOptions) driver.Stmt { 40 | var ( 41 | _, hasExeCtx = stmt.(driver.StmtExecContext) 42 | _, hasQryCtx = stmt.(driver.StmtQueryContext) 43 | c, hasColConv = stmt.(driver.ColumnConverter) 44 | n, hasNamValChk = stmt.(driver.NamedValueChecker) 45 | ) 46 | 47 | s := zStmt{parent: stmt, query: query, tracer: tracer, options: options} 48 | switch { 49 | case !hasExeCtx && !hasQryCtx && !hasColConv && !hasNamValChk: 50 | return struct { 51 | driver.Stmt 52 | }{s} 53 | case !hasExeCtx && hasQryCtx && !hasColConv && !hasNamValChk: 54 | return struct { 55 | driver.Stmt 56 | driver.StmtQueryContext 57 | }{s, s} 58 | case hasExeCtx && !hasQryCtx && !hasColConv && !hasNamValChk: 59 | return struct { 60 | driver.Stmt 61 | driver.StmtExecContext 62 | }{s, s} 63 | case hasExeCtx && hasQryCtx && !hasColConv && !hasNamValChk: 64 | return struct { 65 | driver.Stmt 66 | driver.StmtExecContext 67 | driver.StmtQueryContext 68 | }{s, s, s} 69 | case !hasExeCtx && !hasQryCtx && hasColConv && !hasNamValChk: 70 | return struct { 71 | driver.Stmt 72 | driver.ColumnConverter 73 | }{s, c} 74 | case !hasExeCtx && hasQryCtx && hasColConv && !hasNamValChk: 75 | return struct { 76 | driver.Stmt 77 | driver.StmtQueryContext 78 | driver.ColumnConverter 79 | }{s, s, c} 80 | case hasExeCtx && !hasQryCtx && hasColConv && !hasNamValChk: 81 | return struct { 82 | driver.Stmt 83 | driver.StmtExecContext 84 | driver.ColumnConverter 85 | }{s, s, c} 86 | case hasExeCtx && hasQryCtx && hasColConv && !hasNamValChk: 87 | return struct { 88 | driver.Stmt 89 | driver.StmtExecContext 90 | driver.StmtQueryContext 91 | driver.ColumnConverter 92 | }{s, s, s, c} 93 | 94 | case !hasExeCtx && !hasQryCtx && !hasColConv && hasNamValChk: 95 | return struct { 96 | driver.Stmt 97 | driver.NamedValueChecker 98 | }{s, n} 99 | case !hasExeCtx && hasQryCtx && !hasColConv && hasNamValChk: 100 | return struct { 101 | driver.Stmt 102 | driver.StmtQueryContext 103 | driver.NamedValueChecker 104 | }{s, s, n} 105 | case hasExeCtx && !hasQryCtx && !hasColConv && hasNamValChk: 106 | return struct { 107 | driver.Stmt 108 | driver.StmtExecContext 109 | driver.NamedValueChecker 110 | }{s, s, n} 111 | case hasExeCtx && hasQryCtx && !hasColConv && hasNamValChk: 112 | return struct { 113 | driver.Stmt 114 | driver.StmtExecContext 115 | driver.StmtQueryContext 116 | driver.NamedValueChecker 117 | }{s, s, s, n} 118 | case !hasExeCtx && !hasQryCtx && hasColConv && hasNamValChk: 119 | return struct { 120 | driver.Stmt 121 | driver.ColumnConverter 122 | driver.NamedValueChecker 123 | }{s, c, n} 124 | case !hasExeCtx && hasQryCtx && hasColConv && hasNamValChk: 125 | return struct { 126 | driver.Stmt 127 | driver.StmtQueryContext 128 | driver.ColumnConverter 129 | driver.NamedValueChecker 130 | }{s, s, c, n} 131 | case hasExeCtx && !hasQryCtx && hasColConv && hasNamValChk: 132 | return struct { 133 | driver.Stmt 134 | driver.StmtExecContext 135 | driver.ColumnConverter 136 | driver.NamedValueChecker 137 | }{s, s, c, n} 138 | case hasExeCtx && hasQryCtx && hasColConv && hasNamValChk: 139 | return struct { 140 | driver.Stmt 141 | driver.StmtExecContext 142 | driver.StmtQueryContext 143 | driver.ColumnConverter 144 | driver.NamedValueChecker 145 | }{s, s, s, c, n} 146 | } 147 | panic("unreachable") 148 | } 149 | -------------------------------------------------------------------------------- /driver_go1.10.go: -------------------------------------------------------------------------------- 1 | // +build go1.10 2 | 3 | package zipkinsql 4 | 5 | import ( 6 | "context" 7 | "database/sql" 8 | "database/sql/driver" 9 | 10 | zipkin "github.com/openzipkin/zipkin-go" 11 | ) 12 | 13 | var errConnDone = sql.ErrConnDone 14 | 15 | // Compile time assertion 16 | var ( 17 | _ driver.DriverContext = &zDriver{} 18 | _ driver.Connector = &zDriver{} 19 | ) 20 | 21 | // WrapConnector allows wrapping a database driver.Connector which eliminates 22 | // the need to register zipkinsql as an available driver.Driver. 23 | func WrapConnector(dc driver.Connector, t *zipkin.Tracer, options ...TraceOption) driver.Connector { 24 | opts := TraceOptions{} 25 | for _, o := range options { 26 | o(&opts) 27 | } 28 | 29 | return &zDriver{ 30 | parent: dc.Driver(), 31 | connector: dc, 32 | tracer: t, 33 | options: opts, 34 | } 35 | } 36 | 37 | // zDriver implements driver.Driver 38 | type zDriver struct { 39 | parent driver.Driver 40 | connector driver.Connector 41 | tracer *zipkin.Tracer 42 | options TraceOptions 43 | } 44 | 45 | func wrapDriver(d driver.Driver, t *zipkin.Tracer, o TraceOptions) driver.Driver { 46 | if _, ok := d.(driver.DriverContext); ok { 47 | return zDriver{parent: d, tracer: t, options: o} 48 | } 49 | return struct{ driver.Driver }{zDriver{parent: d, tracer: t, options: o}} 50 | } 51 | 52 | func wrapConn(parent driver.Conn, t *zipkin.Tracer, options TraceOptions) driver.Conn { 53 | var ( 54 | n, hasNameValueChecker = parent.(driver.NamedValueChecker) 55 | s, hasSessionResetter = parent.(driver.SessionResetter) 56 | ) 57 | c := &zConn{parent: parent, tracer: t, options: options} 58 | switch { 59 | case !hasNameValueChecker && !hasSessionResetter: 60 | return c 61 | case hasNameValueChecker && !hasSessionResetter: 62 | return struct { 63 | conn 64 | driver.NamedValueChecker 65 | }{c, n} 66 | case !hasNameValueChecker && hasSessionResetter: 67 | return struct { 68 | conn 69 | driver.SessionResetter 70 | }{c, s} 71 | case hasNameValueChecker && hasSessionResetter: 72 | return struct { 73 | conn 74 | driver.NamedValueChecker 75 | driver.SessionResetter 76 | }{c, n, s} 77 | } 78 | panic("unreachable") 79 | } 80 | 81 | func wrapStmt(stmt driver.Stmt, query string, tracer *zipkin.Tracer, options TraceOptions) driver.Stmt { 82 | var ( 83 | _, hasExeCtx = stmt.(driver.StmtExecContext) 84 | _, hasQryCtx = stmt.(driver.StmtQueryContext) 85 | c, hasColConv = stmt.(driver.ColumnConverter) 86 | n, hasNamValChk = stmt.(driver.NamedValueChecker) 87 | ) 88 | 89 | s := zStmt{parent: stmt, query: query, tracer: tracer, options: options} 90 | switch { 91 | case !hasExeCtx && !hasQryCtx && !hasColConv && !hasNamValChk: 92 | return struct { 93 | driver.Stmt 94 | }{s} 95 | case !hasExeCtx && hasQryCtx && !hasColConv && !hasNamValChk: 96 | return struct { 97 | driver.Stmt 98 | driver.StmtQueryContext 99 | }{s, s} 100 | case hasExeCtx && !hasQryCtx && !hasColConv && !hasNamValChk: 101 | return struct { 102 | driver.Stmt 103 | driver.StmtExecContext 104 | }{s, s} 105 | case hasExeCtx && hasQryCtx && !hasColConv && !hasNamValChk: 106 | return struct { 107 | driver.Stmt 108 | driver.StmtExecContext 109 | driver.StmtQueryContext 110 | }{s, s, s} 111 | case !hasExeCtx && !hasQryCtx && hasColConv && !hasNamValChk: 112 | return struct { 113 | driver.Stmt 114 | driver.ColumnConverter 115 | }{s, c} 116 | case !hasExeCtx && hasQryCtx && hasColConv && !hasNamValChk: 117 | return struct { 118 | driver.Stmt 119 | driver.StmtQueryContext 120 | driver.ColumnConverter 121 | }{s, s, c} 122 | case hasExeCtx && !hasQryCtx && hasColConv && !hasNamValChk: 123 | return struct { 124 | driver.Stmt 125 | driver.StmtExecContext 126 | driver.ColumnConverter 127 | }{s, s, c} 128 | case hasExeCtx && hasQryCtx && hasColConv && !hasNamValChk: 129 | return struct { 130 | driver.Stmt 131 | driver.StmtExecContext 132 | driver.StmtQueryContext 133 | driver.ColumnConverter 134 | }{s, s, s, c} 135 | 136 | case !hasExeCtx && !hasQryCtx && !hasColConv && hasNamValChk: 137 | return struct { 138 | driver.Stmt 139 | driver.NamedValueChecker 140 | }{s, n} 141 | case !hasExeCtx && hasQryCtx && !hasColConv && hasNamValChk: 142 | return struct { 143 | driver.Stmt 144 | driver.StmtQueryContext 145 | driver.NamedValueChecker 146 | }{s, s, n} 147 | case hasExeCtx && !hasQryCtx && !hasColConv && hasNamValChk: 148 | return struct { 149 | driver.Stmt 150 | driver.StmtExecContext 151 | driver.NamedValueChecker 152 | }{s, s, n} 153 | case hasExeCtx && hasQryCtx && !hasColConv && hasNamValChk: 154 | return struct { 155 | driver.Stmt 156 | driver.StmtExecContext 157 | driver.StmtQueryContext 158 | driver.NamedValueChecker 159 | }{s, s, s, n} 160 | case !hasExeCtx && !hasQryCtx && hasColConv && hasNamValChk: 161 | return struct { 162 | driver.Stmt 163 | driver.ColumnConverter 164 | driver.NamedValueChecker 165 | }{s, c, n} 166 | case !hasExeCtx && hasQryCtx && hasColConv && hasNamValChk: 167 | return struct { 168 | driver.Stmt 169 | driver.StmtQueryContext 170 | driver.ColumnConverter 171 | driver.NamedValueChecker 172 | }{s, s, c, n} 173 | case hasExeCtx && !hasQryCtx && hasColConv && hasNamValChk: 174 | return struct { 175 | driver.Stmt 176 | driver.StmtExecContext 177 | driver.ColumnConverter 178 | driver.NamedValueChecker 179 | }{s, s, c, n} 180 | case hasExeCtx && hasQryCtx && hasColConv && hasNamValChk: 181 | return struct { 182 | driver.Stmt 183 | driver.StmtExecContext 184 | driver.StmtQueryContext 185 | driver.ColumnConverter 186 | driver.NamedValueChecker 187 | }{s, s, s, c, n} 188 | } 189 | panic("unreachable") 190 | } 191 | 192 | func (d zDriver) OpenConnector(name string) (driver.Connector, error) { 193 | var err error 194 | d.connector, err = d.parent.(driver.DriverContext).OpenConnector(name) 195 | if err != nil { 196 | return nil, err 197 | } 198 | return d, err 199 | } 200 | 201 | func (d zDriver) Connect(ctx context.Context) (driver.Conn, error) { 202 | c, err := d.connector.Connect(ctx) 203 | if err != nil { 204 | return nil, err 205 | } 206 | return &zConn{parent: c, tracer: d.tracer, options: d.options}, nil 207 | } 208 | 209 | func (d zDriver) Driver() driver.Driver { 210 | return d 211 | } 212 | -------------------------------------------------------------------------------- /driver_test.go: -------------------------------------------------------------------------------- 1 | package zipkinsql 2 | 3 | import ( 4 | "context" 5 | "database/sql" 6 | "testing" 7 | 8 | _ "github.com/mattn/go-sqlite3" 9 | zipkin "github.com/openzipkin/zipkin-go" 10 | "github.com/openzipkin/zipkin-go/model" 11 | zipkinreporter "github.com/openzipkin/zipkin-go/reporter/recorder" 12 | ) 13 | 14 | func createDB(t *testing.T, opts ...TraceOption) (*sql.DB, *zipkin.Tracer, *zipkinreporter.ReporterRecorder) { 15 | reporter := zipkinreporter.NewReporter() 16 | tracer, _ := zipkin.NewTracer(reporter) 17 | 18 | driverName, err := Register("sqlite3", tracer, opts...) 19 | if err != nil { 20 | t.Fatalf("unable to register driver") 21 | } 22 | 23 | db, err := sql.Open(driverName, "file:test.db?cache=shared&mode=memory") 24 | if err != nil { 25 | t.Fatal(err) 26 | } 27 | 28 | return db, tracer, reporter 29 | } 30 | 31 | type testCase struct { 32 | opts []TraceOption 33 | expectedSpans int 34 | } 35 | 36 | func TestQuerySuccess(t *testing.T) { 37 | testCases := []testCase{ 38 | {[]TraceOption{WithAllowRootSpan(false)}, 0}, 39 | {[]TraceOption{WithAllowRootSpan(true)}, 1}, 40 | {[]TraceOption{WithAllowRootSpan(true), WithTagQuery(true), WithTagQueryParams(true)}, 1}, 41 | } 42 | for _, c := range testCases { 43 | db, _, recorder := createDB(t, c.opts...) 44 | 45 | rows, err := db.Query("SELECT 1 WHERE 1 = ?", 1) 46 | if err != nil { 47 | t.Fatalf("unexpected error: %s", err.Error()) 48 | } 49 | defer rows.Close() 50 | 51 | for rows.Next() { 52 | var n int 53 | if err = rows.Scan(&n); err != nil { 54 | t.Fatalf("unexpected error: %s", err.Error()) 55 | } 56 | } 57 | if err = rows.Err(); err != nil { 58 | t.Fatalf("unexpected error: %s", err.Error()) 59 | } 60 | 61 | spans := recorder.Flush() 62 | if want, have := c.expectedSpans, len(spans); want != have { 63 | t.Fatalf("unexpected number of spans, want: %d, have: %d", want, have) 64 | } 65 | 66 | if c.expectedSpans > 0 { 67 | if want, have := "sql/query", spans[0].Name; want != have { 68 | t.Fatalf("unexpected span name, want: %s, have: %s", want, have) 69 | } 70 | 71 | if errMsg, ok := spans[0].Tags["error"]; ok { 72 | t.Fatalf("unexpected error: %s", errMsg) 73 | } 74 | } 75 | 76 | db.Close() 77 | recorder.Close() 78 | } 79 | } 80 | func TestQueryContextSuccess(t *testing.T) { 81 | ctx := context.Background() 82 | testCases := []testCase{ 83 | {[]TraceOption{WithAllowRootSpan(false)}, 0}, 84 | {[]TraceOption{WithAllowRootSpan(true)}, 1}, 85 | {[]TraceOption{WithAllowRootSpan(true), WithTagQuery(true), WithTagQueryParams(true)}, 1}, 86 | } 87 | for _, c := range testCases { 88 | db, _, recorder := createDB(t, c.opts...) 89 | 90 | rows, err := db.QueryContext(ctx, "SELECT 1 WHERE 1 = ?", 1) 91 | if err != nil { 92 | t.Fatalf("unexpected error: %s", err.Error()) 93 | } 94 | defer rows.Close() 95 | 96 | for rows.Next() { 97 | var n int 98 | if err = rows.Scan(&n); err != nil { 99 | t.Fatalf("unexpected error: %s", err.Error()) 100 | } 101 | } 102 | if err = rows.Err(); err != nil { 103 | t.Fatalf("unexpected error: %s", err.Error()) 104 | } 105 | 106 | spans := recorder.Flush() 107 | if want, have := c.expectedSpans, len(spans); want != have { 108 | t.Fatalf("unexpected number of spans, want: %d, have: %d", want, have) 109 | } 110 | 111 | if c.expectedSpans > 0 { 112 | if want, have := "sql/query", spans[0].Name; want != have { 113 | t.Fatalf("unexpected span name, want: %s, have: %s", want, have) 114 | } 115 | 116 | if errMsg, ok := spans[0].Tags["error"]; ok { 117 | t.Fatalf("unexpected error: %s", errMsg) 118 | } 119 | } 120 | 121 | db.Close() 122 | recorder.Close() 123 | } 124 | } 125 | 126 | func TestQueryContextPropagationSuccess(t *testing.T) { 127 | ctx := context.Background() 128 | db, tracer, recorder := createDB(t, WithAllowRootSpan(false)) 129 | 130 | span, ctx := tracer.StartSpanFromContext(ctx, "root") 131 | 132 | rows, err := db.QueryContext(ctx, "SELECT 1 WHERE 1 = ?", 1) 133 | if err != nil { 134 | t.Fatalf("unexpected error: %s", err.Error()) 135 | } 136 | defer rows.Close() 137 | 138 | for rows.Next() { 139 | var n int 140 | if err = rows.Scan(&n); err != nil { 141 | t.Fatalf("unexpected error: %s", err.Error()) 142 | } 143 | } 144 | if err = rows.Err(); err != nil { 145 | t.Fatalf("unexpected error: %s", err.Error()) 146 | } 147 | 148 | span.Finish() 149 | 150 | spans := recorder.Flush() 151 | if want, have := 2, len(spans); want != have { 152 | t.Fatalf("unexpected number of spans, want: %d, have: %d", want, have) 153 | } 154 | 155 | if want, have := "sql/query", spans[0].Name; want != have { 156 | t.Fatalf("unexpected span name, want: %s, have: %s", want, have) 157 | } 158 | 159 | if errMsg, ok := spans[0].Tags["error"]; ok { 160 | t.Fatalf("unexpected error: %s", errMsg) 161 | } 162 | 163 | db.Close() 164 | recorder.Close() 165 | } 166 | 167 | func TestExecContextSuccess(t *testing.T) { 168 | ctx := context.Background() 169 | 170 | testCases := []testCase{ 171 | {[]TraceOption{WithAllowRootSpan(false)}, 0}, 172 | {[]TraceOption{WithAllowRootSpan(true)}, 1}, 173 | {[]TraceOption{WithAllowRootSpan(true), WithLastInsertIDSpan(true)}, 2}, 174 | {[]TraceOption{WithAllowRootSpan(true), WithRowsAffectedSpan(true)}, 2}, 175 | {[]TraceOption{WithAllowRootSpan(true), WithLastInsertIDSpan(true), WithRowsAffectedSpan(true)}, 3}, 176 | {[]TraceOption{WithAllowRootSpan(true), WithLastInsertIDSpan(true), WithRowsAffectedSpan(true), WithTagQuery(true), WithTagQueryParams(true)}, 3}, 177 | {[]TraceOption{WithAllowRootSpan(true), WithRemoteEndpoint(model.Endpoint{ServiceName: "myservice"})}, 1}, 178 | } 179 | for _, c := range testCases { 180 | db, _, recorder := createDB(t, c.opts...) 181 | 182 | sqlStmt := ` 183 | drop table if exists foo; 184 | create table foo (id integer not null primary key, name text); 185 | delete from foo; 186 | ` 187 | 188 | res, err := db.ExecContext(ctx, sqlStmt) 189 | if err != nil { 190 | t.Fatalf("unexpected error: %s", err.Error()) 191 | } 192 | 193 | _, err = res.LastInsertId() 194 | if err != nil { 195 | t.Fatalf("unexpected error: %s", err.Error()) 196 | } 197 | 198 | _, err = res.RowsAffected() 199 | if err != nil { 200 | t.Fatalf("unexpected error: %s", err.Error()) 201 | } 202 | 203 | spans := recorder.Flush() 204 | if want, have := c.expectedSpans, len(spans); want != have { 205 | t.Fatalf("unexpected number of spans, want: %d, have: %d", want, have) 206 | } 207 | 208 | if c.expectedSpans > 0 { 209 | if want, have := "sql/exec", spans[0].Name; want != have { 210 | t.Fatalf("unexpected span name, want: %s, have: %s", want, have) 211 | } 212 | 213 | if errMsg, ok := spans[0].Tags["error"]; ok { 214 | t.Fatalf("unexpected error: %s", errMsg) 215 | } 216 | } 217 | 218 | db.Close() 219 | recorder.Close() 220 | } 221 | } 222 | 223 | func TestTxWithCommitSuccess(t *testing.T) { 224 | ctx := context.Background() 225 | 226 | testCases := []testCase{ 227 | {[]TraceOption{WithAllowRootSpan(false)}, 0}, 228 | {[]TraceOption{WithAllowRootSpan(true)}, 5}, 229 | {[]TraceOption{WithAllowRootSpan(true), WithTagQuery(true), WithTagQueryParams(true)}, 5}, 230 | } 231 | 232 | for _, c := range testCases { 233 | db, _, recorder := createDB(t, c.opts...) 234 | 235 | sqlStmt := ` 236 | drop table if exists foo; 237 | create table foo (id integer not null primary key, name text); 238 | delete from foo; 239 | ` 240 | 241 | _, err := db.ExecContext(ctx, sqlStmt) 242 | if err != nil { 243 | t.Fatalf("unexpected error: %s", err.Error()) 244 | } 245 | 246 | tx, err := db.BeginTx(ctx, nil) 247 | if err != nil { 248 | t.Fatalf("unexpected error: %s", err.Error()) 249 | } 250 | stmt, err := tx.Prepare("insert into foo(id, name) values(?, ?)") 251 | if err != nil { 252 | t.Fatalf("unexpected error: %s", err.Error()) 253 | } 254 | defer stmt.Close() 255 | _, err = stmt.Exec("1", "こんにちわ世界") 256 | if err != nil { 257 | t.Fatalf("unexpected error: %s", err.Error()) 258 | } 259 | tx.Commit() 260 | 261 | spans := recorder.Flush() 262 | if want, have := c.expectedSpans, len(spans); want != have { 263 | t.Fatalf("unexpected number of spans, want: %d, have: %d", want, have) 264 | } 265 | 266 | if c.expectedSpans > 0 { 267 | if want, have := "sql/exec", spans[0].Name; want != have { 268 | t.Fatalf("unexpected first span name, want: %s, have: %s", want, have) 269 | } 270 | if want, have := "sql/begin_transaction", spans[1].Name; want != have { 271 | t.Fatalf("unexpected second span name, want: %s, have: %s", want, have) 272 | } 273 | if want, have := "sql/prepare", spans[2].Name; want != have { 274 | t.Fatalf("unexpected third span name, want: %s, have: %s", want, have) 275 | } 276 | if want, have := "sql/exec", spans[3].Name; want != have { 277 | t.Fatalf("unexpected fourth span name, want: %s, have: %s", want, have) 278 | } 279 | if want, have := "sql/commit", spans[4].Name; want != have { 280 | t.Fatalf("unexpected fifth span name, want: %s, have: %s", want, have) 281 | } 282 | 283 | for i := 0; i < 5; i++ { 284 | if errMsg, ok := spans[i].Tags["error"]; ok { 285 | t.Fatalf("unexpected error: %s", errMsg) 286 | } 287 | } 288 | } 289 | 290 | db.Close() 291 | recorder.Close() 292 | } 293 | } 294 | 295 | func TestTxWithRollbackSuccess(t *testing.T) { 296 | ctx := context.Background() 297 | 298 | testCases := []testCase{ 299 | {[]TraceOption{WithAllowRootSpan(false)}, 0}, 300 | {[]TraceOption{WithAllowRootSpan(true)}, 5}, 301 | {[]TraceOption{WithAllowRootSpan(true), WithTagQuery(true), WithTagQueryParams(true)}, 5}, 302 | } 303 | 304 | for _, c := range testCases { 305 | db, _, recorder := createDB(t, c.opts...) 306 | 307 | sqlStmt := ` 308 | drop table if exists foo; 309 | create table foo (id integer not null primary key, name text); 310 | delete from foo; 311 | ` 312 | 313 | _, err := db.ExecContext(ctx, sqlStmt) 314 | if err != nil { 315 | t.Fatalf("unexpected error: %s", err.Error()) 316 | } 317 | 318 | tx, err := db.BeginTx(ctx, nil) 319 | if err != nil { 320 | t.Fatalf("unexpected error: %s", err.Error()) 321 | } 322 | stmt, err := tx.Prepare("insert into foo(id, name) values(?, ?)") 323 | if err != nil { 324 | t.Fatalf("unexpected error: %s", err.Error()) 325 | } 326 | defer stmt.Close() 327 | _, err = stmt.Exec("1", "こんにちわ世界") 328 | tx.Rollback() 329 | 330 | spans := recorder.Flush() 331 | if want, have := c.expectedSpans, len(spans); want != have { 332 | t.Fatalf("unexpected number of spans, want: %d, have: %d", want, have) 333 | } 334 | 335 | if c.expectedSpans > 0 { 336 | if want, have := "sql/exec", spans[0].Name; want != have { 337 | t.Fatalf("unexpected first span name, want: %s, have: %s", want, have) 338 | } 339 | if want, have := "sql/begin_transaction", spans[1].Name; want != have { 340 | t.Fatalf("unexpected second span name, want: %s, have: %s", want, have) 341 | } 342 | if want, have := "sql/prepare", spans[2].Name; want != have { 343 | t.Fatalf("unexpected third span name, want: %s, have: %s", want, have) 344 | } 345 | if want, have := "sql/exec", spans[3].Name; want != have { 346 | t.Fatalf("unexpected fourth span name, want: %s, have: %s", want, have) 347 | } 348 | if want, have := "sql/rollback", spans[4].Name; want != have { 349 | t.Fatalf("unexpected fifth span name, want: %s, have: %s", want, have) 350 | } 351 | 352 | for i := 0; i < c.expectedSpans; i++ { 353 | if errMsg, ok := spans[i].Tags["error"]; ok { 354 | t.Fatalf("unexpected error: %s", errMsg) 355 | } 356 | } 357 | } 358 | 359 | db.Close() 360 | recorder.Close() 361 | } 362 | } 363 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/openzipkin-contrib/zipkin-go-sql 2 | 3 | go 1.13 4 | 5 | require ( 6 | github.com/go-sql-driver/mysql v1.5.0 // indirect 7 | github.com/jmoiron/sqlx v1.2.0 8 | github.com/lib/pq v1.3.0 9 | github.com/mattn/go-sqlite3 v2.0.3+incompatible 10 | github.com/openzipkin/zipkin-go v0.2.2 11 | ) 12 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= 2 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= 3 | github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo= 4 | github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= 5 | github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= 6 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 7 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 8 | github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= 9 | github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU= 10 | github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= 11 | github.com/envoyproxy/go-control-plane v0.6.9/go.mod h1:SBwIajubJHhxtWwsL9s8ss4safvEdbitLhGGK48rN6g= 12 | github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= 13 | github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= 14 | github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs= 15 | github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= 16 | github.com/gogo/googleapis v1.1.0/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s= 17 | github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= 18 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= 19 | github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= 20 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 21 | github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= 22 | github.com/gorilla/context v1.1.1 h1:AWwleXJkX/nhcU9bZSnZoi3h/qGYqQAGhq6zZe/aQW8= 23 | github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= 24 | github.com/gorilla/mux v1.6.2 h1:Pgr17XVTNXAk3q/r4CpKzC5xBM/qW1uVLV+IhRZpIIk= 25 | github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= 26 | github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= 27 | github.com/jmoiron/sqlx v1.2.0 h1:41Ip0zITnmWNR/vHV+S4m+VoUivnWY5E4OJfLZjCJMA= 28 | github.com/jmoiron/sqlx v1.2.0/go.mod h1:1FEQNm3xlJgrMD+FBdI9+xvCksHtbpVBBw5dYhBSsks= 29 | github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= 30 | github.com/lib/pq v1.3.0 h1:/qkRGz8zljWiDcFvgpwUpwIAPu3r07TDvs3Rws+o/pU= 31 | github.com/lib/pq v1.3.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= 32 | github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= 33 | github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= 34 | github.com/mattn/go-sqlite3 v2.0.3+incompatible h1:gXHsfypPkaMZrKbD5209QV9jbUTJKjyR5WD3HYQSd+U= 35 | github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= 36 | github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= 37 | github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= 38 | github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= 39 | github.com/openzipkin/zipkin-go v0.2.2 h1:nY8Hti+WKaP0cRsSeQ026wU03QsM762XBeCXBb9NAWI= 40 | github.com/openzipkin/zipkin-go v0.2.2/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= 41 | github.com/pierrec/lz4 v1.0.2-0.20190131084431-473cd7ce01a1/go.mod h1:3/3N9NVKO0jef7pBehbT1qWhCMrIgbYNnFAZCqQ5LRc= 42 | github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA= 43 | github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= 44 | github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= 45 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 46 | golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= 47 | golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 48 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 49 | golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= 50 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 51 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 52 | golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 53 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 54 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 55 | golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= 56 | google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= 57 | google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= 58 | google.golang.org/grpc v1.20.0 h1:DlsSIrgEBuZAUFJcta2B5i/lzeHHbnfkNFAfFXLVFYQ= 59 | google.golang.org/grpc v1.20.0/go.mod h1:chYK+tFQF0nDUGJgXMSgLCQk3phJEuONr2DCgLDdAQM= 60 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 61 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 62 | gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= 63 | gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= 64 | gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 65 | honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= 66 | -------------------------------------------------------------------------------- /options.go: -------------------------------------------------------------------------------- 1 | package zipkinsql 2 | 3 | import ( 4 | "github.com/openzipkin/zipkin-go/model" 5 | ) 6 | 7 | // TraceOption allows for managing zipkinsql configuration using functional options. 8 | type TraceOption func(o *TraceOptions) 9 | 10 | // TraceOptions holds configuration of our zipkinsql tracing middleware. 11 | // By default all boolean options are set to false intentionally when creating 12 | // a wrapped driver and provide the most sensible default with both performance 13 | // and security in mind. 14 | type TraceOptions struct { 15 | // AllowRoot, if set to true, will allow zipkinsql to create root spans in 16 | // absence of existing spans or even context. 17 | // Default is to not trace zipkinsql calls if no existing parent span is found 18 | // in context or when using methods not taking context. 19 | AllowRootSpan bool 20 | 21 | // LastInsertIDSpan, if set to true, will enable the creation of spans on 22 | // LastInsertId calls. 23 | LastInsertIDSpan bool 24 | 25 | // RowsAffectedSpan, if set to true, will enable the creation of spans on 26 | // RowsAffectedSpan calls. 27 | RowsAffectedSpan bool 28 | 29 | // TagQuery, if set to true, will enable recording of sql queries in spans. 30 | // Only allow this if it is safe to have queries recorded with respect to 31 | // security. 32 | TagQuery bool 33 | 34 | // TagQueryParams, if set to true, will enable recording of parameters used 35 | // with parametrized queries. Only allow this if it is safe to have 36 | // parameters recorded with respect to security and privacy. 37 | // This setting is a noop if the TagQuery option is set to false. 38 | TagQueryParams bool 39 | 40 | // TagAffectedRows, if set to true, will enable the recording of the number of 41 | // affected rows for the query. Some engines may include this in the response 42 | // of the query but some require an extra query to obtain the number of affected 43 | // rows. 44 | TagAffectedRows bool 45 | 46 | // DefaultTags will be set to each span as default. 47 | DefaultTags map[string]string 48 | 49 | // RemoteEndpoint will include the remote endpoint information into the client 50 | // span. 51 | RemoteEndpoint *model.Endpoint 52 | } 53 | 54 | // WithAllTraceOptions enables all available trace options. 55 | func WithAllTraceOptions() TraceOption { 56 | return func(o *TraceOptions) { 57 | *o = AllTraceOptions 58 | } 59 | } 60 | 61 | // AllTraceOptions has all tracing options enabled. 62 | var AllTraceOptions = TraceOptions{ 63 | AllowRootSpan: true, 64 | RowsAffectedSpan: true, 65 | LastInsertIDSpan: true, 66 | TagQuery: true, 67 | TagQueryParams: true, 68 | TagAffectedRows: true, 69 | RemoteEndpoint: nil, 70 | } 71 | 72 | // WithOptions sets the zipkinsql tracing middleware options through a single 73 | // TraceOptions object. 74 | func WithOptions(options TraceOptions) TraceOption { 75 | return func(o *TraceOptions) { 76 | *o = options 77 | } 78 | } 79 | 80 | // WithAllowRootSpan if set to true, will allow zipkinsql to create root spans in 81 | // absence of exisiting spans or even context. 82 | // Default is to not trace zipkinsql calls if no existing parent span is found 83 | // in context or when using methods not taking context. 84 | func WithAllowRootSpan(b bool) TraceOption { 85 | return func(o *TraceOptions) { 86 | o.AllowRootSpan = b 87 | } 88 | } 89 | 90 | // WithRowsAffectedSpan if set to true, will enable the creation of spans on 91 | // RowsAffected calls. 92 | func WithRowsAffectedSpan(b bool) TraceOption { 93 | return func(o *TraceOptions) { 94 | o.RowsAffectedSpan = b 95 | } 96 | } 97 | 98 | // WithLastInsertIDSpan if set to true, will enable the creation of spans on 99 | // LastInsertId calls. 100 | func WithLastInsertIDSpan(b bool) TraceOption { 101 | return func(o *TraceOptions) { 102 | o.LastInsertIDSpan = b 103 | } 104 | } 105 | 106 | // WithTagQuery if set to true, will enable recording of SQL queries in spans. 107 | // Only allow this if it is safe to have queries recorded with respect to 108 | // security. 109 | func WithTagQuery(b bool) TraceOption { 110 | return func(o *TraceOptions) { 111 | o.TagQuery = b 112 | } 113 | } 114 | 115 | // WithTagQueryParams if set to true, will enable recording of parameters used 116 | // with parametrized queries. Only allow this if it is safe to have 117 | // parameters recorded with respect to security. 118 | // This setting is a noop if the TagQuery option is set to false. 119 | func WithTagQueryParams(b bool) TraceOption { 120 | return func(o *TraceOptions) { 121 | o.TagQueryParams = b 122 | } 123 | } 124 | 125 | // WithTagAffectedRows if set to true, will enable recording of the affected rows 126 | // number in spans. 127 | func WithTagAffectedRows(b bool) TraceOption { 128 | return func(o *TraceOptions) { 129 | o.TagAffectedRows = b 130 | } 131 | } 132 | 133 | // WithDefaultTags will be set to each span as default. 134 | func WithDefaultTags(tags map[string]string) TraceOption { 135 | return func(o *TraceOptions) { 136 | o.DefaultTags = tags 137 | } 138 | } 139 | 140 | // WithRemoteEndpoint will be set to each client span 141 | func WithRemoteEndpoint(e model.Endpoint) TraceOption { 142 | return func(o *TraceOptions) { 143 | o.RemoteEndpoint = &e 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /tests/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.7" 2 | services: 3 | postgres: 4 | image: postgres:latest 5 | environment: 6 | POSTGRES_USER: test_user 7 | POSTGRES_PASSWORD: test_pass 8 | POSTGRES_DB: test_db 9 | ports: 10 | - "5432:5432" 11 | -------------------------------------------------------------------------------- /tests/integration_test.go: -------------------------------------------------------------------------------- 1 | // build+ ignore 2 | 3 | package integration 4 | 5 | import ( 6 | "context" 7 | "database/sql" 8 | "testing" 9 | "time" 10 | 11 | zipkinsql "github.com/openzipkin-contrib/zipkin-go-sql" 12 | 13 | "github.com/openzipkin/zipkin-go" 14 | "github.com/openzipkin/zipkin-go/reporter/recorder" 15 | 16 | "database/sql/driver" 17 | 18 | "github.com/jmoiron/sqlx" 19 | "github.com/lib/pq" 20 | ) 21 | 22 | type testCase struct { 23 | driverName string 24 | driver driver.Driver 25 | dsn string 26 | } 27 | 28 | var ( 29 | postgresTestCase = testCase{ 30 | driverName: "postgres", 31 | driver: &pq.Driver{}, 32 | dsn: "postgres://test_user:test_pass@localhost/test_db?sslmode=disable", 33 | } 34 | ) 35 | 36 | const maxPingRetries = 5 37 | 38 | func TestDriver(t *testing.T) { 39 | tCases := []testCase{ 40 | postgresTestCase, 41 | } 42 | 43 | rec := recorder.NewReporter() 44 | tracer, _ := zipkin.NewTracer(rec, zipkin.WithSampler(zipkin.AlwaysSample)) 45 | 46 | for _, tCase := range tCases { 47 | t.Run("Testing driver "+tCase.driverName, func(t *testing.T) { 48 | driver := zipkinsql.Wrap(tCase.driver, tracer, zipkinsql.WithAllTraceOptions()) 49 | driverName := "traced-" + tCase.driverName 50 | sql.Register(driverName, driver) 51 | db, err := sql.Open(driverName, tCase.dsn) 52 | if err != nil { 53 | t.Fatalf("failed to open a DB: %v\n", err) 54 | } 55 | 56 | db.SetConnMaxLifetime(5 * time.Second) 57 | defer db.Close() 58 | 59 | for i := 0; i < maxPingRetries; i++ { 60 | if err = db.Ping(); err == nil { 61 | break 62 | } 63 | if i == maxPingRetries-1 { 64 | t.Fatalf("failed to ping the database: %v\n", err) 65 | } 66 | time.Sleep(time.Duration(i+1) * 200 * time.Millisecond) 67 | } 68 | ctx := context.Background() 69 | 70 | row := db.QueryRowContext(ctx, "SELECT 1") 71 | res := 0 72 | if err := row.Scan(&res); err != nil { 73 | t.Fatalf("failed to scan the result: %v\n", err) 74 | } 75 | 76 | if want, have := 1, res; want != have { 77 | t.Errorf("incorrect result: want %d, have: %d", want, have) 78 | } 79 | 80 | spans := rec.Flush() 81 | if want, have := 1, len(spans); want != have { 82 | t.Errorf("incorrect number of spans: want %d, have: %d", want, have) 83 | } 84 | 85 | s := spans[0] 86 | if want, have := "sql/query", s.Name; want != have { 87 | t.Errorf("incorrect span name: want %q, have: %q", want, have) 88 | } 89 | 90 | if want, have := "SELECT 1", s.Tags["sql.query"]; want != have { 91 | t.Errorf("incorrect tag: want %q, have: %q", want, have) 92 | } 93 | }) 94 | } 95 | } 96 | 97 | func TestSQLX(t *testing.T) { 98 | rec := recorder.NewReporter() 99 | tracer, _ := zipkin.NewTracer(rec, zipkin.WithSampler(zipkin.AlwaysSample)) 100 | 101 | driverName, err := zipkinsql.Register("postgres", tracer, zipkinsql.WithAllTraceOptions()) 102 | if err != nil { 103 | t.Fatalf("failed to register the driver: %v\n", err) 104 | } 105 | 106 | db, err := sql.Open(driverName, postgresTestCase.dsn) 107 | if err != nil { 108 | t.Fatalf("failed to open a DB: %v\n", err) 109 | } 110 | 111 | db.SetConnMaxLifetime(5 * time.Second) 112 | defer db.Close() 113 | 114 | err = db.Ping() 115 | if err != nil { 116 | t.Fatalf("failed to ping the database: %v\n", err) 117 | } 118 | 119 | ctx := context.Background() 120 | dbx := sqlx.NewDb(db, "postgres") 121 | row := dbx.QueryRowContext(ctx, "SELECT 2") 122 | res := 0 123 | if err := row.Scan(&res); err != nil { 124 | t.Fatalf("failed to scan the result: %v\n", err) 125 | } 126 | 127 | if want, have := 2, res; want != have { 128 | t.Errorf("incorrect result: want %d, have: %d", want, have) 129 | } 130 | 131 | spans := rec.Flush() 132 | if want, have := 1, len(spans); want != have { 133 | t.Errorf("incorrect number of spans: want %d, have: %d", want, have) 134 | } 135 | 136 | s := spans[0] 137 | if want, have := "sql/query", s.Name; want != have { 138 | t.Errorf("incorrect span name of spans: want %q, have: %q", want, have) 139 | } 140 | 141 | if want, have := "SELECT 2", s.Tags["sql.query"]; want != have { 142 | t.Errorf("incorrect tag: want %q, have: %q", want, have) 143 | } 144 | } 145 | --------------------------------------------------------------------------------