memos/store/db/table.go

66 lines
1 KiB
Go
Raw Normal View History

2022-05-22 00:59:22 +08:00
package db
import (
"database/sql"
2022-05-22 00:59:22 +08:00
"strings"
)
type Table struct {
Name string
SQL string
}
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)
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
}
}
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
}
_, err = result.RowsAffected()
2022-05-22 00:59:22 +08:00
return err
}