32 lines
870 B
Go
32 lines
870 B
Go
package history
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"fmt"
|
|
|
|
"reanimator/internal/idgen"
|
|
)
|
|
|
|
func (s *Service) generateID(ctx context.Context, tx *sql.Tx, entityType idgen.EntityType) (string, error) {
|
|
if tx == nil {
|
|
return s.idgen.Generate(ctx, entityType)
|
|
}
|
|
var nextValue int64
|
|
if err := tx.QueryRowContext(ctx, `SELECT next_value FROM id_sequences WHERE entity_type = ? FOR UPDATE`, string(entityType)).Scan(&nextValue); err != nil {
|
|
if err == sql.ErrNoRows {
|
|
return "", fmt.Errorf("sequence not found for entity type: %s", entityType)
|
|
}
|
|
return "", err
|
|
}
|
|
if _, err := tx.ExecContext(ctx, `UPDATE id_sequences SET next_value = next_value + 1 WHERE entity_type = ?`, string(entityType)); err != nil {
|
|
return "", err
|
|
}
|
|
prefix, err := idgen.GetPrefix(entityType)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return idgen.FormatID(prefix, nextValue), nil
|
|
}
|
|
|