6184eafcf1c947f20c56a5455c8290038f8a3b5f
[vchess.git] / models / Problem.js
1 var db = require("../utils/database");
2
3 /*
4 * Structure:
5 * id: problem number (int)
6 * uid: user id (int)
7 * vid: variant id (int)
8 * added: timestamp
9 * instructions: text
10 * solution: text
11 */
12
13 // TODO: callback ?
14 exports.create = function(vname, fen, instructions, solution)
15 {
16 db.serialize(function() {
17 const vidQuery =
18 "SELECT id " +
19 "FROM Variants " +
20 "WHERE name = '" + vname + "'";
21 db.get(vidQuery, (err,variant) => {
22 const insertQuery =
23 "INSERT INTO Problems (added, vid, fen, instructions, solution) VALUES " +
24 "(" +
25 Date.now() + "," +
26 variant.id + "," +
27 fen + "," +
28 instructions + "," +
29 solution +
30 ")";
31 db.run(insertQuery);
32 });
33 });
34 }
35
36 exports.getById = function(id, callback)
37 {
38 db.serialize(function() {
39 const query =
40 "SELECT * FROM Problems " +
41 "WHERE id ='" + id + "'";
42 db.get(query, callback);
43 });
44 }
45
46 exports.getOne = function(vname, pid, callback)
47 {
48 db.serialize(function() {
49 const query =
50 "SELECT * " +
51 "FROM Problems " +
52 "WHERE id = " + pid;
53 db.get(query, callback);
54 });
55 }
56
57 exports.fetchN = function(vname, uid, type, directionStr, lastDt, MaxNbProblems, callback)
58 {
59 db.serialize(function() {
60 let typeLine = "";
61 if (uid > 0)
62 typeLine = "AND id " + (type=="others" ? "!=" : "=") + " " + uid;
63 const query =
64 "SELECT * FROM Problems " +
65 "WHERE vid = (SELECT id FROM Variants WHERE name = '" + vname + "') " +
66 " AND added " + directionStr + " " + lastDt + " " + typeLine + " " +
67 "ORDER BY added " + (directionStr=="<" ? "DESC " : "") +
68 "LIMIT " + MaxNbProblems,
69 db.all(query, callback);
70 });
71 }
72
73 exports.update = function(id, uid, fen, instructions, solution)
74 {
75 db.serialize(function() {
76 const query =
77 "UPDATE Problems " +
78 "fen = " + fen + ", " +
79 "instructions = " + instructions + ", " +
80 "solution = " + solution + " " +
81 "WHERE id = " + id + " AND uid = " + uid;
82 db.run(query);
83 });
84 }
85
86 exports.remove = function(id, uid)
87 {
88 db.serialize(function() {
89 const query =
90 "DELETE FROM Problems " +
91 "WHERE id = " + id + " AND uid = " + uid;
92 db.run(query);
93 });
94 }