Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions query/delete.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package query

import "strings"

// DeleteQuery represents an immutable DELETE query builder.
// Each method returns a new instance without modifying the original.
type DeleteQuery struct {
table string
where whereClauses
}

// Delete creates a new [DeleteQuery] for the given table.
func Delete(table string) DeleteQuery {
return DeleteQuery{table: table}
}

// Where appends an AND WHERE condition.
func (query DeleteQuery) Where(sql string, args ...any) DeleteQuery {
query.where = query.where.add("AND", sql, args)

return query
}

// OrWhere appends an OR WHERE condition.
func (query DeleteQuery) OrWhere(sql string, args ...any) DeleteQuery {
query.where = query.where.add("OR", sql, args)

return query
}

// Build produces the SQL query string and its positional arguments.
func (query DeleteQuery) Build() (string, []any) {
var builder strings.Builder
var args []any

builder.WriteString("DELETE FROM ")
builder.WriteString(query.table)

query.where.render(&builder, &args)

return builder.String(), args
}
75 changes: 75 additions & 0 deletions query/delete_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package query_test

import (
"testing"

"github.com/studiolambda/cosmos/query"
)

func TestDeleteBasic(t *testing.T) {
t.Parallel()

sql, args := query.Delete("users").
Where("id = ?", 1).
Build()

if sql != "DELETE FROM users WHERE id = ?" {
t.Errorf("unexpected sql: %s", sql)
}

if len(args) != 1 || args[0] != 1 {
t.Errorf("unexpected args: %v", args)
}
}

func TestDeleteOrWhere(t *testing.T) {
t.Parallel()

sql, args := query.Delete("sessions").
Where("expired = ?", true).
OrWhere("revoked = ?", true).
Build()

expected := "DELETE FROM sessions WHERE expired = ? OR revoked = ?"

if sql != expected {
t.Errorf("unexpected sql: %s", sql)
}

if len(args) != 2 || args[0] != true || args[1] != true {
t.Errorf("unexpected args: %v", args)
}
}

func TestDeleteNoWhere(t *testing.T) {
t.Parallel()

sql, args := query.Delete("logs").Build()

if sql != "DELETE FROM logs" {
t.Errorf("unexpected sql: %s", sql)
}

if len(args) != 0 {
t.Errorf("unexpected args: %v", args)
}
}

func TestDeleteImmutability(t *testing.T) {
t.Parallel()

base := query.Delete("users")
first := base.Where("id = ?", 1)
second := base.Where("id = ?", 2)

_, argsFirst := first.Build()
_, argsSecond := second.Build()

if argsFirst[0] != 1 {
t.Errorf("unexpected first args: %v", argsFirst)
}

if argsSecond[0] != 2 {
t.Errorf("unexpected second args: %v", argsSecond)
}
}
17 changes: 17 additions & 0 deletions query/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Package query provides an immutable, copy-on-write SQL query builder
// that produces parameterized query strings with positional placeholders (?).
//
// The builder supports SELECT, INSERT, UPDATE, and DELETE statements
// with support for raw SQL expressions via [Raw] and [Expr].
//
// Each method returns a new value without mutating the original,
// making it safe to derive queries from shared base instances:
//
// base := query.Select("users").Columns("id", "name").Where("active = ?", true)
// admins := base.Where("role = ?", "admin")
// editors := base.Where("role = ?", "editor")
//
// The produced queries use ? as the placeholder character. Use your
// database driver's rebind functionality if your database requires
// a different placeholder style (e.g., $1 for PostgreSQL).
package query
3 changes: 3 additions & 0 deletions query/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/studiolambda/cosmos/query

go 1.25.0
65 changes: 65 additions & 0 deletions query/insert.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package query

import (
"slices"
"strings"
)

// insertPair holds a column name and its associated value.
type insertPair struct {
column string
value any
}

// InsertQuery represents an immutable INSERT query builder.
// Each method returns a new instance without modifying the original.
type InsertQuery struct {
table string
pairs []insertPair
}

// Insert creates a new [InsertQuery] for the given table.
func Insert(table string) InsertQuery {
return InsertQuery{table: table}
}

// Set adds a column-value pair to the INSERT statement. The value can
// be a plain value (emits ?), [Raw] (emits literal SQL), or [Expr]
// (emits SQL with embedded placeholders).
func (query InsertQuery) Set(column string, value any) InsertQuery {
query.pairs = append(slices.Clone(query.pairs), insertPair{column: column, value: value})

return query
}

// Build produces the SQL query string and its positional arguments.
func (query InsertQuery) Build() (string, []any) {
var builder strings.Builder
var args []any

builder.WriteString("INSERT INTO ")
builder.WriteString(query.table)
builder.WriteString(" (")

for i, pair := range query.pairs {
if i > 0 {
builder.WriteString(", ")
}

builder.WriteString(pair.column)
}

builder.WriteString(") VALUES (")

for i, pair := range query.pairs {
if i > 0 {
builder.WriteString(", ")
}

renderValue(&builder, &args, pair.value)
}

builder.WriteByte(')')

return builder.String(), args
}
77 changes: 77 additions & 0 deletions query/insert_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package query_test

import (
"testing"

"github.com/studiolambda/cosmos/query"
)

func TestInsertBasic(t *testing.T) {
t.Parallel()

sql, args := query.Insert("users").
Set("name", "Erik").
Set("email", "erik@example.com").
Build()

if sql != "INSERT INTO users (name, email) VALUES (?, ?)" {
t.Errorf("unexpected sql: %s", sql)
}

if len(args) != 2 || args[0] != "Erik" || args[1] != "erik@example.com" {
t.Errorf("unexpected args: %v", args)
}
}

func TestInsertRaw(t *testing.T) {
t.Parallel()

sql, args := query.Insert("users").
Set("name", "Erik").
Set("created_at", query.Raw("NOW()")).
Build()

if sql != "INSERT INTO users (name, created_at) VALUES (?, NOW())" {
t.Errorf("unexpected sql: %s", sql)
}

if len(args) != 1 || args[0] != "Erik" {
t.Errorf("unexpected args: %v", args)
}
}

func TestInsertExpr(t *testing.T) {
t.Parallel()

sql, args := query.Insert("events").
Set("name", "deploy").
Set("scheduled_at", query.Expr{SQL: "NOW() + INTERVAL ? HOUR", Args: []any{2}}).
Build()

if sql != "INSERT INTO events (name, scheduled_at) VALUES (?, NOW() + INTERVAL ? HOUR)" {
t.Errorf("unexpected sql: %s", sql)
}

if len(args) != 2 || args[0] != "deploy" || args[1] != 2 {
t.Errorf("unexpected args: %v", args)
}
}

func TestInsertImmutability(t *testing.T) {
t.Parallel()

base := query.Insert("users").Set("role", "user")
admin := base.Set("name", "Admin")
editor := base.Set("name", "Editor")

sqlAdmin, argsAdmin := admin.Build()
sqlEditor, argsEditor := editor.Build()

if argsAdmin[1] != "Admin" {
t.Errorf("unexpected admin args: %v (sql: %s)", argsAdmin, sqlAdmin)
}

if argsEditor[1] != "Editor" {
t.Errorf("unexpected editor args: %v (sql: %s)", argsEditor, sqlEditor)
}
}
49 changes: 49 additions & 0 deletions query/raw.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package query

import "strings"

// Raw represents a raw SQL fragment that is embedded directly into
// the query without a placeholder. Use this for SQL functions and
// expressions like NOW(), COUNT(*), etc.
type Raw string

// Expr represents a raw SQL fragment with embedded placeholders
// and their corresponding arguments. Use this for expressions that
// require parameterized values within raw SQL.
type Expr struct {
SQL string
Args []any
}

// renderValue writes a single value to the builder. If the value is
// a [Raw], its SQL is written directly. If it is an [Expr], its SQL
// is written and its args are appended. Otherwise, a ? placeholder
// is written and the value is appended to args.
func renderValue(builder *strings.Builder, args *[]any, value any) {
switch v := value.(type) {
case Raw:
builder.WriteString(string(v))
case Expr:
builder.WriteString(v.SQL)
*args = append(*args, v.Args...)
default:
builder.WriteByte('?')
*args = append(*args, value)
}
}

// renderColumn writes a column reference to the builder. If the value
// is a [Raw], its SQL is written directly. If it is an [Expr], its SQL
// is written and its args are appended. Otherwise, the value is written
// as a plain string column name.
func renderColumn(builder *strings.Builder, args *[]any, column any) {
switch v := column.(type) {
case Raw:
builder.WriteString(string(v))
case Expr:
builder.WriteString(v.SQL)
*args = append(*args, v.Args...)
case string:
builder.WriteString(v)
}
}
Loading