connector.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "encoding/json"
  6. "database/sql"
  7. _ "github.com/go-sql-driver/mysql"
  8. )
  9. type ConnectionProperties struct {
  10. User string
  11. Pass string
  12. Host string
  13. Db string
  14. }
  15. type connection struct {
  16. dBOpenStr string
  17. connProperties ConnectionProperties
  18. }
  19. func (c *connection) Init(filepath string){
  20. if (NOMYSQL) {
  21. return
  22. }
  23. b, err := ioutil.ReadFile(filepath)
  24. if err != nil {
  25. fmt.Print(err)
  26. }
  27. propJson := string(b)
  28. json.Unmarshal([]byte(propJson), &c.connProperties)
  29. //c.connProperties.Db = "nosite"
  30. fmt.Printf("Connection data:\n%s\n%s\n%s\n%s\n", c.connProperties.User, c.connProperties.Pass, c.connProperties.Host, c.connProperties.Db)
  31. c.dBOpenStr = fmt.Sprintf ("%s:%s@tcp(%s)/%s", c.connProperties.User, c.connProperties.Pass, c.connProperties.Host, c.connProperties.Db)
  32. fmt.Printf("Connecting with:\n%s\n", c.dBOpenStr)
  33. db, err := sql.Open("mysql", c.dBOpenStr)
  34. if err != nil {
  35. panic(err)
  36. }
  37. if err = db.Ping(); err != nil {
  38. db.Close()
  39. logger.Print("Fatal : Error with connection to database!")
  40. } else {
  41. fmt.Print("Connection succesfull!")
  42. return
  43. }
  44. logger.Print("Trying to connect to DB-server...")
  45. c.dBOpenStr = fmt.Sprintf ("%s:%s@tcp(%s)/", c.connProperties.User, c.connProperties.Pass, c.connProperties.Host)
  46. fmt.Printf("Connecting with:\n%s\n", c.dBOpenStr)
  47. db, err = sql.Open("mysql", c.dBOpenStr)
  48. if err != nil {
  49. panic(err)
  50. }
  51. if err = db.Ping(); err != nil {
  52. db.Close()
  53. logger.Print("Fatal : Error with connection to database server!")
  54. return
  55. } else {
  56. }
  57. c.databaseInitialization();
  58. }
  59. /* создает на сервере необходимую бд и таблицы */
  60. func (c *connection) databaseInitialization() {
  61. db, err := sql.Open("mysql", c.dBOpenStr)
  62. if err != nil {
  63. panic(err)
  64. }
  65. defer db.Close()
  66. var counter int
  67. var act_query string
  68. logger.Printf("Checking for existence of database '%s' on server...", c.connProperties.Db)
  69. act_query = "SELECT count(*) FROM information_schema.tables WHERE TABLE_SCHEMA = '" + c.connProperties.Db + "';"
  70. db.QueryRow(act_query).Scan(&counter)
  71. fmt.Print(counter)
  72. if (counter != 0) {
  73. logger.Print("Server already has the specified database")
  74. } else {
  75. logger.Print("The server does not have the specified database")
  76. logger.Printf("Creating database '%s'...", c.connProperties.Db)
  77. act_query = "CREATE SCHEMA " + c.connProperties.Db + " DEFAULT CHARACTER SET utf8 ;"
  78. result, err := db.Exec(act_query)
  79. if err != nil{
  80. panic(err)
  81. }
  82. rowsCount, _ := result.RowsAffected()
  83. fmt.Printf("Lines changed: %d\n", rowsCount)
  84. if (rowsCount == 1) {
  85. logger.Print("Succesfull!")
  86. }
  87. }
  88. logger.Print("Checking for existence of table 'users' on server...")
  89. act_query = "SELECT count(*) FROM information_schema.tables WHERE TABLE_NAME = 'users' AND TABLE_SCHEMA = '"+ c.connProperties.Db +"';"
  90. db.QueryRow(act_query).Scan(&counter)
  91. fmt.Print(counter)
  92. if (counter != 0) {
  93. logger.Print("Server already has the specified table!")
  94. } else {
  95. logger.Print("The server does not have the specified table")
  96. logger.Printf("Creating table '%s'.'users'...",c.connProperties.Db)
  97. act_query = "CREATE TABLE `" + c.connProperties.Db + "`.`users` ( `idusers` INT NOT NULL AUTO_INCREMENT,`username` VARCHAR(45) NOT NULL, `password` VARCHAR(45) NOT NULL, PRIMARY KEY(`idusers`), UNIQUE INDEX `idusers_UNIQUE` (`idusers` ASC), UNIQUE INDEX `username_UNIQUE` (`username` ASC)) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 ;"
  98. fmt.Print(act_query)
  99. _, err := db.Exec(act_query)
  100. if err != nil{
  101. panic(err)
  102. }
  103. logger.Print("Succesfull!")
  104. }
  105. }
  106. func (c connection) LogIn(username string, password string) bool{
  107. fmt.Printf("\n\nLogIn\nConnecting with:\n%s\n", c.dBOpenStr)
  108. db, err := sql.Open("mysql", c.dBOpenStr)
  109. if err != nil {
  110. panic(err)
  111. }
  112. defer db.Close()
  113. var counter int
  114. //fmt.Printf("%s\n%s\n", username, password)
  115. act_query := fmt.Sprintf("SELECT count(*) FROM %s.users WHERE username='%s' AND password=SHA('%s');", c.connProperties.Db, username, password)
  116. db.QueryRow(act_query).Scan(&counter)
  117. fmt.Println("we have", counter, "rows")
  118. if (counter == 0) {
  119. return false
  120. }
  121. return true
  122. }
  123. func (c connection) IsNameUsed(username string) bool {
  124. db, err := sql.Open("mysql", c.dBOpenStr)
  125. if err != nil {
  126. panic(err)
  127. }
  128. defer db.Close()
  129. var counter int
  130. act_query := fmt.Sprintf("SELECT count(*) FROM %s.users WHERE username='%s';", c.connProperties.Db, username)
  131. db.QueryRow(act_query).Scan(&counter)
  132. if (counter == 0) {
  133. fmt.Printf("Username unused\n")
  134. return false
  135. }
  136. fmt.Printf("Username used\n")
  137. return true
  138. }
  139. func (c connection) SigInUser(username string, password string) bool {
  140. db, err := sql.Open("mysql", c.dBOpenStr)
  141. if err != nil {
  142. panic(err)
  143. }
  144. defer db.Close()
  145. act_query := fmt.Sprintf("INSERT INTO %s.users (username, password) VALUES ('%s', SHA('%s'))", c.connProperties.Db, username, password)
  146. result, err := db.Exec(act_query)
  147. if err != nil{
  148. panic(err)
  149. }
  150. rowsCount, _ := result.RowsAffected()
  151. if (rowsCount == 1) {
  152. fmt.Printf("Lines changed: %d\n", rowsCount)
  153. return true
  154. } else {
  155. return false
  156. }
  157. }
  158. func (c connection) SubmitScore(score int){
  159. fmt.Printf("Submiting score %d", score)
  160. }
  161. /*
  162. func main() {
  163. var dBConnector connection
  164. dBConnector.Init("config.json")
  165. if (dBConnector.LogIn("Alex", "09Alex09")) {
  166. fmt.Printf("Succesfull logIn\n")
  167. } else {
  168. fmt.Printf("logIn error\n")
  169. }
  170. if (dBConnector.LogIn("Alax", "09Alex09")) {
  171. fmt.Printf("Succesfull logIn\n")
  172. } else {
  173. fmt.Printf("logIn error\n")
  174. }
  175. }
  176. */