Skip to content

Commit 2347323

Browse files
author
Emmanuel T Odeke
authored
Merge pull request #9 from opencensus-integrations/sqlx-named-queries
adds note on sqlx named queries to readme
2 parents 63b3e35 + 9d9b8c1 commit 2347323

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,33 @@ sql.Register("ocsql-sqlite3", driver)
6464
db, err = sql.Open("ocsql-sqlite3", "resource.db")
6565
```
6666

67+
## jmoiron/sqlx
68+
69+
If using the `sqlx` library with named queries you will need to use the
70+
`sqlx.NewDb` function to wrap an existing `*sql.DB` connection. Do not use the
71+
`sqlx.Open` and `sqlx.Connect` methods.
72+
`sqlx` uses the driver name to figure out which database is being used. It uses
73+
this knowledge to convert named queries to the correct bind type (dollar sign,
74+
question mark) if named queries are not supported natively by the
75+
database. Since ocsql creates a new driver name it will not be recognized by
76+
sqlx and named queries will fail.
77+
78+
Use one of the above methods to first create a `*sql.DB` connection and then
79+
create a `*sqlx.DB` connection by wrapping the `*sql.DB` like this:
80+
81+
```go
82+
// Register our ocsql wrapper for the provided Postgres driver.
83+
driverName, err := ocsql.Register("postgres", ocsql.WithAllTraceOptions())
84+
if err != nil { ... }
85+
86+
// Connect to a Postgres database using the ocsql driver wrapper.
87+
db, err := sql.Open(driverName, "postgres://localhost:5432/my_database")
88+
if err != nil { ... }
89+
90+
// Wrap our *sql.DB with sqlx. use the original db driver name!!!
91+
dbx := sqlx.NewDB(db, "postgres")
92+
```
93+
6794
## context
6895

6996
To really take advantage of ocsql, all database calls should be made using the

0 commit comments

Comments
 (0)