func getCardsTableName() string { secrets := hush.Hushfile() table, ok := secrets.GetString("table") if !ok { log.Fatal("No table name exists") return "" } return table }
// InitDB initializes the database connection func InitDB() { secrets := hush.Hushfile() log.Println("Initiating connection to database.") user, ok := secrets.GetString("username") if !ok { panic("Could not get the username from .hushfile") } dbname, ok := secrets.GetString("dbname") if !ok { panic("Could not get the dbname from .hushfile") } password, ok := secrets.GetString("password") if !ok { panic("Could not get the password from .hushfile") } connString := fmt.Sprintf("user=%s dbname=%s password=%s sslmode=disable", user, dbname, password) var err error Database, err = sql.Open("postgres", connString) if err != nil { panic(err) } log.Println("Pinging db...") err = Database.Ping() if err != nil { panic(err) } log.Println("No errors. Connected to database successfully.") }
// WriteToDB writes the records in the CSV to the db func WriteToDB() { secrets := hush.Hushfile() db := getDBConnection(secrets) csvFile := csv.NewReader(getCSVFile(os.Args[2])) records, err := csvFile.ReadAll() if err != nil { panic(err) } table, ok := secrets.GetString("table") if !ok { panic("Could not get the table name.") } sql := fmt.Sprintf("INSERT INTO %s VALUES ($1, $2, $3, $4);", table) stmt, err := db.Prepare(sql) if err != nil { panic(err) } for _, record := range records { cardType, err := strconv.ParseInt(record[2], 0, 0) if err != nil { panic(err) } cardBlanks, err := strconv.ParseInt(record[3], 0, 0) if err != nil { panic(err) } res, err := stmt.Exec(record[1], cardType, cardBlanks, true) if err != nil { panic(err) } fmt.Println(res) } }