highscore-server/src/database.v

67 lines
1.5 KiB
V
Raw Normal View History

2023-01-07 13:00:00 +01:00
module main
[table: 'Score']
struct ScoreTable {
mut:
id int [primary; sql: serial]
player string [nonull]
game string [nonull]
key string [nonull]
score int [nonull]
time i64 [nonull]
2023-01-07 13:00:00 +01:00
}
fn (mut app App) create_tables() ! {
sql app.db {
create table ScoreTable
}!
2023-01-07 13:00:00 +01:00
}
fn (mut app App) insert_score_res(scores []ScoreTable) ![]ScoreRes {
mut score_res := []ScoreRes{}
app.db.exec('BEGIN')!
for _, score in scores {
sql app.db {
insert score into ScoreTable
} or {
app.db.exec('ROLLBACK')!
return err
}
last_id := app.db.last_id() as int
score_tables := sql app.db {
select from ScoreTable where id == last_id
} or {
app.db.exec('ROLLBACK')!
return err
}
score_res << (score_tables[0] or {
app.db.exec('ROLLBACK')!
return error('Result returned zero')
}).convert_to_res()
}
app.db.exec('COMMIT')!
return score_res
}
fn (mut app App) get_scores(game string, key string) ![]ScoreRes {
score_table := sql app.db {
select from ScoreTable where game == game && key == key order by score desc
}!
return score_table.convert_to_res()
2023-01-07 13:00:00 +01:00
}
fn (mut app App) get_scores_limit(game string, key string, offset int, rows int) ![]ScoreRes {
score_table := sql app.db {
select from ScoreTable where game == game && key == key order by score desc limit rows offset offset
}!
return score_table.convert_to_res()
2023-01-07 13:00:00 +01:00
}
fn (mut app App) delete_score(score_id int) ! {
2023-01-11 19:08:24 +01:00
sql app.db {
delete from ScoreTable where id == score_id
}!
2023-01-07 13:00:00 +01:00
}