Skip to content

Commit f74cece

Browse files
authored
Merge pull request #4 from furusax0621/refactor
Refactor
2 parents fc09c88 + ba4df3d commit f74cece

File tree

10 files changed

+79
-95
lines changed

10 files changed

+79
-95
lines changed

go.mod

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ require (
99
github.com/hashicorp/go-version v1.6.0
1010
github.com/icrowley/fake v0.0.0-20221112152111-d7b7e2276db2
1111
github.com/kr/pretty v0.3.1
12-
github.com/pkg/errors v0.9.1
1312
github.com/sirupsen/logrus v1.9.0
1413
gopkg.in/alecthomas/kingpin.v2 v2.2.6
1514
)

go.sum

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,6 @@ github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
2727
github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ=
2828
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
2929
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
30-
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
31-
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
3230
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
3331
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
3432
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=

internal/getters/date.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,7 @@ type RandomDateInRange struct {
4242
}
4343

4444
func (r *RandomDateInRange) Value() interface{} {
45-
rand.Seed(time.Now().UnixNano())
46-
var randomSeconds int64
47-
randomSeconds = rand.Int63n(oneYear) + rand.Int63n(100)
45+
randomSeconds := rand.Int63n(oneYear) + rand.Int63n(100)
4846
d := time.Now().Add(-1 * time.Duration(randomSeconds) * time.Second)
4947
return d
5048
}

internal/getters/datetime.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,14 @@ import (
77
)
88

99
type RandomDateTimeInRange struct {
10+
name string
1011
min string
1112
max string
1213
allowNull bool
1314
}
1415

1516
// Value returns a random time.Time in the range specified by the New method
1617
func (r *RandomDateTimeInRange) Value() interface{} {
17-
rand.Seed(time.Now().UnixNano())
1818
randomSeconds := rand.Int63n(oneYear)
1919
d := time.Now().Add(-1 * time.Duration(randomSeconds) * time.Second)
2020
return d
@@ -32,15 +32,15 @@ func (r *RandomDateTimeInRange) Quote() string {
3232
}
3333

3434
// NewRandomDateTimeInRange returns a new random date in the specified range
35-
func NewRandomDateTimeInRange(name string, min, max string, allowNull bool) *RandomDateInRange {
35+
func NewRandomDateTimeInRange(name string, min, max string, allowNull bool) *RandomDateTimeInRange {
3636
if min == "" {
3737
t := time.Now().Add(-1 * time.Duration(oneYear) * time.Second)
38-
min = t.Format("2006-01-02")
38+
min = t.Format("2006-01-02 15:03:04")
3939
}
40-
return &RandomDateInRange{name, min, max, allowNull}
40+
return &RandomDateTimeInRange{name, min, max, allowNull}
4141
}
4242

4343
// NewRandomDateTime returns a new random datetime between Now() and Now() - 1 year
44-
func NewRandomDateTime(name string, allowNull bool) *RandomDateInRange {
45-
return &RandomDateInRange{name, "", "", allowNull}
44+
func NewRandomDateTime(name string, allowNull bool) *RandomDateTimeInRange {
45+
return &RandomDateTimeInRange{name, "", "", allowNull}
4646
}

internal/getters/getters.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
package getters
22

3+
import (
4+
"math/rand"
5+
"time"
6+
)
7+
38
// All types defined here satisfy the Getter interface
49
// type Getter interface {
510
// Value() interface{}
@@ -12,3 +17,7 @@ const (
1217
oneYear = int64(60 * 60 * 24 * 365)
1318
NULL = "NULL"
1419
)
20+
21+
func init() {
22+
rand.Seed(time.Now().UnixMicro())
23+
}

main.go

Lines changed: 25 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ import (
1818
"github.com/gosuri/uiprogress"
1919
"github.com/kr/pretty"
2020

21-
log "github.com/sirupsen/logrus"
22-
kingpin "gopkg.in/alecthomas/kingpin.v2"
21+
"github.com/sirupsen/logrus"
22+
"gopkg.in/alecthomas/kingpin.v2"
2323
)
2424

2525
type cliOptions struct {
@@ -55,10 +55,7 @@ type mysqlOptions struct {
5555
}
5656

5757
var (
58-
opts *cliOptions
59-
60-
validFunctions = []string{"int", "string", "date", "date_in_range"}
61-
maxValues = map[string]int64{
58+
maxValues = map[string]int64{
6259
"tinyint": 0xF,
6360
"smallint": 0xFF,
6461
"mediumint": 0x7FFFF,
@@ -95,7 +92,7 @@ func main() {
9592

9693
opts, err := processCliParams()
9794
if err != nil {
98-
log.Fatal(err.Error())
95+
logrus.Fatal(err.Error())
9996
}
10097

10198
if *opts.Version {
@@ -134,36 +131,36 @@ func main() {
134131

135132
// SET TimeZone to UTC to avoid errors due to random dates & daylight saving valid values
136133
if _, err = db.Exec(`SET @@session.time_zone = "+00:00"`); err != nil {
137-
log.Printf("Cannot set time zone to UTC: %s\n", err)
134+
logrus.Printf("Cannot set time zone to UTC: %s\n", err)
138135
db.Close()
139136
os.Exit(1)
140137
}
141138

142139
table, err := tableparser.NewTable(db, *opts.Schema, *opts.TableName)
143140
if err != nil {
144-
log.Printf("cannot get table %s struct: %s", *opts.TableName, err)
141+
logrus.Printf("cannot get table %s struct: %s", *opts.TableName, err)
145142
db.Close()
146143
os.Exit(1)
147144
}
148145

149-
log.SetFormatter(&log.TextFormatter{FullTimestamp: true})
146+
logrus.SetFormatter(&logrus.TextFormatter{FullTimestamp: true})
150147
if *opts.Debug {
151-
log.SetLevel(log.DebugLevel)
148+
logrus.SetLevel(logrus.DebugLevel)
152149
*opts.NoProgress = true
153150
}
154-
log.Debug(pretty.Sprint(table))
151+
logrus.Debug(pretty.Sprint(table))
155152

156153
if len(table.Triggers) > 0 {
157-
log.Warnf("There are triggers on the %s table that might affect this process:", *opts.TableName)
154+
logrus.Warnf("There are triggers on the %s table that might affect this process:", *opts.TableName)
158155
for _, t := range table.Triggers {
159-
log.Warnf("Trigger %q, %s %s", t.Trigger, t.Timing, t.Event)
160-
log.Warnf("Statement: %s", t.Statement)
156+
logrus.Warnf("Trigger %q, %s %s", t.Trigger, t.Timing, t.Event)
157+
logrus.Warnf("Statement: %s", t.Statement)
161158
}
162159
}
163160

164161
if *opts.Rows < 1 {
165162
db.Close() // golint:noerror
166-
log.Warnf("Number of rows < 1. There is nothing to do. Exiting")
163+
logrus.Warnf("Number of rows < 1. There is nothing to do. Exiting")
167164
os.Exit(1)
168165
}
169166

@@ -183,7 +180,7 @@ func main() {
183180
}
184181

185182
if !*opts.Print {
186-
log.Info("Starting")
183+
logrus.Info("Starting")
187184
}
188185

189186
// Example: want 11 rows with bulksize 4:
@@ -198,7 +195,7 @@ func main() {
198195
remainder := *opts.Rows - count**opts.BulkSize
199196
semaphores := makeSemaphores(*opts.MaxThreads)
200197
rowValues := makeValueFuncs(db, table.Fields, *opts.Samples)
201-
log.Debugf("Must run %d bulk inserts having %d rows each", count, *opts.BulkSize)
198+
logrus.Debugf("Must run %d bulk inserts having %d rows each", count, *opts.BulkSize)
202199

203200
runInsertFunc := runInsert
204201
if *opts.Print {
@@ -220,14 +217,14 @@ func main() {
220217

221218
okCount, err := run(db, table, bar, semaphores, rowValues, count, *opts.BulkSize, runInsertFunc, newLineOnEachRow)
222219
if err != nil {
223-
log.Errorln(err)
220+
logrus.Errorln(err)
224221
}
225222
var okrCount, okiCount int // remainder & individual inserts OK count
226223
if remainder > 0 {
227-
log.Debugf("Must run 1 extra bulk insert having %d rows, to complete %d rows", remainder, *opts.Rows)
224+
logrus.Debugf("Must run 1 extra bulk insert having %d rows, to complete %d rows", remainder, *opts.Rows)
228225
okrCount, err = run(db, table, bar, semaphores, rowValues, 1, remainder, runInsertFunc, newLineOnEachRow)
229226
if err != nil {
230-
log.Errorln(err)
227+
logrus.Errorln(err)
231228
}
232229
}
233230

@@ -236,12 +233,12 @@ func main() {
236233
totalOkCount := okCount + okrCount
237234
retries := 0
238235
if totalOkCount < *opts.Rows {
239-
log.Debugf("Running extra %d individual inserts (duplicated keys?)", *opts.Rows-totalOkCount)
236+
logrus.Debugf("Running extra %d individual inserts (duplicated keys?)", *opts.Rows-totalOkCount)
240237
}
241238
for totalOkCount < *opts.Rows && retries < *opts.MaxRetries {
242239
okiCount, err = run(db, table, bar, semaphores, rowValues, *opts.Rows-totalOkCount, 1, runInsertFunc, newLineOnEachRow)
243240
if err != nil {
244-
log.Errorf("Cannot run extra insert: %s", err)
241+
logrus.Errorf("Cannot run extra insert: %s", err)
245242
}
246243

247244
retries++
@@ -250,7 +247,7 @@ func main() {
250247

251248
time.Sleep(500 * time.Millisecond) // Let the progress bar to update
252249
if !*opts.Print {
253-
log.Printf("%d rows inserted", totalOkCount)
250+
logrus.Printf("%d rows inserted", totalOkCount)
254251
}
255252
db.Close()
256253
}
@@ -370,7 +367,7 @@ func generateInsertStmt(table *tableparser.Table) string {
370367
func runInsert(db *sql.DB, insertQuery string, resultsChan chan int, sem chan bool, wg *sync.WaitGroup) {
371368
result, err := db.Exec(insertQuery)
372369
if err != nil {
373-
log.Debugf("Cannot run insert: %s", err)
370+
logrus.Debugf("Cannot run insert: %s", err)
374371
resultsChan <- 0
375372
sem <- true
376373
wg.Done()
@@ -379,7 +376,7 @@ func runInsert(db *sql.DB, insertQuery string, resultsChan chan int, sem chan bo
379376

380377
rowsAffected, err := result.RowsAffected()
381378
if err != nil {
382-
log.Errorf("Cannot get rows affected after insert: %s", err)
379+
logrus.Errorf("Cannot get rows affected after insert: %s", err)
383380
}
384381
resultsChan <- int(rowsAffected)
385382
sem <- true
@@ -399,7 +396,7 @@ func makeValueFuncs(conn *sql.DB, fields []tableparser.Field, samples int64) ins
399396
field.Constraint.ReferencedColumnName,
400397
samples, field.DataType)
401398
if err != nil {
402-
log.Printf("cannot get samples for field %q: %s\n", field.ColumnName, err)
399+
logrus.Printf("cannot get samples for field %q: %s\n", field.ColumnName, err)
403400
continue
404401
}
405402
values = append(values, getters.NewRandomSample(field.ColumnName, samples, field.IsNullable))
@@ -435,7 +432,7 @@ func makeValueFuncs(conn *sql.DB, fields []tableparser.Field, samples int64) ins
435432
case "binary", "varbinary":
436433
values = append(values, getters.NewRandomBinary(field.ColumnName, field.CharacterMaximumLength.Int64, field.IsNullable))
437434
default:
438-
log.Printf("cannot get field type: %s: %s\n", field.ColumnName, field.DataType)
435+
logrus.Printf("cannot get field type: %s: %s\n", field.ColumnName, field.DataType)
439436
}
440437
}
441438

main_test.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,17 @@ import (
99

1010
"github.com/furusax0621/mysql_random_data_load/internal/getters"
1111
"github.com/furusax0621/mysql_random_data_load/tableparser"
12-
tu "github.com/furusax0621/mysql_random_data_load/testutils"
12+
"github.com/furusax0621/mysql_random_data_load/testutils"
1313
)
1414

1515
func TestGetSamples(t *testing.T) {
16-
conn := tu.GetMySQLConnection(t)
16+
conn := testutils.GetMySQLConnection(t)
1717
var wantRows int64 = 100
1818
samples, err := getSamples(conn, "sakila", "inventory", "inventory_id", wantRows, "int")
19-
tu.Ok(t, err, "error getting samples")
19+
testutils.Ok(t, err, "error getting samples")
2020
_, ok := samples[0].(int64)
21-
tu.Assert(t, ok, "Wrong data type.")
22-
tu.Assert(t, int64(len(samples)) == wantRows,
21+
testutils.Assert(t, ok, "Wrong data type.")
22+
testutils.Assert(t, int64(len(samples)) == wantRows,
2323
"Wrong number of samples. Have %d, want 100.", len(samples))
2424
}
2525

@@ -64,18 +64,18 @@ func TestGenerateInsertData(t *testing.T) {
6464
generateInsertData(wantRows, values, rowsChan)
6565

6666
wg.Wait()
67-
tu.Assert(t, count == 3, "Invalid number of rows")
67+
testutils.Assert(t, count == 3, "Invalid number of rows")
6868
}
6969

7070
func TestGenerateInsertStmt(t *testing.T) {
7171
var table *tableparser.Table
72-
tu.LoadJson(t, "sakila.film.json", &table)
72+
testutils.LoadJson(t, "sakila.film.json", &table)
7373
want := "INSERT IGNORE INTO `sakila`.`film` " +
7474
"(`title`,`description`,`release_year`,`language_id`," +
7575
"`original_language_id`,`rental_duration`,`rental_rate`," +
7676
"`length`,`replacement_cost`,`rating`,`special_features`," +
7777
"`last_update`) VALUES "
7878

7979
query := generateInsertStmt(table)
80-
tu.Equals(t, want, query)
80+
testutils.Equals(t, want, query)
8181
}

tableparser/tableparser.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import (
99
"strings"
1010
"time"
1111

12-
"github.com/pkg/errors"
1312
log "github.com/sirupsen/logrus"
1413
)
1514

@@ -172,7 +171,7 @@ func (t *Table) parse() error {
172171

173172
cols, err := rows.Columns()
174173
if err != nil {
175-
return errors.Wrap(err, "Cannot get column names")
174+
return fmt.Errorf("cannot get column names: %w", err)
176175
}
177176

178177
for rows.Next() {
@@ -297,7 +296,7 @@ func getIndexes(db *sql.DB, schema, tableName string) (map[string]Index, error)
297296
}
298297
}
299298
if err := rows.Close(); err != nil {
300-
return nil, errors.Wrap(err, "Cannot close query rows at getIndexes")
299+
return nil, fmt.Errorf("cannot close query rows at getIndexes: %w", err)
301300
}
302301

303302
return indexes, nil

0 commit comments

Comments
 (0)