Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
johnstcn merged 2 commits intomainfromcj/dbgen-fk-constraints
Sep 13, 2023
Merged
Show file tree
Hide file tree
Changes fromall 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 deletioncoderd/apikey.go
View file
Open in desktop
Original file line numberDiff line numberDiff 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 deletionscoderd/database/errors.go
View file
Open in desktop
Original file line numberDiff line numberDiff 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 deletionscoderd/database/foreign_key_constraint.go
View file
Open in desktop

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

4 changes: 2 additions & 2 deletionscoderd/database/unique_constraint.go
View file
Open in desktop

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

87 changes: 86 additions & 1 deletionscripts/dbgen/main.go
View file
Open in desktop
Copy link
MemberAuthor

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 numberDiff line numberDiff 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 DownExpand Up@@ -125,7 +130,7 @@ func generateUniqueConstraints() error {

s := &bytes.Buffer{}

_, _ = fmt.Fprint(s, `// Code generated bygen/enum. DO NOT EDIT.
_, _ = fmt.Fprint(s, `// Code generated byscripts/dbgen/main.go. DO NOT EDIT.
package database
`)
_, _ = fmt.Fprint(s, `
Expand DownExpand 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
MemberAuthor

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 DownExpand 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

[8]ページ先頭

©2009-2025 Movatter.jp