package infra

import (
	"database/sql"
	"fmt"
)

// ColumnExists reports whether the named column exists in the given table
// by querying PRAGMA table_info. Returns false if the table does not exist.
func ColumnExists(conn *sql.DB, table, name string) (bool, error) {
	rows, err := conn.Query(fmt.Sprintf("PRAGMA table_info(%s)", table))
	if err != nil {
		return false, err
	}
	defer rows.Close()
	for rows.Next() {
		var cid int
		var colName, ctype string
		var notnull int
		var dflt sql.NullString
		var pk int
		if err := rows.Scan(&cid, &colName, &ctype, &notnull, &dflt, &pk); err != nil {
			return false, err
		}
		if colName == name {
			return true, nil
		}
	}
	return false, rows.Err()
}
