• Stars
    star
    125
  • Rank 276,982 (Top 6 %)
  • Language
    Go
  • License
    MIT License
  • Created almost 8 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

sqlf generates parameterized SQL statements in Go, sprintf style

sqlf Build Status GoDoc

Generate parameterized SQL statements in Go, sprintf Style.

q := sqlf.Sprintf("SELECT * FROM users WHERE country = %s AND age > %d", "US", 27);
rows, err := db.Query(q.Query(sqlf.SimpleBindVar), q.Args()...) // db is a database/sql.DB

sqlf.Sprintf does not return a string. It returns *sqlf.Query which has methods for a parameterized SQL query and arguments. You then pass that to db.Query, db.Exec, etc. This is not like using fmt.Sprintf, which could expose you to malformed SQL or SQL injection attacks.

sqlf.Query can be passed as an argument to sqlf.Sprintf. It will "flatten" the query string, while preserving the correct variable binding. This allows you to easily compose and build SQL queries. See the below examples to find out more.

// This is an example which shows off embedding SQL, which simplifies building
// complicated SQL queries
name := "John"
age, offset := 27, 100
where := sqlf.Sprintf("name=%s AND age=%d", name, age)
limit := sqlf.Sprintf("%d OFFSET %d", 10, offset)
q := sqlf.Sprintf("SELECT name FROM users WHERE %s LIMIT %s", where, limit)
fmt.Println(q.Query(sqlf.PostgresBindVar))
fmt.Println(q.Args())
// Output: SELECT name FROM users WHERE name=$1 AND age=$2 LIMIT $3 OFFSET $4
// [John 27 10 100]

Another common task is joining conditionals with AND or OR. sqlf simplifies this task with sqlf.Join:

// Our inputs
min_quantity := 100
name_filters := []string{"apple", "orange", "coffee"}

var conds []*sqlf.Query
for _, filter := range name_filters {
    conds = append(conds, sqlf.Sprintf("name LIKE %s", "%"+filter+"%"))
}
sub_query := sqlf.Sprintf("SELECT product_id FROM order_item WHERE quantity > %d", min_quantity)
q := sqlf.Sprintf("SELECT name FROM product WHERE id IN (%s) AND (%s)", sub_query, sqlf.Join(conds, "OR"))

fmt.Println(q.Query(sqlf.PostgresBindVar))
fmt.Println(q.Args())
// Output: SELECT name FROM product WHERE id IN (SELECT product_id FROM order_item WHERE quantity > $1) AND (name LIKE $2 OR name LIKE $3 OR name LIKE $4)
// [100 %apple% %orange% %coffee%]

See https://godoc.org/github.com/keegancsmith/sqlf for more information.

More Repositories

1

shell

Generate Shell Commands in Go, sprintf Style
Go
77
star
2

rpc

Go stdlib net/rpc with context.Context support
Go
37
star
3

prometheus-ec2-discovery

EC2 service discovery for Prometheus based on AWS Tags
Go
23
star
4

rgp

ripgrep plus - Wraps ripgrep to add google like queries to patterns
Go
21
star
5

nth

Find the nth largest element of an unsorted slice in Go. Fast and memory efficient implementation of a Selection Algorithm.
Go
17
star
6

Sliding-Window-Minimum

Sliding window minimum is an interesting algorithm, so I thought I would implement it in a bunch of different languages. This repository contains (or will contain) implementations of the algorithm in different programming languages.
Haskell
12
star
7

tmpfriend

Go library to help tie temporary files to the lifetime of a process.
Go
10
star
8

kubernetes-disk-exporter

Export kubernetes persistent volume metrics to prometheus.
Go
9
star
9

advent

Advent of Code solutions - http://adventofcode.com/
Python
8
star
10

scrabble

Experiments with Django, eventlet, redis and HTML5 Canvas to make a Scrabble game.
Python
6
star
11

dotfiles

My configuration files
Nix
5
star
12

FUSEPod

FUSEPod is a userspace filesystem which mounts your iPod into a directory for easy browsing of your songs on your iPod.
C++
5
star
13

kubernetes-honeycomb-agent

Export kubernetes events into honeycomb.io
Go
4
star
14

counsel-repo

Emacs jump to repository using Ivy
Go
3
star
15

django-fileflatpages

Makes FlatPage fixtures easily
Python
3
star
16

Weighted-Triangulation-Editor

A visual editor for creating Weighted Regions. Made with Qt sauce.
C++
3
star
17

keegancsmith

My homepage built using Sphinx.
Python
2
star
18

watercomp

A compression algorithm targeting molecular dynamics simulations with large amounts of water.
C++
1
star
19

Agatha

Global Game Jam 2011 Entry
JavaScript
1
star
20

MCP-web

Website for MCP
Python
1
star
21

MCP

A program to orchestrate Entellect Challenge bot matches. The Entellect Challenge is a Tron AI competition.
Python
1
star
22

Umonya-Website

Mirror of my bzr branch of the Umonya website
Python
1
star
23

presentations

Go
1
star
24

hgallpaths

A mercurial extension to allow pushing and pulling from all paths.
Python
1
star
25

PMCC

Work done for the Parallel and Multi-Core Computing module I did for Computer Science Honours. Note that the report is not up to scratch, since I wrote most of it past 3am.
C
1
star
26

AmarokQuilt

A Full Screen mode for Amarok which displays a quilt of your album covers as well as the current playing track.
C++
1
star
27

AmarokPidgin

A plugin for Amarok that updates your Pidgin status message with that you are currently listening to.
Python
1
star
28

terraformer-google-compute-disk

Export existing Google Compute Disks to Terraform style (tf, tfstate)
Python
1
star