Skip to content

Commit aa19b87

Browse files
committed
fix(database): strip SQL comments before parsing and add expires_at column
The schema migration parser failed to recognize CREATE INDEX statements preceded by SQL comments, causing duplicate index errors on repeated bootstrap. Strip leading comment lines before pattern matching. Also adds the missing expires_at column to user_api_keys via migration 000004, fixing Unknown column errors in API key creation.
1 parent fa4eed1 commit aa19b87

2 files changed

Lines changed: 24 additions & 5 deletions

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
ALTER TABLE user_api_keys ADD COLUMN expires_at DATETIME NULL DEFAULT NULL;

backend/internal/database/schema.go

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -63,19 +63,37 @@ func splitSQLStatements(body string) []string {
6363
}
6464

6565
func applySchemaStatement(ctx context.Context, db *gorm.DB, statement string) error {
66-
if indexName, tableName, ok := parseCreateIndex(statement); ok {
67-
return ensureIndex(ctx, db, tableName, indexName, statement)
66+
cleaned := stripSQLComments(statement)
67+
if cleaned == "" {
68+
return nil
69+
}
70+
71+
if indexName, tableName, ok := parseCreateIndex(cleaned); ok {
72+
return ensureIndex(ctx, db, tableName, indexName, cleaned)
6873
}
69-
if tableName, columnName, ok := parseAlterAddColumn(statement); ok {
70-
return ensureColumn(ctx, db, tableName, columnName, statement)
74+
if tableName, columnName, ok := parseAlterAddColumn(cleaned); ok {
75+
return ensureColumn(ctx, db, tableName, columnName, cleaned)
7176
}
7277

73-
if err := db.WithContext(ctx).Exec(statement).Error; err != nil {
78+
if err := db.WithContext(ctx).Exec(cleaned).Error; err != nil {
7479
return fmt.Errorf("apply schema statement: %w", err)
7580
}
7681
return nil
7782
}
7883

84+
func stripSQLComments(statement string) string {
85+
lines := strings.Split(statement, "\n")
86+
filtered := make([]string, 0, len(lines))
87+
for _, line := range lines {
88+
trimmed := strings.TrimSpace(line)
89+
if trimmed == "" || strings.HasPrefix(trimmed, "--") {
90+
continue
91+
}
92+
filtered = append(filtered, line)
93+
}
94+
return strings.TrimSpace(strings.Join(filtered, "\n"))
95+
}
96+
7997
func parseCreateIndex(statement string) (string, string, bool) {
8098
matches := createIndexPattern.FindStringSubmatch(strings.TrimSpace(statement))
8199
if len(matches) != 3 {

0 commit comments

Comments
 (0)