package main
import (
"database/sql"
"encoding/hex"
"fmt"
"log"
"os"
"strings"
_ "rsc.io/sqlite"
)
const prefix = "\\x"
var file string
var table string
var idColumn string
var hexColumn string
func init() {
if len(os.Args) < 5 {
log.Fatal("Requires args: file, table, id column, and hex column")
}
file = os.Args[1]
table = os.Args[2]
idColumn = os.Args[3]
hexColumn = os.Args[4]
func main() {
db, err := sql.Open("sqlite3", file)
if err != nil {
log.Fatal(err)
err = db.Ping()
tx, err := db.Begin()
rows, err := tx.Query(fmt.Sprintf("SELECT %s, %s FROM %s", idColumn, hexColumn, table))
defer rows.Close()
var updated int
var skipped int
var failed int
for rows.Next() {
var id string
var raw string
if err = rows.Scan(&id, &raw); err != nil {
log.Print(err)
failed++
continue
if !strings.HasPrefix(raw, prefix) {
skipped++
decoded, err := hex.DecodeString(strings.TrimPrefix(raw, prefix))
_, err = tx.Exec(fmt.Sprintf("UPDATE %s SET %s = $1 WHERE %s = $2", table, hexColumn, idColumn), decoded, id)
if err == nil {
updated++
} else {
log.Print("Skipped: ", skipped)
log.Print("Failed: ", failed)
log.Print("Updated: ", updated)
err = rows.Err()
err = tx.Commit()