memos/store/db/table.go

66 lines
1.2 KiB
Go
Raw Normal View History

2022-05-22 00:59:22 +08:00
package db
import (
"context"
"database/sql"
2022-05-22 00:59:22 +08:00
"strings"
)
type Table struct {
Name string
SQL string
}
//lint:ignore U1000 Ignore unused function temporarily for debugging
2022-08-24 20:40:56 +08:00
//nolint:all
func findTable(ctx context.Context, tx *sql.Tx, 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)
query := `
2022-05-22 00:59:22 +08:00
SELECT
tbl_name,
sql
FROM sqlite_schema
WHERE ` + strings.Join(where, " AND ")
rows, err := tx.QueryContext(ctx, query, args...)
2022-05-22 00:59:22 +08:00
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(ctx context.Context, tx *sql.Tx, stmt string) error {
_, err := tx.ExecContext(ctx, stmt)
if err != nil {
return err
2022-05-22 00:59:22 +08:00
}
return nil
2022-05-22 00:59:22 +08:00
}