db_postgres.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. // Copyright 2014 beego Author. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package orm
  15. import (
  16. "fmt"
  17. "strconv"
  18. )
  19. // postgresql operators.
  20. var postgresOperators = map[string]string{
  21. "exact": "= ?",
  22. "iexact": "= UPPER(?)",
  23. "contains": "LIKE ?",
  24. "icontains": "LIKE UPPER(?)",
  25. "gt": "> ?",
  26. "gte": ">= ?",
  27. "lt": "< ?",
  28. "lte": "<= ?",
  29. "eq": "= ?",
  30. "ne": "!= ?",
  31. "startswith": "LIKE ?",
  32. "endswith": "LIKE ?",
  33. "istartswith": "LIKE UPPER(?)",
  34. "iendswith": "LIKE UPPER(?)",
  35. }
  36. // postgresql column field types.
  37. var postgresTypes = map[string]string{
  38. "auto": "serial NOT NULL PRIMARY KEY",
  39. "pk": "NOT NULL PRIMARY KEY",
  40. "bool": "bool",
  41. "string": "varchar(%d)",
  42. "string-text": "text",
  43. "time.Time-date": "date",
  44. "time.Time": "timestamp with time zone",
  45. "int8": `smallint CHECK("%COL%" >= -127 AND "%COL%" <= 128)`,
  46. "int16": "smallint",
  47. "int32": "integer",
  48. "int64": "bigint",
  49. "uint8": `smallint CHECK("%COL%" >= 0 AND "%COL%" <= 255)`,
  50. "uint16": `integer CHECK("%COL%" >= 0)`,
  51. "uint32": `bigint CHECK("%COL%" >= 0)`,
  52. "uint64": `bigint CHECK("%COL%" >= 0)`,
  53. "float64": "double precision",
  54. "float64-decimal": "numeric(%d, %d)",
  55. "json": "json",
  56. "jsonb": "jsonb",
  57. }
  58. // postgresql dbBaser.
  59. type dbBasePostgres struct {
  60. dbBase
  61. }
  62. var _ dbBaser = new(dbBasePostgres)
  63. // get postgresql operator.
  64. func (d *dbBasePostgres) OperatorSQL(operator string) string {
  65. return postgresOperators[operator]
  66. }
  67. // generate functioned sql string, such as contains(text).
  68. func (d *dbBasePostgres) GenerateOperatorLeftCol(fi *fieldInfo, operator string, leftCol *string) {
  69. switch operator {
  70. case "contains", "startswith", "endswith":
  71. *leftCol = fmt.Sprintf("%s::text", *leftCol)
  72. case "iexact", "icontains", "istartswith", "iendswith":
  73. *leftCol = fmt.Sprintf("UPPER(%s::text)", *leftCol)
  74. }
  75. }
  76. // postgresql unsupports updating joined record.
  77. func (d *dbBasePostgres) SupportUpdateJoin() bool {
  78. return false
  79. }
  80. func (d *dbBasePostgres) MaxLimit() uint64 {
  81. return 0
  82. }
  83. // postgresql quote is ".
  84. func (d *dbBasePostgres) TableQuote() string {
  85. return `"`
  86. }
  87. // postgresql value placeholder is $n.
  88. // replace default ? to $n.
  89. func (d *dbBasePostgres) ReplaceMarks(query *string) {
  90. q := *query
  91. num := 0
  92. for _, c := range q {
  93. if c == '?' {
  94. num++
  95. }
  96. }
  97. if num == 0 {
  98. return
  99. }
  100. data := make([]byte, 0, len(q)+num)
  101. num = 1
  102. for i := 0; i < len(q); i++ {
  103. c := q[i]
  104. if c == '?' {
  105. data = append(data, '$')
  106. data = append(data, []byte(strconv.Itoa(num))...)
  107. num++
  108. } else {
  109. data = append(data, c)
  110. }
  111. }
  112. *query = string(data)
  113. }
  114. // make returning sql support for postgresql.
  115. func (d *dbBasePostgres) HasReturningID(mi *modelInfo, query *string) bool {
  116. fi := mi.fields.pk
  117. if fi.fieldType&IsPositiveIntegerField == 0 && fi.fieldType&IsIntegerField == 0 {
  118. return false
  119. }
  120. if query != nil {
  121. *query = fmt.Sprintf(`%s RETURNING "%s"`, *query, fi.column)
  122. }
  123. return true
  124. }
  125. // sync auto key
  126. func (d *dbBasePostgres) setval(db dbQuerier, mi *modelInfo, autoFields []string) error {
  127. if len(autoFields) == 0 {
  128. return nil
  129. }
  130. Q := d.ins.TableQuote()
  131. for _, name := range autoFields {
  132. query := fmt.Sprintf("SELECT setval(pg_get_serial_sequence('%s', '%s'), (SELECT MAX(%s%s%s) FROM %s%s%s));",
  133. mi.table, name,
  134. Q, name, Q,
  135. Q, mi.table, Q)
  136. if _, err := db.Exec(query); err != nil {
  137. return err
  138. }
  139. }
  140. return nil
  141. }
  142. // show table sql for postgresql.
  143. func (d *dbBasePostgres) ShowTablesQuery() string {
  144. return "SELECT table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE' AND table_schema NOT IN ('pg_catalog', 'information_schema')"
  145. }
  146. // show table columns sql for postgresql.
  147. func (d *dbBasePostgres) ShowColumnsQuery(table string) string {
  148. return fmt.Sprintf("SELECT column_name, data_type, is_nullable FROM information_schema.columns where table_schema NOT IN ('pg_catalog', 'information_schema') and table_name = '%s'", table)
  149. }
  150. // get column types of postgresql.
  151. func (d *dbBasePostgres) DbTypes() map[string]string {
  152. return postgresTypes
  153. }
  154. // check index exist in postgresql.
  155. func (d *dbBasePostgres) IndexExists(db dbQuerier, table string, name string) bool {
  156. query := fmt.Sprintf("SELECT COUNT(*) FROM pg_indexes WHERE tablename = '%s' AND indexname = '%s'", table, name)
  157. row := db.QueryRow(query)
  158. var cnt int
  159. row.Scan(&cnt)
  160. return cnt > 0
  161. }
  162. // create new postgresql dbBaser.
  163. func newdbBasePostgres() dbBaser {
  164. b := new(dbBasePostgres)
  165. b.ins = b
  166. return b
  167. }