2022-05-22 00:59:22 +08:00
|
|
|
package db
|
|
|
|
|
|
|
|
import (
|
2022-07-01 20:39:48 +08:00
|
|
|
"database/sql"
|
2022-05-22 00:59:22 +08:00
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Table struct {
|
|
|
|
Name string
|
|
|
|
SQL string
|
|
|
|
}
|
|
|
|
|
2022-07-01 20:39:48 +08:00
|
|
|
func findTable(db *sql.DB, tableName string) (*Table, error) {
|
2022-05-22 00:59:22 +08:00
|
|
|
where, args := []string{"1 = 1"}, []interface{}{}
|
|
|
|
|
|
|
|
where, args = append(where, "type = ?"), append(args, "table")
|
|
|
|
where, args = append(where, "name = ?"), append(args, tableName)
|
|
|
|
|
2022-07-01 20:39:48 +08:00
|
|
|
rows, err := db.Query(`
|
2022-05-22 00:59:22 +08:00
|
|
|
SELECT
|
|
|
|
tbl_name,
|
|
|
|
sql
|
|
|
|
FROM sqlite_schema
|
|
|
|
WHERE `+strings.Join(where, " AND "),
|
|
|
|
args...,
|
|
|
|
)
|
|
|
|
if err != nil {
|
2022-05-22 09:29:34 +08:00
|
|
|
return nil, err
|
2022-05-22 00:59:22 +08:00
|
|
|
}
|
|
|
|
defer rows.Close()
|
|
|
|
|
|
|
|
tableList := make([]*Table, 0)
|
|
|
|
for rows.Next() {
|
|
|
|
var table Table
|
|
|
|
if err := rows.Scan(
|
|
|
|
&table.Name,
|
|
|
|
&table.SQL,
|
|
|
|
); err != nil {
|
2022-05-22 09:29:34 +08:00
|
|
|
return nil, err
|
2022-05-22 00:59:22 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
tableList = append(tableList, &table)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := rows.Err(); err != nil {
|
2022-05-22 09:29:34 +08:00
|
|
|
return nil, err
|
2022-05-22 00:59:22 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
if len(tableList) == 0 {
|
|
|
|
return nil, nil
|
|
|
|
} else {
|
|
|
|
return tableList[0], nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-01 20:39:48 +08:00
|
|
|
func createTable(db *sql.DB, sql string) error {
|
|
|
|
result, err := db.Exec(sql)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2022-05-22 00:59:22 +08:00
|
|
|
}
|
|
|
|
|
2022-07-01 20:39:48 +08:00
|
|
|
_, err = result.RowsAffected()
|
|
|
|
|
2022-05-22 00:59:22 +08:00
|
|
|
return err
|
|
|
|
}
|