initialize database if table doesn't exist
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
This commit is contained in:
parent
022327d539
commit
bb4112e145
@ -86,3 +86,31 @@ func (conf Configuration) Connect() (*Connection, error) {
|
|||||||
|
|
||||||
return conn, nil
|
return conn, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// InitializeDatabase will check if tables exist in the database, and if not then create them.
|
||||||
|
func (conn Connection) InitializeDatabase() error {
|
||||||
|
rows, err := conn.DB.Query(`SHOW TABLES`)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("SHOW TABLES query failed: %v", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
if rows.Next() { // Table already exists, leave with no error
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Table does not exist, create it
|
||||||
|
_, err = conn.DB.Exec(`CREATE TABLE visit (
|
||||||
|
id int(11) NOT NULL AUTO_INCREMENT,
|
||||||
|
ip_address varchar(15) NOT NULL,
|
||||||
|
visits int(11) NOT NULL,
|
||||||
|
last_visited datetime NOT NULL,
|
||||||
|
PRIMARY KEY (id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=latin1;`)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to create table: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
7
main.go
7
main.go
@ -57,6 +57,13 @@ func init() {
|
|||||||
log.Fatalf("failed to connect to database: %v", err)
|
log.Fatalf("failed to connect to database: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check if database needs to be initialized (create tables)
|
||||||
|
// does nothing if tables exist
|
||||||
|
err = dbConn.InitializeDatabase()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("failed to initialize database: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
uniqueVisits, err = dbConn.GetUniqueVisits()
|
uniqueVisits, err = dbConn.GetUniqueVisits()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("failed to get number of unique visits from database: %v", err)
|
log.Fatalf("failed to get number of unique visits from database: %v", err)
|
||||||
|
Loading…
Reference in New Issue
Block a user