Documentation ¶
Index ¶
- Constants
- func GenerateInit(structName, shortName string) string
- func GenerateModel(structPtr interface{}, shortName string) string
- func GenerateModelTest(structPtr interface{}, shortName string) string
- func GenerateSchema(structPtr interface{}) string
- func GetColumnName(modPtr interface{}, colName string) string
- func InitFromEnvVars()
- func InitMigration(isDefault bool) error
- func IsTableExistsError(err error) bool
- func IsUniqueViolationError(err error) bool
- func MakeOrderBy(modelPtr interface{}, sortBy string) (orderField, direction string, ok bool)
- func PathExists(path string) bool
- func RegisterMigrationPath(migrationPath string) error
- type Adapter
- func (a *Adapter) Count(model interface{}, opts ...sqlq.Option) (int, error)
- func (a *Adapter) Delete(structPtr interface{}) error
- func (a *Adapter) DeleteRows(structPtr interface{}, opts ...sqlq.Option) (int64, error)
- func (a *Adapter) Get(structPtr interface{}, opts ...sqlq.Option) (found bool, err error)
- func (a *Adapter) Insert(structPtrs ...interface{}) (sql.Result, error)
- func (a *Adapter) MustCount(model interface{}, opts ...sqlq.Option) int
- func (a *Adapter) MustDelete(structPtr interface{})
- func (a *Adapter) MustDeleteRows(structPtr interface{}, opts ...sqlq.Option) int64
- func (a *Adapter) MustGet(structPtr interface{}, opts ...sqlq.Option) bool
- func (a *Adapter) MustInsert(structPtrs ...interface{}) sql.Result
- func (a *Adapter) MustSelect(structPtr interface{}, opts ...sqlq.Option)
- func (a *Adapter) MustUpdate(structPtr interface{})
- func (a *Adapter) MustUpdateRows(structPtr interface{}, dataMap Map, opts ...sqlq.Option) int64
- func (a *Adapter) Select(destSlicePtr interface{}, opts ...sqlq.Option) error
- func (a *Adapter) Update(structPtr interface{}) error
- func (a *Adapter) UpdateRows(structPtr interface{}, dataMap Map, opts ...sqlq.Option) (int64, error)
- type ConnectVals
- type Connection
- type DB
- func (db *DB) Begin() (*sql.Tx, error)
- func (db *DB) CreateTable(structPtr interface{}) error
- func (db *DB) ExecFile(fileName string) error
- func (db *DB) ExecuteMigration(version string) error
- func (db *DB) InitSchema(execDefault bool) error
- func (db *DB) MustCreateTable(structPtr interface{})
- func (db *DB) PrintVersionStatus() error
- func (db *DB) Reset() error
- func (db *DB) Rollback(version string) error
- func (db *DB) RollbackLatest() error
- func (db *DB) UpdateSchema(execDefault bool) error
- type Map
- type MigrationHandler
- type MigrationLog
- type SchemaMigration
Examples ¶
Constants ¶
const ( // NAMES of variables NOT to be confused with their values // Compare to ConnectVals which is the final product of this file EnvHost = "MYSQL_HOST" EnvPort = "MYSQL_PORT" EnvDBName = "MYSQL_DB_NAME" EnvUserName = "MYSQL_USER_NAME" EnvPassword = "MYSQL_PASSWORD" EnvMigrationPath = "MYSQL_MIGRATION_PATH" EnvUseTLS = "MYSQL_USE_TLS" MaxPort = 65535 // 2^16 - 1 )
const ( VersionTimeFormat = "2006-01-02:15:04:05" // DefaultVersion is used for keeping the default schema that we don't want to execute (but still can if needed) DefaultVersion = "0000-00-00:00:00:00" )
const (
LimitInsert = 1000
)
Limits for db ops.
Variables ¶
This section is empty.
Functions ¶
func GenerateInit ¶
This will be (probably) only used by our mwcmd to create this stub for doing other generation. There is not an easy way to dynamically generate things from structs like in other languages
func GenerateModel ¶
Get the create SQL statement which is generally the most useful since we need to add this to a schema migration file.
Example ¶
package main import ( "fmt" "time" mw "github.com/cliqueinc/mysql-wear" ) // Example email struct used for generating sql, model, test type Email struct { ID string EmailID string RejectionReason string `mw:nullable` Sent time.Time Created time.Time Updated time.Time } func main() { fmt.Println(mw.GenerateSchema(&Email{})) fmt.Println(mw.GenerateModel(&Email{}, "email")) fmt.Println(mw.GenerateModelTest(&Email{}, "email")) }
Output:
func GenerateModelTest ¶
func GenerateSchema ¶
func GenerateSchema(structPtr interface{}) string
GenerateSchema generates table schema from struct model.
func GetColumnName ¶
GetColumnName returns the column name with prepending table name.
func InitMigration ¶
InitMigration generates new migration file.
func IsTableExistsError ¶
IsTableExistsError checks whether an error is table already exists error.
func IsUniqueViolationError ¶
func MakeOrderBy ¶
MakeOrderBy makes "order by" sql clause by parsing incoming field string and model type. Field string is expected to be either struct field name, or underscored pg column name, For "userID" field name the output will be "order by user_id asc", for the field with "-" prefix, like "-userID", the output is "order by user_id desc". if there is no userID (or UserID, userid etc) field in struct, or no user_id column name, empty string returned.
func PathExists ¶
func RegisterMigrationPath ¶
RegisterMigrationPath registers migration path for performing migration operations.
Types ¶
type Adapter ¶
type Adapter struct {
// contains filtered or unexported fields
}
Adapter handles basic operations with mysql.
func Wrap ¶
func Wrap(con Connection) *Adapter
Wrap wraps connection for dealing with select, insert, delete operaion Connection can be one of *sql.DB, *sql.Tx.
func (*Adapter) DeleteRows ¶
DeleteRows deletes rows by specified options. Returns number of affected rows. In case when you really need to update all rows (e.g. migration script), you need to pass mw.QueryAll() option. It is done to avoid unintentional update of all rows.
func (*Adapter) Insert ¶
Insert inserts one or more struct into db. If no options specied, struct will be updated by primary key. Limit of items to insert at once is 1000 items.
func (*Adapter) MustDelete ¶
func (a *Adapter) MustDelete(structPtr interface{})
MustDelete ensures struct will be deleted without errors, panics othervise.
func (*Adapter) MustDeleteRows ¶
MustDeleteRows ensures rows are deleted without errors, panics othervise. Returns number of affected rows. In case when you really need to update all rows (e.g. migration script), you need to pass mw.QueryAll() option. It is done to avoid unintentional update of all rows.
func (*Adapter) MustInsert ¶
MustInsert ensures structs are inserted without errors, panics othervise. Limit of items to insert at once is 1000 items.
func (*Adapter) MustSelect ¶
MustSelect ensures select will not produce any error, panics othervise.
func (*Adapter) MustUpdate ¶
func (a *Adapter) MustUpdate(structPtr interface{})
MustUpdate ensures struct will be updated without errors, panics othervise.
func (*Adapter) MustUpdateRows ¶
MustUpdateRows ensures rows are updated without errors, panics othervise. Returns number of affected rows. In case when you really need to update all rows (e.g. migration script), you need to pass mw.QueryAll() option. It is done to avoid unintentional update of all rows.
func (*Adapter) Select ¶
Select performs select using query options. If no options specified, all rows will be returned. destSlicePtr parameter expects pointer to a slice
func (*Adapter) UpdateRows ¶
func (a *Adapter) UpdateRows(structPtr interface{}, dataMap Map, opts ...sqlq.Option) (int64, error)
UpdateRows updates rows with specified map data by query, returns number of affected rows. In case when you really need to update all rows (e.g. migration script), you need to pass mw.QueryAll() option. It is done to avoid unintentional update of all rows.
type ConnectVals ¶
type ConnectVals struct { Host string UnixSocket string // Supersedes tcp connection Port int DBName string UserName string Password string // Required for InitWithSchema MigrationPath string UseTLS bool // Should default to true }
ConnectVals hold connection info for mysql UnixSocket should be a full path like for CloudSQL: /cloudsql/PROJECT_ID:REGION_ID:INSTANCE_ID
func ReadEnvFile ¶
func ReadEnvFile(fileName string) (*ConnectVals, error)
Use a very simple .mysqlenv file
func (ConnectVals) TLS ¶
func (cv ConnectVals) TLS() string
type Connection ¶
type DB ¶
DB is a wrapper around standard sql db that also wraps common sql opperations.
func InitOnly ¶
func InitOnly(cv ConnectVals) (*DB, error)
InitOnly simply creates the connection to mysql and doesn't mess with schema updates at all
func InitWithSchema ¶
func InitWithSchema(cv ConnectVals) (*DB, error)
Init mysql, mw, load and update any schema
func New ¶
New initializes new mysql-wear client assuming that sql connection already has been configured. Use this when you want to manually configure your mysql connection string (not recommended)
func (*DB) CreateTable ¶
CreateTable creates table from struct.
func (*DB) ExecuteMigration ¶
ExecuteMigration executes particular migration.
func (*DB) InitSchema ¶
Set up mw schema migration on a new mysql database without mw_schema_migration OR mw_migration_log tables. We'll fail if either exists.
Passing execDefault=true will run the default schema 000-00-00:00:00:00.sql
func (*DB) MustCreateTable ¶
func (db *DB) MustCreateTable(structPtr interface{})
MustCreateTable ensures table is created from struct.
func (*DB) PrintVersionStatus ¶
TODO print the version and latest X logs in a less retarded way
func (*DB) RollbackLatest ¶
RollbackLatest rollbacks latest migration.
func (*DB) UpdateSchema ¶
UpdateSchema updates schema in case if new migrations appear. if execDefault param is set to true, default schema will be executed if exists.
type Map ¶
type Map map[string]interface{}
Map is a short representation of map[string]interface{}, used in adapter ops.
type MigrationHandler ¶
type MigrationHandler struct { // migration paht is used to determine absolute path to each migration so mw cmd tool may be called from everywhere. // If not set, relative path is used to find migration file. MigrationPath string // contains filtered or unexported fields }
migrationHandler handles all db migrations.
func (*MigrationHandler) MigrationVersions ¶
func (h *MigrationHandler) MigrationVersions() []string
MigrationVersions returns slice of sorted migration versions.
func (*MigrationHandler) RegisterMigration ¶
func (h *MigrationHandler) RegisterMigration(name string, upSQL, downSQL string)
RegisterMigration registers migration to process during migration update.
type MigrationLog ¶
type MigrationLog struct { Action string Created time.Time ID int `mw:"pk"` Message string Success bool Version string }
MigrationLog tracks all migration activity.
func NewLog ¶
func NewLog(action, message string, version string) *MigrationLog
If this wasn't successful, manually set that fact after calling this
func (MigrationLog) TableName ¶
func (mwsv MigrationLog) TableName() string
type SchemaMigration ¶
SchemaMigration tracks all performed migrations.
func (SchemaMigration) TableName ¶
func (SchemaMigration) TableName() string