This repository has been archived on 2022-11-30. You can view files and clone it, but cannot push or open issues or pull requests.
hex-decode-fix/main.go

100 lines
1.5 KiB
Go

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()
if err != nil {
log.Fatal(err)
}
tx, err := db.Begin()
if err != nil {
log.Fatal(err)
}
rows, err := tx.Query(fmt.Sprintf("SELECT %s, %s FROM %s", idColumn, hexColumn, table))
if err != nil {
log.Fatal(err)
}
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++
continue
}
decoded, err := hex.DecodeString(strings.TrimPrefix(raw, prefix))
if err != nil {
log.Print(err)
failed++
continue
}
_, 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(err)
failed++
}
}
log.Print("Skipped: ", skipped)
log.Print("Failed: ", failed)
log.Print("Updated: ", updated)
err = rows.Err()
if err != nil {
log.Fatal(err)
}
err = tx.Commit()
if err != nil {
log.Fatal(err)
}
}