summaryrefslogtreecommitdiffstats
path: root/src/server/database.rs
blob: 99e0dded8289b302a5b460d22771c22d5bea3aed (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
use rusqlite::{params, Connection};

pub fn init_db(conn: &Connection) {
    conn.execute(
        "CREATE TABLE IF NOT EXISTS users (
            username TEXT PRIMARY KEY,
            hashed_password TEXT NOT NULL,
            account_id INTEGER UNIQUE,
            balance INTEGER DEFAULT 1000
        )",
        [],
    )
    .unwrap();
    // Add column if not exists (for migration)
    let _ = conn.execute("ALTER TABLE users ADD COLUMN account_id INTEGER UNIQUE", []);
    let _ = conn.execute(
        "ALTER TABLE users ADD COLUMN balance INTEGER DEFAULT 1000",
        [],
    );
    conn.execute(
        "CREATE TABLE IF NOT EXISTS plays (
            session_id TEXT PRIMARY KEY,
            username TEXT NOT NULL,
            game_type TEXT NOT NULL,
            bet_amount INTEGER NOT NULL,
            winnings INTEGER NOT NULL,
            balance_after INTEGER NOT NULL,
            details TEXT NOT NULL DEFAULT '{}',
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )",
        [],
    )
    .unwrap();
}

pub fn add_user(
    conn: &Connection,
    username: &str,
    hashed_password: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    if get_hashed_password(conn, username).is_some() {
        return Err("user already exists".into());
    }

    for _ in 0..10 {
        let account_id: u32 = rand::random::<u32>();
        match conn.execute(
            "INSERT INTO users (username, hashed_password, account_id, balance)
             VALUES (?1, ?2, ?3, ?4)",
            params![username, hashed_password, account_id as i64, 1000i64],
        ) {
            Ok(_) => return Ok(()),
            Err(rusqlite::Error::SqliteFailure(error, _))
                if error.code == rusqlite::ErrorCode::ConstraintViolation =>
            {
                continue;
            }
            Err(error) => return Err(Box::new(error)),
        }
    }

    Err("could not allocate a unique account id".into())
}

pub fn get_hashed_password(conn: &Connection, username: &str) -> Option<String> {
    let mut stmt = conn
        .prepare("SELECT hashed_password FROM users WHERE username = ?1")
        .unwrap();
    let mut rows = stmt.query([username]).unwrap();
    if let Ok(Some(row)) = rows.next() {
        row.get(0).ok()
    } else {
        None
    }
}

pub fn set_hashed_password(
    conn: &Connection,
    username: &str,
    hashed_password: &str,
) -> rusqlite::Result<()> {
    conn.execute(
        "UPDATE users SET hashed_password = ?1 WHERE username = ?2",
        params![hashed_password, username],
    )?;
    Ok(())
}

pub fn get_account_id(conn: &Connection, username: &str) -> Option<i64> {
    let mut stmt = conn
        .prepare("SELECT account_id FROM users WHERE username = ?1")
        .unwrap();
    let mut rows = stmt.query([username]).unwrap();
    if let Ok(Some(row)) = rows.next() {
        Some(row.get::<_, i64>(0).ok()?)
    } else {
        None
    }
}

pub fn get_balance(conn: &Connection, username: &str) -> Option<i64> {
    let mut stmt = conn
        .prepare("SELECT balance FROM users WHERE username = ?1")
        .unwrap();
    let mut rows = stmt.query([username]).unwrap();
    if let Ok(Some(row)) = rows.next() {
        Some(row.get::<_, i64>(0).ok()?)
    } else {
        None
    }
}

/// Settle one play and record its audit row in a single transaction.
///
/// `details` is a JSON object with game-specific fields (reels, cards,
/// winning number, crash point, ...). All SQL is parameterized: usernames are
/// data, never part of the statement text.
///
/// Returns the balance after the play.
#[allow(clippy::too_many_arguments)]
pub fn apply_play(
    conn: &mut Connection,
    session_id: &str,
    username: &str,
    game_type: &str,
    bet_amount: i64,
    winnings: i64,
    details: &str,
) -> rusqlite::Result<i64> {
    let tx = conn.transaction()?;

    let deducted = tx.execute(
        "UPDATE users SET balance = balance - ?1
         WHERE username = ?2 AND balance >= ?1",
        params![bet_amount, username],
    )?;
    if deducted != 1 {
        return Err(rusqlite::Error::QueryReturnedNoRows);
    }

    tx.execute(
        "UPDATE users SET balance = balance + ?1 WHERE username = ?2",
        params![winnings, username],
    )?;

    let balance_after: i64 = tx.query_row(
        "SELECT balance FROM users WHERE username = ?1",
        [username],
        |row| row.get(0),
    )?;

    tx.execute(
        "INSERT INTO plays
            (session_id, username, game_type, bet_amount, winnings,
             balance_after, details)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
        params![
            session_id,
            username,
            game_type,
            bet_amount,
            winnings,
            balance_after,
            details
        ],
    )?;

    tx.commit()?;
    Ok(balance_after)
}

pub fn count_plays(conn: &Connection, username: &str) -> i64 {
    conn.query_row(
        "SELECT COUNT(*) FROM plays WHERE username = ?1",
        [username],
        |row| row.get(0),
    )
    .unwrap_or(0)
}

/// Reserve a bet before a multi-step hand starts.
pub fn debit(conn: &mut Connection, username: &str, amount: i64) -> rusqlite::Result<i64> {
    let tx = conn.transaction()?;
    let updated = tx.execute(
        "UPDATE users SET balance = balance - ?1
         WHERE username = ?2 AND balance >= ?1",
        params![amount, username],
    )?;
    if updated != 1 {
        return Err(rusqlite::Error::QueryReturnedNoRows);
    }
    let balance = tx.query_row(
        "SELECT balance FROM users WHERE username = ?1",
        [username],
        |row| row.get(0),
    )?;
    tx.commit()?;
    Ok(balance)
}

/// Put a reserved bet back (disconnect or cancel).
pub fn credit(conn: &mut Connection, username: &str, amount: i64) -> rusqlite::Result<i64> {
    let tx = conn.transaction()?;
    tx.execute(
        "UPDATE users SET balance = balance + ?1 WHERE username = ?2",
        params![amount, username],
    )?;
    let balance = tx.query_row(
        "SELECT balance FROM users WHERE username = ?1",
        [username],
        |row| row.get(0),
    )?;
    tx.commit()?;
    Ok(balance)
}

/// Settle a hand whose bet was already reserved: credit winnings, write the
/// audit row, and return the new balance.
#[allow(clippy::too_many_arguments)]
pub fn settle_play(
    conn: &mut Connection,
    session_id: &str,
    username: &str,
    game_type: &str,
    bet_amount: i64,
    winnings: i64,
    details: &str,
) -> rusqlite::Result<i64> {
    let tx = conn.transaction()?;

    tx.execute(
        "UPDATE users SET balance = balance + ?1 WHERE username = ?2",
        params![winnings, username],
    )?;

    let balance_after: i64 = tx.query_row(
        "SELECT balance FROM users WHERE username = ?1",
        [username],
        |row| row.get(0),
    )?;

    tx.execute(
        "INSERT INTO plays
            (session_id, username, game_type, bet_amount, winnings,
             balance_after, details)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
        params![
            session_id,
            username,
            game_type,
            bet_amount,
            winnings,
            balance_after,
            details
        ],
    )?;

    tx.commit()?;
    Ok(balance_after)
}