-
Notifications
You must be signed in to change notification settings - Fork 0
/
tabel.go
100 lines (82 loc) · 2 KB
/
tabel.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
package main
import (
"database/sql"
"encoding/json"
"fmt"
"net/http"
_ "github.com/mattn/go-sqlite3"
)
type TableInfo struct {
Name string `json:"table_name"`
Schema []Column `json:"schema"`
}
type Column struct {
Name string `json:"column_name"`
DataType string `json:"data_type"`
Primary bool `json:"primary"`
}
func listTablesHandler(w http.ResponseWriter, r *http.Request) {
if db == nil {
http.Error(w, "Database not connected", http.StatusBadRequest)
return
}
tables, err := getTables()
if err != nil {
http.Error(w, fmt.Sprintf("Error getting tables: %v", err), http.StatusInternalServerError)
return
}
data, err := json.Marshal(tables)
if err != nil {
http.Error(w, fmt.Sprintf("Error serializing data to JSON: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(data)
}
func getTables() ([]TableInfo, error) {
rows, err := db.Query("SELECT name FROM sqlite_master WHERE type = 'table'")
if err != nil {
return nil, err
}
defer rows.Close()
var tables []TableInfo
for rows.Next() {
var tableName string
if err := rows.Scan(&tableName); err != nil {
return nil, err
}
tableInfo, err := getTableSchema(tableName)
if err != nil {
return nil, err
}
tables = append(tables, tableInfo)
}
return tables, nil
}
func getTableSchema(tableName string) (TableInfo, error) {
rows, err := db.Query(fmt.Sprintf("PRAGMA table_info(%s)", tableName))
if err != nil {
return TableInfo{}, err
}
defer rows.Close()
var tableInfo TableInfo
tableInfo.Name = tableName
for rows.Next() {
var cid int
var name string
var dataType string
var notnull string
var dflt_value sql.NullString
var pk string
if err := rows.Scan(&cid, &name, &dataType, ¬null, &dflt_value, &pk); err != nil {
return TableInfo{}, err
}
column := Column{
Name: name,
DataType: dataType,
Primary: pk == "1",
}
tableInfo.Schema = append(tableInfo.Schema, column)
}
return tableInfo, nil
}