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

CircleCI codecov Go Report Card Godoc Reference

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 constants in the code, and using them in an easy way inside your application with all the profit of compile time constants.

qry recursively loads all .sql files from a specified folder, parses them according to predefined rules and returns a reusable object, which is actually just a map[string]string with some sugar. Multiple queries inside a single file are separated with standard SQL comment syntax: -- qry: QueryName. A QueryName must match [A-Za-z_]+.

gen tool is used for automatic generation of constants for all user specified query_names.

Installation

go get -u github.com/HnH/qry/cmd/qry-gen

Usage

Prepare sql files: queries/one.sql:

-- qry: InsertUser
INSERT INTO `users` (`name`) VALUES (?);

-- qry: GetUserById
SELECT * FROM `users` WHERE `user_id` = ?;

And the second one queries/two.sql:

-- qry: DeleteUsersByIds
DELETE FROM `users` WHERE `user_id` IN ({ids});

Generate constants: qry-gen -dir=./queries -pkg=/path/to/your/go/pkg Will produce /path/to/your/go/pkg/qry.go with:

package pkg

const (
	// one.sql
	InsertUser  = "INSERT INTO `users` (`name`) VALUES (?);"
	GetUserById = "SELECT * FROM `users` WHERE `user_id` = ?;"

	// two.sql
	DeleteUsersByIds = "DELETE FROM `users` WHERE `user_id` IN ({ids});"
)

As a best practice include this qry-gen call in your source code with go:generate prefix: //go:generate qry-gen -dir=./queries -pkg=/path/to/your/go/pkg and just execute go generate before each build. Now it's time to use qry inside your project:

func main() {
	/**
	 * The most obvious way is to use generated constants in the source code
	 */
	 
	// INSERT INTO `users` (`name`) VALUES (?);
	println(pkg.InsertUser)
	
	// DELETE FROM `users` WHERE `user_id` IN (?,?,?);
	println(qry.Query(pkg.DeleteUsersByIds).Replace("{ids}", qry.In(3)))
	
	/**
	 * As an alternative you can manually parse .sql files in the directory and work with output
	 */
	if q, err := qry.Dir("/path/to/your/go/pkg/queries"); err != nil {
		log.Fatal(err)
	}

	// SELECT * FROM `users` WHERE `user_id` = ?;
	println(q["one.sql"]["GetUserById"])
  
	// DELETE FROM `users` WHERE `user_id` IN (?,?,?);
	println(q["two.sql"]["DeleteUsersByIds"].Replace("{ids}", qry.In(3)))
}
Owner
Sergey Treinis
Tech Lead / Golang software engineer
Sergey Treinis
Similar Resources

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

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

A Go (golang) package that enhances the standard database/sql package by providing powerful data retrieval methods as well as DB-agnostic query building capabilities.

ozzo-dbx Summary Description Requirements Installation Supported Databases Getting Started Connecting to Database Executing Queries Binding Parameters

Dec 31, 2022

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

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

Fluent SQL generation for golang

sqrl - fat-free version of squirrel - fluent SQL generator for Go Non thread safe fork of squirrel. The same handy fluffy helper, but with extra lette

Dec 16, 2022

Fluent SQL generation for golang

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

Jan 6, 2023

GraphJin - Build APIs in 5 minutes with GraphQL. An instant GraphQL to SQL compiler.

GraphJin - Build APIs in 5 minutes with GraphQL. An instant GraphQL to SQL compiler.

GraphJin - Build APIs in 5 minutes GraphJin gives you a high performance GraphQL API without you having to write any code. GraphQL is automagically co

Jan 4, 2023

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
Comments
  • Add comment generation

    Add comment generation

    fixes #2

    Adding comment generation (for exported variables) as well as command option to disable it.

    Generated file looks like this:

    const (
      // one.sql
    
      // InsertUser query
      InsertUser = "INSERT INTO `users` (`name`) VALUES (?);"
      // GetUserById query
      GetUserById = "SELECT * FROM `users` WHERE `user_id` = ?;"
    
      // two.sql
    
      // DeleteUsersByIds query
      DeleteUsersByIds = "DELETE FROM `users` WHERE `user_id` IN ({ids});"
      // UglyMultiLineQuery query
      UglyMultiLineQuery = "SELECT * FROM `users` WHERE YEAR(`birth_date`) > 2000;"
    )
    
  • SQL comment support

    SQL comment support

    Hello again,

    I found myself wanting to use comments in my queries, so I made a PR that makes it possible. I added support for both inline (--) and multiline (/* */) comments

  • Request for double quote escaping

    Request for double quote escaping

    Double quote escaping is necessary to use JSON variables, for example:

    -- qry: EscapedJSONQuery
    INSERT INTO "data" (id, "data") VALUES
      (1, '{"test": 1}'),
      (2, '{"test": 2}');
    

    Current solution produces an invalid golang string when " is present, throwing an error when formatting:

    cannot acquire gofmt stdout
    database/queries.go:8: running "qry-gen": exit status 1
    

    Will update my current PR to fix this too

  • Comment for exported query linter error

    Comment for exported query linter error

    Hello,

    I suggest to improve the generated comment to follow go-lint guidelines for exported variables.

    Currently the following error is given: error_qry

    I'll make a PR to address this issue soon

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
💥 A lightweight DSL & ORM which helps you to write SQL in Go.
💥 A lightweight DSL & ORM which helps you to write SQL in Go.

sqlingo is a SQL DSL (a.k.a. SQL Builder or ORM) library in Go. It generates code from the database and lets you write SQL queries in an elegant way.

Jan 2, 2023
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
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

May 9, 2023
Squat is an application that provides simple SQL data generation functionality.

Squat Squat is an application that provides simple SQL data generation functionality. It generates synthetic SQL data based on the table definition, t

Sep 22, 2022
Mocking your SQL database in Go tests has never been easier.

copyist Mocking your SQL database in Go tests has never been easier. The copyist library automatically records low-level SQL calls made during your te

Dec 19, 2022
A Golang library for using SQL.

dotsql A Golang library for using SQL. It is not an ORM, it is not a query builder. Dotsql is a library that helps you keep sql files in one place and

Dec 27, 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
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
SQL builder and query library for golang

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

Dec 30, 2022