main.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "io/ioutil"
  6. "path/filepath"
  7. "github.com/vladimirok5959/golang-sql/gosql"
  8. )
  9. func main() {
  10. // Get temp file name
  11. f, err := ioutil.TempFile("", "go-sqlite-")
  12. if err != nil {
  13. panic(fmt.Sprintf("%s", err))
  14. }
  15. f.Close()
  16. // Set migration directory
  17. migrationsDir, err := filepath.Abs("./db/migrations")
  18. if err != nil {
  19. panic(fmt.Sprintf("%s", err))
  20. }
  21. // Open DB connection, SQLite is used as example
  22. // You can use here MySQL or PostgreSQL, just change dbURL
  23. db, err := gosql.Open("sqlite://"+f.Name(), migrationsDir, true)
  24. if err != nil {
  25. panic(fmt.Sprintf("%s", err))
  26. }
  27. // DB struct here ./db/migrations/20220527233113_test_migration.sql
  28. // Insert some data to users table:
  29. if _, err := db.Exec(
  30. context.Background(),
  31. "INSERT INTO users (id, name) VALUES ($1, $2)",
  32. 5, "John",
  33. ); err != nil {
  34. panic(fmt.Sprintf("%s", err))
  35. }
  36. // Select all rows from users table:
  37. if rows, err := db.Query(
  38. context.Background(),
  39. "SELECT id, name FROM users ORDER BY id DESC",
  40. ); err == nil {
  41. type rowStruct struct {
  42. ID int64
  43. Name string
  44. }
  45. defer rows.Close()
  46. for rows.Next() {
  47. var row rowStruct
  48. if err := rows.Scan(&row.ID, &row.Name); err != nil {
  49. panic(fmt.Sprintf("%s", err))
  50. }
  51. fmt.Printf("ID: %d, Name: %s\n", row.ID, row.Name)
  52. }
  53. if err := rows.Err(); err != nil {
  54. panic(fmt.Sprintf("%s", err))
  55. }
  56. } else {
  57. panic(fmt.Sprintf("%s", err))
  58. }
  59. // Close DB connection
  60. if err := db.Close(); err != nil {
  61. panic(fmt.Sprintf("%s", err))
  62. }
  63. }