fkey:

“fkey:” Overview

Sqac annotated go structs are used to supply the sqac runtime with the information required to create and alter tables in the database. The following examples illustrate the use of the “fkey:” ‘sqac:’ tag described in the Sqac Tag Overview section of this document.

The “fkey:” tag is used to declare a foreign key for a column in the source go struct. Declaration of a foreign-key results in a foreign-key constraint on the assigned column, thereby limiting its allowable values to those found in the table.column referenced in the foreign-key declaration.

“fkey:<ftable_name>(<fcolumn_name>)” Overview

The following example illustrates the use of the “fkey:” tag to declare a foreign key for table column product.warehouse_id. Following the creation of tables “warehouse” and “product”, the foreign-key constraints in the model will be evaluated by the sqac runtime. Both tables must exist in the database in order for the creation of the new constraint to be possible.

Once the foreign-key constraint has been created on column product.warehouse_id, it will only permit values that exist in table column warehouse.id.

type Warehouse struct {
    ID       uint64 `db:"id" json:"id" sqac:"primary_key:inc;start:40000000"`
    City     string `db:"city" json:"city" sqac:"nullable:false;default:Calgary"`
    Quadrant string `db:"quadrant" json:"quadrant" sqac:"nullable:false;default:SE"`
}

type Product struct {
    ID          uint64 `db:"id" json:"id" sqac:"primary_key:inc;start:95000000"`
    ProductName string `db:"product_name" json:"product_name" sqac:"nullable:false;default:unknown"`
    ProductCode string `db:"product_code" json:"product_code" sqac:"nullable:false;default:0000-0000-00"`
    UOM         string `db:"uom" json:"uom" sqac:"nullable:false;default:EA"`
    // foreign-key declared against table "warehouse", column "id"
    WarehouseID uint64 `db:"warehouse_id" json:"warehouse_id" sqac:"nullable:false;fkey:warehouse(id)"`
}

Sqac Foreign-Key Naming Standard

By sqac convention, foreign-keys will be created using the following naming standard:

“fk_product_warehouse_id” which equates to:

**“fk_<from_table>_<ref_table>_<ref_table_key_column>”**