2022-05-21 19:59:22 +03:00
|
|
|
package db
|
|
|
|
|
|
|
|
import (
|
2022-07-01 15:39:48 +03:00
|
|
|
"database/sql"
|
2022-05-21 19:59:22 +03:00
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Table struct {
|
|
|
|
Name string
|
|
|
|
SQL string
|
|
|
|
}
|
|
|
|
|
2022-07-01 15:39:48 +03:00
|
|
|
func findTable(db *sql.DB, tableName string) (*Table, error) {
|
2022-05-21 19:59:22 +03: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 15:39:48 +03:00
|
|
|
rows, err := db.Query(`
|
2022-05-21 19:59:22 +03:00
|
|
|
SELECT
|
|
|
|
tbl_name,
|
|
|
|
sql
|
|
|
|
FROM sqlite_schema
|
|
|
|
WHERE `+strings.Join(where, " AND "),
|
|
|
|
args...,
|
|
|
|
)
|
|
|
|
if err != nil {
|
2022-05-22 04:29:34 +03:00
|
|
|
return nil, err
|
2022-05-21 19:59:22 +03: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 04:29:34 +03:00
|
|
|
return nil, err
|
2022-05-21 19:59:22 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
tableList = append(tableList, &table)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := rows.Err(); err != nil {
|
2022-05-22 04:29:34 +03:00
|
|
|
return nil, err
|
2022-05-21 19:59:22 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if len(tableList) == 0 {
|
|
|
|
return nil, nil
|
|
|
|
} else {
|
|
|
|
return tableList[0], nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-01 15:39:48 +03:00
|
|
|
func createTable(db *sql.DB, sql string) error {
|
|
|
|
result, err := db.Exec(sql)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2022-05-21 19:59:22 +03:00
|
|
|
}
|
|
|
|
|
2022-07-01 15:39:48 +03:00
|
|
|
_, err = result.RowsAffected()
|
|
|
|
|
2022-05-21 19:59:22 +03:00
|
|
|
return err
|
|
|
|
}
|