|
1 |
| -def setup_table |
2 |
| - drop_table |
3 |
| - create_table |
4 |
| - create_indexes |
5 |
| -end |
6 |
| - |
7 |
| -private def drop_table |
8 |
| - @db.exec("DROP TABLE IF EXISTS punches CASCADE") |
9 |
| -end |
| 1 | +module PunchingBag |
| 2 | + class Tracker |
| 3 | + def initialize(@db : DB::Database) |
| 4 | + end |
10 | 5 |
|
11 |
| -private def create_table |
12 |
| - @db.exec <<-SQL |
13 |
| - CREATE TABLE punches ( |
14 |
| - id BIGSERIAL PRIMARY KEY, |
15 |
| - punchable_type VARCHAR(255), |
16 |
| - punchable_id BIGINT, |
17 |
| - hits INTEGER DEFAULT 1, |
18 |
| - created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, |
19 |
| - starts_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, |
20 |
| - ends_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP |
| 6 | + def hit(punchable_type : String, punchable_id : Int32) |
| 7 | + @db.exec( |
| 8 | + "INSERT INTO hits (punchable_type, punchable_id, hits, created_at, updated_at) |
| 9 | + VALUES ($1, $2, 1, NOW(), NOW()) |
| 10 | + ON CONFLICT (punchable_type, punchable_id) |
| 11 | + DO UPDATE SET hits = hits.hits + 1, updated_at = NOW()", |
| 12 | + punchable_type, punchable_id |
21 | 13 | )
|
22 |
| - SQL |
23 |
| -end |
| 14 | + end |
| 15 | + |
| 16 | + def setup_table |
| 17 | + drop_table |
| 18 | + create_table |
| 19 | + create_indexes |
| 20 | + end |
| 21 | + |
| 22 | + private def drop_table |
| 23 | + @db.exec("DROP TABLE IF EXISTS hits CASCADE") |
| 24 | + end |
| 25 | + |
| 26 | + private def create_table |
| 27 | + @db.exec <<-SQL |
| 28 | + CREATE TABLE hits ( |
| 29 | + id BIGSERIAL PRIMARY KEY, |
| 30 | + punchable_type VARCHAR(255), |
| 31 | + punchable_id BIGINT, |
| 32 | + hits INTEGER DEFAULT 1, |
| 33 | + created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, |
| 34 | + updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP |
| 35 | + ) |
| 36 | + SQL |
| 37 | + end |
24 | 38 |
|
25 |
| -private def create_indexes |
26 |
| - @db.exec("CREATE INDEX IF NOT EXISTS idx_punches_punchable ON punches(punchable_type, punchable_id)") |
| 39 | + private def create_indexes |
| 40 | + @db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_hits_punchable ON hits(punchable_type, punchable_id)") |
| 41 | + end |
| 42 | + end |
27 | 43 | end
|
0 commit comments