| 1 |
|
package db |
| 2 |
|
|
| 3 |
|
import ( |
| 4 |
|
"context" |
| 5 |
|
"fmt" |
| 6 |
|
) |
| 7 |
|
|
| 8 |
|
// EnsureUser upserts a user row by username and returns its id. spec.sr.ht is |
| 9 |
|
// single-owner; this seeds the one row core-go's user-scoped webhook model |
| 10 |
|
// references (user_id FK). Idempotent — the daemon calls it every startup. |
| 11 |
3 |
func (s *Store) EnsureUser(ctx context.Context, username string) (int, error) { |
| 12 |
3 |
const q = ` |
| 13 |
3 |
INSERT INTO "user" (created, updated, username, email, user_type) |
| 14 |
3 |
VALUES (NOW() at time zone 'utc', NOW() at time zone 'utc', $1, '', 'USER') |
| 15 |
3 |
ON CONFLICT (username) DO UPDATE SET updated = NOW() at time zone 'utc' |
| 16 |
3 |
RETURNING id` |
| 17 |
3 |
var id int |
| 18 |
3 |
if err := s.q.QueryRowContext(ctx, q, username).Scan(&id); err != nil { |
| 19 |
0 |
return 0, fmt.Errorf("ensure user %q: %w", username, err) |
| 20 |
0 |
} |
| 21 |
3 |
return id, nil |
| 22 |
|
} |