1 var db
= require("../utils/database");
4 * Structure table Games:
6 * vid: integer (variant id)
7 * fenStart: varchar (initial position)
8 * fen: varchar (current position)
10 * score: varchar (result)
12 * Structure table Players:
17 * Structure table Moves:
19 * squares: varchar (description)
27 create: function(vid
, fen
, timeControl
, players
, cb
)
29 db
.serialize(function() {
31 "INSERT INTO Games (vid, fenStart, fen, score, timeControl) VALUES " +
32 "(" + vid
+ ",'" + fen
+ "','" + fen
+ "','*','" + timeControl
+ "')";
33 db
.run(query
, function(err
) {
36 players
.forEach((p
,idx
) => {
37 const color
= (idx
==0 ? "w" : "b");
39 "INSERT INTO Players VALUES " +
40 "(" + this.lastID
+ "," + p
.id
+ ",'" + color
+ "')";
43 cb(null, {gid: this.lastID
});
48 // TODO: queries here could be async, and wait for all to complete
49 getOne: function(id
, cb
)
51 db
.serialize(function() {
52 // TODO: optimize queries?
54 "SELECT g.id, g.vid, g.fen, g.fenStart, g.timeControl, g.score, " +
60 db
.get(query
, (err
,gameInfo
) => {
64 "SELECT p.uid, p.color, u.name " +
68 "WHERE p.gid = " + id
;
69 db
.all(query
, (err2
,players
) => {
73 "SELECT squares, message, played, idx " +
76 db
.all(query
, (err3
,moves
) => {
79 const game
= Object
.assign({},
86 return cb(null, game
);
93 getByUser: function(uid
, excluded
, cb
)
95 db
.serialize(function() {
96 // Next query is fine because a player appear at most once in a game
100 "WHERE uid " + (excluded
? "<>" : "=") + " " + uid
;
101 db
.run(query
, (err
,gameIds
) => {
104 gameIds
= gameIds
|| []; //might be empty
106 gameIds
.forEach(gidRow
=> {
107 GameModel
.getOne(gidRow
["gid"], (err2
,game
) => {
110 gameArray
.push(game
);
113 return cb(null, gameArray
);
118 getPlayers: function(id
, cb
)
120 db
.serialize(function() {
125 db
.all(query
, (err
,players
) => {
126 return cb(err
, players
);
131 // obj can have fields move, fen and/or score
132 update: function(id
, obj
)
134 db
.parallelize(function() {
139 query
+= "fen = '" + obj
.fen
+ "',";
141 query
+= "score = '" + obj
.score
+ "',";
142 query
= query
.slice(0,-1); //remove last comma
143 query
+= " WHERE id = " + id
;
149 "INSERT INTO Moves (gid, squares, message, played, idx) VALUES " +
150 "(" + id
+ ",'" + JSON
.stringify(m
.squares
) + "','" + m
.message
+
151 "'," + m
.played
+ "," + m
.idx
+ ")";
159 db
.parallelize(function() {
161 "DELETE FROM Games " +
165 "DELETE FROM Players " +
169 "DELETE FROM Moves " +
176 module
.exports
= GameModel
;