sqlc implements a Dynamic Query Builder for SQLC and more specifically MySQL queries.

sqlc-go-builder

sqlc implements a Dynamic Query Builder for SQLC and more specifically MySQL queries.

It implements a parser using vitess-go-sqlparser to parse and rewrite Complex MySQL queries on the fly using their AST and Rewrite functionality provided by the sqlparser package.

Features

  1. Allows Where, Order, In, Offset, Limit, Group dynamically.
  2. Supports complex SELECT queries.
  3. Safe from SQLi by using Parameterized Arguments for everything dynamic.
  4. Sanitizes code by using Vitess SQL parser.

Example

Using as standalone

?", 18). Group("name, age"). Order("name ASC, age DESC"). Offset(10). Limit(5) query, args, err := builder.Build("select id from user_items") if err != nil { panic(err) } fmt.Printf("query= %s\n args= %v\n", query, args) } // Output: // query= select id from user_items where id in (?, ?, ?) and `name` = ? and age > ? group by `name`, age order by `name` asc, age desc limit 10, 5 // args= [1 2 3 John 18]">
package main

import (
	"fmt"

	sqlc "github.com/projectdiscovery/sqlc-go-builder"
)

func main() {
	builder := sqlc.New().
		In("id", 1, 2, 3).
		Where("name = ?", "John").
		Where("age > ?", 18).
        	Group("name, age").
		Order("name ASC, age DESC").
		Offset(10).
		Limit(5)

	query, args, err := builder.Build("select id from user_items")
	if err != nil {
		panic(err)
	}
	fmt.Printf("query= %s\n args= %v\n", query, args)
}

// Output:
// query= select id from user_items where id in (?, ?, ?) and `name` = ? and age > ? group by `name`, age order by `name` asc, age desc limit 10, 5
// args= [1 2 3 John 18]

Wrapping with SQLC

") if err != nil { t.Fatal(err) } defer db.Close() querier := dbsql.New(sqlc.Wrap(db.Pool)) //querier := db.Queries() data, err := querier.GetData( sqlc.Build(context.Background(), func(builder *sqlc.Builder) { builder.Limit(10) }), ) if err != nil { t.Fatal(err) } for _, item := range data { item := item fmt.Printf("%v\n", item) } }">
package background

import (
	"context"
	"fmt"
	"testing"

	v2 "github.com/test-repo/pkg/db/v2"
	"github.com/test-repo/pkg/db/v2/dbsql"
	sqlc "github.com/projectdiscovery/sqlc-go-builder"
)

func TestPaginationDynamic(t *testing.T) {
	db, err := v2.New("")
	if err != nil {
		t.Fatal(err)
	}
	defer db.Close()

	querier := dbsql.New(sqlc.Wrap(db.Pool))
	//querier := db.Queries()
	data, err := querier.GetData(
		sqlc.Build(context.Background(), func(builder *sqlc.Builder) {
			builder.Limit(10)
		}),
	)
	if err != nil {
		t.Fatal(err)
	}

	for _, item := range data {
		item := item
		fmt.Printf("%v\n", item)
	}
}

TODO

  • Better error handling
  • More tests

Credits

  1. https://github.com/yiplee/sqlc - Original inspiration for this library. The concepts have been extended to support AST rewrite instead of string formatting and things have been made safer (No SQLi).
Owner
ProjectDiscovery
Security Through Intelligent Automation
ProjectDiscovery
Similar Resources

Write your SQL queries in raw files with all benefits of modern IDEs, use them in an easy way inside your application with all the profit of compile time constants

About qry is a general purpose library for storing your raw database queries in .sql files with all benefits of modern IDEs, instead of strings and co

Dec 25, 2022

Go fearless SQL. Sqlvet performs static analysis on raw SQL queries in your Go code base.

Sqlvet Sqlvet performs static analysis on raw SQL queries in your Go code base to surface potential runtime errors at build time. Feature highlights:

Dec 19, 2022

a golang library for sql builder

Gendry gendry is a Go library that helps you operate database. Based on go-sql-driver/mysql, it provides a series of simple but useful tools to prepar

Dec 26, 2022

An easy-use SQL builder.

EQL An easy-use SQL builder. Design We are not English native speaker, so we use Chinese to write the design documents. We plan to translate them to E

Dec 26, 2022

PirateBuilder - Pirate Builder For Golang

PirateBuilder - Pirate Builder For Golang

PirateBuilder Builder You need to extract the file "PirateBuilder.rar". Start "P

Jun 10, 2022

Nerdlight-firmwarebuilder - Nerdlight NodeMCU Firmware Builder CLI

nerdlight-firmwarebuilder ⚒ ⚡️ Nerdlight NodeMCU Firmware Builder CLI ⚒ Descript

Feb 12, 2022

Query AWS Athena and download the result as CSV.

Overview This tool can download an Athena SQL query results in CSV format. Installation Using Homebrew: $ brew tap flowerinthenight/tap $ brew install

Nov 11, 2021

Command line tool to generate idiomatic Go code for SQL databases supporting PostgreSQL, MySQL, SQLite, Oracle, and Microsoft SQL Server

About xo xo is a command-line tool to generate Go code based on a database schema or a custom query. xo works by using database metadata and SQL intro

Jan 8, 2023

Golang Sequel ORM that support Enum, JSON, Spatial and many more

Golang Sequel ORM that support Enum, JSON, Spatial and many more

sqlike A golang SQL ORM which anti toxic query and focus on latest features. Installation go get github.com/si3nloong/sqlike Fully compatible with nat

Nov 21, 2022
Comments
  • Panics writing output using vitess go parser

    Panics writing output using vitess go parser

    echo: http: panic serving [::1]:55003: runtime error: invalid memory address or nil pointer dereference
    goroutine 409 [running]:
    net/http.(*conn).serve.func1()
            /opt/homebrew/opt/go/libexec/src/net/http/server.go:1854 +0xb0
    panic({0x10514ffa0, 0x108368190})
            /opt/homebrew/opt/go/libexec/src/runtime/panic.go:890 +0x248
    vitess.io/vitess/go/vt/sqlparser.(*TrackedBuffer).printExpr(0x14002bb8280, {0x105a5f350, 0x14002bb8240}, {0x0?, 0x0?}, 0x80?)
            /Users/ice3man/go/pkg/mod/vitess.io/[email protected]/go/vt/sqlparser/tracked_buffer.go:118 +0x148
    vitess.io/vitess/go/vt/sqlparser.(*ComparisonExpr).formatFast(0x14002bb8240, 0x14002bb8280)
            /Users/ice3man/go/pkg/mod/vitess.io/[email protected]/go/vt/sqlparser/ast_format_fast.go:1653 +0x398
    vitess.io/vitess/go/vt/sqlparser.(*TrackedBuffer).printExpr(0x14002bb8280, {0x105a5efc0, 0x14002bbe020}, {0x105a5f350?, 0x14002bb8240?}, 0x2?)
            /Users/ice3man/go/pkg/mod/vitess.io/[email protected]/go/vt/sqlparser/tracked_buffer.go:118 +0x154
    vitess.io/vitess/go/vt/sqlparser.(*AndExpr).formatFast(0x14002bbe020, 0x14002bb8280)
            /Users/ice3man/go/pkg/mod/vitess.io/[email protected]/go/vt/sqlparser/ast_format_fast.go:1624 +0x11c
    vitess.io/vitess/go/vt/sqlparser.(*Where).formatFast(0x14002bb2768, 0x14002bb8280)
            /Users/ice3man/go/pkg/mod/vitess.io/[email protected]/go/vt/sqlparser/ast_format_fast.go:1607 +0x2e4
    vitess.io/vitess/go/vt/sqlparser.(*Select).formatFast(0x14003245a40, 0x14002bb8280)
            /Users/ice3man/go/pkg/mod/vitess.io/[email protected]/go/vt/sqlparser/ast_format_fast.go:61 +0x800
    vitess.io/vitess/go/vt/sqlparser.String({0x105a4de08, 0x14003245a40})
            /Users/ice3man/go/pkg/mod/vitess.io/[email protected]/go/vt/sqlparser/tracked_buffer.go:303 +0xf4
    github.com/projectdiscovery/sqlc-go-builder.(*Builder).Build(0x14002bb8080, {0x1400127cb40?, 0x1084ace38?}, {0x140011c5f00, 0x1, 0x1})
    

    Generated during fuzzing of a using server

  • Bump vitess.io/vitess from 0.16.1 to 0.16.2

    Bump vitess.io/vitess from 0.16.1 to 0.16.2

    Bumps vitess.io/vitess from 0.16.1 to 0.16.2.

    Commits
    • 6076fed Release of v16.0.2 (#13050)
    • 6934444 Summary changes and code freeze for release of v16.0.2 (#13049)
    • 808821c [release-16.0] vtgate : Disable Automatically setting immediateCallerID to us...
    • 24ca345 gen4 planner: allow last_insert_id with arguments (#13026) (#13033)
    • 199e53c [release-16.0] update v16 release notes about VTGate Advertised MySQL Version...
    • b05d3a4 fix: union distinct between unsharded route and sharded join (#12974)
    • b194834 test: change cfc test to make it work consistently (#12960)
    • d5d6954 fix: reset transaction session with better checks when no reserved connection...
    • 818ccd5 Remove recent golangci-lint version bump (#12909)
    • e18974d [release-16.0] planner fix: scoping rules for JOIN ON expression inside a sub...
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) You can disable automated security fix PRs for this repo from the Security Alerts page.
SQL builder and query library for golang

__ _ ___ __ _ _ _ / _` |/ _ \ / _` | | | | | (_| | (_) | (_| | |_| | \__, |\___/ \__, |\__,_| |___/ |_| goqu is an expressive SQL bu

Dec 30, 2022
Type safe SQL builder with code generation and automatic query result data mapping
Type safe SQL builder with code generation and automatic query result data mapping

Jet Jet is a complete solution for efficient and high performance database access, consisting of type-safe SQL builder with code generation and automa

Jan 6, 2023
Type safe SQL query builder and struct mapper for Go

sq (Structured Query) ?? ?? sq is a code-generated, type safe query builder and struct mapper for Go. ?? ?? Documentation • Reference • Examples This

Dec 19, 2022
Database Abstraction Layer (dbal) for Go. Support SQL builder and get result easily (now only support mysql)

godbal Database Abstraction Layer (dbal) for go (now only support mysql) Motivation I wanted a DBAL that No ORM、No Reflect、Concurrency Save, support S

Nov 17, 2022
Go database query builder library for PostgreSQL

buildsqlx Go Database query builder library Installation Selects, Ordering, Limit & Offset GroupBy / Having Where, AndWhere, OrWhere clauses WhereIn /

Dec 23, 2022
SQL query builder for Go

GoSQL Query builder with some handy utility functions. Documentation For full documentation see the pkg.go.dev or GitBook. Examples // Open database a

Dec 12, 2022
Fast SQL query builder for Go

sqlf A fast SQL query builder for Go. sqlf statement builder provides a way to: Combine SQL statements from fragments of raw SQL and arguments that ma

Dec 23, 2022
Simple query builder for MongoDB

?? greenleaf - simple, type safe and easy to use query builder for MongoDB Installation To install use: go get github.com/slavabobik/greenleaf Quick

Nov 27, 2022
gosq is a parsing engine for a simplicity-focused, template-based SQL query builder for Go.

gosq is a parsing engine for a simplicity-focused, template-based SQL query builder for Go.

Oct 24, 2022
golang orm and sql builder

gosql gosql is a easy ORM library for Golang. Style: var userList []UserModel err := db.FetchAll(&userList, gosql.Columns("id","name"), gosql.

Dec 22, 2022