jmoiron / modl

golang database modelling library
MIT License
479 stars 48 forks source link

Added TableNameMapper to modl #11

Closed silasdavis closed 10 years ago

silasdavis commented 10 years ago

modl uses sqlx's NameMapper function to map struct field names to database columns.

This is a nice feature, but it currently also uses NameMapper to map struct type names to database table names. This is a bit of an abuse of sqlx.NameMapper. See the docs from sqlx (it says the function is for column names, not table names):

// NameMapper is used to map column names to struct field names.  By default,
// it uses strings.ToLower to lowercase struct field names.  It can be set
// to whatever you want, but it is encouraged to be set before sqlx is used
// as field-to-name mappings are cached after first use on a type.
var NameMapper = strings.ToLower

We may have (probably do have) different conventions for mapping struct types to tables names, so this pull request introduces a TableNameMapper function in modl (I considered adding to sqlx, but decided it didn't belong there since I don't think sqlx deals with mapping to tables (it already has the rows).

It doesn't change any functionality until you set it. For example I have:

import (
    "github.com/jmoiron/sqlx"
    "bitbucket.org/pkg/inflect"
    "code.google.com/p/go-uuid/uuid"
    "errors"
    "fmt"
    "github.com/silasdavis/modl"
    "reflect"
)

func init(){
    sqlx.NameMapper = inflect.Underscore
    modl.TableNameMapper = func(word string) string { return inflect.Underscore(inflect.Pluralize(word)) }
}

Which means I can use modl's AddTable rather than AddTableWithName which is repetitive given I am following a naming convention.

jmoiron commented 10 years ago

I like this. It makes me wish I'd have thought to name sqlx's ColumnNameMapper.