Squirrel

repository·master·Indexed 27 days ago

https://github.com/masterminds/squirrel

A fluent SQL generator for Go that helps build complex SQL queries from composable parts. Squirrel is not an ORM, but a tool for constructing SQL strings and executing them against a database using methods like Select, From, Join, Where, Insert, and Delete. It supports custom placeholder formats for PostgreSQL, prepared statement caching via NewStmtCache, and direct execution through RunWith.

Tokens
8.5K
Snippets
9
Records
88
Agent score
92%

What's inside squirrel

  1. Configure PostgreSQL placeholder format

    master
    By default, Squirrel uses question marks (?) as placeholders. For PostgreSQL, you must set the PlaceholderFormat to sq.Dollar to use $1, $2, etc. You can apply this to a StatementBuilder to ensure all queries generated from that builder use the correct format.
  2. Build SQL queries with Squirrel

    master
    Squirrel is a fluent SQL generator that allows you to build queries from composable parts. You can use methods like Select, From, Join, Where, Insert, Columns, and Values to construct your SQL statements. Use .ToSql() to generate the raw SQL string and the slice of arguments.
  3. Use StatementCache and StatementBuilder for efficiency

    master

    To improve performance and keep syntax clean, you can use NewStmtCache to cache prepared statements and StatementBuilder to create a reusable builder instance configured with a specific database and placeholder format.

    // StmtCache caches Prepared Stmts for you
    dbCache := sq.NewStmtCache(db)
    
    // StatementBuilder keeps your syntax neat
    mydb := sq.StatementBuilder.RunWith(dbCache)
    select_users := mydb.Select("*").From("users")
  4. Execute queries directly with RunWith

    master

    Instead of just generating SQL strings, you can execute queries directly against a database connection by using the .RunWith(db) method. This allows you to call .Query(), .QueryRow(), or .Exec() directly on the builder.

    // Assuming 'users' is a SelectBuilder and 'db' is a *sql.DB
    stooges := users.Where(sq.Eq{"username": []string{"moe", "larry", "curly", "shemp"}})
    three_stooges := stooges.Limit(3)
    
    // Executes the query against the database
    rows, err := three_stooges.RunWith(db).Query()
  5. Escape question marks in PostgreSQL queries

    master
    When using PostgreSQL with sq.Dollar placeholder format, you may need to use literal question marks (e.g., for JSONB operators like ?|). To prevent Squirrel from treating these as placeholders, escape them by using two question marks (??).
  6. Troubleshoot context-aware SELECT execution errors

    master

    When using ExecContext, QueryContext, or QueryRowContext on a SelectBuilder, you may encounter the following errors:

    • RunnerNotSet: You called an execution method without first calling .RunWith(runner).
    • NoContextSupport: The runner provided to .RunWith() does not implement the required context interface (e.g., ExecerContext or QueryerContext).
    • RunnerNotQueryRunner: Specifically for QueryRowContext, the runner was set but does not implement QueryRowerContext or QueryerContext.
  7. Troubleshoot Runner errors

    master

    When working with Squirrel builders, you may encounter these specific errors:

    • RunnerNotSet: Returned by methods that require a Runner (set via .RunWith()) but none was provided.
    • RunnerNotQueryRunner: Returned by QueryRow if the provided Runner does not implement the QueryRower interface.
  8. Troubleshoot context-aware UPDATE errors

    master

    When using context-aware methods on UpdateBuilder, you may encounter the following errors:

    • RunnerNotSet: You forgot to call .RunWith(runner) on your builder.
    • NoContextSupport: The runner provided to .RunWith() does not implement the required context interface (ExecerContext, QueryerContext, or QueryRowerContext).
    • RunnerNotQueryRunner: You called QueryRowContext or ScanContext, but the runner only supports QueryerContext (standard Query) and not QueryRowerContext (standard QueryRow).
  9. Build SQL CASE statements with CaseBuilder

    master

    Use CaseBuilder to construct SQL CASE expressions. You can define an optional expression for the CASE value, multiple WHEN ... THEN ... clauses, and an optional ELSE clause.

    Methods:

    • what(expr interface{}) CaseBuilder: Sets the optional expression for the CASE [value] part.
    • When(when interface{}, then interface{}) CaseBuilder: Adds a WHEN ... THEN ... clause. Both arguments can be raw values or other Sqlizer types.
    • Else(expr interface{}) CaseBuilder: Sets the optional ELSE clause.
    • ToSql() (string, []interface{}, error): Generates the SQL string and its associated arguments. Returns an error if no WHEN clauses are provided.
    • MustSql() (string, []interface{}): Generates the SQL string and arguments, but panics if an error occurs (e.g., if no WHEN clauses exist).
  10. Use StmtCache for context-aware database operations

    master

    The StmtCache type provides context-aware versions of standard database operations. When you call these methods, the cache automatically prepares the statement (if not already cached) and then executes it using the provided context.

    Supported methods:

    • ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
    • QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
    • QueryRowContext(ctx context.Context, query string, args ...interface{}) RowScanner
    • PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)