Skip to content

Commit 45c4346

Browse files
c9845 (AA)c9845 (AA)
c9845 (AA)
authored and
c9845 (AA)
committed
Implement logging levels, instead of just debug logging on or off, to allow for more options when logging is required.
This does break things a bit since the Debug field is removed and replaced with LoggingLevel, although this is a pretty minor breakage. Also performed some general cleanup.
1 parent 83b7316 commit 45c4346

7 files changed

+118
-78
lines changed

sqldb-deploySchema.go

+14-11
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ func (cfg *Config) DeploySchemaWithOps(ops DeploySchemaOptions) (err error) {
110110
connection := cfg.Connection()
111111

112112
//Run each deploy query.
113-
cfg.debugPrintln("sqldb.DeploySchema", "Running DeployQueries...")
113+
cfg.infoPrintln("sqldb.DeploySchema", "Running DeployQueries...")
114114
for _, q := range cfg.DeployQueries {
115115
//Translate the query if needed. This will only translate queries with
116116
//CREATE TABLE in the text.
@@ -120,10 +120,10 @@ func (cfg *Config) DeploySchemaWithOps(ops DeploySchemaOptions) (err error) {
120120
if strings.Contains(q, "CREATE TABLE") {
121121
idx := strings.Index(q, "(")
122122
if idx > 0 {
123-
cfg.debugPrintln(strings.TrimSpace(q[:idx]) + "...")
123+
cfg.infoPrintln(strings.TrimSpace(q[:idx]) + "...")
124124
}
125125
} else {
126-
cfg.debugPrintln(q)
126+
cfg.infoPrintln(q)
127127
}
128128

129129
//Execute the query. Always log on error so users can identify query that has
@@ -136,35 +136,38 @@ func (cfg *Config) DeploySchemaWithOps(ops DeploySchemaOptions) (err error) {
136136
return
137137
}
138138
}
139-
cfg.debugPrintln("sqldb.DeploySchema", "Running DeployQueries...done")
139+
cfg.infoPrintln("sqldb.DeploySchema", "Running DeployQueries...done")
140140

141141
//Run each deploy func.
142-
cfg.debugPrintln("sqldb.DeploySchema", "Running DeployFuncs...")
142+
cfg.infoPrintln("sqldb.DeploySchema", "Running DeployFuncs...")
143143
for _, f := range cfg.DeployFuncs {
144144
//Get function name for diagnostics.
145145
rawNameWithPath := runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
146146
funcName := path.Base(rawNameWithPath)
147147

148148
//Log out some info about the func being run for diagnostics.
149-
cfg.debugPrintln(funcName)
149+
cfg.infoPrintln(funcName)
150150

151151
//Execute the func. Always log on error so users can identify func that has
152152
//an error. Connection always gets closed since an error occured.
153153
innerErr := f(connection)
154154
if innerErr != nil {
155155
err = innerErr
156-
log.Println("sqldb.DeploySchema()", "Error with func.", funcName)
156+
cfg.errorPrintln("sqldb.DeploySchema", "Error with DeployFunc.", funcName)
157157
cfg.Close()
158158
return innerErr
159159
}
160160
}
161-
cfg.debugPrintln("sqldb.DeploySchema", "Running DeployFuncs...done")
161+
cfg.infoPrintln("sqldb.DeploySchema", "Running DeployFuncs...done")
162162

163+
//Close the connection to the database, if needed. We want to keep the connection
164+
//open mostly for tests since tests might use an in-memory database (SQLite) and
165+
//if the connection is closed the database gets wiped away.
163166
if ops.CloseConnection {
164-
//Close() is handled by defer above.
165-
cfg.debugPrintln("sqldb.DeploySchema()", "Connection closed after success.")
167+
cfg.Close()
168+
cfg.debugPrintln("sqldb.DeploySchema", "Connection closed after success.")
166169
} else {
167-
cfg.debugPrintln("sqldb.DeploySchema()", "Connection left open after success.")
170+
cfg.debugPrintln("sqldb.DeploySchema", "Connection left open after success.")
168171
}
169172

170173
return

sqldb-logging.go

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package sqldb
2+
3+
import "log"
4+
5+
//This file specifically deals with logging. See the config LoggingLevel field.
6+
7+
// errorPrintLn performs log.Println if LoggingLevel is set to LogLevelError or a
8+
// higher logging level.
9+
func (cfg *Config) errorPrintln(v ...any) {
10+
if cfg.LoggingLevel >= LogLevelError {
11+
log.Println(v...)
12+
}
13+
}
14+
15+
// infoPrintLn performs log.Println if LoggingLevel is set to LogLevelInfo or a
16+
// higher logging level.
17+
func (cfg *Config) infoPrintln(v ...any) {
18+
if cfg.LoggingLevel >= LogLevelInfo {
19+
log.Println(v...)
20+
}
21+
}
22+
23+
// debugPrintLn performs log.Println if LoggingLevel is set to LogLevelDebug or a
24+
// higher logging level.
25+
func (cfg *Config) debugPrintln(v ...any) {
26+
if cfg.LoggingLevel >= LogLevelDebug {
27+
log.Println(v...)
28+
}
29+
}

sqldb-mssql.go

-2
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,6 @@ func NewMSSQLConfig(host string, port uint, name, user, password string) (cfg *C
1515
cfg.User = user
1616
cfg.Password = password
1717

18-
cfg.ConnectionOptions = make(map[string]string)
19-
2018
return
2119
}
2220

sqldb-mysql.go

-2
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,6 @@ func NewMySQLConfig(host string, port uint, name, user, password string) (cfg *C
1515
cfg.User = user
1616
cfg.Password = password
1717

18-
cfg.ConnectionOptions = make(map[string]string)
19-
2018
return
2119
}
2220

sqldb-sqlite.go

-2
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,6 @@ func NewSQLiteConfig(pathToFile string) (cfg *Config) {
3939
cfg.SQLitePragmas = sqliteDefaultPragmas
4040
cfg.UseDefaultTranslateFuncs()
4141

42-
cfg.ConnectionOptions = make(map[string]string)
43-
4442
return
4543
}
4644

sqldb-updateSchema.go

+35-32
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ func (cfg *Config) UpdateSchemaWithOps(ops UpdateSchemaOptions) (err error) {
7979
defer tx.Rollback()
8080

8181
//Run each update query.
82-
cfg.debugPrintln("sqldb.UpdateSchema", "Running UpdateQueries...")
82+
cfg.infoPrintln("sqldb.UpdateSchema", "Running UpdateQueries...")
8383
for _, q := range cfg.UpdateQueries {
8484
//Translate the query if needed. This will only translate queries with
8585
//CREATE TABLE in the text.
@@ -93,10 +93,10 @@ func (cfg *Config) UpdateSchemaWithOps(ops UpdateSchemaOptions) (err error) {
9393
if strings.Contains(q, "CREATE TABLE") {
9494
idx := strings.Index(q, "(")
9595
if idx > 0 {
96-
cfg.debugPrintln(strings.TrimSpace(q[:idx]) + "...")
96+
cfg.infoPrintln(strings.TrimSpace(q[:idx]) + "...")
9797
}
9898
} else {
99-
cfg.debugPrintln(q)
99+
cfg.infoPrintln(q)
100100
}
101101

102102
//Execute the query. Always log on error so users can identify query that has
@@ -109,29 +109,29 @@ func (cfg *Config) UpdateSchemaWithOps(ops UpdateSchemaOptions) (err error) {
109109
return
110110
}
111111
}
112-
cfg.debugPrintln("sqldb.UpdateSchema", "Running UpdateQueries...done")
112+
cfg.infoPrintln("sqldb.UpdateSchema", "Running UpdateQueries...done")
113113

114114
//Run each update func.
115-
cfg.debugPrintln("sqldb.UpdateSchema", "Running UpdateFuncs...")
115+
cfg.infoPrintln("sqldb.UpdateSchema", "Running UpdateFuncs...")
116116
for _, f := range cfg.UpdateFuncs {
117117
//Get function name for diagnostics.
118118
rawNameWithPath := runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
119119
funcName := path.Base(rawNameWithPath)
120120

121121
//Log out some info about the func being run for diagnostics.
122-
cfg.debugPrintln(funcName)
122+
cfg.infoPrintln(funcName)
123123

124124
//Execute the func. Always log on error so users can identify func that has
125125
//an error. Connection always gets closed since an error occured.
126126
innerErr := f(tx)
127127
if innerErr != nil {
128128
err = innerErr
129-
log.Println("sqldb.UpdateSchema()", "Error with func.", funcName)
129+
cfg.errorPrintln("sqldb.UpdateSchema", "Error with UpdateFunc.", funcName)
130130
cfg.Close()
131131
return innerErr
132132
}
133133
}
134-
cfg.debugPrintln("sqldb.UpdateSchema", "Running UpdateFuncs...done")
134+
cfg.infoPrintln("sqldb.UpdateSchema", "Running UpdateFuncs...done")
135135

136136
//Commit transaction now that all UpdateQueries have been run successfully.
137137
err = tx.Commit()
@@ -140,8 +140,11 @@ func (cfg *Config) UpdateSchemaWithOps(ops UpdateSchemaOptions) (err error) {
140140
return
141141
}
142142

143+
//Close the connection to the database, if needed. We want to keep the connection
144+
//open mostly for tests since tests might use an in-memory database (SQLite) and
145+
//if the connection is closed the database gets wiped away.
143146
if ops.CloseConnection {
144-
//Close() is handled by defer above.
147+
cfg.Close()
145148
cfg.debugPrintln("sqldb.UpdateSchama", "Connection closed after success.")
146149
} else {
147150
cfg.debugPrintln("sqldb.UpdateSchama", "Connection left open after success.")
@@ -172,13 +175,13 @@ func UpdateSchema() (err error) {
172175
}
173176

174177
// ignoreUpdateSchemaErrors handles when an error is returned from an UpdateQuery when
175-
// run from UpdateSchema(). This is used to handle queries that can fail and aren't really
176-
// an error (i.e.: adding a column that already exists). Excusable errors can happen
177-
// because UpdateQueries should be able to run more than once (i.e.: if you run UpdateSchema()
178-
// each time your app starts).
178+
// run from UpdateSchema(). This is used to handle queries that can fail and aren't
179+
// really an error (i.e.: adding a column that already exists). Excusable errors can
180+
// happen because UpdateQueries should be able to run more than once (i.e.: if you run
181+
// UpdateSchema() each time your app starts).
179182
//
180-
// The query to update the schema is passed in so that we can check what an error is in
181-
// relation to. Sometimes the error returned doesn't provide enough context.
183+
// The query to update the schema is passed in so that we can check what an error is
184+
// in relation to. Sometimes the error returned doesn't provide enough context.
182185
func (cfg *Config) ignoreUpdateSchemaErrors(query string, err error) bool {
183186
//make sure an error was provided
184187
if err == nil {
@@ -199,17 +202,17 @@ func (cfg *Config) ignoreUpdateSchemaErrors(query string, err error) bool {
199202
}
200203

201204
// UpdateIgnoreErrorFunc is function for handling errors returned when trying to update
202-
// the schema of your database using UpdateSchema(). The query being run, as well as the
203-
// error from running the query, are passed in so that the function can determine if this
204-
// error can be ignored for this query. Each function of this type, and used for this
205-
// purpose should be very narrowly focused so as not to ignore errors by mistake (false
206-
// positives).
205+
// the schema of your database using UpdateSchema(). The query being run, as well as
206+
// the error from running the query, are passed in so that the function can determine
207+
// if this error can be ignored for this query. Each function of this type, and used
208+
// for this purpose should be very narrowly focused so as not to ignore errors by
209+
// mistake (false positives).
207210
type UpdateIgnoreErrorFunc func(Config, string, error) bool
208211

209-
// UFAddDuplicateColumn checks if an error was generated because a column already exists.
210-
// This typically happens because you are rerunning UpdateSchema() and the column has
211-
// already been added. This error can be safely ignored since a duplicate column won't
212-
// be create.
212+
// UFAddDuplicateColumn checks if an error was generated because a column already
213+
// exists. This typically happens because you are rerunning UpdateSchema() and the
214+
// column has already been added. This error can be safely ignored since a duplicate
215+
// column won't be create.
213216
func UFAddDuplicateColumn(c Config, query string, err error) bool {
214217
addCol := strings.Contains(strings.ToUpper(query), "ADD COLUMN")
215218
dup := strings.Contains(strings.ToLower(err.Error()), "duplicate column")
@@ -222,9 +225,9 @@ func UFAddDuplicateColumn(c Config, query string, err error) bool {
222225
return false
223226
}
224227

225-
// UFDropUnknownColumn checks if an error from was generated because a column does not exist.
226-
// This typically happens because you are rerunning UpdateSchema() and the column has
227-
// already been dropped. This error can be safely ignored in most cases.
228+
// UFDropUnknownColumn checks if an error from was generated because a column does not
229+
// exist. This typically happens because you are rerunning UpdateSchema() and the
230+
// column has already been dropped. This error can be safely ignored in most cases.
228231
func UFDropUnknownColumn(c Config, query string, err error) bool {
229232
dropCol := strings.Contains(strings.ToUpper(query), "DROP COLUMN")
230233

@@ -244,12 +247,12 @@ func UFDropUnknownColumn(c Config, query string, err error) bool {
244247

245248
// UFModifySQLiteColumn checks if an error occured because you are trying to modify a
246249
// column for a SQLite database. SQLite does not allow modifying columns. In this case,
247-
// we just ignore the error. This is ok since SQLite allows you to store any type of value
248-
// in any column.
250+
// we just ignore the error. This is ok since SQLite allows you to store any type of
251+
// value in any column.
249252
//
250-
// To get around this error, you should create a new table with the new schema, copy the
251-
// old data to the new table, delete the old table, and rename the new table to the old
252-
// table.
253+
// To get around this error, you should create a new table with the new schema, copy
254+
// the old data to the new table, delete the old table, and rename the new table to
255+
// the old table.
253256
func UFModifySQLiteColumn(c Config, query string, err error) bool {
254257
//ignore queries that modify a column for sqlite dbs
255258
if strings.Contains(strings.ToUpper(query), "MODIFY COLUMN") && c.Type == DBTypeSQLite {

0 commit comments

Comments
 (0)