Skip to content

dynajoe/sql-gen-go

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SQL Gen Go

This package takes a directory and builds go types to be used with generated sql query builder.

Example:

Assume this directory structure

./sql 
    /authors
        create.sql
        fetch.sql
        list.sql

This tool will build an output like this (annotated in comments):

// Code generated by go generate; DO NOT EDIT.
package sql

// Based on the directory and file authors/create.sql
// parameters from the sql file e.g. :bio and :name are available as part of the struct.
// in the future these params will be able to be annotated with primitives or sql.* types.
type AuthorsCreate struct {
	Bio  interface{}
	Name interface{}
}

// authors/fetch.sql
type AuthorsFetch struct {
	AuthorId interface{}
}

// authors/list.sql (no parameters)
type AuthorsList struct {
}

func (p AuthorsCreate) Build() (string, []interface{}) {
	return "INSERT INTO authors (\n  name, bio\n) VALUES (\n  $1, $2\n)\nRETURNING *;", []interface{}{
		p.Name,
		p.Bio,
	}
}

func (p AuthorsFetch) Build() (string, []interface{}) {
	return "SELECT * FROM authors\nWHERE id = $1 LIMIT 1;", []interface{}{
		p.AuthorId,
	}
}

func (p AuthorsList) Build() (string, []interface{}) {
	return "SELECT * FROM authors\nORDER BY name;", []interface{}{}
}

And usage:

package main

import "github.com/dynajoe/sql-gen-go/sql"

func main() {
    query, params := (sql.AuthorsCreate{
        Name: "Joe",
        Bio: "I like databases",
    }).Build()

    // Use query and params with your sql driver of choice
}

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published