| 1 | BEGIN;
|
|---|
| 2 |
|
|---|
| 3 | -- Use a DO block so we can iterate stadiums and use their capacity directly
|
|---|
| 4 | DO $$
|
|---|
| 5 | DECLARE
|
|---|
| 6 | s RECORD;
|
|---|
| 7 | rows_per_stad INT;
|
|---|
| 8 | seats_per_row INT;
|
|---|
| 9 | inserted_count INT;
|
|---|
| 10 | BEGIN
|
|---|
| 11 | FOR s IN
|
|---|
| 12 | SELECT st.stadium_id, st.capacity
|
|---|
| 13 | FROM Stadium st
|
|---|
| 14 | WHERE NOT EXISTS (
|
|---|
| 15 | SELECT 1 FROM Seat se WHERE se.stadium_id = st.stadium_id
|
|---|
| 16 | )
|
|---|
| 17 | ORDER BY st.stadium_id
|
|---|
| 18 | LOOP
|
|---|
| 19 | -- Pick a roughly square-ish grid; minimum 1 row.
|
|---|
| 20 | rows_per_stad := GREATEST(1, CEIL(SQRT(s.capacity::numeric / 20.0))::int);
|
|---|
| 21 | seats_per_row := GREATEST(1, CEIL(s.capacity::numeric / rows_per_stad)::int);
|
|---|
| 22 |
|
|---|
| 23 | INSERT INTO Seat (stadium_id, row, number)
|
|---|
| 24 | SELECT
|
|---|
| 25 | s.stadium_id,
|
|---|
| 26 | r,
|
|---|
| 27 | n
|
|---|
| 28 | FROM generate_series(1, rows_per_stad) AS r
|
|---|
| 29 | CROSS JOIN generate_series(1, seats_per_row) AS n
|
|---|
| 30 | ORDER BY r, n
|
|---|
| 31 | LIMIT s.capacity;
|
|---|
| 32 |
|
|---|
| 33 | GET DIAGNOSTICS inserted_count = ROW_COUNT;
|
|---|
| 34 | RAISE NOTICE 'Stadium % : capacity=% , inserted=% seats',
|
|---|
| 35 | s.stadium_id, s.capacity, inserted_count;
|
|---|
| 36 | END LOOP;
|
|---|
| 37 | END $$;
|
|---|
| 38 |
|
|---|
| 39 | COMMIT;
|
|---|