postgres_dialect.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 (db *Postgres) AutoIncrStr() string {
  25. return ""
  26. }
  27. func (db *Postgres) SqlType(c *Column) string {
  28. var res string
  29. switch t := c.Type; t {
  30. case DB_TinyInt:
  31. res = DB_SmallInt
  32. return res
  33. case DB_MediumInt, DB_Int, DB_Integer:
  34. if c.IsAutoIncrement {
  35. return DB_Serial
  36. }
  37. return DB_Integer
  38. case DB_Serial, DB_BigSerial:
  39. c.IsAutoIncrement = true
  40. c.Nullable = false
  41. res = t
  42. case DB_Binary, DB_VarBinary:
  43. return DB_Bytea
  44. case DB_DateTime:
  45. res = DB_TimeStamp
  46. case DB_TimeStampz:
  47. return "timestamp with time zone"
  48. case DB_Float:
  49. res = DB_Real
  50. case DB_TinyText, DB_MediumText, DB_LongText:
  51. res = DB_Text
  52. case DB_NVarchar:
  53. res = DB_Varchar
  54. case DB_Uuid:
  55. res = DB_Uuid
  56. case DB_Blob, DB_TinyBlob, DB_MediumBlob, DB_LongBlob:
  57. return DB_Bytea
  58. case DB_Double:
  59. return "DOUBLE PRECISION"
  60. default:
  61. if c.IsAutoIncrement {
  62. return DB_Serial
  63. }
  64. res = t
  65. }
  66. var hasLen1 bool = (c.Length > 0)
  67. var hasLen2 bool = (c.Length2 > 0)
  68. if hasLen2 {
  69. res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")"
  70. } else if hasLen1 {
  71. res += "(" + strconv.Itoa(c.Length) + ")"
  72. }
  73. return res
  74. }
  75. func (db *Postgres) TableCheckSql(tableName string) (string, []interface{}) {
  76. args := []interface{}{"grafana", tableName}
  77. sql := "SELECT `TABLE_NAME` from `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA`=? and `TABLE_NAME`=?"
  78. return sql, args
  79. }
  80. func (db *Postgres) DropIndexSql(tableName string, index *Index) string {
  81. quote := db.Quote
  82. idxName := index.XName(tableName)
  83. return fmt.Sprintf("DROP INDEX %v", quote(idxName))
  84. }