72ee0dcb44938ec58c6999e7b9b8c3d95adbbf3c
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() {
137 move.played
= Date
.now();
138 query
+= "move = " + obj
.move + ","; //TODO: already stringified?!
141 query
+= "fen = " + obj
.fen
+ ",";
143 query
+= "score = " + obj
.score
+ ",";
144 query
= query
.slice(0,-1); //remove last comma
145 query
+= " WHERE gameId = " + id
;
146 db
.run(query
, (err
) => {
154 db
.parallelize(function() {
156 "DELETE FROM Games " +
160 "DELETE FROM Players " +
164 "DELETE FROM Moves " +
171 module
.exports
= GameModel
;