Follow the leader with help from a server
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

sql_service.go 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. // NGnius 2020-02-11
  2. package main
  3. import (
  4. "database/sql"
  5. "fmt"
  6. "time"
  7. _ "github.com/lib/pq" // postgres
  8. _ "github.com/mattn/go-sqlite3" // sqlite
  9. )
  10. const (
  11. sqlServerDefault = "sqlite3"
  12. sqlConnectionDefault = "test.sqlite"
  13. )
  14. var (
  15. // command line arguments
  16. sqlServer string
  17. sqlConnection string
  18. buildTables bool
  19. populateTables bool
  20. // internal variables
  21. db *sql.DB
  22. queryType int
  23. queryStrings [][]string
  24. )
  25. func sqlInit() error {
  26. var dbOpenErr error
  27. if sqlServer == "postgres" {
  28. queryType = 1
  29. } else { // sqlite3
  30. queryType = 0
  31. }
  32. queryStrings = [][]string{
  33. []string{ // sqlite
  34. "SELECT * FROM Boards WHERE name=? LIMIT 1;",
  35. "SELECT * FROM Players WHERE name=? LIMTI 1;",
  36. "INSERT INTO Entries(score, player, board, time) VALUES (?, ?, ?, ?);",
  37. "INSERT INTO Keys(token, player, time) VALUES (?, ?, ?);",
  38. "SELECT * FROM Keys WHERE token=? AND player=? AND time=?",
  39. "SELECT * FROM Keys WHERE token=? LIMIT 1;",
  40. "SELECT * FROM Keys WHERE player=? LIMIT 1;",
  41. "SELECT * FROM Boards WHERE id=?",
  42. "INSERT OR REPLACE INTO Boards(id, name, description) VALUES (?, ?, ?);",
  43. "SELECT * FROM Entries WHERE board=?",
  44. "SELECT * FROM Entries WHERE board=? and rank >= ? and rank <= ? ORDER BY rank ASC;",
  45. "SELECT * FROM Players WHERE id=? LIMIT 1;",
  46. "INSERT OR REPLACE INTO Players(id, name) VALUES (?, ?);",
  47. "SELECT * FROM Entries WHERE player=?",
  48. "SELECT * FROM Entries WHERE player=? ORDER BY time DESC LIMIT ?;",
  49. "SELECT * FROM Entries WHERE id=? LIMIT 1;",
  50. "INSERT OR REPLACE INTO Entries(id, rank, score, player, board, time, metadata) VALUES (?, ?, ?, ?, ?, ?, ?);",
  51. "SELECT * FROM Keys WHERE id=? LIMIT 1;",
  52. "INSERT OR REPLACE INTO Keys(id, token, player, time, metadata) VALUES (?, ?, ?, ?, ?);",
  53. "CREATE TABLE IF NOT EXISTS Players (id INTEGER PRIMARY KEY, name TEXT NOT NULL);",
  54. "CREATE TABLE IF NOT EXISTS Boards (id INTEGER PRIMARY KEY, name TEXT NOT NULL, description TEXT NOT NULL);",
  55. "CREATE TABLE IF NOT EXISTS Entries (id INTEGER PRIMARY KEY, rank INTEGER NOT NULL DEFAULT -1, score INTEGER NOT NULL, player INTEGER NOT NULL, board INTEGER NOT NULL, time INTEGER NOT NULL, metadata BLOB NOT NULL DEFAULT x'FF', FOREIGN KEY(player) REFERENCES Players(id), FOREIGN KEY(board) REFERENCES Boards(id));",
  56. "CREATE TABLE IF NOT EXISTS Keys (id INTEGER PRIMARY KEY, token TEXT NOT NULL, player INTEGER NOT NULL, time INTEGER NOT NULL, metadata BLOB NOT NULL DEFAULT x'FF', FOREIGN KEY(player) REFERENCES Players(id));",
  57. },
  58. []string{ // postgres
  59. "SELECT * FROM Boards WHERE name=$1 LIMIT 1;",
  60. "SELECT * FROM Players WHERE name=$1 LIMTI 1;",
  61. "INSERT INTO Entries(score, player, board, time) VALUES ($1, $2, $3, $4);",
  62. "INSERT INTO Keys(token, player, time) VALUES ($1, $2, $3);",
  63. "SELECT * FROM Keys WHERE token=$1 AND player=$2 AND time=$3",
  64. "SELECT * FROM Keys WHERE token=$1 LIMIT 1;",
  65. "SELECT * FROM Keys WHERE player=$1 LIMIT 1;",
  66. "SELECT * FROM Boards WHERE id=$1",
  67. "INSERT INTO Boards(id, name, description) VALUES ($1, $2, $3) ON CONFLICT(id) DO UPDATE SET name=$2, description=$3;",
  68. "SELECT * FROM Entries WHERE board=$1",
  69. "SELECT * FROM Entries WHERE board=$1 and rank >= $2 and rank <= $3 ORDER BY rank ASC;",
  70. "SELECT * FROM Players WHERE id=$1 LIMIT 1;",
  71. "INSERT INTO Players(id, name) VALUES ($1, $2) ON CONFLICT(id) DO UPDATE SET name=$2;",
  72. "SELECT * FROM Entries WHERE player=$1",
  73. "SELECT * FROM Entries WHERE player=$1 ORDER BY time DESC LIMIT $2;",
  74. "SELECT * FROM Entries WHERE id=$1 LIMIT 1;",
  75. "INSERT INTO Entries(id, rank, score, player, board, time, metadata) VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT(id) DO UPDATE SET rank=$2, score=$3, player=$4, board=$5, time=$6, metadata=$7;",
  76. "SELECT * FROM Keys WHERE id=$1 LIMIT 1;",
  77. "INSERT INTO Keys(id, token, player, time, metadata) VALUES ($1, $2, $3, $4, $5) ON CONFLICT(id) DO UPDATE SET token=$2, player=$3, time=$4, metadata=$5;",
  78. "CREATE TABLE IF NOT EXISTS Players (id BIGSERIAL PRIMARY KEY, name TEXT NOT NULL);",
  79. "CREATE TABLE IF NOT EXISTS Boards (id BIGSERIAL PRIMARY KEY, name TEXT NOT NULL, description TEXT NOT NULL);",
  80. "CREATE TABLE IF NOT EXISTS Entries (id BIGSERIAL PRIMARY KEY, rank INTEGER NOT NULL DEFAULT -1, score INTEGER NOT NULL, player INTEGER NOT NULL, board INTEGER NOT NULL, time INTEGER NOT NULL, metadata BYTEA NOT NULL DEFAULT E'\\\\xFF', FOREIGN KEY(player) REFERENCES Players(id), FOREIGN KEY(board) REFERENCES Boards(id));",
  81. "CREATE TABLE IF NOT EXISTS Keys (id BIGSERIAL PRIMARY KEY, token TEXT NOT NULL, player INTEGER NOT NULL, time INTEGER NOT NULL, metadata BYTEA NOT NULL DEFAULT E'\\\\xFF', FOREIGN KEY(player) REFERENCES Players(id));",
  82. },
  83. }
  84. fmt.Printf("SQL Server %s is query type %d\n", sqlServer, queryType)
  85. //fmt.Println(len(queryStrings[queryType]))
  86. db, dbOpenErr = sql.Open(sqlServer, sqlConnection)
  87. if dbOpenErr != nil {
  88. return dbOpenErr
  89. }
  90. if buildTables {
  91. fmt.Println("Building tables in database...")
  92. sqlBuildTables()
  93. }
  94. if populateTables {
  95. fmt.Println("Populating tables in database...")
  96. sqlPopulateTables()
  97. }
  98. return nil
  99. }
  100. func sqlClose() error {
  101. if db != nil {
  102. err := db.Close()
  103. if err != nil {
  104. return err
  105. }
  106. db = nil
  107. }
  108. return nil
  109. }
  110. func boardByName(name string) (*Board, error) {
  111. b := &Board{}
  112. return b, db.QueryRow(queryStrings[queryType][0], name).Scan(b.Intake()...)
  113. }
  114. func playerByName(name string) (*Player, error) {
  115. p := &Player{}
  116. return p, db.QueryRow(queryStrings[queryType][1], name).Scan(p.Intake()...)
  117. }
  118. func newEntrySql(score, player, board int64) error {
  119. tx, _ := db.Begin()
  120. stmt, _ := tx.Prepare(queryStrings[queryType][2])
  121. _, err := stmt.Exec(score, player, board, time.Now().Unix())
  122. if err != nil {
  123. tx.Rollback()
  124. return err
  125. }
  126. tx.Commit()
  127. return nil
  128. }
  129. func newKeySql(player int64) (*Key, error) {
  130. tx, _ := db.Begin()
  131. newKey := &Key{Token: "new", Player: player, Time: time.Now().Unix()}
  132. stmt, _ := tx.Prepare(queryStrings[queryType][3])
  133. _, err := stmt.Exec(newKey.Token, newKey.Player, newKey.Time)
  134. if err != nil {
  135. tx.Rollback()
  136. return nil, err
  137. }
  138. tx.Commit()
  139. db.QueryRow(queryStrings[queryType][4], newKey.Token, newKey.Player, newKey.Time).Scan(newKey.Intake()...)
  140. tokenErr := newKey.GenerateToken()
  141. if tokenErr != nil {
  142. return nil, tokenErr
  143. }
  144. newKey.Metadata = []byte{0xFE} // enable key with not extra permissions
  145. return newKey, newKey.Commit()
  146. }
  147. func keyByToken(token string) (*Key, error) {
  148. k := &Key{}
  149. return k, db.QueryRow(queryStrings[queryType][5], token).Scan(k.Intake()...)
  150. }
  151. func keyByPlayer(player int64) (*Key, error) {
  152. k := &Key{}
  153. return k, db.QueryRow(queryStrings[queryType][6], player).Scan(k.Intake()...)
  154. }
  155. // internal operations
  156. func sqlBuildTables() {
  157. transaction, txErr := db.Begin()
  158. if txErr != nil {
  159. return
  160. }
  161. // test table
  162. //transaction.Exec("CREATE TABLE IF NOT EXISTS Test (Sometext VARCHAR, Somenumber);")
  163. //transaction.Exec("INSERT INTO Test (Sometext, Somenumber) VALUES (?,?);", "Hello sqlite", 123)
  164. // build real tables
  165. transaction.Exec(queryStrings[queryType][19])
  166. transaction.Exec(queryStrings[queryType][20])
  167. transaction.Exec(queryStrings[queryType][21])
  168. transaction.Exec(queryStrings[queryType][22])
  169. transaction.Commit()
  170. }
  171. func sqlPopulateTables() {
  172. boards := []*Board{
  173. &Board{ID: 1, Name: "main-test", Description: "Overall best (test data)"},
  174. &Board{ID: 2, Name: "coolest-test", Description: "Coolest score (test data)"},
  175. &Board{ID: 3, Name: "fastest-test", Description: "Fastest time (test data)"},
  176. }
  177. for _, b := range boards {
  178. err := b.Commit()
  179. if err != nil {
  180. fmt.Printf("Error creating board %d: %s\n", b.ID, err)
  181. }
  182. }
  183. players := []*Player{
  184. &Player{ID: 1, Name: "NGnius (test)"},
  185. &Player{ID: 2, Name: "Also NGnius (test)"},
  186. &Player{ID: 3, Name: ".xX||eDgY TeeNaGeR||Xx. (test)"},
  187. &Player{ID: 4, Name: "New username who dis? (test)"},
  188. &Player{ID: 5, Name: "Extremely Ridiculously Long Name to break things (test)"},
  189. &Player{ID: 6, Name: "P|P3 |o|z (test)"},
  190. &Player{ID: 7, Name: "Waldo (test)"},
  191. &Player{ID: 8, Name: "Zettagram.com (test)"},
  192. &Player{ID: 9, Name: "The Doctor (test)"},
  193. &Player{ID: 10, Name: "Marvin the Paranoid Android (test)"},
  194. &Player{ID: 11, Name: "IDK HOW (test)"},
  195. &Player{ID: 12, Name: "If you can read this your API may be wrong (test)"},
  196. &Player{ID: 13, Name: "Unlucky 7 (test)"},
  197. }
  198. for _, p := range players {
  199. err := p.Commit()
  200. if err != nil {
  201. fmt.Printf("Error creating player %d: %s\n", p.ID, err)
  202. }
  203. }
  204. now := time.Now().Unix()
  205. metadata := []byte{0x00, 0x00, 0x00, 0x00}
  206. entries := []*Entry{
  207. &Entry{ID: 1, Rank: 1, Score: 1000, Player: players[0].ID, Board: boards[0].ID, Time: now, Metadata: metadata},
  208. &Entry{ID: 2, Rank: 2, Score: 900, Player: players[1].ID, Board: boards[0].ID, Time: now, Metadata: metadata},
  209. &Entry{ID: 3, Rank: 3, Score: 400, Player: players[2].ID, Board: boards[0].ID, Time: now, Metadata: metadata},
  210. &Entry{ID: 4, Rank: 4, Score: 350, Player: players[3].ID, Board: boards[0].ID, Time: now, Metadata: metadata},
  211. &Entry{ID: 5, Rank: 5, Score: 350, Player: players[4].ID, Board: boards[0].ID, Time: now, Metadata: metadata},
  212. &Entry{ID: 6, Rank: 6, Score: 250, Player: players[5].ID, Board: boards[0].ID, Time: now, Metadata: metadata},
  213. &Entry{ID: 7, Rank: 7, Score: 200, Player: players[6].ID, Board: boards[0].ID, Time: now, Metadata: metadata},
  214. &Entry{ID: 8, Rank: 8, Score: 175, Player: players[7].ID, Board: boards[0].ID, Time: now, Metadata: metadata},
  215. &Entry{ID: 9, Rank: 9, Score: 150, Player: players[8].ID, Board: boards[0].ID, Time: now, Metadata: metadata},
  216. &Entry{ID: 10, Rank: 10, Score: 140, Player: players[9].ID, Board: boards[0].ID, Time: now, Metadata: metadata},
  217. &Entry{ID: 11, Rank: 11, Score: 10, Player: players[10].ID, Board: boards[0].ID, Time: now, Metadata: metadata},
  218. &Entry{ID: 12, Rank: 12, Score: 60, Player: players[11].ID, Board: boards[0].ID, Time: now, Metadata: metadata},
  219. &Entry{ID: 13, Rank: 13, Score: 13, Player: players[12].ID, Board: boards[0].ID, Time: now},
  220. }
  221. for _, e := range entries {
  222. err := e.Commit()
  223. if err != nil {
  224. fmt.Printf("Error creating entry %d: %s\n", e.ID, err)
  225. }
  226. }
  227. metadata = []byte{0x7E}
  228. keys := []*Key{
  229. &Key{ID: 1, Token: "", Player: players[0].ID, Time: now, Metadata: metadata},
  230. &Key{ID: 2, Token: "", Player: players[1].ID, Time: now, Metadata: metadata},
  231. }
  232. for _, k := range keys {
  233. genErr := k.GenerateToken()
  234. if genErr != nil {
  235. fmt.Printf("Error generating token for key %d, %s\n", k.ID, genErr)
  236. }
  237. //fmt.Printf("Key %d token: %s\n", k.ID, k.Token)
  238. err := k.Commit()
  239. if err != nil {
  240. fmt.Printf("Error creating key %d, %s\n", k.ID, err)
  241. }
  242. // bitwise op test
  243. //fmt.Printf("Key &d is superuser:%t, enabled:%t\n", k.ID, k.IsSuperuser(), k.IsEnabled())
  244. }
  245. }