Initialize the database with migrations
(db *sqlx.DB)
| 257 | |
| 258 | // GenerateRandomID creates a random string ID |
| 259 | func GenerateRandomID() (string, error) { |
| 260 | bytes := make([]byte, 16) // 128 bits |
| 261 | if _, err := rand.Read(bytes); err != nil { |
| 262 | return "", fmt.Errorf("failed to generate random ID: %w", err) |
| 263 | } |
| 264 | return hex.EncodeToString(bytes), nil |
| 265 | } |
| 266 | |
| 267 | // Initialize the database with migrations |
| 268 | func initializeSchema(db *sqlx.DB) error { |
| 269 | // Create migrations table if it doesn't exist |
| 270 | if err := createMigrationsTable(db); err != nil { |
| 271 | return fmt.Errorf("failed to create migrations table: %w", err) |
| 272 | } |
| 273 | |
| 274 | // Get already applied migrations |
| 275 | applied, err := getAppliedMigrations(db) |
| 276 | if err != nil { |
| 277 | return fmt.Errorf("failed to get applied migrations: %w", err) |
| 278 | } |
| 279 | |
| 280 | // Apply missing migrations |
| 281 | sourceMigrations := make(map[int]string, len(migrations)) |
| 282 | for _, migration := range migrations { |
| 283 | sourceMigrations[migration.ID] = migration.Name |
| 284 | if appliedName, ok := applied[migration.ID]; ok && appliedName != migration.Name { |