dialect_postgres.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. package gorm
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "reflect"
  6. "strings"
  7. "time"
  8. )
  9. type postgres struct {
  10. commonDialect
  11. }
  12. func init() {
  13. RegisterDialect("postgres", &postgres{})
  14. RegisterDialect("cloudsqlpostgres", &postgres{})
  15. }
  16. func (postgres) GetName() string {
  17. return "postgres"
  18. }
  19. func (postgres) BindVar(i int) string {
  20. return fmt.Sprintf("$%v", i)
  21. }
  22. func (s *postgres) DataTypeOf(field *StructField) string {
  23. var dataValue, sqlType, size, additionalType = ParseFieldStructForDialect(field, s)
  24. if sqlType == "" {
  25. switch dataValue.Kind() {
  26. case reflect.Bool:
  27. sqlType = "boolean"
  28. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uintptr:
  29. if s.fieldCanAutoIncrement(field) {
  30. field.TagSettingsSet("AUTO_INCREMENT", "AUTO_INCREMENT")
  31. sqlType = "serial"
  32. } else {
  33. sqlType = "integer"
  34. }
  35. case reflect.Int64, reflect.Uint32, reflect.Uint64:
  36. if s.fieldCanAutoIncrement(field) {
  37. field.TagSettingsSet("AUTO_INCREMENT", "AUTO_INCREMENT")
  38. sqlType = "bigserial"
  39. } else {
  40. sqlType = "bigint"
  41. }
  42. case reflect.Float32, reflect.Float64:
  43. sqlType = "numeric"
  44. case reflect.String:
  45. if _, ok := field.TagSettingsGet("SIZE"); !ok {
  46. size = 0 // if SIZE haven't been set, use `text` as the default type, as there are no performance different
  47. }
  48. if size > 0 && size < 65532 {
  49. sqlType = fmt.Sprintf("varchar(%d)", size)
  50. } else {
  51. sqlType = "text"
  52. }
  53. case reflect.Struct:
  54. if _, ok := dataValue.Interface().(time.Time); ok {
  55. sqlType = "timestamp with time zone"
  56. }
  57. case reflect.Map:
  58. if dataValue.Type().Name() == "Hstore" {
  59. sqlType = "hstore"
  60. }
  61. default:
  62. if IsByteArrayOrSlice(dataValue) {
  63. sqlType = "bytea"
  64. if isUUID(dataValue) {
  65. sqlType = "uuid"
  66. }
  67. if isJSON(dataValue) {
  68. sqlType = "jsonb"
  69. }
  70. }
  71. }
  72. }
  73. if sqlType == "" {
  74. panic(fmt.Sprintf("invalid sql type %s (%s) for postgres", dataValue.Type().Name(), dataValue.Kind().String()))
  75. }
  76. if strings.TrimSpace(additionalType) == "" {
  77. return sqlType
  78. }
  79. return fmt.Sprintf("%v %v", sqlType, additionalType)
  80. }
  81. func (s postgres) HasIndex(tableName string, indexName string) bool {
  82. var count int
  83. s.db.QueryRow("SELECT count(*) FROM pg_indexes WHERE tablename = $1 AND indexname = $2 AND schemaname = CURRENT_SCHEMA()", tableName, indexName).Scan(&count)
  84. return count > 0
  85. }
  86. func (s postgres) HasForeignKey(tableName string, foreignKeyName string) bool {
  87. var count int
  88. s.db.QueryRow("SELECT count(con.conname) FROM pg_constraint con WHERE $1::regclass::oid = con.conrelid AND con.conname = $2 AND con.contype='f'", tableName, foreignKeyName).Scan(&count)
  89. return count > 0
  90. }
  91. func (s postgres) HasTable(tableName string) bool {
  92. var count int
  93. s.db.QueryRow("SELECT count(*) FROM INFORMATION_SCHEMA.tables WHERE table_name = $1 AND table_type = 'BASE TABLE' AND table_schema = CURRENT_SCHEMA()", tableName).Scan(&count)
  94. return count > 0
  95. }
  96. func (s postgres) HasColumn(tableName string, columnName string) bool {
  97. var count int
  98. s.db.QueryRow("SELECT count(*) FROM INFORMATION_SCHEMA.columns WHERE table_name = $1 AND column_name = $2 AND table_schema = CURRENT_SCHEMA()", tableName, columnName).Scan(&count)
  99. return count > 0
  100. }
  101. func (s postgres) CurrentDatabase() (name string) {
  102. s.db.QueryRow("SELECT CURRENT_DATABASE()").Scan(&name)
  103. return
  104. }
  105. func (s postgres) LastInsertIDOutputInterstitial(tableName, key string, columns []string) string {
  106. return ""
  107. }
  108. func (s postgres) LastInsertIDReturningSuffix(tableName, key string) string {
  109. return fmt.Sprintf("RETURNING %v.%v", tableName, key)
  110. }
  111. func (postgres) SupportLastInsertID() bool {
  112. return false
  113. }
  114. func isUUID(value reflect.Value) bool {
  115. if value.Kind() != reflect.Array || value.Type().Len() != 16 {
  116. return false
  117. }
  118. typename := value.Type().Name()
  119. lower := strings.ToLower(typename)
  120. return "uuid" == lower || "guid" == lower
  121. }
  122. func isJSON(value reflect.Value) bool {
  123. _, ok := value.Interface().(json.RawMessage)
  124. return ok
  125. }