Gonzalez
Gonzalez

Reputation: 711

Error when trying to create tables from model

I started to play with gorm today but to bad came across some silly error and am stuck on it for a while. At first I am on windows and run MySQL 5 (5.0.51b) and latest version of go. I did go get for gorm and mysql driver and it compiles without an error and is able to connect (likely), but whenever I try to create a table based on declared type it throws an error which isn't informative (because the error is thrown by MySQL). Here is my code:

mport (
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "github.com/jinzhu/gorm"
)

type User struct {
    id int
}

func main() {
    db, err := gorm.Open("mysql", "root:vertrigo@/shop?charset=utf8&parseTime=True&loc=Local")
    fmt.Println(err)

    a := db.Set("gorm:table_options", "ENGINE=InnoDB").CreateTable(&User{})

    fmt.Println(a)
}

So the model is aimed to be very basic, e.g. a table with one column. Now comes the output:

< nil > &{0x111e2230 Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') ENGINE=InnoDB' at line 1 0 0x112d4060 0x112d4000 0x112d8140 0 {0x112a3f20} false map[gorm:table_options:ENGINE=InnoDB] map[]}

The first is a connection error which means it's able to connect but with the query it's not that good and the error says almost nothing other than SQL generated by gorm fails for some reason. So the question is if some one has an idea why the error is thrown and if there is any solution.

Upvotes: 0

Views: 1372

Answers (1)

Mark
Mark

Reputation: 7091

That error occurs when trying to create an empty table, eg:

create table User() ENGINE=InnoDB

gorm generates an empty table statement because the id field of the User struct is private.

Change id int to ID int. Capitalising the first letter of a struct field exposes it to external packages.


As a secondary issue, instead of just printing the error:

db, err := gorm.Open(...
fmt.Println(err)

it's a good idea to check every potential error, and deal with them immediately:

db, err := gorm.Open(...
if err != nil {
    log.Fatal(err)
}

For other errors, gorm's error handling is a little unusual compared to most go code. You'll probably want to frequently check for errors using db.GetErrors().

Upvotes: 1

Related Questions