Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optionally prepend schema for multi-tenancy #3502

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
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
5 changes: 4 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
{
"files.insertFinalNewline": true
"files.insertFinalNewline": true,
"files.associations": {
"*.tmpl": "html"
}
}
3 changes: 3 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
build:
go build ./...

build-local:
go build -o ../sqlc-tilby ./cmd/sqlc

install:
go install ./...

Expand Down
7 changes: 7 additions & 0 deletions internal/codegen/golang/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ type tmplCtx struct {
UsesBatch bool
OmitSqlcVersion bool
BuildTags string
EmitSchemaName bool
}

func (t *tmplCtx) OutputQuery(sourceName string) bool {
Expand All @@ -60,6 +61,10 @@ func (t *tmplCtx) codegenEmitPreparedQueries() bool {
return t.EmitPreparedQueries
}

func (t *tmplCtx) codegenEmitSchemaName() bool {
return t.EmitSchemaName
}

func (t *tmplCtx) codegenQueryMethod(q Query) string {
db := "q.db"
if t.EmitMethodsWithDBArgument {
Expand Down Expand Up @@ -187,6 +192,7 @@ func generate(req *plugin.GenerateRequest, options *opts.Options, enums []Enum,
SqlcVersion: req.SqlcVersion,
BuildTags: options.BuildTags,
OmitSqlcVersion: options.OmitSqlcVersion,
EmitSchemaName: options.EmitSchemaName,
}

if tctx.UsesCopyFrom && !tctx.SQLDriver.IsPGX() && options.SqlDriver != opts.SQLDriverGoSQLDriverMySQL {
Expand Down Expand Up @@ -218,6 +224,7 @@ func generate(req *plugin.GenerateRequest, options *opts.Options, enums []Enum,
"emitPreparedQueries": tctx.codegenEmitPreparedQueries,
"queryMethod": tctx.codegenQueryMethod,
"queryRetval": tctx.codegenQueryRetval,
"emitSchemaName": tctx.codegenEmitSchemaName,
}

tmpl := template.Must(
Expand Down
1 change: 1 addition & 0 deletions internal/codegen/golang/opts/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ type Options struct {
EmitEnumValidMethod bool `json:"emit_enum_valid_method,omitempty" yaml:"emit_enum_valid_method"`
EmitAllEnumValues bool `json:"emit_all_enum_values,omitempty" yaml:"emit_all_enum_values"`
EmitSqlAsComment bool `json:"emit_sql_as_comment,omitempty" yaml:"emit_sql_as_comment"`
EmitSchemaName bool `json:"emit_schema_name,omitempty" yaml:"emit_schema_name"`
JsonTagsCaseStyle string `json:"json_tags_case_style,omitempty" yaml:"json_tags_case_style"`
Package string `json:"package" yaml:"package"`
Out string `json:"out" yaml:"out"`
Expand Down
8 changes: 5 additions & 3 deletions internal/codegen/golang/result.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,9 +141,7 @@ func newGoEmbed(embed *plugin.Identifier, structs []Struct, defaultSchema string
}

fields := make([]Field, len(s.Fields))
for i, f := range s.Fields {
fields[i] = f
}
copy(fields, s.Fields)

return &goEmbed{
modelType: s.Name,
Expand Down Expand Up @@ -216,6 +214,10 @@ func buildQueries(req *plugin.GenerateRequest, options *opts.Options, structs []
}
}

if options.EmitSchemaName {
query.Text = ApplySchema(query.Text)
}

gq := Query{
Cmd: query.Cmd,
ConstantName: constantName,
Expand Down
62 changes: 62 additions & 0 deletions internal/codegen/golang/schema.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package golang

import (
"fmt"
"strings"
)

func ApplySchema(query string) string {
tables := make(map[string]bool)
ctes := make(map[string]bool)

words := strings.Fields(query)

// Getting all the table names and CTEs
withinCTE := false
for i, word := range words {
upperWord := strings.ToUpper(word)

if upperWord == "WITH" {
withinCTE = true
continue
} else if withinCTE {
ctes[words[i]] = true
withinCTE = false
continue
}

if isSQLKeyword(upperWord) {
tables[nextNonKeyword(words, i)] = true
}
}

// Removing from tables the CTEs
for cte := range ctes {
delete(tables, cte)
}

// Replacing the table names with the placeholder
for table := range tables {
query = strings.ReplaceAll(query, " "+table, fmt.Sprintf(" `%%s`.%s", table))
}

return query
}

// Helper function to check if a word is a relevant SQL keyword
func isSQLKeyword(word string) bool {
switch word {
case "FROM", "JOIN", "UPDATE", "INTO":
return true
}
return false
}

func nextNonKeyword(words []string, currentIndex int) string {
for i := currentIndex + 1; i < len(words); i++ {
if !isSQLKeyword(words[i]) && words[i] != "AS" && words[i] != "(" {
return words[i]
}
}
return ""
}
47 changes: 47 additions & 0 deletions internal/codegen/golang/schema_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package golang_test

import (
"testing"

"github.com/sqlc-dev/sqlc/internal/codegen/golang"
)

func TestApplySchema(t *testing.T) {
testCases := []struct {
name string
inputQuery string
expectedQuery string
}{
{
name: "Simple Query with Single Table",
inputQuery: "SELECT * FROM users",
expectedQuery: "SELECT * FROM `%s`.users",
},
{
name: "Query with Multiple Tables",
inputQuery: "SELECT * FROM users JOIN orders ON users.id = orders.user_id",
expectedQuery: "SELECT * FROM `%s`.users JOIN `%s`.orders ON `%s`.users.id = `%s`.orders.user_id",
},
{
name: "Query with CTE",
inputQuery: "WITH user_orders AS (SELECT * FROM users JOIN orders ON users.id = orders.user_id) SELECT * FROM user_orders",
expectedQuery: "WITH user_orders AS (SELECT * FROM `%s`.users JOIN `%s`.orders ON `%s`.users.id = `%s`.orders.user_id) SELECT * FROM user_orders",
},
{
name: "Query with CTE and Aliases",
inputQuery: "WITH user_orders AS (SELECT * FROM users u JOIN orders o ON u.id = o.user_id) SELECT * FROM user_orders uo",
expectedQuery: "WITH user_orders AS (SELECT * FROM `%s`.users u JOIN `%s`.orders o ON u.id = o.user_id) SELECT * FROM user_orders uo",
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
result := golang.ApplySchema(tc.inputQuery)
if result != tc.expectedQuery {
t.Errorf("Expected:\n%s\nGot:\n%s", tc.expectedQuery, result)
}
})
}
}

// "SELECT * FROM `%s`.users JOIN `%s`.orders ON `%s`.users.id `%s`.= `%s`.orders.user_id"
Loading
Loading