Categorygithub.com/env-io/orm
modulepackage
0.0.2
Repository: https://github.com/env-io/orm.git
Documentation: pkg.go.dev

# README

beego orm

Build Status

A powerful orm framework for go.

It is heavily influenced by Django ORM, SQLAlchemy.

Support Database:

Passed all test, but need more feedback.

Features:

  • full go type support
  • easy for usage, simple CRUD operation
  • auto join with relation table
  • cross DataBase compatible query
  • Raw SQL query / mapper without orm model
  • full test keep stable and strong

more features please read the docs

Install:

go get github.com/env-io/orm

Changelog

  • 2013-08-19: support table auto create
  • 2013-08-13: update test for database types
  • 2013-08-13: go type support, such as int8, uint8, byte, rune
  • 2013-08-13: date / datetime timezone support very well

Quick Start

Simple Usage

package main

import (
	"fmt"
	"github.com/env-io/orm"
	_ "github.com/go-sql-driver/mysql" // import your used driver
)

// Model Struct
type User struct {
	Id   int    `orm:"auto"`
	Name string `orm:"size(100)"`
}

func init() {
	// register model
	orm.RegisterModel(new(User))

	// set default database
	orm.RegisterDataBase("default", "mysql", "root:root@/my_db?charset=utf8", 30)

	// create table
	orm.RunSyncdb("default", false, true)
}

func main() {
	o := orm.NewOrm()

	user := User{Name: "slene"}

	// insert
	id, err := o.Insert(&user)

	// update
	user.Name = "astaxie"
	num, err := o.Update(&user)

	// read one
	u := User{Id: user.Id}
	err = o.Read(&u)

	// delete
	num, err = o.Delete(&u)
}

Next with relation

type Post struct {
	Id    int    `orm:"auto"`
	Title string `orm:"size(100)"`
	User  *User  `orm:"rel(fk)"`
}

var posts []*Post
qs := o.QueryTable("post")
num, err := qs.Filter("User__Name", "slene").All(&posts)

Use Raw sql

If you don't like ORM,use Raw SQL to query / mapping without ORM setting

var maps []Params
num, err := o.Raw("SELECT id FROM user WHERE name = ?", "slene").Values(&maps)
if num > 0 {
	fmt.Println(maps[0]["id"])
}

Transaction

o.Begin()
...
user := User{Name: "slene"}
id, err := o.Insert(&user)
if err == nil {
	o.Commit()
} else {
	o.Rollback()
}

Debug Log Queries

In development env, you can simple use

func main() {
	orm.Debug = true
...

enable log queries.

output include all queries, such as exec / prepare / transaction.

like this:

[ORM] - 2013-08-09 13:18:16 - [Queries/default] - [    db.Exec /     0.4ms] - [INSERT INTO `user` (`name`) VALUES (?)] - `slene`
...

note: not recommend use this in product env.

Docs

more details and examples in docs and test

documents

# Packages

No description provided by the author
No description provided by the author
No description provided by the author
Package migration is used for migration The table structure is as follow: CREATE TABLE `migrations` ( `id_migration` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'surrogate key', `name` varchar(255) DEFAULT NULL COMMENT 'migration name, unique', `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'date migrated or rolled back', `statements` longtext COMMENT 'SQL statements for this migration', `rollback_statements` longtext, `status` enum('update','rollback') DEFAULT NULL COMMENT 'update indicates it is a normal migration while rollback means this migration is rolled back', PRIMARY KEY (`id_migration`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;.
No description provided by the author
No description provided by the author

# Functions

AddAliasWthDB add a aliasName for the drivename.
AddGlobalFilterChain adds a new FilterChain All orm instances built after this invocation will use this filterChain, but instances built before this invocation will not be affected.
BootStrap bootstrap models.
ColValue do the field raw changes.
ConnMaxLifetime return a hint about ConnMaxLifetime.
GetDB Get *sql.DB from registered database by db alias name.
MaxIdleConnections return a hint about MaxIdleConnections.
MaxOpenConnections return a hint about MaxOpenConnections.
MaxStmtCacheSize return a hint about MaxStmtCacheSize.
NewCondition return new condition struct.
No description provided by the author
No description provided by the author
NewLog set io.Writer to create a Logger.
NewModelCacheHandler generator of _modelCache.
NewOrm create new orm.
NewOrmUsingDB create new orm with the name.
NewOrmWithDB create a new ormer object with specify *sql.DB for query.
NewQueryBuilder return the QueryBuilder.
RegisterDataBase Setting the database connect params.
RegisterDriver Register a database driver use specify driver name, this can be definition the driver is which database type.
RegisterModel register models.
RegisterModelWithPrefix register models with a prefix.
RegisterModelWithSuffix register models with a suffix.
ResetModelCache Clean model cache.
RunCommand listens for orm command and runs if command arguments have been passed.
RunSyncdb run syncdb command line.
SetDataBaseTZ Change the database default used timezone.
SetMaxIdleConns Change the max idle conns for *sql.DB, use specify database alias name Deprecated you should not use this, we will remove it in the future.
SetMaxOpenConns Change the max open conns for *sql.DB, use specify database alias name Deprecated you should not use this, we will remove it in the future.
SetNameStrategy set different name strategy.
ToInt64 interface to int64.
ToStr interface to string.

# Constants

define Col operations.
define Col operations.
define Col operations.
define Col operations.
define Col operations.
define Col operations.
define Col operations.
define Col operations.
define Col operations.
CommaSpace is the separation.
DebugQueries define the debug.
mysql.
oracle.
pgsql.
sqlite.
TiDB.
ExprSep define the expression separation.
Define some logic enum.
Define some logic enum.
Define some logic enum.
Define some logic enum.
Define the Type enum.
Define the Type enum.
Define the Type enum.
Define the Type enum.
Define the Type enum.
No description provided by the author
Define the Type enum.
Define the Type enum.
Define the Type enum.
Define the Type enum.
Define the Type enum.
Define the Type enum.
Define the Type enum.
Define the Type enum.
Define the Type enum.
Define the Type enum.
Define the Type enum.
Define the Type enum.
Define the Type enum.
Define the Type enum.
Define the Type enum.
Define the Type enum.
Define the Type enum.
Define the Type enum.
Define the Type enum.

# Variables

Define common vars.
Define common vars.
Define common vars.
Define common vars.
Define common vars.
Define common vars.
Define common vars.
ErrMissPK missing pk error.
Define common vars.
Define common vars.
Define common vars.
Define common vars.
Define common vars.
costomer log func.
No description provided by the author

# Structs

Condition struct.
No description provided by the author
No description provided by the author
DoNothingTxOrm is similar with DoNothingOrm, usually you use it to test.
Invocation represents an "Orm" invocation.
Log implement the log.Logger.
MySQLQueryBuilder is the SQL build.
PostgresQueryBuilder is the SQL build.
TiDBQueryBuilder is the SQL build.
No description provided by the author

# Interfaces

Data Manipulation Language.
Data Query Language.
Driver define database driver.
No description provided by the author
Fielder define field info.
Inserter insert prepared statement.
IsApplicableTableForDB if return false, we won't create table to this db.
No description provided by the author
QueryBuilder is the Query builder interface.
QueryExecutor wrapping for ormer.
QueryM2Mer model to model query struct all operations are on the m2m table only, will not affect the origin model table.
QuerySeter query seter.
RawPreparer raw query statement.
RawSeter raw query seter create From Ormer.Raw for example: sql := fmt.Sprintf("SELECT %sid%s,%sname%s FROM %suser%s WHERE id = ?",Q,Q,Q,Q,Q,Q) rs := Ormer.Raw(sql, 1).
TableEngineI is usually used by model when you want to use specific engine, like myisam, you can implement this interface for example: type User struct { ..
TableIndexI is usually used by model when you want to create indexes, you can implement this interface for example: type User struct { ..
TableNaming is usually used by model when you custom your table name, please implement this interfaces for example: type User struct { ..
TableUniqueI is usually used by model when you want to create unique indexes, you can implement this interface for example: type User struct { ..
No description provided by the author
No description provided by the author
No description provided by the author

# Type aliases

BigIntegerField -9223372036854775808 to 9223372036854775807.
BooleanField A true/false field.
CharField A string field required values tag: size The size is enforced at the database level and in models’s validation.
DateField A date, represented in go by a time.Time instance.
DateTimeField A date, represented in go by a time.Time instance.
No description provided by the author
DriverType database driver constant int.
Filter's behavior is a little big strange.
FilterChain is used to build a Filter don't forget to call next(...) inside your Filter.
FloatField A floating-point number represented in go by a float32 value.
IntegerField -2147483648 to 2147483647.
JsonbField postgres json field.
JSONField postgres json field.
Params stores the Params.
ParamsList stores paramslist.
PositiveBigIntegerField 0 to 18446744073709551615.
PositiveIntegerField 0 to 4294967295.
PositiveSmallIntegerField 0 to 65535.
SmallIntegerField -32768 to 32767.
StrTo is the target string.
TextField A large text field.
TimeField A time, represented in go by a time.Time instance.