sql

package
v0.0.0-...-012d1c6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 19, 2021 License: Apache-2.0 Imports: 8 Imported by: 0

README

sql的orm实现

需要支持的一些特性

  • 自动创建Model
    • 自动创建Table
    • 自动创建Index
    • 自动Migrate(仅限新增),
  • 多数据库支持
    • 有一些场景我们希望根据项目分离到不同的数据中操作,以实现隔离,减少相互干扰
  • 功能简单,语义明确
    • 使用过gorm的同学都会有一个感受,不使用debug的模式下,完全不知道他翻译成了什么
  • API安全
    • gorm使用的是链式调用方式,对于一个新手而言,他很容易用错且致命的问题,调用了Find之后,后边的条件都不会生效。比如: select * from orders where id=1 limit 1 这样一条简单的sql语句,如果代码中写成:db.Find(order).Where("id=?", orderId).Limit(1),这里看着还比较符合sql的顺序,但是最终却翻译成了select* from orders,直接忽略了后边的限制条件,而且不会报错,这种操作很致命还很难发现,因此不建议使用gorm这样的库,不如直接使用原生sql

限制

  • 连接字符串仅支持URI的连接方式,比如:mysql://user:pass@localhost/dbname, 因为这样方便统一使用,具体使用方式请见dburl

安装依赖包

docker相关命令

  • 查看镜像: docker container list
  • 停止镜像: docker stop [container-id]

mysql

  • 启动: docker run -p 3306:3306 --name mysql -e MYSQL_ROOT_PASSWORD=123456 -d mysql
    • 测试中如果遇到 docker: Error response from daemon: Conflict. The container name "/mysql" is already,可以使用docker rm /mysql 删除重建
  • 连接: mysql -h localhost -u root -p

postgres

其他

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFoundSQLEngine = errors.New("not found sql engine")
)

Functions

func AddEngine

func AddEngine(e Engine)

Types

type Engine

type Engine interface {
	Clone() Engine
	Bind(db *sql.DB)
	Close() error
	Name() string
	Current() (string, error)
	CreateDatabase(name string) error
	DropDatabase(name string) error
	CreateTable(name string, columns []driver.Column) error
	DropTable(name string) error
	Indexes(table string) ([]*driver.Index, error)
	CreateIndex(table string, index *driver.Index) error
	DropIndex(table string, name string) error
	Insert(table string, doc interface{}, opts *driver.InsertOptions) (*driver.InsertResult, error)
	Delete(table string, filter driver.Cond, opts *driver.DeleteOptions) (*driver.DeleteResult, error)
	Update(table string, filter driver.Cond, update interface{}, opts *driver.UpdateOptions) (*driver.UpdateResult, error)
	Query(table string, filter driver.Cond, opts *driver.QueryOptions) (driver.QueryResult, error)
}

抽象不同数据库接口

null处理: https://github.com/guregu/null switch database:mysql虽然可以使用USE db实现切换,但最好不要做这样的操作,因为connection是有pool的 pg没有切换数据库这样的功能 只能通过重新创建新的连接的方式支持多数据库切换

func GetEngine

func GetEngine(name string) Engine

type MySQLIndex

type MySQLIndex struct {
	Table        string
	NonUnique    int
	KeyName      string
	SeqInIndex   int
	ColumnName   string
	Collation    string         // A升序,B降序
	Cardinality  int            //
	SubPart      sql.NullString //
	Packed       sql.NullBool   //
	Null         string
	IndexType    string
	Comment      sql.NullString
	IndexComment sql.NullString
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL