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, fen, timeControl) " +
34 "VALUES (" + vid
+ ",'" + fen
+ "'," + timeControl
+ ")";
35 db
.run(insertQuery
, err
=> {
38 players
.forEach(p
=> {
40 "INSERT INTO Players VALUES " +
41 // Remaining time = -1 means "unstarted"
42 "(" + this.lastID
+ "," + p
.id
+ "," + p
.color
+ ", -1)";
45 cb(null, {gid: this.lastID
});
50 // TODO: queries here could be async, and wait for all to complete
51 getOne: function(id
, cb
)
53 db
.serialize(function() {
55 "SELECT v.name AS vname, g.fen, g.fenStart, g.score " +
60 db
.get(query
, (err
,gameInfo
) => {
64 "SELECT p.uid AS id, p.color, p.rtime, u.name " +
68 "WHERE p.gid = " + id
;
69 db
.run(query
, (err2
,players
) => {
73 "SELECT move AS desc, message, played, idx, color " +
76 db
.run(query
, (err3
,moves
) => {
81 vname: gameInfo
.vname
,
82 fenStart: gameInfo
.fenStart
,
84 score: gameInfo
.score
,
88 return cb(null, game
);
95 getByUser: function(uid
, excluded
, cb
)
97 db
.serialize(function() {
98 // Next query is fine because a player appear at most once in a game
102 "WHERE uid " + (excluded
? "<>" : "=") + " " + uid
;
103 db
.run(query
, (err
,gameIds
) => {
106 gameIds
= gameIds
|| []; //might be empty
108 gameIds
.forEach(gidRow
=> {
109 GameModel
.getOne(gidRow
["gid"], (err2
,game
) => {
112 gameArray
.push(game
);
115 return cb(null, gameArray
);
122 db
.parallelize(function() {
124 "DELETE FROM Games " +
128 "DELETE FROM Players " +
132 "DELETE FROM Moves " +
139 module
.exports
= GameModel
;