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)
28 create: function(vid
, fen
, timeControl
, players
, cb
)
30 db
.serialize(function() {
32 "INSERT INTO Games (vid, fenStart, fen, score, timeControl) VALUES " +
33 "(" + vid
+ ",'" + fen
+ "','" + fen
+ "','*','" + timeControl
+ "')";
34 db
.run(query
, function(err
) {
37 players
.forEach((p
,idx
) => {
38 const color
= (idx
==0 ? "w" : "b");
40 "INSERT INTO Players VALUES " +
41 "(" + this.lastID
+ "," + p
.id
+ ",'" + color
+ "')";
44 cb(null, {gid: this.lastID
});
49 // TODO: queries here could be async, and wait for all to complete
50 getOne: function(id
, cb
)
52 db
.serialize(function() {
53 // TODO: optimize queries?
55 "SELECT g.id, g.vid, g.fen, g.fenStart, g.timeControl, g.score, " +
61 db
.get(query
, (err
,gameInfo
) => {
65 "SELECT p.uid, p.color, u.name " +
69 "WHERE p.gid = " + id
;
70 db
.all(query
, (err2
,players
) => {
74 "SELECT squares, message, played, idx, color " +
77 db
.all(query
, (err3
,moves
) => {
80 const game
= Object
.assign({},
87 return cb(null, game
);
94 getByUser: function(uid
, excluded
, cb
)
96 db
.serialize(function() {
97 // Next query is fine because a player appear at most once in a game
101 "WHERE uid " + (excluded
? "<>" : "=") + " " + uid
;
102 db
.run(query
, (err
,gameIds
) => {
105 gameIds
= gameIds
|| []; //might be empty
107 gameIds
.forEach(gidRow
=> {
108 GameModel
.getOne(gidRow
["gid"], (err2
,game
) => {
111 gameArray
.push(game
);
114 return cb(null, gameArray
);
119 getPlayers: function(id
, cb
)
121 db
.serialize(function() {
126 db
.all(query
, (err
,players
) => {
127 return cb(err
, players
);
132 // obj can have fields move, fen and/or score
133 update: function(id
, obj
)
142 db
.parallelize(function() {
147 query
+= "fen = " + obj
.fen
+ ",";
149 query
+= "score = " + obj
.score
+ ",";
150 query
= query
.slice(0,-1); //remove last comma
151 query
+= " WHERE gameId = " + id
;
157 "INSERT INTO Moves (gid,squares,message,played,idx,color) VALUES " +
158 "(" + id
+ ",'" + JSON
.stringify(m
.squares
) + "','" + m
.message
+
159 "'" + m
.played
+ "," + m
.idx
+ ",'" + m
.color
+ "')";
167 db
.parallelize(function() {
169 "DELETE FROM Games " +
173 "DELETE FROM Players " +
177 "DELETE FROM Moves " +
184 module
.exports
= GameModel
;