dbmodel

package module
v0.0.0-...-f511b10 Latest Latest
Warning

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

Go to latest
Published: Jan 8, 2017 License: MIT Imports: 6 Imported by: 0

README

dbmodel

Build Status Coverage Status Go Report Card Godoc license

Description

dbmodel is simple database modeling.
dbmodel does not import database driver in production code. You must import database driver in your code.

Databases

  • PostgreSQL: higher 8.4
  • MySQL: not supported yet
  • Oracle: not supported yet
  • SQL Server: not supported yet

Usage

Install and use in your code.

Example (PostgreSQL):

package main

import (
	"fmt"

	"github.com/pinzolo/dbmodel"
)

func main() {
	// Create DataSouce
	ds := dbmodel.NewDataSource("postgres", "9.4", "localhost", 5432, "postgres", "", "sample", map[string]string{"sslmode": "disable"})

	// Create Client
	client := dbmodel.NewClient(ds)

	// Connect to Database.
	client.Connect()
	// You must close connection.
	defer client.Disconnect()

	// AllTables returns all table in sample schema.
	// dbmodel.RequireAll is built in option.
	// When dbmodel.RequireAll is given, client loads all metadata of table.(columns, indices, constraints, foreign keys, referenced keys)
	tables, err := client.AllTables("sample", dbmodel.RequireAll)
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, tbl := range tables {
		for _, col := range tbl.Columns() {
			fmt.Printf("%#v", col)
		}
		for _, idx := range tbl.Indices() {
			fmt.Printf("%#v", idx)
		}
		for _, cns := range tbl.Constraints() {
			fmt.Printf("%#v", cns)
		}
		for _, fk := range tbl.ForeignKeys() {
			fmt.Printf("%#v", fk)
		}
		for _, rk := range tbl.ReferencedKeys() {
			fmt.Printf("%#v", rk)
		}
	}

	// You can load single table users.
	// You need only columns, you can use dbmodel.RequireNone
	table, err := client.Table("sample", "users", dbmodel.RequireNone)
	fmt.Printf("%#v", table)
	if err != nil {
		fmt.Println(err)
		return
	}

	// You can load table names.
	// Returned *dbmodel.Table contains only table name and comment.
	// As well as using client.TableNames("sample", "users"), you can get tables that contains "users" in its name.
	tables, err = client.AllTableNames("sample")
	if err != nil {
		fmt.Println(err)
		return
	}
}

Install

To install, use go get:

$ go get github.com/pinzolo/dbmodel

Contribution

  1. Fork (https://github.com/pinzolo/dbmodel/fork)
  2. Create a feature branch
  3. Commit your changes
  4. Rebase your local changes against the master branch
  5. Run test suite with the go test ./... command and confirm that it passes
  6. Run gofmt -s
  7. Create a new Pull Request

Author

pinzolo

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrSchemaEmpty is raised when schema is not given.
	ErrSchemaEmpty = errors.New("Schema is required")
	// ErrConnNotFound is raised when call function before connect to database.
	ErrConnNotFound = errors.New("Database connection is not found")
	// ErrInvalidDriver is raised when given driver is unknown.
	ErrInvalidDriver = errors.New("Invalid driver")
	// ErrTableNameEmpty is raised when table name is not given.
	ErrTableNameEmpty = errors.New("Table name is required.")
)
View Source
var (
	// RequireAll is loading option for loading all meta data.
	RequireAll = Option{
		Indices:        true,
		ForeignKeys:    true,
		ReferencedKeys: true,
		Constraints:    true,
	}
	// RequireNone is loading option for loading only columns.
	RequireNone = Option{
		Indices:        false,
		ForeignKeys:    false,
		ReferencedKeys: false,
		Constraints:    false,
	}
)

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is table meta data loding client.

func NewClient

func NewClient(ds DataSource) *Client

NewClient returns new Client for connecting to given data source.

func (*Client) AllTableNames

func (c *Client) AllTableNames(schema string) ([]*Table, error)

AllTableNames returns all table names in given schema. If schema is empty, raise ErrSchemaEmpty.

func (*Client) AllTables

func (c *Client) AllTables(schema string, opt Option) ([]*Table, error)

AllTables returns table meta data list that are contained in given schema. If schema is empty, raise ErrSchemaEmpty.

func (*Client) Connect

func (c *Client) Connect()

Connect to database.

func (*Client) Disconnect

func (c *Client) Disconnect() error

Disconnect from datasource and close database connection.

func (*Client) SetProvider

func (c *Client) SetProvider(p Provider)

SetProvider sets custom provider. If use custom provider, call this before Connect.

func (*Client) Table

func (c *Client) Table(schema string, name string, opt Option) (*Table, error)

Table returns table meta data. If schema is empty, raise ErrSchemaEmpty. If name is empaty, raise ErrTableNameEmpty.

func (*Client) TableNames

func (c *Client) TableNames(schema string, name string) ([]*Table, error)

TableNames returns table names in given schema. If schema is empty, raise ErrSchemaEmpty. If name is empaty, TableNames returns all table names orderd by table names. If name is given, TableNames returns table names that matches given name.

type Column

type Column struct {
	// contains filtered or unexported fields
}

Column is database column metadata.

func NewColumn

func NewColumn(schema string, tableName string, name string, comment string, dataType string, size Size, nullable bool, defaultValue string, pkPosition int64) Column

NewColumn returns new Column initialized with arguments.

func (Column) Comment

func (c Column) Comment() string

Comment returns columns comment

func (Column) DataType

func (c Column) DataType() string

DataType returns column data type.

func (Column) DefaultValue

func (c Column) DefaultValue() string

DefaultValue returns column's default value

func (Column) IsNullable

func (c Column) IsNullable() bool

IsNullable returns true if column can accept NULL.

func (Column) Name

func (c Column) Name() string

Name returns column name.

func (Column) PrimaryKeyPosition

func (c Column) PrimaryKeyPosition() int64

PrimaryKeyPosition returns this column's position in primary key columns. If this column is not primary key, returns 0.

func (Column) Schema

func (c Column) Schema() string

Schema returns column schema.

func (Column) Size

func (c Column) Size() Size

Size returns column size.

func (Column) TableName

func (c Column) TableName() string

TableName returns table name that this column belonging.

type ColumnReference

type ColumnReference struct {
	// contains filtered or unexported fields
}

ColumnReference is reference to column from column.

func NewColumnReference

func NewColumnReference(from *Column, to *Column) ColumnReference

NewColumnReference returns new ColumnRef initialized with arguments.

func (ColumnReference) From

func (cr ColumnReference) From() *Column

From returns form column of this reference.

func (ColumnReference) To

func (cr ColumnReference) To() *Column

To returns to column of this reference.

type Constraint

type Constraint struct {
	// contains filtered or unexported fields
}

Constraint is constraint's meta data. This struct using unique constraint and check constraint.

func NewConstraint

func NewConstraint(schema string, tableName string, name string, kind string, content string) Constraint

NewConstraint returns new Constraint initialized with arguments.

func (Constraint) Content

func (c Constraint) Content() string

Content returns constraint's content.

func (Constraint) Kind

func (c Constraint) Kind() string

Kind returns constraint's kind. If Constraint is unique constraint, Kind returns 'UNIQUE'. If Constraint is check constraint, Kind returns 'CHECK'.

func (Constraint) Name

func (c Constraint) Name() string

Name returns constraint's name.

func (Constraint) Schema

func (c Constraint) Schema() string

Schema returns constraint's schema.

func (Constraint) TableName

func (c Constraint) TableName() string

TableName returns table name that having this constraint.

type DataSource

type DataSource struct {
	Driver   string
	Version  string
	Host     string
	Port     int
	User     string
	Password string
	Database string
	Options  map[string]string
}

DataSource is database setting.

func InitDataSource

func InitDataSource() DataSource

InitDataSource returns new DataSource that has initialized Options.

func NewDataSource

func NewDataSource(driver string, version string, host string, port int, user string, password string, database string, options map[string]string) DataSource

NewDataSource returns new DataSource with initialized given arguments.

type ForeignKey

type ForeignKey struct {
	// contains filtered or unexported fields
}

ForeignKey is foreign key's meta data.

func NewForeignKey

func NewForeignKey(schema string, tableName string, name string) ForeignKey

NewForeignKey returns new ForeignKey initialized with arguments.

func (*ForeignKey) AddColumnReference

func (fk *ForeignKey) AddColumnReference(r *ColumnReference)

AddColumnReference appends column reference to ColumnReferences.

func (ForeignKey) ColumnReferences

func (fk ForeignKey) ColumnReferences() []*ColumnReference

ColumnReferences returns foreign key's references from column to other column.

func (ForeignKey) Name

func (fk ForeignKey) Name() string

Name returns foreign key's name.

func (ForeignKey) Schema

func (fk ForeignKey) Schema() string

Schema returns foreign key's schema.

func (ForeignKey) TableName

func (fk ForeignKey) TableName() string

TableName returns table name that having this foreign key.

type Index

type Index struct {
	// contains filtered or unexported fields
}

Index is database index metadata.

func NewIndex

func NewIndex(schema string, tableName string, name string, unique bool) Index

NewIndex returns new Index initialized with arguments.

func (*Index) AddColumn

func (i *Index) AddColumn(col *Column)

AddColumn append column to Columns

func (Index) Columns

func (i Index) Columns() []*Column

Columns returns having columns.

func (Index) IsUnique

func (i Index) IsUnique() bool

IsUnique returns true if this index is unique index.

func (Index) Name

func (i Index) Name() string

Name returns index name.

func (Index) Schema

func (i Index) Schema() string

Schema returns index schema.

func (Index) TableName

func (i Index) TableName() string

TableName returns table name that having this index.

type Option

type Option struct {
	Indices        bool
	ForeignKeys    bool
	ReferencedKeys bool
	Constraints    bool
}

Option is table loding option for Table and AllTables function.

type Provider

type Provider interface {
	// Connect open connection to DataSouce.
	Connect() (*sql.DB, error)
	// AllTableNamesSQL should return SQL for loading table names.
	// Parameters:
	//     1. schema
	// Return columns:
	//     1. schema
	//     2. table name
	//     3. table comment
	// Order: table name
	AllTableNamesSQL() string
	// TableNamesSQL should return SQL for loading table names using LIKE table_name.
	// Parameters:
	//     1. schema
	//     2. table name
	// Return columns:
	//     same as AllTableNamesSQL
	// Order: table name
	TableNamesSQL() string
	// AllTableSQL should return SQL for loading all tables contains columns.
	// Parameters:
	//     1. schema
	// Return columns:
	//      1. schema
	//      2. table name
	//      3. table comment
	//      4. column name
	//      5. column comment
	//      6. data type
	//      7. length (using in text)
	//      8. precision (using in numeric or date)
	//      9. scale (using in numeric)
	//     10. nullable ("YES" or "NO")
	//     11. default value (as text)
	//     12. primary key position
	// Order:
	//     1. table name
	//     2. column position
	AllTablesSQL() string
	// TableSQL should return SQL for loading a table contains columns.
	// Parameters:
	//     1. schema
	//     2. table name
	// Return columns:
	//     same as AllTableSQL
	// Order:
	//     1. column position
	TableSQL() string
	// AllIndicesSQL should return SQL for loading all indices.
	// Parameters:
	//     1. schema
	// Return columns:
	//     1. schema
	//     2. table name
	//     3. index name
	//     4. unique ("YES" or "NO")
	//     5. column name
	// Order:
	//     1. table name
	//     2. index name
	//     3. column position
	AllIndicesSQL() string
	// IndicesSQL should return SQL for loading indices in a table.
	// Parameters:
	//     1. schema
	//     2. table name
	// Return columns:
	//     same as AllIndicesSQL
	// Order:
	//     1. index name
	//     2. column position
	IndicesSQL() string
	// AllForeignKeysSQL should return SQL for loading all foreign keys.
	// Parameters:
	//     1. schema
	// Return columns:
	//     1. foreign key name
	//     2. schema      (from)
	//     3. table name  (from)
	//     4. column name (from)
	//     5. schema      (to)
	//     6. table name  (to)
	//     7. column name (to)
	// Order:
	//     1. table name (from)
	//     2. foreign key name
	//     3. column position (from)
	AllForeignKeysSQL() string
	// ForeignKeysSQL should return SQL for loading foreign keys in a table.
	// Parameters:
	//     1. schema
	//     2. table name
	// Return columns:
	//     same as AllForeignKeysSQL
	// Order:
	//     1. foreign key name
	//     2. column position (from)
	ForeignKeysSQL() string
	// AllReferencedKeysSQL should return SQL for loading all foreign keys.
	// Parameters:
	//     1. schema
	// Return columns:
	//     1. foreign key name
	//     2. schema      (from)
	//     3. table name  (from)
	//     4. column name (from)
	//     5. schema      (to)
	//     6. table name  (to)
	//     7. column name (to)
	// Order:
	//     1. table name (to)
	//     2. foreign key name
	//     3. column position (to)
	AllReferencedKeysSQL() string
	// ReferencedKeys should return SQL for loading referenced foreign keys in a table.
	// Parameters:
	//     1. schema
	//     2. table name
	// Return columns:
	//     same as AllReferencedKeysSQL
	// Order:
	//     1. foreign key name
	//     2. column position (to)
	ReferencedKeysSQL() string
	// AllConstraintsSQL should return SQL for loading all constraints.
	// Parameters:
	//     1. schema
	// Return columns:
	//     1. schema
	//     2. table name
	//     3. constraint name
	//     4. kind (eg. "CHECK", "UNIQUE")
	//     5. content
	// Order:
	//     1. table name
	//     2. kind
	//     3. constraint name
	AllConstraintsSQL() string
	// ConstraintsSQL should return SQL for loading constraints in a table.
	// Parameters:
	//     1. schema
	//     2. table name
	// Return columns:
	//     same as AllConstraintsSQL
	// Order:
	//     1. table name
	//     2. kind
	//     3. constraint name
	ConstraintsSQL() string
}

Provider is interface to absorbe difference of each database.

type Size

type Size struct {
	// contains filtered or unexported fields
}

Size is column size

func NewSize

func NewSize(length sql.NullInt64, precision sql.NullInt64, scale sql.NullInt64) Size

NewSize returns new Size initialized with arguments.

func (Size) IsValid

func (s Size) IsValid() bool

IsValid returns has value. If length, precision and scale are NULL, IsValid returns false.

func (Size) Length

func (s Size) Length() sql.NullInt64

Length returns length.(used when data type is character)

func (Size) Precision

func (s Size) Precision() sql.NullInt64

Precision returns precision.(used when data type is numeric)

func (Size) Scale

func (s Size) Scale() sql.NullInt64

Scale returns scale.(used when data type is numeric)

func (Size) String

func (s Size) String() string

String returns string expression.

type Table

type Table struct {
	// contains filtered or unexported fields
}

Table stores table meta data.

func NewTable

func NewTable(schema string, tableName string, comment string) Table

NewTable returns new Table initialized with arguments.

func (*Table) AddColumn

func (t *Table) AddColumn(col *Column)

AddColumn appends column to Columns.

func (*Table) AddConstraint

func (t *Table) AddConstraint(c *Constraint)

AddConstraint appends foreign key to Constraints.

func (*Table) AddForeignKey

func (t *Table) AddForeignKey(fk *ForeignKey)

AddForeignKey appends foreign key to ForeignKeys.

func (*Table) AddIndex

func (t *Table) AddIndex(idx *Index)

AddIndex appends index to Indecis.

func (*Table) AddReferencedKey

func (t *Table) AddReferencedKey(rk *ForeignKey)

AddReferencedKey appends other table's foreign key that reference this table's column to ReferencedKeys.

func (Table) Columns

func (t Table) Columns() []*Column

Columns returns having columns.

func (Table) Comment

func (t Table) Comment() string

Comment returns table comment.

func (Table) Constraints

func (t Table) Constraints() []*Constraint

Constraints returns having constraints.

func (*Table) FindColumn

func (t *Table) FindColumn(name string) (*Column, bool)

FindColumn returns column that has same name as argument. If column that has same name does not exist, return false as second value.

func (*Table) FindConstraint

func (t *Table) FindConstraint(name string) (*Constraint, bool)

FindConstraint returns constraint that has same name as argument. If constraint that has same name does not exist, return false as second value.

func (*Table) FindForeignKey

func (t *Table) FindForeignKey(name string) (*ForeignKey, bool)

FindForeignKey returns foreign key that has same name as argument. If foreign key that has same name does not exist, return false as second value.

func (*Table) FindIndex

func (t *Table) FindIndex(name string) (*Index, bool)

FindIndex returns index that has same name as argument. If index that has same name does not exist, return false as second value.

func (*Table) FindReferencedKey

func (t *Table) FindReferencedKey(name string) (*ForeignKey, bool)

FindReferencedKey returns referenced key that has same name as argument. If referenced key that has same name does not exist, return false as second value.

func (Table) ForeignKeys

func (t Table) ForeignKeys() []*ForeignKey

ForeignKeys returns having foreign keys.

func (Table) Indices

func (t Table) Indices() []*Index

Indices returns having indices.

func (Table) Name

func (t Table) Name() string

Name returns table name.

func (Table) ReferencedKeys

func (t Table) ReferencedKeys() []*ForeignKey

ReferencedKeys returns having referenced keys.

func (Table) Schema

func (t Table) Schema() string

Schema returns table schema.

Jump to

Keyboard shortcuts

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