Masterminds/squirrel: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 43: Line 43:


<code>getDbHandle()</code> can be implemented as shown in: {{Internal|PostgreSQL_Support_in_Go#With_database/sql_API_and_a_pgx_Driver|Connect to a PostgreSQL Database with <tt>database/sql</tt> API and a pgx Driver}}
<code>getDbHandle()</code> can be implemented as shown in: {{Internal|PostgreSQL_Support_in_Go#With_database/sql_API_and_a_pgx_Driver|Connect to a PostgreSQL Database with <tt>database/sql</tt> API and a pgx Driver}}
==Placeholders==

Revision as of 17:37, 31 May 2024

External

Internal

Overview

Squirrel is a fluent SQL generator for Go. It helps build SQL queries from composable parts representing the SQL SELECT query clauses: SELECT, FROM, JOIN, WHERE, etc. and also other DML statements.

Installation

go get github.com/Masterminds/squirrel

Programming Model

Queries

import sq "github.com/Masterminds/squirrel"

// Get a database/sql database handle
dbHandle = getDbHandle()

// Build the query with a fluent API
query = sq.Select("*").From("person")

// execute the query with the database handle; the syntax is identical to that used with dbHandle.Query()
rows, err := query.RunWith(dbHandle).Query()
if err != nil { ... }
defer func() {
	if err = rows.Close(); err != nil { ... }
}()
for rows.Next() {
	var (
		id   int
		name string
		city sql.NullString
	)
	if err = rows.Scan(&id, &name, &city); err != nil { ... }
	fmt.Printf("id: %d, name: %s, city: %s\n", id, name, city.String)
}

getDbHandle() can be implemented as shown in:

Connect to a PostgreSQL Database with database/sql API and a pgx Driver

Placeholders