-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.go
365 lines (303 loc) · 9.7 KB
/
database.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
package main
import (
"database/sql"
"fmt"
"log"
"time"
_ "github.com/mattn/go-sqlite3"
)
type DayAggregate struct {
Day string
TotalEstimate int
TotalActual int
TotalDone int
}
type TaskTrackingAggregate struct {
Year int
Month time.Month
Day int
TaskCount int
}
type TaskTracking struct {
TaskID int
Date string
HalfHour int
Status string // e.g., "in progress", "done", etc.
}
// Struct to hold task data
type Task struct {
ID int
Name string
Estimate int
Actual int
CreatedAt time.Time
UpdatedAt time.Time
Done bool
Status string
}
func initializeDatabase(dbPath string) *sql.DB {
db, err := sql.Open("sqlite3", dbPath)
if err != nil {
log.Fatal(err)
}
// Create tasks table if it doesn't exist
createTableQuery := `
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
estimate INTEGER NOT NULL,
actual INTEGER DEFAULT 0,
created_at DATETIME DEFAULT (datetime('now', 'localtime')),
updated_at DATETIME DEFAULT (datetime('now', 'localtime')),
done BOOLEAN DEFAULT 0
);`
_, err = db.Exec(createTableQuery)
if err != nil {
log.Fatal(err)
}
createTasksTableQuery := `
CREATE TABLE IF NOT EXISTS task_tracking (
id INTEGER PRIMARY KEY AUTOINCREMENT,
task_id INTEGER NOT NULL,
date DATE NOT NULL,
half_hour INTEGER NOT NULL CHECK (half_hour BETWEEN 0 AND 47),
task_name TEXT,
status TEXT DEFAULT 'active',
FOREIGN KEY (task_id) REFERENCES tasks(id) ON DELETE CASCADE
UNIQUE(task_id, date, half_hour)
);`
_, err = db.Exec(createTasksTableQuery)
if err != nil {
log.Fatal(err)
}
return db
}
func getDailyTasks(db *sql.DB) ([]Task, error){
query := `
SELECT id, name, estimate, actual, created_at, updated_at, done
FROM tasks
WHERE DATE(datetime(created_at, 'localtime')) = DATE('now', 'localtime')
ORDER BY created_at;
`
rows, err := db.Query(query)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var tasks []Task
for rows.Next() {
var id, estimate, actual int
var name string
var createdAt, updatedAt time.Time
var done bool
err := rows.Scan(&id, &name, &estimate, &actual, &createdAt, &updatedAt, &done)
if err != nil {
log.Fatal(err)
}
tasks = append(tasks, Task{ ID: id, Name: name, Estimate: estimate, Actual: actual, CreatedAt: createdAt, UpdatedAt: updatedAt, Done: done })
}
return tasks, nil
}
func getYearlyData(db *sql.DB, year int) ([]TaskTrackingAggregate, error) {
// aggregate half_hours completed for each day for the year
query := fmt.Sprintf(`
WITH RECURSIVE all_dates AS (
SELECT '%d-01-01' as date
UNION ALL
SELECT date(date, '+1 day')
FROM all_dates
WHERE date < '%d-12-31'
)
SELECT a.date, COUNT(t.date) as task_count
FROM all_dates a
LEFT JOIN task_tracking t ON a.date = t.date
GROUP BY a.date
ORDER BY a.date;`, year, year)
rows, err := db.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
var taskTrackingAggregates []TaskTrackingAggregate
for rows.Next() {
var dateStr string
var count int
if err := rows.Scan(&dateStr, &count); err != nil {
return nil, err
}
// parse the date from the string format
date, err := time.Parse("2006-01-02", dateStr)
if err != nil {
return nil, err
}
taskTrackingAggregates = append(taskTrackingAggregates, TaskTrackingAggregate{
Year: date.Year(),
Month: date.Month(),
Day: date.Day(),
TaskCount: count,
})
}
return taskTrackingAggregates, nil
}
// Function to fetch tasks from the database
func getTasks(days int, status string) ([]Task, error) {
var query string
var rows *sql.Rows
var err error
// Build query based on status
if status == "all" {
query = fmt.Sprintf("SELECT * FROM tasks WHERE created_at >= date('now', '-%d days')", days)
} else if status == "wip" || status == "inprogress" {
query = fmt.Sprintf("SELECT * FROM tasks WHERE created_at >= date('now', '-%d days') AND done = 0 AND actual > 0", days)
} else if status == "todo" {
query = fmt.Sprintf("SELECT * FROM tasks WHERE created_at >= date('now', '-%d days') AND done = 0 AND actual = 0", days)
} else if status == "done" {
query = fmt.Sprintf("SELECT * FROM tasks WHERE created_at >= date('now', '-%d days') AND done = 1", days)
} else {
return nil, fmt.Errorf("invalid status filter")
}
rows, err = db.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
// Slice to store task data
tasks := []Task{}
// Fetch data from rows
for rows.Next() {
var task Task
err := rows.Scan(&task.ID, &task.Name, &task.Estimate, &task.Actual, &task.CreatedAt, &task.UpdatedAt, &task.Done)
if err != nil {
return nil, err
}
// Determine task status
if task.Actual > 0 {
task.Status = "In Progress"
} else {
task.Status = "To Do"
}
if task.Done {
task.Status = "Done"
}
tasks = append(tasks, task)
}
return tasks, nil
}
func getTasksForDay(date string) ([]TaskTracking, error) {
rows, err := db.Query(`SELECT task_id, date, half_hour, status FROM task_tracking WHERE date = ?`, date)
if err != nil {
return nil, err
}
defer rows.Close()
var tasks []TaskTracking
for rows.Next() {
var task TaskTracking
err := rows.Scan(&task.TaskID, &task.Date, &task.HalfHour, &task.Status)
if err != nil {
return nil, err
}
tasks = append(tasks, task)
}
return tasks, nil
}
func addTask(db *sql.DB, name string, estimate int) error {
if name == "" {
return fmt.Errorf("task name cannot be empty")
}
now := time.Now().Local()
query := `INSERT INTO tasks (name, estimate, actual, created_at, updated_at, done)
VALUES (?, ?, 0, ?, ?, 0)`
result, err := db.Exec(query, name, estimate, now.Format("2006-01-02 15:04:05"), now.Format("2006-01-02 15:04:05"))
if err != nil {
return fmt.Errorf("failed to add task: %v", err)
}
id, err := result.LastInsertId()
if err != nil {
return fmt.Errorf("failed to get the ID of the inserted task: %v", err)
}
estimateSprouts := generateEmojis(estimate, "🌱")
fmt.Printf("Added task: %s\nID: %d\nEstimate: %d %s\n", name, id, estimate, estimateSprouts)
return nil
}
func insertTrackingTask(id int, currentDate string, halfHour int) error {
query := `
INSERT INTO task_tracking (task_id, date, half_hour, status)
VALUES (?, ?, ?, 'active')
ON CONFLICT(task_id, date, half_hour)
DO UPDATE SET status = 'done';
`
_, err := db.Exec(query, id, currentDate, halfHour)
if err != nil {
return fmt.Errorf("failed to insert tracking task: %v", err)
}
return nil
}
func updateActual(id int) error {
query := `UPDATE tasks SET actual = actual + 1, updated_at = datetime('now', 'localtime') WHERE id = ?`
result, err := db.Exec(query, id)
if err != nil {
return fmt.Errorf("failed to execute update query: %w", err)
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return fmt.Errorf("failed to retrieve rows affected: %w", err)
}
if rowsAffected == 0 {
fmt.Printf("No task found with ID: %d\n", id)
} else {
fmt.Printf("Updated task with ID: %d, increased 'actual' count by 1\n", id)
}
return nil
}
func updateEstimate(id int, newEstimate int) error {
query := `UPDATE tasks SET estimate = ?, updated_at = datetime('now', 'localtime') WHERE id = ?`
result, err := db.Exec(query, newEstimate, id)
if err != nil {
return fmt.Errorf("failed to execute update query: %w", err)
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return fmt.Errorf("failed to retrieve rows affected: %w", err)
}
if rowsAffected == 0 {
fmt.Printf("No task found with ID: %d\n", id)
} else {
fmt.Printf("Task with ID: %d has been updated with new estimate: %d 🌱\n", id, newEstimate)
}
return nil
}
func markAsDone(id int) error {
query := `UPDATE tasks SET done = 1, updated_at = datetime('now', 'localtime') WHERE id = ?`
result, err := db.Exec(query, id)
if err != nil {
return fmt.Errorf("failed to execute update query: %w", err)
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return fmt.Errorf("failed to retrieve rows affected: %w", err)
}
if rowsAffected == 0 {
fmt.Printf("No task found with ID: %d\n", id)
} else {
fmt.Printf("Task with ID: %d has been marked as done\n", id)
}
return nil
}
// delete a task
func deleteTask(db *sql.DB, id int) error {
query := `DELETE FROM tasks WHERE id = ?`
result, err := db.Exec(query, id)
if err != nil {
return fmt.Errorf("failed to delete task: %v", err)
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return fmt.Errorf("failed to retrieve rows affected: %v", err)
}
if rowsAffected == 0 {
fmt.Printf("No task found with ID: %d\n", id)
} else {
fmt.Printf("Task with ID: %d has been deleted\n", id)
}
return nil
}