Updating sqlite implementation
This commit is contained in:
@@ -74,7 +74,43 @@ func (s *SQLiteStore) Close() error {
|
||||
}
|
||||
|
||||
func (s *SQLiteStore) SaveNote(ctx context.Context, note models.Note) (models.Note, error) {
|
||||
return models.Note{}, fmt.Errorf("not implemented")
|
||||
tx, err := s.getWriteTransaction(ctx)
|
||||
if err != nil {
|
||||
return models.Note{}, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
if note.ID == 0 {
|
||||
result, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO notes (content, last_update) VALUES (?, ?);
|
||||
`, note.Content, note.LastUpdate)
|
||||
if err != nil {
|
||||
return models.Note{}, fmt.Errorf("failed to insert note: %w", err)
|
||||
}
|
||||
id, err := result.LastInsertId()
|
||||
if err != nil {
|
||||
return models.Note{}, fmt.Errorf("failed to get last insert ID: %w", err)
|
||||
}
|
||||
note.ID = int(id)
|
||||
} else {
|
||||
_, err := s.scanNote(tx.QueryRowContext(ctx, `
|
||||
SELECT id, content, last_update FROM notes WHERE id = ?;
|
||||
`, note.ID))
|
||||
if err != nil {
|
||||
return models.Note{}, fmt.Errorf("cannot update note not found: %w", err)
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, `
|
||||
UPDATE notes SET content = ?, last_update = ? WHERE id = ?;
|
||||
`, note.Content, note.LastUpdate, note.ID)
|
||||
if err != nil {
|
||||
return models.Note{}, fmt.Errorf("failed to update note: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
return models.Note{}, fmt.Errorf("failed to commit transaction: %w", err)
|
||||
}
|
||||
return note, nil
|
||||
}
|
||||
|
||||
func (s *SQLiteStore) validateSchema(ctx context.Context) error {
|
||||
@@ -87,3 +123,20 @@ func (s *SQLiteStore) validateSchema(ctx context.Context) error {
|
||||
`, nil)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *SQLiteStore) getWriteTransaction(ctx context.Context) (*sql.Tx, error) {
|
||||
tx, err := s.write.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to begin transaction: %w", err)
|
||||
}
|
||||
return tx, nil
|
||||
}
|
||||
|
||||
func (s *SQLiteStore) scanNote(results *sql.Row) (models.Note, error) {
|
||||
var note models.Note
|
||||
err := results.Scan(¬e.ID, ¬e.Content, ¬e.LastUpdate)
|
||||
if err != nil {
|
||||
return models.Note{}, fmt.Errorf("failed to scan note: %w", err)
|
||||
}
|
||||
return note, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user