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
)
135 db
.parallelize(function() {
140 query
+= "fen = '" + obj
.fen
+ "',";
142 query
+= "score = '" + obj
.score
+ "',";
143 query
= query
.slice(0,-1); //remove last comma
144 query
+= " WHERE id = " + id
;
150 "INSERT INTO Moves (gid,squares,message,played,idx,color) VALUES " +
151 "(" + id
+ ",'" + JSON
.stringify(m
.squares
) + "','" + m
.message
+
152 "'," + m
.played
+ "," + m
.idx
+ ",'" + m
.color
+ "')";
160 db
.parallelize(function() {
162 "DELETE FROM Games " +
166 "DELETE FROM Players " +
170 "DELETE FROM Moves " +
177 module
.exports
= GameModel
;