Giter VIP home page Giter VIP logo

sq's Introduction

GoDoc tests Go Report Card Coverage Status

code example of a select query using sq, to give viewers a quick idea of what the library is about

sq (Structured Query)

one-page documentation

sq is a type-safe data mapper and query builder for Go. Its concept is simple: you provide a callback function that maps a row to a struct, generics ensure that you get back a slice of structs at the end. Additionally, mentioning a column in the callback function automatically adds it to the SELECT clause so you don't even have to explicitly mention what columns you want to select: the act of mapping a column is the same as selecting it. This eliminates a source of errors where you have specify the columns twice (once in the query itself, once to the call to rows.Scan) and end up missing a column, getting the column order wrong or mistyping a column name.

Notable features:

  • Works across SQLite, Postgres, MySQL and SQL Server. [more info]
  • Each dialect has its own query builder, allowing you to use dialect-specific features. [more info]
  • Declarative schema migrations. [more info]
  • Supports arrays, enums, JSON and UUID. [more info]
  • Query logging. [more info]

Installation

This package only supports Go 1.19 and above.

$ go get github.com/bokwoon95/sq
$ go install -tags=fts5 github.com/bokwoon95/sqddl@latest

Features

SELECT example (Raw SQL)

db, err := sql.Open("postgres", "postgres://username:password@localhost:5432/sakila?sslmode=disable")

actors, err := sq.FetchAll(db, sq.
    Queryf("SELECT {*} FROM actor AS a WHERE a.actor_id IN ({})",
        []int{1, 2, 3, 4, 5},
    ).
    SetDialect(sq.DialectPostgres),
    func(row *sq.Row) Actor {
        return Actor{
            ActorID:     row.Int("a.actor_id"),
            FirstName:   row.String("a.first_name"),
            LastName:    row.String("a.last_name"),
            LastUpdate:  row.Time("a.last_update"),
        }
    },
)

SELECT example (Query Builder)

To use the query builder, you must first define your table structs.

type ACTOR struct {
    sq.TableStruct
    ACTOR_ID    sq.NumberField
    FIRST_NAME  sq.StringField
    LAST_NAME   sq.StringField
    LAST_UPDATE sq.TimeField
}

db, err := sql.Open("postgres", "postgres://username:password@localhost:5432/sakila?sslmode=disable")

a := sq.New[ACTOR]("a")
actors, err := sq.FetchAll(db, sq.
    From(a).
    Where(a.ACTOR_ID.In([]int{1, 2, 3, 4, 5})).
    SetDialect(sq.DialectPostgres),
    func(row *sq.Row) Actor {
        return Actor{
            ActorID:     row.IntField(a.ACTOR_ID),
            FirstName:   row.StringField(a.FIRST_NAME),
            LastName:    row.StringField(a.LAST_NAME),
            LastUpdate:  row.TimeField(a.LAST_UPDATE),
        }
    },
)

INSERT example (Raw SQL)

db, err := sql.Open("postgres", "postgres://username:password@localhost:5432/sakila?sslmode=disable")

_, err := sq.Exec(db, sq.
    Queryf("INSERT INTO actor (actor_id, first_name, last_name) VALUES {}", sq.RowValues{
        {18, "DAN", "TORN"},
        {56, "DAN", "HARRIS"},
        {166, "DAN", "STREEP"},
    }).
    SetDialect(sq.DialectPostgres),
)

INSERT example (Query Builder)

To use the query builder, you must first define your table structs.

type ACTOR struct {
    sq.TableStruct
    ACTOR_ID    sq.NumberField
    FIRST_NAME  sq.StringField
    LAST_NAME   sq.StringField
    LAST_UPDATE sq.TimeField
}

db, err := sql.Open("postgres", "postgres://username:password@localhost:5432/sakila?sslmode=disable")

a := sq.New[ACTOR]("a")
_, err := sq.Exec(db, sq.
    InsertInto(a).
    Columns(a.ACTOR_ID, a.FIRST_NAME, a.LAST_NAME).
    Values(18, "DAN", "TORN").
    Values(56, "DAN", "HARRIS").
    Values(166, "DAN", "STREEP").
    SetDialect(sq.DialectPostgres),
)

For a more detailed overview, look at the Quickstart.

Project Status

sq is done for my use case (hence it may seem inactive, but it's just complete). At this point I'm just waiting for people to ask questions or file feature requests under discussions.

Contributing

See START_HERE.md.

sq's People

Contributors

bokwoon95 avatar recht avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

sq's Issues

Docs code for setting global dialect doesn't compile

The docs say that it can be done with following code

sq.DefaultDialect.Store(&sq.DialectPostgres)

but it doesn't work, because

invalid operation: cannot take address of sq.DialectPostgres (untyped string constant "postgres")

Which is a fairly common Go "gotcha" ;-).

Can be mitigated with

    d := sq.DialectPostgres
    sq.DefaultDialect.Store(&d)

It is not as "pleasant", though.

Aggregate queries

I've been trying to create a dynamic query to do a simple count as:

sq.Postgres.From(tbl).Select(sq.CountStar().As("count"))

The SQL generated from a CompileExec call is correct:

SELECT COUNT(*) AS count FROM table

but I can't seem to retrieve the result with a rowmapper function. I'm using for rowmapper

func(row *sq.Row) int {
	return row.Int("count")
}

but the fetch call fails with an error (column "count" does not exist (SQLSTATE 42703)).

What's the correct way to do aggregations at the top level without specifying columns and group by clauses?

Thanks!

cannot call JSONField for static queries

Latest release fails for us with cannot call JSONField for static queries. The query is using a mapper that looks something like this:

func mapper(r *sq.Row) json.RawMessage {
	var pref json.RawMessage
	r.JSONField(&pref, table.Value)
	return pref
}

dialect into wrapper/context/global/env/...

Hi,

Thanks for this awesome lib.

There's only one thing I don't like, is that SetDialect needs to be called for all queries. Is there any way to remove this, and need to set it only once per project?

I'm thinking of either something like

type SqWrap struct {
  *sql.DB
  Dialect string
}

or storing it in a global in sq like sq.SetDialect and it would mean for all queries.

Thanks again.

slice in query value

Hi,

I'd like some help with the following:

qry := "SELECT COUNT(*) FROM customers WHERE id IN {id}"
values := []any{sql.Named("id", []int{1})}
cnt, err := sq.FetchOneContext(context.Background(), sq.Log(db), sq.Postgres.Queryf(qry, values...), rowToCount)

Result:
SELECT COUNT(*) FROM customers WHERE id IN 1; err={pq: syntax error at or near "$1"}

I'd expect adding parentheses. If I have multiple values in that param, I get very similar:
SELECT COUNT(*) FROM customers WHERE id IN 1, 2; err={pq: syntax error at or near "$1"}

Docs incomplete probably.

	a := sq.New[models.ACTOR]("a")
	actors, err := sq.FetchAll(lr.Db, sq.
		From(a).
		Where(a.FIRST_NAME.EqString("DAN")).
		SetDialect(sq.DialectPostgres),
		func(row *sq.Row) Actor {
			return Actor{
				ActorID:   row.IntField(a.ACTOR_ID),
				FirstName: row.StringField(a.FIRST_NAME),
				LastName:  row.StringField(a.LAST_NAME),
			}
		},
	)
	
	package models

import (
"database/sql"
"time"

"github.com/bokwoon95/sq"

)

type ACTOR struct {
sq.TableStruct sq:"Actor"
ACTOR_ID sq.NumberField sq:"ActorID"
FIRST_NAME sq.StringField sq:"FirstName"
LAST_NAME sq.StringField sq:"LastName"
LAST_UPDATE sq.TimeField sq:"LastUpdate"
}

undefined: ActorcompilerUndeclaredName

trying to change it to something else leads to:

cannot use row.IntField(a.ACTOR_ID) (value of type int) as sq.NumberField value in struct literalcompilerIncompatibleAssign

	a := sq.New[models.ACTOR]("a")
	actors, err := sq.FetchAll(lr.Db, sq.
		From(a).
		Where(a.FIRST_NAME.EqString("DAN")).
		SetDialect(sq.DialectPostgres),
		func(row *sq.Row) models.ACTOR {
			return models.ACTOR {
				ACTOR_ID:   row.IntField(a.ACTOR_ID),
				FirstName: row.StringField(a.FIRST_NAME),
				LastName:  row.StringField(a.LAST_NAME),
			}
		},
	)

docs seem confusing and i cant figure out how to properly fetch something

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.