-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.go
More file actions
246 lines (187 loc) · 5.77 KB
/
db.go
File metadata and controls
246 lines (187 loc) · 5.77 KB
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
package database
import (
"context"
"database/sql"
"errors"
"fmt"
"musicboxapi/configuration"
"musicboxapi/logging"
"os"
"path/filepath"
"strconv"
"strings"
"time"
_ "github.com/lib/pq"
)
const ReturningIdParameter = "RETURNING"
const ReturningIdParameterLower = "returning"
const DatabaseDriver = "postgres"
const MigrationFolder = "migration_scripts"
const MaxOpenConnections = 15
const MaxIdleConnections = 10
const MaxConnectionIdleTimeInMinutes = 10
const MaxConnectionLifeTimeInMinutes = 10
var DbInstance *sql.DB
type BaseTable struct {
DB *sql.DB
}
func NewBaseTableInstance() BaseTable {
return BaseTable{
DB: DbInstance,
}
}
// Base
func CreateDatabasConnectionPool() error {
// Will throw an error if its missing a method implementation from interface
// will throw a compile time error
// Should create test for these?
var _ ISongTable = (*SongTable)(nil)
var _ IPlaylistTable = (*PlaylistTable)(nil)
var _ IPlaylistSongTable = (*PlaylistsongTable)(nil)
var _ ITasklogTable = (*TasklogTable)(nil)
var _ IMigrationTable = (*MigrationTable)(nil)
baseConnectionString := "user=postgres dbname=postgres password=%s %s sslmode=disable"
password := os.Getenv("POSTGRES_PASSWORD")
host := "host=127.0.0.1 port=5432"
if configuration.Config.UseDevUrl {
host = "host=127.0.0.1 port=5433"
}
connectionString := fmt.Sprintf(baseConnectionString, password, host)
DB, err := sql.Open(DatabaseDriver, connectionString)
if err != nil {
logging.Error(fmt.Sprintf("Failed to init database connection: %s", err.Error()))
logging.ErrorStackTrace(err)
return err
}
DB.SetMaxOpenConns(MaxOpenConnections)
DB.SetMaxIdleConns(MaxIdleConnections)
DB.SetConnMaxIdleTime(MaxConnectionIdleTimeInMinutes * time.Minute)
DB.SetConnMaxLifetime(MaxConnectionLifeTimeInMinutes * time.Minute)
DbInstance = DB
return nil
}
// Base methods
func (base *BaseTable) InsertWithReturningId(query string, params ...any) (lastInsertedId int, err error) {
if !strings.Contains(query, ReturningIdParameter) {
return -1, errors.New("Query does not contain RETURNING keyword")
}
transaction, err := base.DB.Begin()
statement, err := transaction.Prepare(query)
if err != nil {
logging.ErrorStackTrace(err)
return -1, err
}
defer statement.Close()
err = statement.QueryRow(params...).Scan(&lastInsertedId)
if err != nil {
logging.ErrorStackTrace(err)
transaction.Rollback()
return -1, err
}
err = transaction.Commit()
if err != nil {
logging.ErrorStackTrace(err)
transaction.Rollback()
return -1, err
}
return lastInsertedId, nil
}
func (base *BaseTable) NonScalarQuery(query string, params ...any) (error error) {
transaction, err := base.DB.Begin()
if err != nil {
logging.Error(fmt.Sprintf("Transaction error: %s", err.Error()))
logging.ErrorStackTrace(err)
return err
}
statement, err := transaction.Prepare(query)
if err != nil {
logging.Error(fmt.Sprintf("Prepared statement error: %s", err.Error()))
logging.ErrorStackTrace(err)
return err
}
defer statement.Close()
_, err = statement.Exec(params...)
if err != nil {
logging.ErrorStackTrace(err)
return err
}
err = transaction.Commit()
if err != nil {
logging.Error(fmt.Sprintf("Transaction commit error: %s", err.Error()))
logging.ErrorStackTrace(err)
return err
}
return nil
}
func (base *BaseTable) QueryRow(query string, params ...any) *sql.Row {
return base.DB.QueryRow(query, params...)
}
func (base *BaseTable) QueryRowsContex(ctx context.Context, query string, params ...any) (*sql.Rows, error) {
return base.DB.QueryContext(ctx, query, params...)
}
func (base *BaseTable) QueryRows(query string) (*sql.Rows, error) {
return base.DB.QueryContext(context.Background(), query)
}
func ApplyMigrations() {
logging.Info("Checking for database migration files")
// files will be sorted by filename
// to make sure the migrations are executed in order
// this naming convention must be used
// 0 initial script.sql
// 1 update column.sql
// etc....
// entries are sorted by file name
dirs, err := os.ReadDir(MigrationFolder)
if err != nil {
logging.ErrorStackTrace(err)
return
}
migrationTable := NewMigrationTableInstance()
currentMigrationFileName, err := migrationTable.GetCurrentAppliedMigrationFileName()
// start at -1 if lastMigrationFileName is empty OR migration table does not exists
// start applying from 0
if currentMigrationFileName == "" || err != nil {
if strings.Contains(err.Error(), `relation "migration" does not exist`) {
logging.Info("First time running database script migrations")
} else {
logging.ErrorStackTrace(err)
return
}
// makes sure we start at script 0
currentMigrationFileName = "-1 nil.sql"
}
currentMigrationFileId, err := strconv.Atoi(strings.Split(currentMigrationFileName, " ")[0])
if err != nil {
logging.ErrorStackTrace(err)
return
}
for _, migrationFile := range dirs {
filePath := filepath.Join(MigrationFolder, migrationFile.Name())
migrationFileId, err := strconv.Atoi(strings.Split(migrationFile.Name(), " ")[0])
if err != nil {
logging.ErrorStackTrace(err)
continue
}
if migrationFileId <= currentMigrationFileId {
continue
}
migrationFileContents, err := os.ReadFile(filePath)
if err != nil {
logging.ErrorStackTrace(err)
continue
}
err = migrationTable.ApplyMigration(string(migrationFileContents))
if err != nil {
logging.Error(fmt.Sprintf("Failed to apply %s", migrationFile.Name()))
logging.ErrorStackTrace(err)
} else {
err = migrationTable.Insert(migrationFile.Name(), string(migrationFileContents))
if err != nil {
logging.Error(fmt.Sprintf("Failed to insert migration entry %s: %s", migrationFile.Name(), err.Error()))
logging.ErrorStackTrace(err)
return
}
logging.Info(fmt.Sprintf("Applied script: %s", migrationFile.Name()))
}
}
}