eaigner / hood

Database agnostic ORM for Go
MIT License
710 stars 52 forks source link

Add ability to define foreign keys in models #67

Open adam-frisby opened 11 years ago

adam-frisby commented 11 years ago

Adds a ForeignKeyed interface similar to the Index interface for defining foreign keys in models. (It only supports single column foreign keys)


Example Schemas

type User struct {
    Id   hood.Id
    Name string
}

type Post struct {
    Id      hood.Id
    Content string
    UserId  int64
}

func (table *Post) ForeignKeys(foreignKeys *hood.ForeignKeys) {
    foreignKeys.Add("test_fk", "user_id", "user", "id", hood.Cascade, hood.Cascade)
}

I added a ReferentialAction type. Cascase, Restrict, NoAction, and SetNull are constants defined. It follows the same pattern that Join does.

The function signature for foreignKeys.Add is

Add(name string, column string, referenceTable string, referenceColumn string, onUpdate ReferentialAction, onDelete ReferentialAction)

name: Name of foreign key constraint column: The column in the table/model to create the foreign key on referenceTable: The name of the table with the column the foreign key will reference referenceColumn: The column in the referenceTable the foreign key will reference

Two functions were added to dialect.go: ForeignKey and ReferentialAction.

Foreign keys are created when the table is created.