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:
16 * rtime: real (remaining time)
18 * Structure table Moves:
20 * move: varchar (description)
29 create: function(vid
, fen
, timeControl
, players
, cb
)
31 db
.serialize(function() {
33 "INSERT INTO Games (vid, fenStart, score, timeControl) " +
34 "VALUES (" + vid
+ ",'" + fen
+ "','*','" + timeControl
+ "')";
35 db
.run(query
, function(err
) {
38 players
.forEach((p
,idx
) => {
39 const color
= (idx
==0 ? "w" : "b");
41 "INSERT INTO Players VALUES " +
42 // Remaining time = -1 means "unstarted"
43 "(" + this.lastID
+ "," + p
.id
+ ",'" + color
+ "', -1)";
46 cb(null, {gid: this.lastID
});
51 // TODO: queries here could be async, and wait for all to complete
52 getOne: function(id
, cb
)
54 db
.serialize(function() {
59 db
.get(query
, (err
,gameInfo
) => {
63 "SELECT uid, color, rtime " +
66 db
.all(query
, (err2
,players
) => {
70 "SELECT move, message, played, idx, color " +
73 db
.all(query
, (err3
,moves
) => {
76 const game
= Object
.assign({},
83 return cb(null, game
);
90 getByUser: function(uid
, excluded
, cb
)
92 db
.serialize(function() {
93 // Next query is fine because a player appear at most once in a game
97 "WHERE uid " + (excluded
? "<>" : "=") + " " + uid
;
98 db
.run(query
, (err
,gameIds
) => {
101 gameIds
= gameIds
|| []; //might be empty
103 gameIds
.forEach(gidRow
=> {
104 GameModel
.getOne(gidRow
["gid"], (err2
,game
) => {
107 gameArray
.push(game
);
110 return cb(null, gameArray
);
115 getPlayers: function(id
, cb
)
117 db
.serialize(function() {
122 db
.all(query
, (err
,players
) => {
123 return cb(err
, players
);
128 // obj can have fields move, fen and/or score
129 update: function(id
, obj
, cb
)
131 db
.serialize(function() {
136 query
+= "move = " + obj
.move + ","; //TODO: already stringified?!
138 query
+= "fen = " + obj
.fen
+ ",";
140 query
+= "score = " + obj
.score
+ ",";
141 query
= query
.slice(0,-1); //remove last comma
142 query
+= " WHERE gameId = " + id
;
143 db
.run(query
, (err
) => {
151 db
.parallelize(function() {
153 "DELETE FROM Games " +
157 "DELETE FROM Players " +
161 "DELETE FROM Moves " +
168 module
.exports
= GameModel
;