memos/store/db/table.go

66 lines
1.0 KiB
Go
Raw Normal View History

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