Convert Figma logo to code with AI

Masterminds logosquirrel

Fluent SQL generation for golang

6,816
460
6,816
84

Top Related Projects

19,285

A query builder for PostgreSQL, MySQL, CockroachDB, SQL Server, SQLite3 and Oracle, designed to be flexible, portable, and fun to use.

16,124

general purpose extensions to golang's database/sql

12,916

Generate type-safe code from SQL

36,742

The fantastic ORM library for Golang, aims to be developer friendly

Generate a Go ORM tailored to your database schema.

2,383

SQL builder and query library for golang

Quick Overview

Squirrel is a fluent SQL generator for Go. It provides a set of expressive Go functions to build complex SQL queries without writing raw SQL strings. This library aims to make SQL query construction more type-safe and less error-prone while maintaining readability.

Pros

  • Type-safe query construction, reducing runtime errors
  • Fluent API for building complex queries
  • Supports multiple database dialects (MySQL, PostgreSQL, SQLite)
  • Helps prevent SQL injection attacks

Cons

  • Learning curve for developers used to writing raw SQL
  • May not support all advanced SQL features
  • Potential performance overhead compared to raw SQL strings
  • Limited to Go language ecosystem

Code Examples

Building a simple SELECT query:

import sq "github.com/Masterminds/squirrel"

users := sq.Select("name", "email").From("users").Where(sq.Eq{"active": true})
sql, args, err := users.ToSql()

Constructing an INSERT query with multiple values:

insert := sq.Insert("users").Columns("name", "email")
for _, user := range newUsers {
    insert = insert.Values(user.Name, user.Email)
}
sql, args, err := insert.ToSql()

Using placeholders and named arguments:

update := sq.Update("users").
    Set("name", sq.Expr("COALESCE(?, name)", sq.Named("name", newName))).
    Where(sq.Eq{"id": userId})
sql, args, err := update.ToSql()

Getting Started

To use Squirrel in your Go project:

  1. Install the package:

    go get -u github.com/Masterminds/squirrel
    
  2. Import it in your code:

    import sq "github.com/Masterminds/squirrel"
    
  3. Start building queries:

    query := sq.Select("*").From("users").Where(sq.Eq{"status": "active"})
    sql, args, err := query.ToSql()
    if err != nil {
        // Handle error
    }
    // Use sql and args with your database driver
    

Competitor Comparisons

19,285

A query builder for PostgreSQL, MySQL, CockroachDB, SQL Server, SQLite3 and Oracle, designed to be flexible, portable, and fun to use.

Pros of Knex

  • Supports multiple database systems (PostgreSQL, MySQL, SQLite3, Oracle)
  • Provides a powerful migration system for schema versioning
  • Offers a promise-based interface for asynchronous operations

Cons of Knex

  • Steeper learning curve due to more complex API
  • Larger codebase and dependencies, potentially impacting performance
  • Less idiomatic SQL generation compared to Squirrel's fluent interface

Code Comparison

Knex query:

knex('users')
  .where('id', 1)
  .update({ name: 'John Doe' })

Squirrel query:

sq.Update("users").
    Set("name", "John Doe").
    Where(sq.Eq{"id": 1})

Both Knex and Squirrel are query builders, but they cater to different ecosystems and programming paradigms. Knex is more feature-rich and versatile, supporting multiple databases and providing a comprehensive migration system. It's well-suited for complex Node.js applications. Squirrel, on the other hand, offers a simpler, more Go-idiomatic approach to query building, with a focus on generating SQL strings. It's lightweight and efficient, making it a good choice for Go projects that prioritize simplicity and performance.

16,124

general purpose extensions to golang's database/sql

Pros of sqlx

  • Provides a more lightweight and simpler API for database operations
  • Supports both database-specific features and a database-agnostic interface
  • Offers compile-time query checking for improved safety and performance

Cons of sqlx

  • Less flexible for complex query building compared to Squirrel
  • May require more manual SQL writing for complex queries
  • Limited support for advanced query composition techniques

Code Comparison

sqlx:

var users []User
err := sqlx.Select(db, &users, "SELECT * FROM users WHERE active = ?", true)

Squirrel:

users := []User{}
err := sq.Select("*").From("users").Where(sq.Eq{"active": true}).
    RunWith(db).QueryStructs(&users)

Both libraries aim to simplify database operations in Go, but they take different approaches. sqlx focuses on extending the standard database/sql package with convenient methods and struct scanning, while Squirrel provides a fluent interface for building SQL queries programmatically.

sqlx is generally easier to use for simpler queries and offers better performance due to its lightweight nature. However, Squirrel excels in scenarios where complex, dynamic query building is required, offering more flexibility and readability for such cases.

The choice between these libraries depends on the specific needs of your project, such as query complexity, performance requirements, and developer preferences.

12,916

Generate type-safe code from SQL

Pros of sqlc

  • Generates type-safe Go code from SQL queries, reducing runtime errors
  • Supports complex queries and joins, offering more flexibility
  • Provides better performance due to compile-time code generation

Cons of sqlc

  • Steeper learning curve, especially for developers new to SQL
  • Requires writing raw SQL queries, which may be less intuitive for some
  • Less flexibility in dynamically constructing queries at runtime

Code Comparison

sqlc:

-- name: GetAuthor :one
SELECT * FROM authors
WHERE id = $1 LIMIT 1;
author, err := queries.GetAuthor(ctx, id)

Squirrel:

sql, args, err := sq.Select("*").From("authors").Where(sq.Eq{"id": id}).ToSql()
var author Author
err = db.QueryRowContext(ctx, sql, args...).Scan(&author)

Summary

sqlc offers strong type safety and performance benefits but requires more SQL knowledge. Squirrel provides a more flexible, Go-centric approach to query building but may be less performant for complex queries. The choice between them depends on project requirements, team expertise, and performance needs.

36,742

The fantastic ORM library for Golang, aims to be developer friendly

Pros of gorm

  • Full-featured ORM with support for associations, migrations, and callbacks
  • More abstracted and higher-level API, reducing boilerplate code
  • Active development and large community support

Cons of gorm

  • Steeper learning curve due to its extensive feature set
  • Potential performance overhead for complex queries
  • Less control over generated SQL compared to Squirrel

Code Comparison

gorm example:

db.Where("name = ?", "jinzhu").First(&user)

Squirrel example:

sql, args, err := sq.Select("*").From("users").Where(sq.Eq{"name": "jinzhu"}).ToSql()

Summary

gorm is a full-featured ORM that provides a higher level of abstraction and more built-in functionality, making it suitable for complex applications with intricate data models. It offers a more concise API but may introduce some performance overhead.

Squirrel, on the other hand, is a lightweight SQL builder that gives developers more control over generated SQL. It has a lower learning curve and potentially better performance for complex queries, but requires more manual work for features like associations and migrations.

The choice between the two depends on the project's requirements, complexity, and the developer's preference for abstraction level and control over SQL generation.

Generate a Go ORM tailored to your database schema.

Pros of sqlboiler

  • Generates type-safe Go code from database schema, reducing boilerplate
  • Supports complex queries and relationships out of the box
  • Offers better performance due to generated code optimization

Cons of sqlboiler

  • Requires code generation step, which can complicate the development workflow
  • Less flexible for ad-hoc queries compared to Squirrel's query builder
  • Steeper learning curve for developers new to code generation tools

Code Comparison

sqlboiler (generated code):

users, err := models.Users().All(ctx, db)
if err != nil {
    return err
}

Squirrel:

users := []User{}
err := sq.Select("*").From("users").RunWith(db).QueryStructs(&users)
if err != nil {
    return err
}

Both libraries aim to simplify database operations in Go, but take different approaches. sqlboiler generates type-safe code based on your database schema, while Squirrel provides a flexible query builder. sqlboiler offers better performance and type safety at the cost of added complexity, while Squirrel provides more flexibility for dynamic queries but with less compile-time safety.

2,383

SQL builder and query library for golang

Pros of goqu

  • More extensive feature set, including support for complex queries, subqueries, and joins
  • Better support for multiple database dialects (MySQL, PostgreSQL, SQLite, and more)
  • More active development and maintenance

Cons of goqu

  • Steeper learning curve due to its more comprehensive API
  • Slightly more verbose syntax for simple queries
  • Less widespread adoption compared to Squirrel

Code Comparison

Squirrel:

users := sq.Select("*").From("users").Where(sq.Eq{"id": 1})
sql, args, err := users.ToSql()

goqu:

users := goqu.From("users").Select("*").Where(goqu.C("id").Eq(1))
sql, args, err := users.ToSQL()

Both libraries provide similar functionality for basic queries, but goqu offers more advanced features for complex operations. While Squirrel has a simpler API that's easier to pick up, goqu provides greater flexibility and support for various database systems. The choice between the two depends on the project's requirements and the developer's preference for simplicity versus feature richness.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Stability: Maintenance

Squirrel is "complete".

Bug fixes will still be merged (slowly). Bug reports are welcome, but I will not necessarily respond to them. If another fork (or substantially similar project) actively improves on what Squirrel does, let me know and I may link to it here.

Squirrel - fluent SQL generator for Go

import "github.com/Masterminds/squirrel"

GoDoc Build Status

Squirrel is not an ORM. For an application of Squirrel, check out structable, a table-struct mapper

Squirrel helps you build SQL queries from composable parts:

import sq "github.com/Masterminds/squirrel"

users := sq.Select("*").From("users").Join("emails USING (email_id)")

active := users.Where(sq.Eq{"deleted_at": nil})

sql, args, err := active.ToSql()

sql == "SELECT * FROM users JOIN emails USING (email_id) WHERE deleted_at IS NULL"
sql, args, err := sq.
    Insert("users").Columns("name", "age").
    Values("moe", 13).Values("larry", sq.Expr("? + 5", 12)).
    ToSql()

sql == "INSERT INTO users (name,age) VALUES (?,?),(?,? + 5)"

Squirrel can also execute queries directly:

stooges := users.Where(sq.Eq{"username": []string{"moe", "larry", "curly", "shemp"}})
three_stooges := stooges.Limit(3)
rows, err := three_stooges.RunWith(db).Query()

// Behaves like:
rows, err := db.Query("SELECT * FROM users WHERE username IN (?,?,?,?) LIMIT 3",
                      "moe", "larry", "curly", "shemp")

Squirrel makes conditional query building a breeze:

if len(q) > 0 {
    users = users.Where("name LIKE ?", fmt.Sprint("%", q, "%"))
}

Squirrel wants to make your life easier:

// 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")

Squirrel loves PostgreSQL:

psql := sq.StatementBuilder.PlaceholderFormat(sq.Dollar)

// You use question marks for placeholders...
sql, _, _ := psql.Select("*").From("elephants").Where("name IN (?,?)", "Dumbo", "Verna").ToSql()

/// ...squirrel replaces them using PlaceholderFormat.
sql == "SELECT * FROM elephants WHERE name IN ($1,$2)"


/// You can retrieve id ...
query := sq.Insert("nodes").
    Columns("uuid", "type", "data").
    Values(node.Uuid, node.Type, node.Data).
    Suffix("RETURNING \"id\"").
    RunWith(m.db).
    PlaceholderFormat(sq.Dollar)

query.QueryRow().Scan(&node.id)

You can escape question marks by inserting two question marks:

SELECT * FROM nodes WHERE meta->'format' ??| array[?,?]

will generate with the Dollar Placeholder:

SELECT * FROM nodes WHERE meta->'format' ?| array[$1,$2]

FAQ

  • How can I build an IN query on composite keys / tuples, e.g. WHERE (col1, col2) IN ((1,2),(3,4))? (#104)

    Squirrel does not explicitly support tuples, but you can get the same effect with e.g.:

    sq.Or{
      sq.Eq{"col1": 1, "col2": 2},
      sq.Eq{"col1": 3, "col2": 4}}
    
    WHERE (col1 = 1 AND col2 = 2) OR (col1 = 3 AND col2 = 4)
    

    (which should produce the same query plan as the tuple version)

  • Why doesn't Eq{"mynumber": []uint8{1,2,3}} turn into an IN query? (#114)

    Values of type []byte are handled specially by database/sql. In Go, byte is just an alias of uint8, so there is no way to distinguish []uint8 from []byte.

  • Some features are poorly documented!

    This isn't a frequent complaints section!

  • Some features are poorly documented?

    Yes. The tests should be considered a part of the documentation; take a look at those for ideas on how to express more complex queries.

License

Squirrel is released under the MIT License.