Draft Game and Challenge models
[vchess.git] / models / Problem.js
CommitLineData
8d7e2786
BA
1var db = require("../utils/database");
2
3/*
4 * Structure:
c018b304 5 * id: problem number (int)
8d7e2786
BA
6 * uid: user id (int)
7 * vid: variant id (int)
8 * added: timestamp
9 * instructions: text
10 * solution: text
11 */
12
badeb466 13exports.create = function(uid, vid, fen, instructions, solution, cb)
8d7e2786
BA
14{
15 db.serialize(function() {
badeb466
BA
16 const insertQuery =
17 "INSERT INTO Problems (added, uid, vid, fen, instructions, solution) " +
18 "VALUES (" + Date.now() + "," + uid + "," + vid + ",'" + fen + "',?,?)";
19 db.run(insertQuery, [instructions, solution], err => {
20 if (!!err)
21 return cb(err);
22 db.get("SELECT last_insert_rowid() AS rowid", cb);
23 });
8d7e2786
BA
24 });
25}
26
582df349 27exports.getOne = function(id, callback)
8d7e2786
BA
28{
29 db.serialize(function() {
936dc463
BA
30 const query =
31 "SELECT * " +
32 "FROM Problems " +
582df349 33 "WHERE id = " + id;
936dc463
BA
34 db.get(query, callback);
35 });
36}
37
582df349 38exports.fetchN = function(vid, uid, type, directionStr, lastDt, MaxNbProblems, callback)
936dc463
BA
39{
40 db.serialize(function() {
41 let typeLine = "";
42 if (uid > 0)
badeb466 43 typeLine = "AND uid " + (type=="others" ? "!=" : "=") + " " + uid;
936dc463 44 const query =
8d7e2786 45 "SELECT * FROM Problems " +
582df349 46 "WHERE vid = " + vid +
936dc463 47 " AND added " + directionStr + " " + lastDt + " " + typeLine + " " +
8d7e2786 48 "ORDER BY added " + (directionStr=="<" ? "DESC " : "") +
fd08ab2c 49 "LIMIT " + MaxNbProblems;
936dc463 50 db.all(query, callback);
8d7e2786
BA
51 });
52}
53
badeb466
BA
54// TODO: update fails (but insert is OK)
55exports.update = function(id, uid, fen, instructions, solution, cb)
8d7e2786
BA
56{
57 db.serialize(function() {
936dc463 58 const query =
badeb466
BA
59 "UPDATE Problems SET " +
60 "fen = '" + fen + "', " +
61 "instructions = ?, " +
62 "solution = ? " +
936dc463 63 "WHERE id = " + id + " AND uid = " + uid;
badeb466 64 db.run(query, [instructions,solution], cb);
8d7e2786
BA
65 });
66}
67
68exports.remove = function(id, uid)
69{
70 db.serialize(function() {
936dc463 71 const query =
8d7e2786 72 "DELETE FROM Problems " +
936dc463
BA
73 "WHERE id = " + id + " AND uid = " + uid;
74 db.run(query);
8d7e2786
BA
75 });
76}