Separate client and server codes. Keep everything in one git repo for simplicity
[vchess.git] / server / 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
ab4f4bf2 13const ProblemModel =
8d7e2786 14{
ab4f4bf2
BA
15 create: function(uid, vid, fen, instructions, solution, cb)
16 {
17 db.serialize(function() {
18 const insertQuery =
19 "INSERT INTO Problems (added, uid, vid, fen, instructions, solution) " +
20 "VALUES (" + Date.now() + "," + uid + "," + vid + ",'" + fen + "',?,?)";
21 db.run(insertQuery, [instructions, solution], err => {
22 if (!!err)
23 return cb(err);
24 db.get("SELECT last_insert_rowid() AS rowid", cb);
25 });
badeb466 26 });
ab4f4bf2 27 },
8d7e2786 28
ab4f4bf2
BA
29 getOne: function(id, callback)
30 {
31 db.serialize(function() {
32 const query =
33 "SELECT * " +
34 "FROM Problems " +
35 "WHERE id = " + id;
36 db.get(query, callback);
37 });
38 },
936dc463 39
ab4f4bf2
BA
40 fetchN: function(vid, uid, type, directionStr, lastDt, MaxNbProblems, callback)
41 {
42 db.serialize(function() {
43 let typeLine = "";
44 if (uid > 0)
45 typeLine = "AND uid " + (type=="others" ? "!=" : "=") + " " + uid;
46 const query =
47 "SELECT * FROM Problems " +
48 "WHERE vid = " + vid +
49 " AND added " + directionStr + " " + lastDt + " " + typeLine + " " +
50 "ORDER BY added " + (directionStr=="<" ? "DESC " : "") +
51 "LIMIT " + MaxNbProblems;
52 db.all(query, callback);
53 });
54 },
8d7e2786 55
ab4f4bf2
BA
56 // TODO: update fails (but insert is OK)
57 update: function(id, uid, fen, instructions, solution, cb)
58 {
59 db.serialize(function() {
60 const query =
61 "UPDATE Problems SET " +
62 "fen = '" + fen + "', " +
63 "instructions = ?, " +
64 "solution = ? " +
65 "WHERE id = " + id + " AND uid = " + uid;
66 db.run(query, [instructions,solution], cb);
67 });
68 },
8d7e2786 69
ab4f4bf2
BA
70 remove: function(id, uid)
71 {
72 db.serialize(function() {
73 const query =
74 "DELETE FROM Problems " +
75 "WHERE id = " + id + " AND uid = " + uid;
76 db.run(query);
77 });
78 },
8d7e2786 79}
ab4f4bf2
BA
80
81module.exports = ProblemModel;