-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
53 lines (43 loc) · 1.35 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package main
import (
"context"
"database/sql"
"golang-postgresql-sql-builder-example/.gen/blog/public/model"
"golang-postgresql-sql-builder-example/repositories"
"log"
"os"
_ "github.com/lib/pq"
)
func openDbConnection() *sql.DB {
postgresUrl := os.Getenv("POSTGRES_URL")
if postgresUrl == "" {
postgresUrl = "postgres://postgres:password@localhost:5432/blog?sslmode=disable"
}
db, openErr := sql.Open("postgres", postgresUrl)
if openErr != nil {
log.Fatal("Error opening database: ", openErr)
}
return db
}
func main() {
db := openDbConnection()
defer db.Close()
usersRepo := &repositories.UsersRepository{Db: db}
user, _ := usersRepo.CreateUser("Alex", "asmartishin@gmail.com")
log.Printf("New user: %v\n", user)
postsRepo := &repositories.PostsRepository{Db: db}
post1, _ := postsRepo.CreatePost(user.ID, "My new post 1", "Post 1")
log.Printf("New post 1: %v\n", post1)
post1.Title = "My updated post 1"
post2, _ := postsRepo.CreatePost(user.ID, "My new post 2", "Post 2")
log.Printf("New post 2: %v\n", post2)
post2.Title = "My updated post 2"
ctx := context.Background()
postsToUpdate := []*model.Posts{post1, post2}
_ = postsRepo.UpdatePosts(ctx, postsToUpdate)
updatedPost1, err := postsRepo.GetPostByID(post1.ID)
if err != nil {
log.Fatal("Error getting post: ", err)
}
log.Printf("Update post 1: %v\n", updatedPost1)
}