-
Notifications
You must be signed in to change notification settings - Fork 11
/
database.go
119 lines (99 loc) Β· 2.19 KB
/
database.go
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
package db
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
)
var DB *sql.DB
/*
ConnectDB connects the fiber app to the database.
@param dbURI - database URI (eg: ./sqlite_database/data.db)
*/
func ConnectDB(dbUri string) error {
var err error
DB, err = sql.Open("sqlite3", dbUri)
if err != nil {
return err
}
if err = DB.Ping(); err != nil {
return err
}
return nil
}
/*
GetTables gets list of tables from the database
*/
func GetTables() ([]string, error) {
tableNames := make([]string, 0)
rows, err := DB.Query("SELECT name FROM sqlite_schema WHERE type='table' ORDER BY name")
if err != nil {
panic(err)
}
defer func() {
err = rows.Close()
if err != nil {
panic(err)
}
}()
for rows.Next() {
var tn string
if err := rows.Scan(&tn); err != nil {
panic(err)
}
tableNames = append(tableNames, tn)
}
if err := rows.Err(); err != nil {
panic(err)
}
return tableNames, nil
}
/*
CreateTable adds a table to the database.
@param tableName - name of the table
*/
func CreateTable(tableName string) error {
_, err := DB.Exec(fmt.Sprintf("CREATE TABLE '%v'('id' INTEGER NOT NULL PRIMARY KEY)", tableName))
if err != nil {
return err
}
return nil
}
/*
DeleteTable deletes a table from the database.
@param tableName - name of the table
*/
func DropTable(tableName string) error {
_, err := DB.Exec(fmt.Sprintf("DROP TABLE '%v'", tableName))
if err != nil {
return err
}
return nil
}
func GetSQLQuery(tableName string) (string, error) {
sql := "SELECT sql FROM sqlite_master where tbl_name=?"
params := []interface{}{tableName}
stmt, err := DB.Prepare(sql)
if err != nil {
return "", err
}
defer stmt.Close()
var sqltext string
err = stmt.QueryRow(params...).Scan(&sqltext)
if err != nil {
return "", err
}
return sqltext, nil
}
/*
AddColumn adds a column to a specified table.
@param tableName - name of the table
@param columnName - name of column to be added
@param dataType - field type of the new column
*/
func AddColumn(tableName string, columnName string, dataType string) error {
_, err := DB.Exec(fmt.Sprintf("ALTER TABLE '%s' ADD '%s' '%s'", tableName, columnName, dataType))
if err != nil {
return err
}
return nil
}