xorm/dialects/db2.go

433 lines
11 KiB
Go
Raw Normal View History

2020-02-25 05:30:15 +00:00
// Copyright 2020 The Xorm Authors. All rights reserved.
2019-08-07 07:19:49 +00:00
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
2020-02-25 05:30:15 +00:00
package dialects
2019-08-07 07:19:49 +00:00
import (
"errors"
"fmt"
"strconv"
"strings"
"xorm.io/xorm/core"
2020-02-25 05:30:15 +00:00
"xorm.io/xorm/schemas"
)
var (
db2ReservedWords = map[string]bool{}
2019-08-07 07:19:49 +00:00
)
type db2 struct {
2020-02-25 05:30:15 +00:00
Base
2019-08-07 07:19:49 +00:00
}
2020-02-25 05:30:15 +00:00
func (db *db2) Init(d *core.DB, uri *URI, drivername, dataSourceName string) error {
2019-08-07 07:19:49 +00:00
err := db.Base.Init(d, db, uri, drivername, dataSourceName)
if err != nil {
return err
}
return nil
}
2020-02-25 05:30:15 +00:00
func (db *db2) SQLType(c *schemas.Column) string {
2019-08-07 07:19:49 +00:00
var res string
switch t := c.SQLType.Name; t {
2020-02-25 05:30:15 +00:00
case schemas.TinyInt:
res = schemas.SmallInt
2019-08-07 07:19:49 +00:00
return res
2020-02-25 05:30:15 +00:00
case schemas.Bit:
res = schemas.Boolean
2019-08-07 07:19:49 +00:00
return res
2020-02-25 05:30:15 +00:00
case schemas.Binary, schemas.VarBinary:
return schemas.Bytea
case schemas.DateTime:
res = schemas.TimeStamp
case schemas.TimeStampz:
2019-08-07 07:19:49 +00:00
return "timestamp with time zone"
2020-02-25 05:30:15 +00:00
case schemas.TinyText, schemas.MediumText, schemas.LongText:
res = schemas.Text
case schemas.NVarchar:
res = schemas.Varchar
case schemas.Uuid:
return schemas.Uuid
case schemas.Blob, schemas.TinyBlob, schemas.MediumBlob, schemas.LongBlob:
return schemas.Bytea
2019-08-07 07:19:49 +00:00
default:
res = t
}
if strings.EqualFold(res, "bool") {
// for bool, we don't need length information
return res
}
hasLen1 := (c.Length > 0)
hasLen2 := (c.Length2 > 0)
if hasLen2 {
res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")"
} else if hasLen1 {
res += "(" + strconv.Itoa(c.Length) + ")"
}
return res
}
func (db *db2) SupportInsertMany() bool {
return true
}
func (db *db2) IsReserved(name string) bool {
2020-02-25 05:30:15 +00:00
_, ok := db2ReservedWords[name]
2019-08-07 07:19:49 +00:00
return ok
}
2020-02-25 05:30:15 +00:00
func (db *db2) Quoter() schemas.Quoter {
return schemas.Quoter{"\"", "\""}
2019-08-07 07:19:49 +00:00
}
func (db *db2) AutoIncrStr() string {
return ""
}
func (db *db2) SupportEngine() bool {
return false
}
func (db *db2) SupportCharset() bool {
return false
}
func (db *db2) IndexOnTable() bool {
return false
}
2020-02-25 05:30:15 +00:00
func (db *db2) CreateTableSql(table *schemas.Table, tableName, storeEngine, charset string) string {
2019-12-12 14:36:21 +00:00
var sql string
sql = "CREATE TABLE "
if tableName == "" {
tableName = table.Name
}
2020-02-25 05:30:15 +00:00
sql += db.Quoter().Quote(tableName) + " ("
2019-12-12 14:36:21 +00:00
pkList := table.PrimaryKeys
for _, colName := range table.ColumnsSeq() {
col := table.GetColumn(colName)
2020-02-25 05:30:15 +00:00
sql += StringNoPk(db, col)
2019-12-12 14:36:21 +00:00
if col.IsAutoIncrement {
sql += " GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1 )"
}
sql = strings.TrimSpace(sql)
sql += ", "
}
if len(pkList) > 0 {
sql += "PRIMARY KEY ( "
2020-02-25 05:30:15 +00:00
sql += db.Quoter().Join(pkList, ",")
2019-12-12 14:36:21 +00:00
sql += " ), "
}
sql = sql[:len(sql)-2] + ")"
return sql
}
2020-02-25 05:30:15 +00:00
func (db *db2) IndexCheckSQL(tableName, idxName string) (string, []interface{}) {
if len(db.uri.Schema) == 0 {
2019-08-07 07:19:49 +00:00
args := []interface{}{tableName, idxName}
return `SELECT indexname FROM pg_indexes WHERE tablename = ? AND indexname = ?`, args
}
2020-02-25 05:30:15 +00:00
args := []interface{}{db.uri.Schema, tableName, idxName}
2019-08-07 07:19:49 +00:00
return `SELECT indexname FROM pg_indexes ` +
`WHERE schemaname = ? AND tablename = ? AND indexname = ?`, args
}
2020-02-25 05:30:15 +00:00
func (db *db2) TableCheckSQL(tableName string) (string, []interface{}) {
if len(db.uri.Schema) == 0 {
2019-08-07 07:19:49 +00:00
args := []interface{}{tableName}
return `SELECT tablename FROM pg_tables WHERE tablename = ?`, args
}
2020-02-25 05:30:15 +00:00
args := []interface{}{db.uri.Schema, tableName}
2019-08-07 07:19:49 +00:00
return `SELECT tablename FROM pg_tables WHERE schemaname = ? AND tablename = ?`, args
}
2020-02-25 05:30:15 +00:00
func (db *db2) ModifyColumnSQL(tableName string, col *schemas.Column) string {
if len(db.uri.Schema) == 0 {
2019-08-07 07:19:49 +00:00
return fmt.Sprintf("alter table %s ALTER COLUMN %s TYPE %s",
2020-02-25 05:30:15 +00:00
tableName, col.Name, db.SQLType(col))
2019-08-07 07:19:49 +00:00
}
return fmt.Sprintf("alter table %s.%s ALTER COLUMN %s TYPE %s",
2020-02-25 05:30:15 +00:00
db.uri.Schema, tableName, col.Name, db.SQLType(col))
2019-08-07 07:19:49 +00:00
}
2020-02-25 05:30:15 +00:00
func (db *db2) DropIndexSQL(tableName string, index *schemas.Index) string {
quote := db.Quoter().Quote
2019-08-07 07:19:49 +00:00
idxName := index.Name
tableName = strings.Replace(tableName, `"`, "", -1)
tableName = strings.Replace(tableName, `.`, "_", -1)
if !strings.HasPrefix(idxName, "UQE_") &&
!strings.HasPrefix(idxName, "IDX_") {
2020-02-25 05:30:15 +00:00
if index.Type == schemas.UniqueType {
2019-08-07 07:19:49 +00:00
idxName = fmt.Sprintf("UQE_%v_%v", tableName, index.Name)
} else {
idxName = fmt.Sprintf("IDX_%v_%v", tableName, index.Name)
}
}
2020-02-25 05:30:15 +00:00
if db.uri.Schema != "" {
idxName = db.uri.Schema + "." + idxName
2019-08-07 07:19:49 +00:00
}
return fmt.Sprintf("DROP INDEX %v", quote(idxName))
}
func (db *db2) IsColumnExist(tableName, colName string) (bool, error) {
2020-02-25 05:30:15 +00:00
args := []interface{}{db.uri.Schema, tableName, colName}
2019-08-07 07:19:49 +00:00
query := "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = $1 AND table_name = $2" +
" AND column_name = $3"
2020-02-25 05:30:15 +00:00
if len(db.uri.Schema) == 0 {
2019-08-07 07:19:49 +00:00
args = []interface{}{tableName, colName}
query = "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = $1" +
" AND column_name = $2"
}
db.LogSQL(query, args)
rows, err := db.DB().Query(query, args...)
if err != nil {
return false, err
}
defer rows.Close()
return rows.Next(), nil
}
2020-02-25 05:30:15 +00:00
func (db *db2) GetColumns(tableName string) ([]string, map[string]*schemas.Column, error) {
2019-08-07 07:19:49 +00:00
args := []interface{}{tableName}
2019-11-18 01:39:01 +00:00
s := `Select c.colname as column_name,
c.colno as position,
c.typename as data_type,
c.length,
c.scale,
c.remarks as description,
case when c.nulls = 'Y' then 1 else 0 end as nullable,
default as default_value,
case when c.identity ='Y' then 1 else 0 end as is_identity,
case when c.generated ='' then 0 else 1 end as is_computed,
c.text as computed_formula
from syscat.columns c
inner join syscat.tables t on
t.tabschema = c.tabschema and t.tabname = c.tabname
where t.type = 'T' AND c.tabname = ?`
2019-08-07 07:19:49 +00:00
var f string
2020-02-25 05:30:15 +00:00
if len(db.uri.Schema) != 0 {
args = append(args, db.uri.Schema)
2019-11-18 01:39:01 +00:00
f = " AND c.tabschema = ?"
2019-08-07 07:19:49 +00:00
}
2019-11-18 01:39:01 +00:00
s = s + f
2019-08-07 07:19:49 +00:00
db.LogSQL(s, args)
rows, err := db.DB().Query(s, args...)
if err != nil {
return nil, nil, err
}
defer rows.Close()
2020-02-25 05:30:15 +00:00
cols := make(map[string]*schemas.Column)
2019-08-07 07:19:49 +00:00
colSeq := make([]string, 0)
for rows.Next() {
2020-02-25 05:30:15 +00:00
col := new(schemas.Column)
2019-08-07 07:19:49 +00:00
col.Indexes = make(map[string]int)
2019-11-18 01:39:01 +00:00
var colName, position, dataType, numericScale string
var description, colDefault, computedFormula, maxLenStr *string
var isComputed bool
err = rows.Scan(&colName, &position, &dataType, &maxLenStr, &numericScale, &description, &col.Nullable, &colDefault, &col.IsPrimaryKey, &isComputed, &computedFormula)
2019-08-07 07:19:49 +00:00
if err != nil {
return nil, nil, err
}
2019-11-18 01:39:01 +00:00
//fmt.Println(colName, position, dataType, maxLenStr, numericScale, description, col.Nullable, colDefault, col.IsPrimaryKey, isComputed, computedFormula)
2019-08-07 07:19:49 +00:00
var maxLen int
if maxLenStr != nil {
maxLen, err = strconv.Atoi(*maxLenStr)
if err != nil {
return nil, nil, err
}
}
col.Name = strings.Trim(colName, `" `)
2019-11-18 01:39:01 +00:00
if colDefault != nil {
col.DefaultIsEmpty = false
col.Default = *colDefault
2019-08-07 07:19:49 +00:00
}
if colDefault != nil && strings.HasPrefix(*colDefault, "nextval(") {
col.IsAutoIncrement = true
}
switch dataType {
2019-11-18 01:39:01 +00:00
case "character", "CHARACTER":
2020-02-25 05:30:15 +00:00
col.SQLType = schemas.SQLType{Name: schemas.Char, DefaultLength: 0, DefaultLength2: 0}
2019-08-07 07:19:49 +00:00
case "timestamp without time zone":
2020-02-25 05:30:15 +00:00
col.SQLType = schemas.SQLType{Name: schemas.DateTime, DefaultLength: 0, DefaultLength2: 0}
2019-08-07 07:19:49 +00:00
case "timestamp with time zone":
2020-02-25 05:30:15 +00:00
col.SQLType = schemas.SQLType{Name: schemas.TimeStampz, DefaultLength: 0, DefaultLength2: 0}
2019-08-07 07:19:49 +00:00
case "double precision":
2020-02-25 05:30:15 +00:00
col.SQLType = schemas.SQLType{Name: schemas.Double, DefaultLength: 0, DefaultLength2: 0}
2019-08-07 07:19:49 +00:00
case "boolean":
2020-02-25 05:30:15 +00:00
col.SQLType = schemas.SQLType{Name: schemas.Bool, DefaultLength: 0, DefaultLength2: 0}
2019-08-07 07:19:49 +00:00
case "time without time zone":
2020-02-25 05:30:15 +00:00
col.SQLType = schemas.SQLType{Name: schemas.Time, DefaultLength: 0, DefaultLength2: 0}
2019-08-07 07:19:49 +00:00
case "oid":
2020-02-25 05:30:15 +00:00
col.SQLType = schemas.SQLType{Name: schemas.BigInt, DefaultLength: 0, DefaultLength2: 0}
2019-08-07 07:19:49 +00:00
default:
2020-02-25 05:30:15 +00:00
col.SQLType = schemas.SQLType{Name: strings.ToUpper(dataType), DefaultLength: 0, DefaultLength2: 0}
2019-08-07 07:19:49 +00:00
}
2020-02-25 05:30:15 +00:00
if _, ok := schemas.SqlTypes[col.SQLType.Name]; !ok {
2019-08-07 07:19:49 +00:00
return nil, nil, fmt.Errorf("Unknown colType: %v", dataType)
}
col.Length = maxLen
if col.SQLType.IsText() || col.SQLType.IsTime() {
if col.Default != "" {
col.Default = "'" + col.Default + "'"
} else {
if col.DefaultIsEmpty {
col.Default = "''"
}
}
}
cols[col.Name] = col
colSeq = append(colSeq, col.Name)
}
return colSeq, cols, nil
}
2020-02-25 05:30:15 +00:00
func (db *db2) GetTables() ([]*schemas.Table, error) {
2019-08-07 07:19:49 +00:00
args := []interface{}{}
2019-12-12 14:36:21 +00:00
s := "SELECT TABNAME FROM SYSCAT.TABLES WHERE type = 'T' AND OWNERTYPE = 'U'"
2020-02-25 05:30:15 +00:00
if len(db.uri.Schema) != 0 {
args = append(args, db.uri.Schema)
2019-12-12 14:36:21 +00:00
s = s + " AND TABSCHEMA = ?"
2019-08-07 07:19:49 +00:00
}
db.LogSQL(s, args)
rows, err := db.DB().Query(s, args...)
if err != nil {
return nil, err
}
defer rows.Close()
2020-02-25 05:30:15 +00:00
tables := make([]*schemas.Table, 0)
2019-08-07 07:19:49 +00:00
for rows.Next() {
2020-02-25 05:30:15 +00:00
table := schemas.NewEmptyTable()
2019-08-07 07:19:49 +00:00
var name string
err = rows.Scan(&name)
if err != nil {
return nil, err
}
table.Name = name
tables = append(tables, table)
}
return tables, nil
}
2020-02-25 05:30:15 +00:00
func (db *db2) GetIndexes(tableName string) (map[string]*schemas.Index, error) {
2019-08-07 07:19:49 +00:00
args := []interface{}{tableName}
2019-11-18 01:39:01 +00:00
s := fmt.Sprintf(`select uniquerule,
indname as index_name,
replace(substring(colnames,2,length(colnames)),'+',',') as columns
from syscat.indexes WHERE tabname = ?`)
2020-02-25 05:30:15 +00:00
if len(db.uri.Schema) != 0 {
args = append(args, db.uri.Schema)
2019-11-18 01:39:01 +00:00
s = s + " AND tabschema=?"
2019-08-07 07:19:49 +00:00
}
db.LogSQL(s, args)
rows, err := db.DB().Query(s, args...)
if err != nil {
return nil, err
}
defer rows.Close()
2020-02-25 05:30:15 +00:00
indexes := make(map[string]*schemas.Index, 0)
2019-08-07 07:19:49 +00:00
for rows.Next() {
2019-11-18 01:39:01 +00:00
var indexTypeName, indexName, columns string
/*when 'P' then 'Primary key'
when 'U' then 'Unique'
when 'D' then 'Nonunique'*/
err = rows.Scan(&indexTypeName, &indexName, &columns)
2019-08-07 07:19:49 +00:00
if err != nil {
return nil, err
}
indexName = strings.Trim(indexName, `" `)
if strings.HasSuffix(indexName, "_pkey") {
continue
}
2019-11-18 01:39:01 +00:00
var indexType int
if strings.EqualFold(indexTypeName, "U") {
2020-02-25 05:30:15 +00:00
indexType = schemas.UniqueType
2019-11-18 01:39:01 +00:00
} else if strings.EqualFold(indexTypeName, "D") {
2020-02-25 05:30:15 +00:00
indexType = schemas.IndexType
2019-08-07 07:19:49 +00:00
}
var isRegular bool
if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) {
newIdxName := indexName[5+len(tableName):]
isRegular = true
if newIdxName != "" {
indexName = newIdxName
}
}
2020-02-25 05:30:15 +00:00
index := &schemas.Index{Name: indexName, Type: indexType, Cols: make([]string, 0)}
2019-11-18 01:39:01 +00:00
colNames := strings.Split(columns, ",")
2019-08-07 07:19:49 +00:00
for _, colName := range colNames {
index.Cols = append(index.Cols, strings.Trim(colName, `" `))
}
index.IsRegular = isRegular
indexes[index.Name] = index
}
return indexes, nil
}
2020-02-25 05:30:15 +00:00
func (db *db2) Filters() []Filter {
return []Filter{&QuoteFilter{}}
2019-08-07 07:19:49 +00:00
}
type db2Driver struct{}
2020-02-25 05:30:15 +00:00
func (p *db2Driver) Parse(driverName, dataSourceName string) (*URI, error) {
2019-08-07 07:19:49 +00:00
var dbName string
2019-12-12 14:36:21 +00:00
var defaultSchema string
2019-08-07 07:19:49 +00:00
kv := strings.Split(dataSourceName, ";")
for _, c := range kv {
2019-11-18 01:39:01 +00:00
vv := strings.SplitN(strings.TrimSpace(c), "=", 2)
2019-08-07 07:19:49 +00:00
if len(vv) == 2 {
switch strings.ToLower(vv[0]) {
case "database":
dbName = vv[1]
2019-12-12 14:36:21 +00:00
case "uid":
defaultSchema = vv[1]
2019-08-07 07:19:49 +00:00
}
}
}
if dbName == "" {
return nil, errors.New("no db name provided")
}
2020-02-25 05:30:15 +00:00
return &URI{
DBName: dbName,
DBType: "db2",
2019-12-12 14:36:21 +00:00
Schema: defaultSchema,
}, nil
2019-08-07 07:19:49 +00:00
}