Documentation ¶
Overview ¶
Package pgtools contains features HATCH Studio developed and rely upon to use PostgreSQL more effectively with Go. It was designed to be used alongside github.com/jackc/pgx and github.com/georgysavva/scany.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Fields ¶
func Fields(v interface{}) []string
Fields returns column names for a SQL table that can be queried by a given Go struct. Only use this function to list fields on a struct.
To avoid ambiguity issues, it's important to use the Wildcard function instead of calling strings.Join(pgtools.Field(v), ", ") to generate the query expression.
Example ¶
package main import ( "fmt" "strings" "time" "github.com/hatch-studio/pgtools" ) type User struct { Username string FullName string Email string Alias string `db:"id"` Theme Theme `db:"theme,json"` LastSeen time.Time `db:"-"` } type Theme struct { PrimaryColor string SecondaryColor string TextColor string TextUppercase bool FontFamilyHeadings string FontFamilyBody string FontFamilyDefault string } func main() { fmt.Println(strings.Join(pgtools.Fields(User{}), "\n")) }
Output: username full_name email id theme
func Wildcard ¶
func Wildcard(v interface{}) string
Wildcard returns an expression that can be used for querying a SQL database.
To make usage simpler in the happy path, Wildcard doesn't return an error. However, this means you should check if the value generated by the function is valid (panic is not used as it would introduce unwanted risk).
The "db" key in the struct field's tag can specify the "json" option when a JSON or JSONB data type is used in PostgreSQL.
It is useful to ensure scany works after adding a field to the databsase, and for performance reasons too by reducing the number of places where a wildcard (*) is used for convenience in SELECT queries.
See example for usage. It was envisioned to use with github.com/georgysavva/scany, but you can use it without it too.
If you're curious about doing this "in the other direction", see https://github.com/golang/pkgsite/blob/2d3ade3c90634f9afed7aa772e53a62bb433447a/internal/database/reflect.go#L20-L46
Example ¶
package main import ( "fmt" "time" "github.com/hatch-studio/pgtools" ) type User struct { Username string FullName string Email string Alias string `db:"id"` Theme Theme `db:"theme,json"` LastSeen time.Time `db:"-"` } type Theme struct { PrimaryColor string SecondaryColor string TextColor string TextUppercase bool FontFamilyHeadings string FontFamilyBody string FontFamilyDefault string } func main() { sql := "SELECT " + pgtools.Wildcard(User{}) + " WHERE id = $1" fmt.Println(sql) }
Output: SELECT "username","full_name","email","id","theme" WHERE id = $1
Types ¶
This section is empty.