Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat: added simple query builder to avoid always raw commands

=d116f40f78c2
diff --git a/backend-go/internal/database/pg/qb/delete.go b/backend-go/internal/database/pg/qb/delete.go
new file mode 100644
index 0000000000..668e0a051a
--- /dev/null
+++ b/backend-go/internal/database/pg/qb/delete.go
@@ -0,0 +1,61 @@
+package qb
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/jackc/pgx/v5"
+)
+
+type DeleteBuilder struct {
+ table string
+ where []string
+ args pgx.NamedArgs
+ returning string
+}
+
+func Delete(table string) *DeleteBuilder {
+ return &DeleteBuilder{
+ table: table,
+ args: pgx.NamedArgs{},
+ }
+}
+
+func (b *DeleteBuilder) Where(clause, argName string, argValue any) *DeleteBuilder {
+ b.where = append(b.where, clause)
+ if argName != "" {
+ b.args[argName] = argValue
+ }
+ return b
+}
+
+func (b *DeleteBuilder) WhereIf(condition bool, clause, argName string, argValue any) *DeleteBuilder {
+ if condition {
+ return b.Where(clause, argName, argValue)
+ }
+ return b
+}
+
+func (b *DeleteBuilder) WhereClause(clause string) *DeleteBuilder {
+ b.where = append(b.where, clause)
+ return b
+}
+
+func (b *DeleteBuilder) Returning(cols string) *DeleteBuilder {
+ b.returning = cols
+ return b
+}
+
+func (b *DeleteBuilder) Build() (string, pgx.NamedArgs) {
+ query := fmt.Sprintf("DELETE FROM %s", b.table)
+
+ if len(b.where) > 0 {
+ query += " WHERE " + strings.Join(b.where, " AND ")
+ }
+
+ if b.returning != "" {
+ query += " RETURNING " + b.returning
+ }
+
+ return query, b.args
+}
diff --git a/backend-go/internal/database/pg/qb/delete_test.go b/backend-go/internal/database/pg/qb/delete_test.go
new file mode 100644
index 0000000000..c3929da0d8
--- /dev/null
+++ b/backend-go/internal/database/pg/qb/delete_test.go
@@ -0,0 +1,210 @@
+package qb
+
+import (
+ "testing"
+
+ "github.com/google/uuid"
+)
+
+func TestDelete_Basic(t *testing.T) {
+ sql, args := Delete("users").Build()
+
+ expectedSQL := "DELETE FROM users"
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+ if len(args) != 0 {
+ t.Errorf("args should be empty, got %v", args)
+ }
+}
+
+func TestDelete_WithWhere(t *testing.T) {
+ id := uuid.MustParse("11111111-1111-1111-1111-111111111111")
+
+ sql, args := Delete("users").
+ Where("id = @id", "id", id).
+ Build()
+
+ expectedSQL := "DELETE FROM users WHERE id = @id"
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+ if args["id"] != id {
+ t.Errorf("args[id] = %v, want %v", args["id"], id)
+ }
+}
+
+func TestDelete_MultipleWhere(t *testing.T) {
+ id := uuid.MustParse("11111111-1111-1111-1111-111111111111")
+ orgID := uuid.MustParse("22222222-2222-2222-2222-222222222222")
+
+ sql, args := Delete("users").
+ Where("id = @id", "id", id).
+ Where("org_id = @orgID", "orgID", orgID).
+ Build()
+
+ expectedSQL := "DELETE FROM users WHERE id = @id AND org_id = @orgID"
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+ if args["id"] != id {
+ t.Errorf("args[id] = %v, want %v", args["id"], id)
+ }
+ if args["orgID"] != orgID {
+ t.Errorf("args[orgID] = %v, want %v", args["orgID"], orgID)
+ }
+}
+
+func TestDelete_WithReturning(t *testing.T) {
+ id := uuid.MustParse("11111111-1111-1111-1111-111111111111")
+
+ sql, _ := Delete("users").
+ Where("id = @id", "id", id).
+ Returning("*").
+ Build()
+
+ expectedSQL := "DELETE FROM users WHERE id = @id RETURNING *"
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+}
+
+func TestDelete_ReturningSpecificColumns(t *testing.T) {
+ sql, _ := Delete("users").
+ Where("id = @id", "id", uuid.New()).
+ Returning("id, name").
+ Build()
+
+ expectedSQL := "DELETE FROM users WHERE id = @id RETURNING id, name"
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+}
+
+func TestDelete_WhereIf(t *testing.T) {
+ tests := []struct {
+ name string
+ condition bool
+ expectedSQL string
+ hasOrgID bool
+ }{
+ {
+ name: "condition true includes where clause",
+ condition: true,
+ expectedSQL: "DELETE FROM users WHERE id = @id AND org_id = @orgID",
+ hasOrgID: true,
+ },
+ {
+ name: "condition false excludes where clause",
+ condition: false,
+ expectedSQL: "DELETE FROM users WHERE id = @id",
+ hasOrgID: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ id := uuid.New()
+ orgID := uuid.New()
+
+ sql, args := Delete("users").
+ Where("id = @id", "id", id).
+ WhereIf(tt.condition, "org_id = @orgID", "orgID", orgID).
+ Build()
+
+ if sql != tt.expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, tt.expectedSQL)
+ }
+ _, hasOrgID := args["orgID"]
+ if hasOrgID != tt.hasOrgID {
+ t.Errorf("has orgID arg = %v, want %v", hasOrgID, tt.hasOrgID)
+ }
+ })
+ }
+}
+
+func TestDelete_WhereClause(t *testing.T) {
+ sql, _ := Delete("users").
+ WhereClause("deleted_at IS NOT NULL").
+ WhereClause("active = false").
+ Build()
+
+ expectedSQL := "DELETE FROM users WHERE deleted_at IS NOT NULL AND active = false"
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+}
+
+func TestDelete_WhereClauseWithWhere(t *testing.T) {
+ id := uuid.New()
+
+ sql, args := Delete("users").
+ Where("id = @id", "id", id).
+ WhereClause("active = false").
+ Build()
+
+ expectedSQL := "DELETE FROM users WHERE id = @id AND active = false"
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+ if args["id"] != id {
+ t.Errorf("args[id] = %v, want %v", args["id"], id)
+ }
+}
+
+func TestDelete_WhereWithEmptyArgName(t *testing.T) {
+ sql, args := Delete("users").
+ Where("active = true", "", nil).
+ Build()
+
+ expectedSQL := "DELETE FROM users WHERE active = true"
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+ if len(args) != 0 {
+ t.Errorf("args should be empty when argName is empty, got %v", args)
+ }
+}
+
+func TestDelete_Chaining(t *testing.T) {
+ id := uuid.New()
+
+ builder := Delete("users")
+ builder.Where("id = @id", "id", id)
+ builder.WhereClause("active = false")
+ builder.Returning("*")
+
+ sql, args := builder.Build()
+
+ expectedSQL := "DELETE FROM users WHERE id = @id AND active = false RETURNING *"
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+ if args["id"] != id {
+ t.Errorf("args[id] = %v, want %v", args["id"], id)
+ }
+}
+
+func TestDelete_ComplexExample(t *testing.T) {
+ userID := uuid.New()
+ orgID := uuid.New()
+ includeOrg := true
+
+ sql, args := Delete("secrets").
+ Where("user_id = @userID", "userID", userID).
+ WhereIf(includeOrg, "org_id = @orgID", "orgID", orgID).
+ WhereClause("expired_at < NOW()").
+ Returning("id, key").
+ Build()
+
+ expectedSQL := "DELETE FROM secrets WHERE user_id = @userID AND org_id = @orgID AND expired_at < NOW() RETURNING id, key"
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+ if args["userID"] != userID {
+ t.Errorf("args[userID] = %v, want %v", args["userID"], userID)
+ }
+ if args["orgID"] != orgID {
+ t.Errorf("args[orgID] = %v, want %v", args["orgID"], orgID)
+ }
+}
diff --git a/backend-go/internal/database/pg/qb/insert.go b/backend-go/internal/database/pg/qb/insert.go
new file mode 100644
index 0000000000..f020a07216
--- /dev/null
+++ b/backend-go/internal/database/pg/qb/insert.go
@@ -0,0 +1,67 @@
+package qb
+
+import (
+ "fmt"
+ "strings"
+)
+
+type InsertBuilder struct {
+ table string
+ columns []string
+ values [][]any
+ returning string
+}
+
+func Insert(table string, columns ...string) *InsertBuilder {
+ return &InsertBuilder{
+ table: table,
+ columns: columns,
+ }
+}
+
+func (b *InsertBuilder) Values(vals ...any) *InsertBuilder {
+ if len(vals) != len(b.columns) {
+ panic(fmt.Sprintf("qb.Insert: values count (%d) != columns count (%d)", len(vals), len(b.columns)))
+ }
+ b.values = append(b.values, vals)
+ return b
+}
+
+func (b *InsertBuilder) Returning(cols string) *InsertBuilder {
+ b.returning = cols
+ return b
+}
+
+func (b *InsertBuilder) Build() (sql string, args []any) {
+ if len(b.values) == 0 {
+ panic("qb.Insert: no values provided")
+ }
+
+ args = make([]any, 0, len(b.values)*len(b.columns))
+ valueGroups := make([]string, 0, len(b.values))
+ argNum := 1
+ colCount := len(b.columns)
+
+ for _, row := range b.values {
+ placeholders := make([]string, colCount)
+ for i := 0; i < colCount; i++ {
+ placeholders[i] = fmt.Sprintf("$%d", argNum)
+ args = append(args, row[i])
+ argNum++
+ }
+ valueGroups = append(valueGroups, "("+strings.Join(placeholders, ", ")+")")
+ }
+
+ sql = fmt.Sprintf(
+ "INSERT INTO %s (%s) VALUES %s",
+ b.table,
+ strings.Join(b.columns, ", "),
+ strings.Join(valueGroups, ", "),
+ )
+
+ if b.returning != "" {
+ sql += " RETURNING " + b.returning
+ }
+
+ return sql, args
+}
diff --git a/backend-go/internal/database/pg/qb/insert_test.go b/backend-go/internal/database/pg/qb/insert_test.go
new file mode 100644
index 0000000000..d469055deb
--- /dev/null
+++ b/backend-go/internal/database/pg/qb/insert_test.go
@@ -0,0 +1,169 @@
+package qb
+
+import (
+ "reflect"
+ "testing"
+
+ "github.com/google/uuid"
+)
+
+func TestInsert_SingleRow(t *testing.T) {
+ id := uuid.MustParse("11111111-1111-1111-1111-111111111111")
+
+ sql, args := Insert("users", "id", "name", "email").
+ Values(id, "John", "[email protected]").
+ Build()
+
+ expectedSQL := "INSERT INTO users (id, name, email) VALUES ($1, $2, $3)"
+ expectedArgs := []any{id, "John", "[email protected]"}
+
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+ if !reflect.DeepEqual(args, expectedArgs) {
+ t.Errorf("args = %v, want %v", args, expectedArgs)
+ }
+}
+
+func TestInsert_MultipleRows(t *testing.T) {
+ id1 := uuid.MustParse("11111111-1111-1111-1111-111111111111")
+ id2 := uuid.MustParse("22222222-2222-2222-2222-222222222222")
+ id3 := uuid.MustParse("33333333-3333-3333-3333-333333333333")
+
+ sql, args := Insert("users", "id", "name").
+ Values(id1, "Alice").
+ Values(id2, "Bob").
+ Values(id3, "Charlie").
+ Build()
+
+ expectedSQL := "INSERT INTO users (id, name) VALUES ($1, $2), ($3, $4), ($5, $6)"
+ expectedArgs := []any{id1, "Alice", id2, "Bob", id3, "Charlie"}
+
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+ if !reflect.DeepEqual(args, expectedArgs) {
+ t.Errorf("args = %v, want %v", args, expectedArgs)
+ }
+}
+
+func TestInsert_WithReturning(t *testing.T) {
+ sql, args := Insert("users", "name", "email").
+ Values("John", "[email protected]").
+ Returning("*").
+ Build()
+
+ expectedSQL := "INSERT INTO users (name, email) VALUES ($1, $2) RETURNING *"
+ expectedArgs := []any{"John", "[email protected]"}
+
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+ if !reflect.DeepEqual(args, expectedArgs) {
+ t.Errorf("args = %v, want %v", args, expectedArgs)
+ }
+}
+
+func TestInsert_WithReturningSpecificColumns(t *testing.T) {
+ sql, _ := Insert("users", "name", "email").
+ Values("John", "[email protected]").
+ Returning("id, created_at").
+ Build()
+
+ expectedSQL := "INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id, created_at"
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+}
+
+func TestInsert_NilValues(t *testing.T) {
+ sql, args := Insert("users", "name", "email", "phone").
+ Values("John", "[email protected]", nil).
+ Build()
+
+ expectedSQL := "INSERT INTO users (name, email, phone) VALUES ($1, $2, $3)"
+ expectedArgs := []any{"John", "[email protected]", nil}
+
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+ if !reflect.DeepEqual(args, expectedArgs) {
+ t.Errorf("args = %v, want %v", args, expectedArgs)
+ }
+}
+
+func TestInsert_SingleColumn(t *testing.T) {
+ sql, args := Insert("tags", "name").
+ Values("important").
+ Values("urgent").
+ Build()
+
+ expectedSQL := "INSERT INTO tags (name) VALUES ($1), ($2)"
+ expectedArgs := []any{"important", "urgent"}
+
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+ if !reflect.DeepEqual(args, expectedArgs) {
+ t.Errorf("args = %v, want %v", args, expectedArgs)
+ }
+}
+
+func TestInsert_NoValues_Panics(t *testing.T) {
+ defer func() {
+ if r := recover(); r == nil {
+ t.Error("Insert.Build() with no values should panic")
+ }
+ }()
+
+ Insert("users", "name", "email").Build()
+}
+
+func TestInsert_MismatchedValuesCount_Panics(t *testing.T) {
+ defer func() {
+ r := recover()
+ if r == nil {
+ t.Error("Insert.Values() with wrong count should panic")
+ }
+ msg, ok := r.(string)
+ if !ok {
+ t.Errorf("panic value should be string, got %T", r)
+ }
+ if msg == "" {
+ t.Error("panic message should not be empty")
+ }
+ }()
+
+ Insert("users", "name", "email").
+ Values("John"). // missing email
+ Build()
+}
+
+func TestInsert_TooManyValues_Panics(t *testing.T) {
+ defer func() {
+ if r := recover(); r == nil {
+ t.Error("Insert.Values() with too many values should panic")
+ }
+ }()
+
+ Insert("users", "name").
+ Values("John", "extra"). // too many
+ Build()
+}
+
+func TestInsert_Chaining(t *testing.T) {
+ builder := Insert("users", "a", "b")
+ builder.Values(1, 2)
+ builder.Values(3, 4)
+ builder.Returning("*")
+
+ sql, args := builder.Build()
+
+ expectedSQL := "INSERT INTO users (a, b) VALUES ($1, $2), ($3, $4) RETURNING *"
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+ if len(args) != 4 {
+ t.Errorf("args length = %d, want 4", len(args))
+ }
+}
diff --git a/backend-go/internal/database/pg/qb/update.go b/backend-go/internal/database/pg/qb/update.go
new file mode 100644
index 0000000000..58e5f765b6
--- /dev/null
+++ b/backend-go/internal/database/pg/qb/update.go
@@ -0,0 +1,110 @@
+package qb
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/jackc/pgx/v5"
+)
+
+type UpdateBuilder struct {
+ table string
+ sets []string
+ where []string
+ args pgx.NamedArgs
+ returning string
+}
+
+func Update(table string) *UpdateBuilder {
+ return &UpdateBuilder{
+ table: table,
+ args: pgx.NamedArgs{},
+ }
+}
+
+func (b *UpdateBuilder) Set(column string, value any) *UpdateBuilder {
+ argName := toArgName(column)
+ b.sets = append(b.sets, fmt.Sprintf("%s = @%s", column, argName))
+ b.args[argName] = value
+ return b
+}
+
+func (b *UpdateBuilder) SetIf(condition bool, column string, value any) *UpdateBuilder {
+ if condition {
+ return b.Set(column, value)
+ }
+ return b
+}
+
+func (b *UpdateBuilder) SetMap(values map[string]any) *UpdateBuilder {
+ for column, value := range values {
+ b.Set(column, value)
+ }
+ return b
+}
+
+func (b *UpdateBuilder) Where(clause, argName string, argValue any) *UpdateBuilder {
+ b.where = append(b.where, clause)
+ if argName != "" {
+ b.args[argName] = argValue
+ }
+ return b
+}
+
+func (b *UpdateBuilder) WhereIf(condition bool, clause, argName string, argValue any) *UpdateBuilder {
+ if condition {
+ return b.Where(clause, argName, argValue)
+ }
+ return b
+}
+
+func (b *UpdateBuilder) WhereClause(clause string) *UpdateBuilder {
+ b.where = append(b.where, clause)
+ return b
+}
+
+func (b *UpdateBuilder) Returning(cols string) *UpdateBuilder {
+ b.returning = cols
+ return b
+}
+
+func (b *UpdateBuilder) Build() (string, pgx.NamedArgs) {
+ if len(b.sets) == 0 {
+ panic("qb.Update: no SET columns provided")
+ }
+
+ query := fmt.Sprintf(
+ "UPDATE %s SET %s",
+ b.table,
+ strings.Join(b.sets, ", "),
+ )
+
+ if len(b.where) > 0 {
+ query += " WHERE " + strings.Join(b.where, " AND ")
+ }
+
+ if b.returning != "" {
+ query += " RETURNING " + b.returning
+ }
+
+ return query, b.args
+}
+
+func toArgName(column string) string {
+ result := strings.Builder{}
+ upperNext := false
+ for i, r := range column {
+ if r == '_' {
+ upperNext = true
+ continue
+ }
+ if upperNext && i > 0 {
+ if r >= 'a' && r <= 'z' {
+ r -= 32
+ }
+ upperNext = false
+ }
+ result.WriteRune(r)
+ }
+ return result.String()
+}
diff --git a/backend-go/internal/database/pg/qb/update_test.go b/backend-go/internal/database/pg/qb/update_test.go
new file mode 100644
index 0000000000..3ad068b888
--- /dev/null
+++ b/backend-go/internal/database/pg/qb/update_test.go
@@ -0,0 +1,273 @@
+package qb
+
+import (
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+func TestUpdate_Basic(t *testing.T) {
+ sql, args := Update("users").
+ Set("name", "John").
+ Build()
+
+ expectedSQL := "UPDATE users SET name = @name"
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+ if args["name"] != "John" {
+ t.Errorf("args[name] = %v, want %q", args["name"], "John")
+ }
+}
+
+func TestUpdate_MultipleSet(t *testing.T) {
+ now := time.Now()
+
+ sql, args := Update("users").
+ Set("name", "John").
+ Set("email", "[email protected]").
+ Set("updated_at", now).
+ Build()
+
+ expectedSQL := "UPDATE users SET name = @name, email = @email, updated_at = @updatedAt"
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+ if args["name"] != "John" {
+ t.Errorf("args[name] = %v, want %q", args["name"], "John")
+ }
+ if args["email"] != "[email protected]" {
+ t.Errorf("args[email] = %v, want %q", args["email"], "[email protected]")
+ }
+ if args["updatedAt"] != now {
+ t.Errorf("args[updatedAt] = %v, want %v", args["updatedAt"], now)
+ }
+}
+
+func TestUpdate_WithWhere(t *testing.T) {
+ id := uuid.MustParse("11111111-1111-1111-1111-111111111111")
+
+ sql, args := Update("users").
+ Set("name", "John").
+ Where("id = @id", "id", id).
+ Build()
+
+ expectedSQL := "UPDATE users SET name = @name WHERE id = @id"
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+ if args["id"] != id {
+ t.Errorf("args[id] = %v, want %v", args["id"], id)
+ }
+}
+
+func TestUpdate_MultipleWhere(t *testing.T) {
+ id := uuid.MustParse("11111111-1111-1111-1111-111111111111")
+ orgID := uuid.MustParse("22222222-2222-2222-2222-222222222222")
+
+ sql, args := Update("users").
+ Set("name", "John").
+ Where("id = @id", "id", id).
+ Where("org_id = @orgID", "orgID", orgID).
+ Build()
+
+ expectedSQL := "UPDATE users SET name = @name WHERE id = @id AND org_id = @orgID"
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+ if args["id"] != id {
+ t.Errorf("args[id] = %v, want %v", args["id"], id)
+ }
+ if args["orgID"] != orgID {
+ t.Errorf("args[orgID] = %v, want %v", args["orgID"], orgID)
+ }
+}
+
+func TestUpdate_WithReturning(t *testing.T) {
+ sql, _ := Update("users").
+ Set("name", "John").
+ Where("id = @id", "id", uuid.New()).
+ Returning("*").
+ Build()
+
+ expectedSQL := "UPDATE users SET name = @name WHERE id = @id RETURNING *"
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+}
+
+func TestUpdate_ReturningSpecificColumns(t *testing.T) {
+ sql, _ := Update("users").
+ Set("name", "John").
+ Where("id = @id", "id", uuid.New()).
+ Returning("id, name, updated_at").
+ Build()
+
+ expectedSQL := "UPDATE users SET name = @name WHERE id = @id RETURNING id, name, updated_at"
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+}
+
+func TestUpdate_SetIf(t *testing.T) {
+ tests := []struct {
+ name string
+ condition bool
+ expectedSQL string
+ hasEmail bool
+ }{
+ {
+ name: "condition true includes column",
+ condition: true,
+ expectedSQL: "UPDATE users SET name = @name, email = @email",
+ hasEmail: true,
+ },
+ {
+ name: "condition false excludes column",
+ condition: false,
+ expectedSQL: "UPDATE users SET name = @name",
+ hasEmail: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql, args := Update("users").
+ Set("name", "John").
+ SetIf(tt.condition, "email", "[email protected]").
+ Build()
+
+ if sql != tt.expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, tt.expectedSQL)
+ }
+ _, hasEmail := args["email"]
+ if hasEmail != tt.hasEmail {
+ t.Errorf("has email arg = %v, want %v", hasEmail, tt.hasEmail)
+ }
+ })
+ }
+}
+
+func TestUpdate_SetMap(t *testing.T) {
+ values := map[string]any{
+ "name": "John",
+ "email": "[email protected]",
+ }
+
+ sql, args := Update("users").
+ SetMap(values).
+ Build()
+
+ if args["name"] != "John" {
+ t.Errorf("args[name] = %v, want %q", args["name"], "John")
+ }
+ if args["email"] != "[email protected]" {
+ t.Errorf("args[email] = %v, want %q", args["email"], "[email protected]")
+ }
+
+ // SQL should contain both SET clauses (order may vary due to map iteration)
+ if sql == "" {
+ t.Error("SQL should not be empty")
+ }
+}
+
+func TestUpdate_WhereIf(t *testing.T) {
+ tests := []struct {
+ name string
+ condition bool
+ expectedSQL string
+ hasOrgID bool
+ }{
+ {
+ name: "condition true includes where clause",
+ condition: true,
+ expectedSQL: "UPDATE users SET name = @name WHERE id = @id AND org_id = @orgID",
+ hasOrgID: true,
+ },
+ {
+ name: "condition false excludes where clause",
+ condition: false,
+ expectedSQL: "UPDATE users SET name = @name WHERE id = @id",
+ hasOrgID: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ orgID := uuid.New()
+
+ sql, args := Update("users").
+ Set("name", "John").
+ Where("id = @id", "id", uuid.New()).
+ WhereIf(tt.condition, "org_id = @orgID", "orgID", orgID).
+ Build()
+
+ if sql != tt.expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, tt.expectedSQL)
+ }
+ _, hasOrgID := args["orgID"]
+ if hasOrgID != tt.hasOrgID {
+ t.Errorf("has orgID arg = %v, want %v", hasOrgID, tt.hasOrgID)
+ }
+ })
+ }
+}
+
+func TestUpdate_WhereClause(t *testing.T) {
+ sql, _ := Update("users").
+ Set("name", "John").
+ WhereClause("deleted_at IS NULL").
+ Build()
+
+ expectedSQL := "UPDATE users SET name = @name WHERE deleted_at IS NULL"
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+}
+
+func TestUpdate_NoSet_Panics(t *testing.T) {
+ defer func() {
+ if r := recover(); r == nil {
+ t.Error("Update.Build() with no SET should panic")
+ }
+ }()
+
+ Update("users").
+ Where("id = @id", "id", uuid.New()).
+ Build()
+}
+
+func TestUpdate_NoWhere(t *testing.T) {
+ sql, _ := Update("users").
+ Set("active", false).
+ Build()
+
+ expectedSQL := "UPDATE users SET active = @active"
+ if sql != expectedSQL {
+ t.Errorf("SQL = %q, want %q", sql, expectedSQL)
+ }
+}
+
+func TestToArgName(t *testing.T) {
+ tests := []struct {
+ input string
+ expected string
+ }{
+ {"name", "name"},
+ {"user_id", "userId"},
+ {"created_at", "createdAt"},
+ {"org_member_id", "orgMemberId"},
+ {"id", "id"},
+ {"a_b_c", "aBC"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.input, func(t *testing.T) {
+ got := toArgName(tt.input)
+ if got != tt.expected {
+ t.Errorf("toArgName(%q) = %q, want %q", tt.input, got, tt.expected)
+ }
+ })
+ }
+}
diff --git a/backend-go/internal/database/pg/qb/where.go b/backend-go/internal/database/pg/qb/where.go
new file mode 100644
index 0000000000..43c758d750
--- /dev/null
+++ b/backend-go/internal/database/pg/qb/where.go
@@ -0,0 +1,64 @@
+package qb
+
+import "strings"
+
+type Where struct {
+ clauses []string
+ isOr bool
+}
+
+func NewWhere() *Where {
+ return &Where{isOr: false}
+}
+
+func newOrWhere() *Where {
+ return &Where{isOr: true}
+}
+
+func (w *Where) Add(clause string) *Where {
+ w.clauses = append(w.clauses, clause)
+ return w
+}
+
+func (w *Where) AddIf(condition bool, clause string) *Where {
+ if condition {
+ w.clauses = append(w.clauses, clause)
+ }
+ return w
+}
+
+func (w *Where) Or(clause string) *Where {
+ w.clauses = append(w.clauses, clause)
+ w.isOr = true
+ return w
+}
+
+func (w *Where) Group(sub *Where) *Where {
+ if !sub.IsEmpty() {
+ w.clauses = append(w.clauses, "("+sub.String()+")")
+ }
+ return w
+}
+
+func (w *Where) OrGroup(buildFn func(w *Where)) *Where {
+ sub := newOrWhere()
+ buildFn(sub)
+ return w.Group(sub)
+}
+
+func (w *Where) AndGroup(buildFn func(w *Where)) *Where {
+ sub := NewWhere()
+ buildFn(sub)
+ return w.Group(sub)
+}
+
+func (w *Where) String() string {
+ if w.isOr {
+ return strings.Join(w.clauses, " OR ")
+ }
+ return strings.Join(w.clauses, " AND ")
+}
+
+func (w *Where) IsEmpty() bool {
+ return len(w.clauses) == 0
+}
diff --git a/backend-go/internal/database/pg/qb/where_test.go b/backend-go/internal/database/pg/qb/where_test.go
new file mode 100644
index 0000000000..96afb42081
--- /dev/null
+++ b/backend-go/internal/database/pg/qb/where_test.go
@@ -0,0 +1,214 @@
+package qb
+
+import (
+ "testing"
+)
+
+func TestNewWhere(t *testing.T) {
+ w := NewWhere()
+ if w == nil {
+ t.Fatal("NewWhere returned nil")
+ }
+ if !w.IsEmpty() {
+ t.Error("new Where should be empty")
+ }
+ if w.String() != "" {
+ t.Errorf("empty Where.String() = %q, want empty string", w.String())
+ }
+}
+
+func TestWhere_Add(t *testing.T) {
+ tests := []struct {
+ name string
+ clauses []string
+ expected string
+ }{
+ {
+ name: "single clause",
+ clauses: []string{"id = @id"},
+ expected: "id = @id",
+ },
+ {
+ name: "multiple clauses joined with AND",
+ clauses: []string{"id = @id", "name = @name", "active = true"},
+ expected: "id = @id AND name = @name AND active = true",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ w := NewWhere()
+ for _, clause := range tt.clauses {
+ w.Add(clause)
+ }
+ if got := w.String(); got != tt.expected {
+ t.Errorf("Where.String() = %q, want %q", got, tt.expected)
+ }
+ if w.IsEmpty() && len(tt.clauses) > 0 {
+ t.Error("Where should not be empty after Add")
+ }
+ })
+ }
+}
+
+func TestWhere_AddIf(t *testing.T) {
+ tests := []struct {
+ name string
+ condition bool
+ clause string
+ expected string
+ isEmpty bool
+ }{
+ {
+ name: "condition true adds clause",
+ condition: true,
+ clause: "id = @id",
+ expected: "id = @id",
+ isEmpty: false,
+ },
+ {
+ name: "condition false skips clause",
+ condition: false,
+ clause: "id = @id",
+ expected: "",
+ isEmpty: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ w := NewWhere()
+ w.AddIf(tt.condition, tt.clause)
+ if got := w.String(); got != tt.expected {
+ t.Errorf("Where.String() = %q, want %q", got, tt.expected)
+ }
+ if w.IsEmpty() != tt.isEmpty {
+ t.Errorf("Where.IsEmpty() = %v, want %v", w.IsEmpty(), tt.isEmpty)
+ }
+ })
+ }
+}
+
+func TestWhere_AddIfMultiple(t *testing.T) {
+ w := NewWhere()
+ w.Add("base = @base")
+ w.AddIf(true, "included = @included")
+ w.AddIf(false, "excluded = @excluded")
+ w.AddIf(true, "also_included = @also")
+
+ expected := "base = @base AND included = @included AND also_included = @also"
+ if got := w.String(); got != expected {
+ t.Errorf("Where.String() = %q, want %q", got, expected)
+ }
+}
+
+func TestWhere_Or(t *testing.T) {
+ w := NewWhere()
+ w.Add("a = 1")
+ w.Or("b = 2")
+ w.Or("c = 3")
+
+ expected := "a = 1 OR b = 2 OR c = 3"
+ if got := w.String(); got != expected {
+ t.Errorf("Where.String() = %q, want %q", got, expected)
+ }
+}
+
+func TestWhere_Group(t *testing.T) {
+ outer := NewWhere()
+ outer.Add("active = true")
+
+ inner := newOrWhere()
+ inner.Add("role = @role1")
+ inner.Add("role = @role2")
+
+ outer.Group(inner)
+
+ expected := "active = true AND (role = @role1 OR role = @role2)"
+ if got := outer.String(); got != expected {
+ t.Errorf("Where.String() = %q, want %q", got, expected)
+ }
+}
+
+func TestWhere_GroupEmpty(t *testing.T) {
+ outer := NewWhere()
+ outer.Add("active = true")
+
+ inner := NewWhere()
+ outer.Group(inner)
+
+ expected := "active = true"
+ if got := outer.String(); got != expected {
+ t.Errorf("empty group should not be added: got %q, want %q", got, expected)
+ }
+}
+
+func TestWhere_OrGroup(t *testing.T) {
+ w := NewWhere()
+ w.Add("folder_id = @folderID")
+ w.OrGroup(func(sub *Where) {
+ sub.Add("key LIKE @search")
+ sub.Add("name LIKE @search")
+ })
+
+ expected := "folder_id = @folderID AND (key LIKE @search OR name LIKE @search)"
+ if got := w.String(); got != expected {
+ t.Errorf("Where.String() = %q, want %q", got, expected)
+ }
+}
+
+func TestWhere_AndGroup(t *testing.T) {
+ w := NewWhere()
+ w.Add("active = true")
+ w.AndGroup(func(sub *Where) {
+ sub.Add("role = @role")
+ sub.Add("org_id = @orgID")
+ })
+
+ expected := "active = true AND (role = @role AND org_id = @orgID)"
+ if got := w.String(); got != expected {
+ t.Errorf("Where.String() = %q, want %q", got, expected)
+ }
+}
+
+func TestWhere_OrGroupEmpty(t *testing.T) {
+ w := NewWhere()
+ w.Add("active = true")
+ w.OrGroup(func(sub *Where) {
+ // empty - nothing added
+ })
+
+ expected := "active = true"
+ if got := w.String(); got != expected {
+ t.Errorf("empty OrGroup should not affect result: got %q, want %q", got, expected)
+ }
+}
+
+func TestWhere_NestedGroups(t *testing.T) {
+ w := NewWhere()
+ w.Add("a = 1")
+ w.OrGroup(func(outer *Where) {
+ outer.Add("b = 2")
+ outer.AndGroup(func(inner *Where) {
+ inner.Add("c = 3")
+ inner.Add("d = 4")
+ })
+ })
+
+ expected := "a = 1 AND (b = 2 OR (c = 3 AND d = 4))"
+ if got := w.String(); got != expected {
+ t.Errorf("nested groups: got %q, want %q", got, expected)
+ }
+}
+
+func TestWhere_Chaining(t *testing.T) {
+ w := NewWhere().
+ Add("a = 1").
+ AddIf(true, "b = 2").
+ AddIf(false, "c = 3")
+
+ expected := "a = 1 AND b = 2"
+ if got := w.String(); got != expected {
+ t.Errorf("chained Where.String() = %q, want %q", got, expected)
+ }
+}