postgres_dialect.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package migrator
  2. import (
  3. "fmt"
  4. "strconv"
  5. )
  6. type Postgres struct {
  7. BaseDialect
  8. }
  9. func NewPostgresDialect() *Postgres {
  10. d := Postgres{}
  11. d.BaseDialect.dialect = &d
  12. d.BaseDialect.driverName = POSTGRES
  13. return &d
  14. }
  15. func (db *Postgres) SupportEngine() bool {
  16. return false
  17. }
  18. func (db *Postgres) Quote(name string) string {
  19. return "\"" + name + "\""
  20. }
  21. func (db *Postgres) QuoteStr() string {
  22. return "\""
  23. }
  24. func (b *Postgres) LikeStr() string {
  25. return "ILIKE"
  26. }
  27. func (db *Postgres) AutoIncrStr() string {
  28. return ""
  29. }
  30. func (b *Postgres) Default(col *Column) string {
  31. if col.Type == DB_Bool {
  32. if col.Default == "0" {
  33. return "FALSE"
  34. } else {
  35. return "TRUE"
  36. }
  37. }
  38. return col.Default
  39. }
  40. func (db *Postgres) SqlType(c *Column) string {
  41. var res string
  42. switch t := c.Type; t {
  43. case DB_TinyInt:
  44. res = DB_SmallInt
  45. return res
  46. case DB_MediumInt, DB_Int, DB_Integer:
  47. if c.IsAutoIncrement {
  48. return DB_Serial
  49. }
  50. return DB_Integer
  51. case DB_Serial, DB_BigSerial:
  52. c.IsAutoIncrement = true
  53. c.Nullable = false
  54. res = t
  55. case DB_Binary, DB_VarBinary:
  56. return DB_Bytea
  57. case DB_DateTime:
  58. res = DB_TimeStamp
  59. case DB_TimeStampz:
  60. return "timestamp with time zone"
  61. case DB_Float:
  62. res = DB_Real
  63. case DB_TinyText, DB_MediumText, DB_LongText:
  64. res = DB_Text
  65. case DB_NVarchar:
  66. res = DB_Varchar
  67. case DB_Uuid:
  68. res = DB_Uuid
  69. case DB_Blob, DB_TinyBlob, DB_MediumBlob, DB_LongBlob:
  70. return DB_Bytea
  71. case DB_Double:
  72. return "DOUBLE PRECISION"
  73. default:
  74. if c.IsAutoIncrement {
  75. return DB_Serial
  76. }
  77. res = t
  78. }
  79. var hasLen1 bool = (c.Length > 0)
  80. var hasLen2 bool = (c.Length2 > 0)
  81. if hasLen2 {
  82. res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")"
  83. } else if hasLen1 {
  84. res += "(" + strconv.Itoa(c.Length) + ")"
  85. }
  86. return res
  87. }
  88. func (db *Postgres) TableCheckSql(tableName string) (string, []interface{}) {
  89. args := []interface{}{"grafana", tableName}
  90. sql := "SELECT `TABLE_NAME` from `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA`=? and `TABLE_NAME`=?"
  91. return sql, args
  92. }
  93. func (db *Postgres) DropIndexSql(tableName string, index *Index) string {
  94. quote := db.Quote
  95. idxName := index.XName(tableName)
  96. return fmt.Sprintf("DROP INDEX %v", quote(idxName))
  97. }