-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql.go
More file actions
411 lines (328 loc) · 8.26 KB
/
sql.go
File metadata and controls
411 lines (328 loc) · 8.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package main
import (
"context"
"crypto/rand"
"database/sql"
"encoding/json"
"fmt"
_ "github.com/go-sql-driver/mysql"
_ "github.com/mattn/go-sqlite3"
"log"
"time"
)
type PostData struct {
Id string
Title string `json:"title"`
Content string `json:"content"`
Date string `json:"date"`
}
type ImageServ struct {
Id string
Image []byte `json:"image"`
}
type Db struct {
Tables map[string]map[string]string
DbName string
DbPath string
PostD PostData
TableName string
FetchInfo string
ImageS ImageServ
}
const (
username = "root"
password = "root"
hostname = "localhost:3307"
dbname = "eska"
)
func uuid4SQL() string {
/*
Генератор уникальных id
*/
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
log.Fatal(err)
}
uuid := fmt.Sprintf("%x-%x-%x-%x-%x",
b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
return uuid
}
func dsn() string {
return fmt.Sprintf("%s:%s@tcp(%s)/%s", username, password, hostname, dbname)
}
func dbConnection() (*sql.DB, error) {
var dbFirstName = "root:root@tcp(docker.for.mac.localhost:3307)/"
db, err := sql.Open("mysql", dbFirstName)
if err != nil {
log.Printf("Error %s when opening DB\n", err)
return nil, err
}
ctx, cancelfunc := context.WithTimeout(context.Background(), time.Second*5)
defer cancelfunc()
res, err := db.ExecContext(ctx, `CREATE DATABASE IF NOT EXISTS eska`)
if err != nil {
log.Printf("Error %s when creating DB\n", err)
return nil, err
}
no, err := res.RowsAffected()
if err != nil {
log.Printf("Error %s when fetching rows", err)
return nil, err
}
log.Printf("rows affected %d\n", no)
db.Close()
db, err = sql.Open("mysql", "root:root@tcp(docker.for.mac.localhost:3307)/eska")
if err != nil {
log.Printf("Error %s when opening DB", err)
return nil, err
}
//defer db.Close()
db.SetMaxOpenConns(20)
db.SetMaxIdleConns(20)
db.SetConnMaxLifetime(time.Minute * 5)
ctx, cancelfunc = context.WithTimeout(context.Background(), 5*time.Second)
defer cancelfunc()
err = db.PingContext(ctx)
if err != nil {
log.Printf("Errors %s pinging DB", err)
return nil, err
}
log.Printf("Connected to DB %s successfully\n", dbname)
return db, nil
}
func (c Db) AddPost() error {
/*
Добавляет пост в БД
*/
db, dateBaseError := dbConnection()
if dateBaseError != nil {
panic(dateBaseError)
}
var ErrorAddInfo error
records := `INSERT INTO posts VALUES (?, ?, ?, ?)`
query, prepareError := db.Prepare(records)
if prepareError != nil {
ErrorAddInfo = prepareError
}
_, execError := query.Exec(c.PostD.Id, c.PostD.Title, c.PostD.Content, c.PostD.Date)
if execError != nil {
ErrorAddInfo = execError
}
return ErrorAddInfo
}
func (c Db) AddImage() error {
/*
Добавляет пост в БД
*/
db, dateBaseError := dbConnection()
if dateBaseError != nil {
panic(dateBaseError)
}
var ErrorAddInfo error
records := `INSERT INTO post_images VALUES (?, ?)`
query, prepareError := db.Prepare(records)
if prepareError != nil {
ErrorAddInfo = prepareError
}
_, execError := query.Exec(c.ImageS.Id, c.ImageS.Image)
if execError != nil {
ErrorAddInfo = execError
}
return ErrorAddInfo
}
func (c Db) ChangePost() error {
/*
Добавляет пост в БД
*/
db, dateBaseError := dbConnection()
if dateBaseError != nil {
panic(dateBaseError)
}
var ErrorAddInfo error
//
//records := `UPDATE posts SET Title = ?, Content = ? WHERE Id = ?`
//_, execError := db.Exec(records, c.PostD.Title, c.PostD.Content, c.PostD.Id)
//...
_, execError := db.Exec("update posts set content = ?, date = ? where id = ?", c.PostD.Title, c.PostD.Content, c.PostD.Id) //ебанутая хуйня которая парашно работает не обращать внимание на логику её тут нет
if execError != nil {
ErrorAddInfo = execError
}
return ErrorAddInfo
}
func (c Db) removeInfo() (bool, error) {
/*
Удаляет данные из БД
*/
db, dateBaseError := dbConnection()
if dateBaseError != nil {
return false, nil
}
var IdDb = c.PostD.Id
var deleteReq = fmt.Sprintf("DELETE FROM " + c.TableName + " WHERE Id = '" + IdDb + "'")
_, execError := db.Exec(deleteReq)
if execError != nil {
return false, nil
}
return true, nil
}
func (c Db) removeInfoImage() (bool, error) {
/*
Удаляет данные из БД
*/
db, dateBaseError := dbConnection()
if dateBaseError != nil {
return false, nil
}
var deleteReq = fmt.Sprintf("DELETE FROM " + c.TableName + " WHERE Id = '" + c.ImageS.Id + "'")
_, execError := db.Exec(deleteReq)
if execError != nil {
return false, nil
}
return true, nil
}
func (c Db) fetchInfo() ([]any, error) {
/*
Выкачивает всю инфу из БД
*/
db, dateBaseError := dbConnection()
if dateBaseError != nil {
panic(dateBaseError)
}
var results []any
record, queryError := db.Query("SELECT * FROM " + c.TableName)
if queryError != nil {
return nil, queryError
}
defer func(record *sql.Rows) {
err := record.Close()
if err != nil {
panic(err)
}
}(record)
if c.FetchInfo == "posts" {
for record.Next() {
var Id string
var Title string
var Content string
var Date string
scanError := record.Scan(&Id, &Title, &Content, &Date)
if scanError != nil {
return results, scanError
}
var user = PostData{Id: Id, Title: Title, Content: Content, Date: Date}
results = append(results, user)
}
return results, nil
}
return nil, nil
}
func (c Db) getImageById() ([]byte, error) {
/*
Выкачивает всю инфу из БД
*/
db, dateBaseError := dbConnection()
if dateBaseError != nil {
panic(dateBaseError)
}
record, queryError := db.Query("SELECT Image FROM " + c.TableName + " WHERE Id= '" + c.ImageS.Id + "'")
if queryError != nil {
return nil, queryError
}
defer func(record *sql.Rows) {
err := record.Close()
if err != nil {
panic(err)
}
}(record)
if c.FetchInfo == "post_images" {
for record.Next() {
var Image []byte
scanError := record.Scan(&Image)
return Image, scanError
}
}
return nil, nil
}
func (c Db) getPostById() ([]byte, error) {
/*
Выкачивает всю инфу из БД
*/
db, dateBaseError := dbConnection()
if dateBaseError != nil {
panic(dateBaseError)
}
record, queryError := db.Query("SELECT * FROM " + c.TableName + " WHERE Id= '" + c.PostD.Id + "'")
if queryError != nil {
return nil, queryError
}
defer func(record *sql.Rows) {
err := record.Close()
if err != nil {
panic(err)
}
}(record)
if c.FetchInfo == "posts" {
for record.Next() {
var Id string
var Title string
var Content string
var Date string
scanError := record.Scan(&Id, &Title, &Content, &Date)
var data = map[string]any{"title": Title, "content": Content, "id": Id, "date": Date}
var dataPosts, jsonError = json.MarshalIndent(data, "", " ")
if jsonError != nil {
panic(jsonError)
}
return dataPosts, scanError
}
}
return nil, nil
}
func (c Db) createTable() error {
/*
Создает таблицу posts
*/
db, dateBaseError := dbConnection()
if dateBaseError != nil {
panic(dateBaseError)
}
var table string
for tableName, Params := range c.Tables {
var tableType = "CREATE TABLE IF NOT EXISTS "
table = tableType + tableName + " (Id CHAR(50) NOT NULL,\n"
for name, param := range Params {
table = table + name + " " + param + ",\n"
}
table = table[:len(table)-2]
table = table + ");"
}
fmt.Println("СОЗДАНИЕ ТАБЛИЦЫ: ", table)
query, prepareError := db.Prepare(table)
if prepareError != nil {
return prepareError
}
_, execError := query.Exec()
if execError != nil {
return execError
}
return nil
}
func InitImagesDbAdmin() {
var imageTable = map[string]string{"Image": "BLOB"}
var tables = map[string]map[string]string{"post_images": imageTable}
var db = Db{DbName: "eska", TableName: "post_images", FetchInfo: "post_images", Tables: tables}
Err := db.createTable()
if Err != nil {
panic(Err)
}
}
func InitPostsDbAdmin() {
var postsTable = map[string]string{"Title": "TEXT", "Content": "TEXT", "Date": "TEXT"}
var tables2 = map[string]map[string]string{"posts": postsTable}
var db = Db{DbName: "eska", TableName: "posts", FetchInfo: "posts", Tables: tables2}
Err := db.createTable()
if Err != nil {
panic(Err)
}
}