I'm using sqlx to connect my MySQL database to Golang. I've got an SQL schema where all the CREATE TABLE IF NOT EXISTS...
statements are defined. Here an example:
CREATE TABLE IF NOT EXISTS `users`
(
`id` INT(0) NOT NULL auto_increment,
`language_code` VARCHAR(5) NOT NULL,
`premium` BIT(0) DEFAULT 0,
`status` VARCHAR(100) NOT NULL DEFAULT '',
`user_id` INT(0) NOT NULL,
PRIMARY KEY (id)
);
...
Here how I connect to database and I execute all the queries everytime:
Database, err = sqlx.Connect(Config.Database.Type, Config.Database.DataSourceString) // Connect to the database
if err != nil { // If there's an error, handle it
panic(err.Error())
}
defer Database.Close() // Close the database when the function finishes
schemaSQL, err := ioutil.ReadFile("schema.sql") // Read the configuration file (DealsFinderBot/config.yaml)
if err != nil { // If there's an error, handle it
panic(err.Error())
}
for _, query := range strings.Split(string(schemaSQL), ";") { // Loop on the queries of the schema
if strings.TrimSpace(query) != "" { // If the query is not empty
Database.MustExec(query) // Execute the query
}
}
I would like to update every time (alter a table) everytime I add a new column or I edit some parameters (like NOT NULL
or DEFAULT ''
). How could I do this?