|
| 1 | +// Copyright 2022 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package gosql |
| 16 | + |
| 17 | +import ( |
| 18 | + "context" |
| 19 | + "database/sql" |
| 20 | + "fmt" |
| 21 | + "net/http" |
| 22 | + "net/url" |
| 23 | + "reflect" |
| 24 | + "runtime" |
| 25 | + "sort" |
| 26 | + "strings" |
| 27 | + |
| 28 | + "go.opentelemetry.io/otel/propagation" |
| 29 | +) |
| 30 | + |
| 31 | +const ( |
| 32 | + route string = "route" |
| 33 | + controller string = "controller" |
| 34 | + action string = "action" |
| 35 | + framework string = "framework" |
| 36 | + driver string = "driver" |
| 37 | + traceparent string = "traceparent" |
| 38 | +) |
| 39 | + |
| 40 | +type DB struct { |
| 41 | + *sql.DB |
| 42 | + options CommenterOptions |
| 43 | +} |
| 44 | + |
| 45 | +type CommenterOptions struct { |
| 46 | + EnableDBDriver bool |
| 47 | + EnableRoute bool |
| 48 | + EnableFramework bool |
| 49 | + EnableController bool |
| 50 | + EnableAction bool |
| 51 | + EnableTraceparent bool |
| 52 | +} |
| 53 | + |
| 54 | +func Open(driverName string, dataSourceName string, options CommenterOptions) (*DB, error) { |
| 55 | + db, err := sql.Open(driverName, dataSourceName) |
| 56 | + return &DB{DB: db, options: options}, err |
| 57 | +} |
| 58 | + |
| 59 | +// ***** Query Functions ***** |
| 60 | + |
| 61 | +func (db *DB) Query(query string, args ...any) (*sql.Rows, error) { |
| 62 | + return db.DB.Query(db.withComment(context.Background(), query), args...) |
| 63 | +} |
| 64 | + |
| 65 | +func (db *DB) QueryRow(query string, args ...interface{}) *sql.Row { |
| 66 | + return db.DB.QueryRow(db.withComment(context.Background(), query), args...) |
| 67 | +} |
| 68 | + |
| 69 | +func (db *DB) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) { |
| 70 | + return db.DB.QueryContext(ctx, db.withComment(ctx, query), args...) |
| 71 | +} |
| 72 | + |
| 73 | +func (db *DB) Exec(query string, args ...any) (sql.Result, error) { |
| 74 | + return db.DB.Exec(db.withComment(context.Background(), query), args...) |
| 75 | +} |
| 76 | + |
| 77 | +func (db *DB) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) { |
| 78 | + return db.DB.ExecContext(ctx, db.withComment(ctx, query), args...) |
| 79 | +} |
| 80 | + |
| 81 | +func (db *DB) Prepare(query string) (*sql.Stmt, error) { |
| 82 | + return db.DB.Prepare(db.withComment(context.Background(), query)) |
| 83 | +} |
| 84 | + |
| 85 | +func (db *DB) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) { |
| 86 | + return db.DB.PrepareContext(ctx, db.withComment(ctx, query)) |
| 87 | +} |
| 88 | + |
| 89 | +// ***** Query Functions ***** |
| 90 | + |
| 91 | +// ***** Framework Functions ***** |
| 92 | + |
| 93 | +func AddHttpRouterTags(r *http.Request, next any) context.Context { // any type is set because we need to refrain from importing http-router package |
| 94 | + ctx := context.Background() |
| 95 | + ctx = context.WithValue(ctx, route, r.URL.Path) |
| 96 | + ctx = context.WithValue(ctx, action, getFunctionName(next)) |
| 97 | + ctx = context.WithValue(ctx, framework, "net/http") |
| 98 | + return ctx |
| 99 | +} |
| 100 | + |
| 101 | +// ***** Framework Functions ***** |
| 102 | + |
| 103 | +// ***** Commenter Functions ***** |
| 104 | + |
| 105 | +func (db *DB) withComment(ctx context.Context, query string) string { |
| 106 | + var commentsMap = map[string]string{} |
| 107 | + query = strings.TrimSpace(query) |
| 108 | + |
| 109 | + // Sorted alphabetically |
| 110 | + if db.options.EnableAction && (ctx.Value(action) != nil) { |
| 111 | + commentsMap[action] = ctx.Value(action).(string) |
| 112 | + } |
| 113 | + |
| 114 | + // `driver` information should not be coming from framework. |
| 115 | + // So, explicitly adding that here. |
| 116 | + if db.options.EnableDBDriver { |
| 117 | + commentsMap[driver] = "database/sql" |
| 118 | + } |
| 119 | + |
| 120 | + if db.options.EnableFramework && (ctx.Value(framework) != nil) { |
| 121 | + commentsMap[framework] = ctx.Value(framework).(string) |
| 122 | + } |
| 123 | + |
| 124 | + if db.options.EnableRoute && (ctx.Value(route) != nil) { |
| 125 | + commentsMap[route] = ctx.Value(route).(string) |
| 126 | + } |
| 127 | + |
| 128 | + if db.options.EnableTraceparent { |
| 129 | + carrier := extractTraceparent(ctx) |
| 130 | + if val, ok := carrier["traceparent"]; ok { |
| 131 | + commentsMap[traceparent] = val |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + var commentsString string = "" |
| 136 | + if len(commentsMap) > 0 { // Converts comments map to string and appends it to query |
| 137 | + commentsString = fmt.Sprintf("/*%s*/", convertMapToComment(commentsMap)) |
| 138 | + } |
| 139 | + |
| 140 | + // A semicolon at the end of the SQL statement means the query ends there. |
| 141 | + // We need to insert the comment before that to be considered as part of the SQL statemtent. |
| 142 | + if query[len(query)-1:] == ";" { |
| 143 | + return fmt.Sprintf("%s%s;", strings.TrimSuffix(query, ";"), commentsString) |
| 144 | + } |
| 145 | + return fmt.Sprintf("%s%s", query, commentsString) |
| 146 | +} |
| 147 | + |
| 148 | +// ***** Commenter Functions ***** |
| 149 | + |
| 150 | +// ***** Util Functions ***** |
| 151 | + |
| 152 | +func encodeURL(k string) string { |
| 153 | + return url.QueryEscape(string(k)) |
| 154 | +} |
| 155 | + |
| 156 | +func getFunctionName(i interface{}) string { |
| 157 | + return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name() |
| 158 | +} |
| 159 | + |
| 160 | +func convertMapToComment(tags map[string]string) string { |
| 161 | + var sb strings.Builder |
| 162 | + i, sz := 0, len(tags) |
| 163 | + |
| 164 | + //sort by keys |
| 165 | + sortedKeys := make([]string, 0, len(tags)) |
| 166 | + for k := range tags { |
| 167 | + sortedKeys = append(sortedKeys, k) |
| 168 | + } |
| 169 | + sort.Strings(sortedKeys) |
| 170 | + |
| 171 | + for _, key := range sortedKeys { |
| 172 | + if i == sz-1 { |
| 173 | + sb.WriteString(fmt.Sprintf("%s=%v", encodeURL(key), encodeURL(tags[key]))) |
| 174 | + } else { |
| 175 | + sb.WriteString(fmt.Sprintf("%s=%v,", encodeURL(key), encodeURL(tags[key]))) |
| 176 | + } |
| 177 | + i++ |
| 178 | + } |
| 179 | + return sb.String() |
| 180 | +} |
| 181 | + |
| 182 | +func extractTraceparent(ctx context.Context) propagation.MapCarrier { |
| 183 | + // Serialize the context into carrier |
| 184 | + propgator := propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}) |
| 185 | + carrier := propagation.MapCarrier{} |
| 186 | + propgator.Inject(ctx, carrier) |
| 187 | + return carrier |
| 188 | +} |
| 189 | + |
| 190 | +// ***** Util Functions ***** |
0 commit comments