You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
1.3 KiB

package WorstCaptcha
import (
"os"
"fmt"
"database/sql"
_ "github.com/mattn/go-sqlite3"
)
type Db struct {
Client *sql.DB
}
func NewDb() Db {
dir, _ := os.Getwd()
db, err := sql.Open("sqlite3", dir + "/worstcaptcha.db")
if err != nil {
fmt.Println("Failed to open database:", err)
os.Exit(1)
}
db.Exec(`
CREATE TABLE IF NOT EXISTS tokens (
"id" integer NOT NULL PRIMARY KEY,
"word" text,
"token" text
);
`)
return Db{db}
}
func (d *Db) InsertToken(word string, token string) {
stmt, _ := d.Client.Prepare(`
INSERT INTO tokens("word", "token")
VALUES (?, ?)
`)
defer stmt.Close()
stmt.Exec(word, token)
}
func (d *Db) GetWordByToken(token string) string {
var returningWord string
rows, _ := d.Client.Query(
"SELECT `id`, `word` FROM tokens WHERE `token` = ?",
token,
)
// Make map with rows to delete from database
toDelete := make(map[int]bool)
for rows.Next() {
var id int
var word string
// Fill vars with data
_ = rows.Scan(&id, &word)
// Append to map to delete
toDelete[id] = true
returningWord = word
}
rows.Close()
// Loop trough the map with ids to remove
for id, _ := range toDelete {
stmt, _ := d.Client.Prepare("DELETE FROM tokens WHERE id = ?")
stmt.Exec(id)
stmt.Close()
}
return returningWord
}