Skip to content

feat(coderd/database): generate foreign key constraints and add database.IsForeignKeyViolation #9657

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

Merged
merged 2 commits into from
Sep 13, 2023
Merged
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
2 changes: 1 addition & 1 deletion coderd/apikey.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ func (api *API) postToken(rw http.ResponseWriter, r *http.Request) {
TokenName: tokenName,
})
if err != nil {
if database.IsUniqueViolation(err, database.UniqueIndexApiKeyName) {
if database.IsUniqueViolation(err, database.UniqueIndexAPIKeyName) {
httpapi.Write(ctx, rw, http.StatusConflict, codersdk.Response{
Message: fmt.Sprintf("A token with name %q already exists.", tokenName),
Validations: []codersdk.ValidationError{{
Expand Down
22 changes: 22 additions & 0 deletions coderd/database/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,28 @@ func IsUniqueViolation(err error, uniqueConstraints ...UniqueConstraint) bool {
return false
}

// IsForeignKeyViolation checks if the error is due to a foreign key violation.
// If one or more specific foreign key constraints are given as arguments,
// the error must be caused by one of them. If no constraints are given,
// this function returns true for any foreign key violation.
func IsForeignKeyViolation(err error, foreignKeyConstraints ...ForeignKeyConstraint) bool {
var pqErr *pq.Error
if errors.As(err, &pqErr) {
if pqErr.Code.Name() == "foreign_key_violation" {
if len(foreignKeyConstraints) == 0 {
return true
}
for _, fc := range foreignKeyConstraints {
if pqErr.Constraint == string(fc) {
return true
}
}
}
}

return false
}

// IsQueryCanceledError checks if the error is due to a query being canceled.
func IsQueryCanceledError(err error) bool {
var pqErr *pq.Error
Expand Down
49 changes: 49 additions & 0 deletions coderd/database/foreign_key_constraint.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions coderd/database/unique_constraint.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

87 changes: 86 additions & 1 deletion scripts/dbgen/main.go
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note: I haven't performed any DRY refactoring on this piece here; I figure de-duplication is premature.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💯 agreed.

Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,11 @@ return %s
return xerrors.Errorf("generate unique constraints: %w", err)
}

err = generateForeignKeyConstraints()
if err != nil {
return xerrors.Errorf("generate foreign key constraints: %w", err)
}

return nil
}

Expand Down Expand Up @@ -125,7 +130,7 @@ func generateUniqueConstraints() error {

s := &bytes.Buffer{}

_, _ = fmt.Fprint(s, `// Code generated by gen/enum. DO NOT EDIT.
_, _ = fmt.Fprint(s, `// Code generated by scripts/dbgen/main.go. DO NOT EDIT.
package database
`)
_, _ = fmt.Fprint(s, `
Expand Down Expand Up @@ -160,6 +165,78 @@ const (
return os.WriteFile(outputPath, data, 0o600)
}

// generateForeignKeyConstraints generates the ForeignKeyConstraint enum.
func generateForeignKeyConstraints() error {
localPath, err := localFilePath()
if err != nil {
return err
}
databasePath := filepath.Join(localPath, "..", "..", "..", "coderd", "database")

dump, err := os.Open(filepath.Join(databasePath, "dump.sql"))
if err != nil {
return err
}
defer dump.Close()

var foreignKeyConstraints []string
dumpScanner := bufio.NewScanner(dump)
query := ""
for dumpScanner.Scan() {
line := strings.TrimSpace(dumpScanner.Text())
switch {
case strings.HasPrefix(line, "--"):
case line == "":
case strings.HasSuffix(line, ";"):
query += line
if strings.Contains(query, "FOREIGN KEY") {
foreignKeyConstraints = append(foreignKeyConstraints, query)
}
query = ""
default:
query += line + " "
}
}

if err := dumpScanner.Err(); err != nil {
return err
}

s := &bytes.Buffer{}

_, _ = fmt.Fprint(s, `// Code generated by scripts/dbgen/main.go. DO NOT EDIT.
package database
`)
_, _ = fmt.Fprint(s, `
// ForeignKeyConstraint represents a named foreign key constraint on a table.
type ForeignKeyConstraint string

// ForeignKeyConstraint enums.
const (
`)
for _, query := range foreignKeyConstraints {
name := ""
switch {
case strings.Contains(query, "ALTER TABLE") && strings.Contains(query, "ADD CONSTRAINT"):
name = strings.Split(query, " ")[6]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

parsing is pretty flimsy, but I guess the rest of the file is no better...

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah... it works for the moment.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it's worth improving, SQL is pretty stable 😄.

default:
return xerrors.Errorf("unknown foreign key constraint format: %s", query)
}
_, _ = fmt.Fprintf(s, "\tForeignKey%s ForeignKeyConstraint = %q // %s\n", nameFromSnakeCase(name), name, query)
}
_, _ = fmt.Fprint(s, ")\n")

outputPath := filepath.Join(databasePath, "foreign_key_constraint.go")

data, err := imports.Process(outputPath, s.Bytes(), &imports.Options{
Comments: true,
})
if err != nil {
return err
}
return os.WriteFile(outputPath, data, 0o600)
}

type stubParams struct {
FuncName string
Parameters string
Expand Down Expand Up @@ -560,6 +637,14 @@ func nameFromSnakeCase(s string) string {
ret += "JWT"
case "idx":
ret += "Index"
case "api":
ret += "API"
case "uuid":
ret += "UUID"
case "gitsshkeys":
ret += "GitSSHKeys"
case "fkey":
// ignore
default:
ret += strings.Title(ss)
}
Expand Down