Skip to content

Commit

Permalink
Merge pull request #32 from Pomog/yurii_dev
Browse files Browse the repository at this point in the history
added dbrepo functions
  • Loading branch information
TartuDen authored Dec 4, 2023
2 parents befd4ac + 909d57e commit 15e89df
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 0 deletions.
77 changes: 77 additions & 0 deletions internal/repository/dbrepo/sqllite.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,80 @@ func (m *SqliteBDRepo) CreateThread(userID int, thread models.Thread) error {
}
return nil
}

// CreatePost insert post into SQLite DB
func (m *SqliteBDRepo) CreatePost(post models.Post) error {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()

stmt := `insert into post
(subject, content, threadID, userID)
values ($1, $2, $3, $4
)
`

_, err := m.DB.ExecContext(ctx, stmt,
post.Subject,
post.Content,
post.ThreadId,
post.UserID,
)

if err != nil {
return err
}
return nil
}

// isThreadExist returns true if Thread with same Subject exist
func (m *SqliteBDRepo) IsThreadExist(thread models.Thread) (bool, error) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()

query := `select count(id)
from thread
where subject = $1
`
var numRows int
row := m.DB.QueryRowContext(ctx, query, thread.Subject)

err := row.Scan(&numRows)
if err != nil {
return false, nil
}

if numRows == 0 {
return false, nil
}

return true, nil
}

// GetAllPostsFromThread returns all slice of all Posts with given ThreadID, nil if there are no Posts
func (m *SqliteBDRepo) GetAllPostsFromThread(threadID int) ([]models.Post, error) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()

query := `select *
from post
where threadID = $1
`
rows, err := m.DB.QueryContext(ctx, query, threadID)
if err != nil {
return nil, err
}
defer rows.Close()

var posts []models.Post

for rows.Next() {
var post models.Post
err := rows.Scan(&post.ID, &post.Subject, &post.Content, &post.Created, &post.ThreadId, &post.UserID)
if err != nil {
return nil, err
}
posts = append(posts, post)
}

return posts, nil
}
3 changes: 3 additions & 0 deletions internal/repository/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,7 @@ type DatabaseInt interface {
UserPresent(userName, email string) (bool, error)
CreateUser(r models.User) error
CreateThread(userID int, thread models.Thread) error
CreatePost(post models.Post) error
IsThreadExist(thread models.Thread) (bool, error)
GetAllPostsFromThread(threadID int) ([]models.Post, error)
}
Binary file modified mainDB.db
Binary file not shown.

0 comments on commit 15e89df

Please sign in to comment.