Basics: Logging
sq comes with a built-in logger. It logs the query to stdout, so you can use it to debug if something was wrong.
It does not log errors. It returns errors, and it is up to you if you want to log the error.
The logger can be enabled on an individual query with WithDefaultLog(<LogFlag>)
:
// No logging
Select(u.USER_ID, u.NAME).From(u).Where(u.USER_ID.LtInt(15))
// With logging
WithDefaultLog(0).Select(u.USER_ID, u.NAME).From(u).Where(u.USER_ID.LtInt(15))
Which will result in the output looking like
2020/06/14 17:20:57 my_file.go:315 [sq] SELECT u.user_id, u.name FROM public.users AS u WHERE u.user_id < $1 [15]
If you want to enable logging for every query, see Building off a common query builder.
There are various LogFlags that affect the output of the logger:
const (
// Interpolate the args into the query
Linterpolate LogFlag = 1 << iota
// Show the query before interpolation, after interpolation and time taken
Lstats
// Show the first 5 rows of the result
Lresults
// Combine both Lstats and Lresults
Lverbose = Lstats | Lresults
)
Example of what the logger with Lverbose
looks like (thanks to jOOQ for the idea)
2020/06/14 17:20:57 my_file.go:315 [sq]
----[ Executing query ]----
SELECT u.user_id, u.name FROM public.users AS u WHERE u.user_id < $1 [15]
----[ with bind values ]----
SELECT u.user_id, u.name FROM public.users AS u WHERE u.user_id < 15
2020/06/14 17:20:57 my_file.go:315 [sq]
----[ Row 1 ]----
u.user_id: 1
u.name: Tom
----[ Row 2 ]----
u.user_id: 2
u.name: Dick
----[ Row 3 ]----
u.user_id: 3
u.name: Harry
----[ Row 4 ]----
u.user_id: 4
u.name: John
----[ Row 5 ]----
u.user_id: 5
u.name: Jane
...
(Fetched 14 rows in 6.568672ms)