add schema support for postgres

This commit is contained in:
Lunny Xiao 2016-03-03 11:03:26 +08:00
parent 8c05434162
commit 4fec1167de
7 changed files with 40 additions and 32 deletions

View File

@ -1 +1 @@
xorm v0.5.1.0301 xorm v0.5.2.0303

View File

@ -129,6 +129,7 @@ func (engine *Engine) Quote(sql string) string {
if string(sql[0]) == engine.dialect.QuoteStr() || sql[0] == '`' { if string(sql[0]) == engine.dialect.QuoteStr() || sql[0] == '`' {
return sql return sql
} }
sql = strings.Replace(sql, ".", engine.dialect.QuoteStr()+"."+engine.dialect.QuoteStr(), -1)
return engine.dialect.QuoteStr() + sql + engine.dialect.QuoteStr() return engine.dialect.QuoteStr() + sql + engine.dialect.QuoteStr()
} }
@ -423,6 +424,10 @@ func (engine *Engine) DumpTables(tables []*core.Table, w io.Writer, tp ...core.D
return engine.dumpTables(tables, w, tp...) return engine.dumpTables(tables, w, tp...)
} }
func (engine *Engine) tbName(tb *core.Table) string {
return tb.Name
}
// DumpAll dump database all table structs and data to w with specify db type // DumpAll dump database all table structs and data to w with specify db type
func (engine *Engine) dumpAll(w io.Writer, tp ...core.DbType) error { func (engine *Engine) dumpAll(w io.Writer, tp ...core.DbType) error {
tables, err := engine.DBMetas() tables, err := engine.DBMetas()
@ -459,13 +464,13 @@ func (engine *Engine) dumpAll(w io.Writer, tp ...core.DbType) error {
return err return err
} }
for _, index := range table.Indexes { for _, index := range table.Indexes {
_, err = io.WriteString(w, dialect.CreateIndexSql(table.Name, index)+";\n") _, err = io.WriteString(w, dialect.CreateIndexSql(engine.tbName(table), index)+";\n")
if err != nil { if err != nil {
return err return err
} }
} }
rows, err := engine.DB().Query("SELECT * FROM " + engine.Quote(table.Name)) rows, err := engine.DB().Query("SELECT * FROM " + engine.Quote(engine.tbName(table)))
if err != nil { if err != nil {
return err return err
} }
@ -484,7 +489,7 @@ func (engine *Engine) dumpAll(w io.Writer, tp ...core.DbType) error {
return err return err
} }
_, err = io.WriteString(w, "INSERT INTO "+dialect.Quote(table.Name)+" ("+dialect.Quote(strings.Join(cols, dialect.Quote(", ")))+") VALUES (") _, err = io.WriteString(w, "INSERT INTO "+dialect.Quote(engine.tbName(table))+" ("+dialect.Quote(strings.Join(cols, dialect.Quote(", ")))+") VALUES (")
if err != nil { if err != nil {
return err return err
} }
@ -559,13 +564,13 @@ func (engine *Engine) dumpTables(tables []*core.Table, w io.Writer, tp ...core.D
return err return err
} }
for _, index := range table.Indexes { for _, index := range table.Indexes {
_, err = io.WriteString(w, dialect.CreateIndexSql(table.Name, index)+";\n") _, err = io.WriteString(w, dialect.CreateIndexSql(engine.tbName(table), index)+";\n")
if err != nil { if err != nil {
return err return err
} }
} }
rows, err := engine.DB().Query("SELECT * FROM " + engine.Quote(table.Name)) rows, err := engine.DB().Query("SELECT * FROM " + engine.Quote(engine.tbName(table)))
if err != nil { if err != nil {
return err return err
} }
@ -584,7 +589,7 @@ func (engine *Engine) dumpTables(tables []*core.Table, w io.Writer, tp ...core.D
return err return err
} }
_, err = io.WriteString(w, "INSERT INTO "+dialect.Quote(table.Name)+" ("+dialect.Quote(strings.Join(cols, dialect.Quote(", ")))+") VALUES (") _, err = io.WriteString(w, "INSERT INTO "+dialect.Quote(engine.tbName(table))+" ("+dialect.Quote(strings.Join(cols, dialect.Quote(", ")))+") VALUES (")
if err != nil { if err != nil {
return err return err
} }
@ -1350,7 +1355,7 @@ func (engine *Engine) Sync(beans ...interface{}) error {
session := engine.NewSession() session := engine.NewSession()
session.Statement.RefTable = table session.Statement.RefTable = table
defer session.Close() defer session.Close()
err = session.addUnique(table.Name, name) err = session.addUnique(engine.tbName(table), name)
if err != nil { if err != nil {
return err return err
} }
@ -1364,7 +1369,7 @@ func (engine *Engine) Sync(beans ...interface{}) error {
session := engine.NewSession() session := engine.NewSession()
session.Statement.RefTable = table session.Statement.RefTable = table
defer session.Close() defer session.Close()
err = session.addIndex(table.Name, name) err = session.addIndex(engine.tbName(table), name)
if err != nil { if err != nil {
return err return err
} }

View File

@ -836,6 +836,7 @@ func (db *postgres) IsReserved(name string) bool {
} }
func (db *postgres) Quote(name string) string { func (db *postgres) Quote(name string) string {
name = strings.Replace(name, ".", `"."`, -1)
return "\"" + name + "\"" return "\"" + name + "\""
} }
@ -912,8 +913,7 @@ func (db *postgres) IsColumnExist(tableName, colName string) (bool, error) {
} }
func (db *postgres) GetColumns(tableName string) ([]string, map[string]*core.Column, error) { func (db *postgres) GetColumns(tableName string) ([]string, map[string]*core.Column, error) {
pgSchema := "public" args := []interface{}{tableName, db.URI().Schema}
args := []interface{}{tableName, pgSchema}
s := `SELECT column_name, column_default, is_nullable, data_type, character_maximum_length, numeric_precision, numeric_precision_radix , s := `SELECT column_name, column_default, is_nullable, data_type, character_maximum_length, numeric_precision, numeric_precision_radix ,
CASE WHEN p.contype = 'p' THEN true ELSE false END AS primarykey, CASE WHEN p.contype = 'p' THEN true ELSE false END AS primarykey,
CASE WHEN p.contype = 'u' THEN true ELSE false END AS uniquekey CASE WHEN p.contype = 'u' THEN true ELSE false END AS uniquekey
@ -1013,7 +1013,7 @@ WHERE c.relkind = 'r'::char AND c.relname = $1 AND s.table_schema = $2 AND f.att
func (db *postgres) GetTables() ([]*core.Table, error) { func (db *postgres) GetTables() ([]*core.Table, error) {
args := []interface{}{} args := []interface{}{}
s := "SELECT tablename FROM pg_tables where schemaname = 'public'" s := fmt.Sprintf("SELECT tablename FROM pg_tables where schemaname = '%s'", db.Uri.Schema)
db.LogSQL(s, args) db.LogSQL(s, args)
rows, err := db.DB().Query(s, args...) rows, err := db.DB().Query(s, args...)
@ -1038,7 +1038,7 @@ func (db *postgres) GetTables() ([]*core.Table, error) {
func (db *postgres) GetIndexes(tableName string) (map[string]*core.Index, error) { func (db *postgres) GetIndexes(tableName string) (map[string]*core.Index, error) {
args := []interface{}{tableName} args := []interface{}{tableName}
s := "SELECT indexname, indexdef FROM pg_indexes WHERE schemaname='public' AND tablename=$1" s := fmt.Sprintf("SELECT indexname, indexdef FROM pg_indexes WHERE schemaname='%s' AND tablename=$1", db.URI().Schema)
db.LogSQL(s, args) db.LogSQL(s, args)
rows, err := db.DB().Query(s, args...) rows, err := db.DB().Query(s, args...)

View File

@ -115,5 +115,9 @@ func (p *pqDriver) Parse(driverName, dataSourceName string) (*core.Uri, error) {
if db.DbName == "" { if db.DbName == "" {
return nil, errors.New("dbname is empty") return nil, errors.New("dbname is empty")
} }
db.Schema = o.Get("schema")
if len(db.Schema) == 0 {
db.Schema = "public"
}
return db, nil return db, nil
} }

View File

@ -2285,10 +2285,8 @@ func (session *Session) innerInsertMulti(rowsSlicePtr interface{}) (int64, error
} }
cleanupProcessorsClosures(&session.beforeClosures) cleanupProcessorsClosures(&session.beforeClosures)
statement := fmt.Sprintf("INSERT INTO %v%v%v (%v%v%v) VALUES (%v)", statement := fmt.Sprintf("INSERT INTO %s (%v%v%v) VALUES (%v)",
session.Engine.QuoteStr(), session.Engine.Quote(session.Statement.TableName()),
session.Statement.TableName(),
session.Engine.QuoteStr(),
session.Engine.QuoteStr(), session.Engine.QuoteStr(),
strings.Join(colNames, session.Engine.QuoteStr()+", "+session.Engine.QuoteStr()), strings.Join(colNames, session.Engine.QuoteStr()+", "+session.Engine.QuoteStr()),
session.Engine.QuoteStr(), session.Engine.QuoteStr(),
@ -3160,10 +3158,8 @@ func (session *Session) innerInsert(bean interface{}) (int64, error) {
colPlaces = colPlaces[0 : len(colPlaces)-2] colPlaces = colPlaces[0 : len(colPlaces)-2]
} }
sqlStr := fmt.Sprintf("INSERT INTO %v%v%v (%v%v%v) VALUES (%v)", sqlStr := fmt.Sprintf("INSERT INTO %s (%v%v%v) VALUES (%v)",
session.Engine.QuoteStr(), session.Engine.Quote(session.Statement.TableName()),
session.Statement.TableName(),
session.Engine.QuoteStr(),
session.Engine.QuoteStr(), session.Engine.QuoteStr(),
strings.Join(colNames, session.Engine.Quote(", ")), strings.Join(colNames, session.Engine.Quote(", ")),
session.Engine.QuoteStr(), session.Engine.QuoteStr(),
@ -4087,7 +4083,7 @@ func (s *Session) Sync2(beans ...interface{}) error {
engine.dialect.DBType() == core.POSTGRES { engine.dialect.DBType() == core.POSTGRES {
engine.LogInfof("Table %s column %s change type from %s to %s\n", engine.LogInfof("Table %s column %s change type from %s to %s\n",
table.Name, col.Name, curType, expectedType) table.Name, col.Name, curType, expectedType)
_, err = engine.Exec(engine.dialect.ModifyColumnSql(table.Name, col)) _, err = engine.Exec(engine.dialect.ModifyColumnSql(engine.tbName(table), col))
} else { } else {
engine.LogWarnf("Table %s column %s db type is %s, struct type is %s\n", engine.LogWarnf("Table %s column %s db type is %s, struct type is %s\n",
table.Name, col.Name, curType, expectedType) table.Name, col.Name, curType, expectedType)
@ -4097,7 +4093,7 @@ func (s *Session) Sync2(beans ...interface{}) error {
if oriCol.Length < col.Length { if oriCol.Length < col.Length {
engine.LogInfof("Table %s column %s change type from varchar(%d) to varchar(%d)\n", engine.LogInfof("Table %s column %s change type from varchar(%d) to varchar(%d)\n",
table.Name, col.Name, oriCol.Length, col.Length) table.Name, col.Name, oriCol.Length, col.Length)
_, err = engine.Exec(engine.dialect.ModifyColumnSql(table.Name, col)) _, err = engine.Exec(engine.dialect.ModifyColumnSql(engine.tbName(table), col))
} }
} }
} else { } else {
@ -4109,7 +4105,7 @@ func (s *Session) Sync2(beans ...interface{}) error {
if oriCol.Length < col.Length { if oriCol.Length < col.Length {
engine.LogInfof("Table %s column %s change type from varchar(%d) to varchar(%d)\n", engine.LogInfof("Table %s column %s change type from varchar(%d) to varchar(%d)\n",
table.Name, col.Name, oriCol.Length, col.Length) table.Name, col.Name, oriCol.Length, col.Length)
_, err = engine.Exec(engine.dialect.ModifyColumnSql(table.Name, col)) _, err = engine.Exec(engine.dialect.ModifyColumnSql(engine.tbName(table), col))
} }
} }
} }
@ -4176,12 +4172,12 @@ func (s *Session) Sync2(beans ...interface{}) error {
session := engine.NewSession() session := engine.NewSession()
session.Statement.RefTable = table session.Statement.RefTable = table
defer session.Close() defer session.Close()
err = session.addUnique(table.Name, name) err = session.addUnique(engine.tbName(table), name)
} else if index.Type == core.IndexType { } else if index.Type == core.IndexType {
session := engine.NewSession() session := engine.NewSession()
session.Statement.RefTable = table session.Statement.RefTable = table
defer session.Close() defer session.Close()
err = session.addIndex(table.Name, name) err = session.addIndex(engine.tbName(table), name)
} }
if err != nil { if err != nil {
return err return err

View File

@ -652,6 +652,10 @@ func (statement *Statement) TableName() string {
} }
if statement.RefTable != nil { if statement.RefTable != nil {
schema := statement.Engine.dialect.URI().Schema
if len(schema) > 0 {
return schema + "." + statement.RefTable.Name
}
return statement.RefTable.Name return statement.RefTable.Name
} }
return "" return ""
@ -1078,7 +1082,7 @@ func (s *Statement) genIndexSQL() []string {
quote := s.Engine.Quote quote := s.Engine.Quote
for idxName, index := range s.RefTable.Indexes { for idxName, index := range s.RefTable.Indexes {
if index.Type == core.IndexType { if index.Type == core.IndexType {
sql := fmt.Sprintf("CREATE INDEX %v ON %v (%v);", quote(indexName(tbName, idxName)), sql := fmt.Sprintf("CREATE INDEX %v ON %v (%v);", quote(indexName(s.RefTable.Name, idxName)),
quote(tbName), quote(strings.Join(index.Cols, quote(",")))) quote(tbName), quote(strings.Join(index.Cols, quote(","))))
sqls = append(sqls, sql) sqls = append(sqls, sql)
} }
@ -1092,10 +1096,9 @@ func uniqueName(tableName, uqeName string) string {
func (s *Statement) genUniqueSQL() []string { func (s *Statement) genUniqueSQL() []string {
var sqls []string = make([]string, 0) var sqls []string = make([]string, 0)
tbName := s.TableName()
for _, index := range s.RefTable.Indexes { for _, index := range s.RefTable.Indexes {
if index.Type == core.UniqueType { if index.Type == core.UniqueType {
sql := s.Engine.dialect.CreateIndexSql(tbName, index) sql := s.Engine.dialect.CreateIndexSql(s.RefTable.Name, index)
sqls = append(sqls, sql) sqls = append(sqls, sql)
} }
} }
@ -1107,9 +1110,9 @@ func (s *Statement) genDelIndexSQL() []string {
for idxName, index := range s.RefTable.Indexes { for idxName, index := range s.RefTable.Indexes {
var rIdxName string var rIdxName string
if index.Type == core.UniqueType { if index.Type == core.UniqueType {
rIdxName = uniqueName(s.TableName(), idxName) rIdxName = uniqueName(s.RefTable.Name, idxName)
} else if index.Type == core.IndexType { } else if index.Type == core.IndexType {
rIdxName = indexName(s.TableName(), idxName) rIdxName = indexName(s.RefTable.Name, idxName)
} }
sql := fmt.Sprintf("DROP INDEX %v", s.Engine.Quote(rIdxName)) sql := fmt.Sprintf("DROP INDEX %v", s.Engine.Quote(rIdxName))
if s.Engine.dialect.IndexOnTable() { if s.Engine.dialect.IndexOnTable() {

View File

@ -17,7 +17,7 @@ import (
) )
const ( const (
Version string = "0.5.1.0301" Version string = "0.5.2.0303"
) )
func regDrvsNDialects() bool { func regDrvsNDialects() bool {