|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "database/sql" |
| 5 | + "fmt" |
| 6 | + "log" |
| 7 | + |
| 8 | + "github.com/VauntDev/tqla" |
| 9 | + _ "github.com/go-sql-driver/mysql" |
| 10 | +) |
| 11 | + |
| 12 | +const ( |
| 13 | + host = "localhost" |
| 14 | + port = 3306 |
| 15 | + user = "root" |
| 16 | + password = "root" |
| 17 | + dbname = "mysql-test-db" |
| 18 | +) |
| 19 | + |
| 20 | +type todo struct { |
| 21 | + Id int |
| 22 | + Title string |
| 23 | + Description string |
| 24 | + Completed bool |
| 25 | +} |
| 26 | + |
| 27 | +const todoSchema = `CREATE TABLE IF NOT EXISTS todos ( |
| 28 | + id INT PRIMARY KEY, |
| 29 | + title TEXT NOT NULL, |
| 30 | + description TEXT NOT NULL, |
| 31 | + completed BOOLEAN DEFAULT FALSE |
| 32 | +);` |
| 33 | + |
| 34 | +func main() { |
| 35 | + |
| 36 | + log.Println("connecting to db...") |
| 37 | + dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", user, password, host, port, dbname) |
| 38 | + |
| 39 | + db, err := sql.Open("mysql", dsn) |
| 40 | + if err != nil { |
| 41 | + log.Fatal(err) |
| 42 | + } |
| 43 | + defer db.Close() |
| 44 | + |
| 45 | + log.Println("creating table if it does not exist...") |
| 46 | + if _, err := db.Exec(todoSchema); err != nil { |
| 47 | + log.Fatal(err) |
| 48 | + } |
| 49 | + |
| 50 | + todos := []*todo{ |
| 51 | + {Id: 1, Title: "todo 1", Description: "first todo", Completed: false}, |
| 52 | + {Id: 2, Title: "todo 2", Description: "second todo", Completed: false}, |
| 53 | + {Id: 3, Title: "todo 3", Description: "third todo", Completed: false}, |
| 54 | + {Id: 4, Title: "todo 4", Description: "fourth todo", Completed: false}, |
| 55 | + {Id: 5, Title: "todo 5", Description: "fifth todo", Completed: false}, |
| 56 | + } |
| 57 | + |
| 58 | + t, err := tqla.New() |
| 59 | + if err != nil { |
| 60 | + log.Fatal(err) |
| 61 | + } |
| 62 | + |
| 63 | + log.Println("adding todos...") |
| 64 | + insertStmt, insertArgs, err := t.Compile(` |
| 65 | + {{ $len := 4 -}} |
| 66 | + INSERT INTO todos (id, title, description, completed) |
| 67 | + VALUES {{ range $i, $v := . }} |
| 68 | + ( {{$v.Id}}, {{$v.Title}}, {{$v.Description}}, {{ $v.Completed }} ){{if lt $i $len}},{{else}};{{end -}} |
| 69 | + {{end}} |
| 70 | + `, todos) |
| 71 | + if err != nil { |
| 72 | + log.Fatal(err) |
| 73 | + } |
| 74 | + |
| 75 | + if _, err := db.Exec(insertStmt, insertArgs...); err != nil { |
| 76 | + log.Fatal(err) |
| 77 | + } |
| 78 | + |
| 79 | + log.Println("looking up todo...") |
| 80 | + selectStmt, selectArgs, err := t.Compile(`SELECT * FROM todos WHERE id = {{ . }}`, 5) |
| 81 | + if err != nil { |
| 82 | + log.Fatal(err) |
| 83 | + } |
| 84 | + |
| 85 | + todo := &todo{} |
| 86 | + row := db.QueryRow(selectStmt, selectArgs...) |
| 87 | + if err := row.Scan(&todo.Id, &todo.Title, &todo.Description, &todo.Completed); err != nil { |
| 88 | + log.Fatal(err) |
| 89 | + } |
| 90 | + |
| 91 | + log.Println("found: ", todo) |
| 92 | +} |
0 commit comments