ddl.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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 migration
  15. import (
  16. "fmt"
  17. "github.com/cnlh/nps/vender/github.com/astaxie/beego"
  18. )
  19. // Index struct defines the structure of Index Columns
  20. type Index struct {
  21. Name string
  22. }
  23. // Unique struct defines a single unique key combination
  24. type Unique struct {
  25. Definition string
  26. Columns []*Column
  27. }
  28. //Column struct defines a single column of a table
  29. type Column struct {
  30. Name string
  31. Inc string
  32. Null string
  33. Default string
  34. Unsign string
  35. DataType string
  36. remove bool
  37. Modify bool
  38. }
  39. // Foreign struct defines a single foreign relationship
  40. type Foreign struct {
  41. ForeignTable string
  42. ForeignColumn string
  43. OnDelete string
  44. OnUpdate string
  45. Column
  46. }
  47. // RenameColumn struct allows renaming of columns
  48. type RenameColumn struct {
  49. OldName string
  50. OldNull string
  51. OldDefault string
  52. OldUnsign string
  53. OldDataType string
  54. NewName string
  55. Column
  56. }
  57. // CreateTable creates the table on system
  58. func (m *Migration) CreateTable(tablename, engine, charset string, p ...func()) {
  59. m.TableName = tablename
  60. m.Engine = engine
  61. m.Charset = charset
  62. m.ModifyType = "create"
  63. }
  64. // AlterTable set the ModifyType to alter
  65. func (m *Migration) AlterTable(tablename string) {
  66. m.TableName = tablename
  67. m.ModifyType = "alter"
  68. }
  69. // NewCol creates a new standard column and attaches it to m struct
  70. func (m *Migration) NewCol(name string) *Column {
  71. col := &Column{Name: name}
  72. m.AddColumns(col)
  73. return col
  74. }
  75. //PriCol creates a new primary column and attaches it to m struct
  76. func (m *Migration) PriCol(name string) *Column {
  77. col := &Column{Name: name}
  78. m.AddColumns(col)
  79. m.AddPrimary(col)
  80. return col
  81. }
  82. //UniCol creates / appends columns to specified unique key and attaches it to m struct
  83. func (m *Migration) UniCol(uni, name string) *Column {
  84. col := &Column{Name: name}
  85. m.AddColumns(col)
  86. uniqueOriginal := &Unique{}
  87. for _, unique := range m.Uniques {
  88. if unique.Definition == uni {
  89. unique.AddColumnsToUnique(col)
  90. uniqueOriginal = unique
  91. }
  92. }
  93. if uniqueOriginal.Definition == "" {
  94. unique := &Unique{Definition: uni}
  95. unique.AddColumnsToUnique(col)
  96. m.AddUnique(unique)
  97. }
  98. return col
  99. }
  100. //ForeignCol creates a new foreign column and returns the instance of column
  101. func (m *Migration) ForeignCol(colname, foreigncol, foreigntable string) (foreign *Foreign) {
  102. foreign = &Foreign{ForeignColumn: foreigncol, ForeignTable: foreigntable}
  103. foreign.Name = colname
  104. m.AddForeign(foreign)
  105. return foreign
  106. }
  107. //SetOnDelete sets the on delete of foreign
  108. func (foreign *Foreign) SetOnDelete(del string) *Foreign {
  109. foreign.OnDelete = "ON DELETE" + del
  110. return foreign
  111. }
  112. //SetOnUpdate sets the on update of foreign
  113. func (foreign *Foreign) SetOnUpdate(update string) *Foreign {
  114. foreign.OnUpdate = "ON UPDATE" + update
  115. return foreign
  116. }
  117. //Remove marks the columns to be removed.
  118. //it allows reverse m to create the column.
  119. func (c *Column) Remove() {
  120. c.remove = true
  121. }
  122. //SetAuto enables auto_increment of column (can be used once)
  123. func (c *Column) SetAuto(inc bool) *Column {
  124. if inc {
  125. c.Inc = "auto_increment"
  126. }
  127. return c
  128. }
  129. //SetNullable sets the column to be null
  130. func (c *Column) SetNullable(null bool) *Column {
  131. if null {
  132. c.Null = ""
  133. } else {
  134. c.Null = "NOT NULL"
  135. }
  136. return c
  137. }
  138. //SetDefault sets the default value, prepend with "DEFAULT "
  139. func (c *Column) SetDefault(def string) *Column {
  140. c.Default = "DEFAULT " + def
  141. return c
  142. }
  143. //SetUnsigned sets the column to be unsigned int
  144. func (c *Column) SetUnsigned(unsign bool) *Column {
  145. if unsign {
  146. c.Unsign = "UNSIGNED"
  147. }
  148. return c
  149. }
  150. //SetDataType sets the dataType of the column
  151. func (c *Column) SetDataType(dataType string) *Column {
  152. c.DataType = dataType
  153. return c
  154. }
  155. //SetOldNullable allows reverting to previous nullable on reverse ms
  156. func (c *RenameColumn) SetOldNullable(null bool) *RenameColumn {
  157. if null {
  158. c.OldNull = ""
  159. } else {
  160. c.OldNull = "NOT NULL"
  161. }
  162. return c
  163. }
  164. //SetOldDefault allows reverting to previous default on reverse ms
  165. func (c *RenameColumn) SetOldDefault(def string) *RenameColumn {
  166. c.OldDefault = def
  167. return c
  168. }
  169. //SetOldUnsigned allows reverting to previous unsgined on reverse ms
  170. func (c *RenameColumn) SetOldUnsigned(unsign bool) *RenameColumn {
  171. if unsign {
  172. c.OldUnsign = "UNSIGNED"
  173. }
  174. return c
  175. }
  176. //SetOldDataType allows reverting to previous datatype on reverse ms
  177. func (c *RenameColumn) SetOldDataType(dataType string) *RenameColumn {
  178. c.OldDataType = dataType
  179. return c
  180. }
  181. //SetPrimary adds the columns to the primary key (can only be used any number of times in only one m)
  182. func (c *Column) SetPrimary(m *Migration) *Column {
  183. m.Primary = append(m.Primary, c)
  184. return c
  185. }
  186. //AddColumnsToUnique adds the columns to Unique Struct
  187. func (unique *Unique) AddColumnsToUnique(columns ...*Column) *Unique {
  188. unique.Columns = append(unique.Columns, columns...)
  189. return unique
  190. }
  191. //AddColumns adds columns to m struct
  192. func (m *Migration) AddColumns(columns ...*Column) *Migration {
  193. m.Columns = append(m.Columns, columns...)
  194. return m
  195. }
  196. //AddPrimary adds the column to primary in m struct
  197. func (m *Migration) AddPrimary(primary *Column) *Migration {
  198. m.Primary = append(m.Primary, primary)
  199. return m
  200. }
  201. //AddUnique adds the column to unique in m struct
  202. func (m *Migration) AddUnique(unique *Unique) *Migration {
  203. m.Uniques = append(m.Uniques, unique)
  204. return m
  205. }
  206. //AddForeign adds the column to foreign in m struct
  207. func (m *Migration) AddForeign(foreign *Foreign) *Migration {
  208. m.Foreigns = append(m.Foreigns, foreign)
  209. return m
  210. }
  211. //AddIndex adds the column to index in m struct
  212. func (m *Migration) AddIndex(index *Index) *Migration {
  213. m.Indexes = append(m.Indexes, index)
  214. return m
  215. }
  216. //RenameColumn allows renaming of columns
  217. func (m *Migration) RenameColumn(from, to string) *RenameColumn {
  218. rename := &RenameColumn{OldName: from, NewName: to}
  219. m.Renames = append(m.Renames, rename)
  220. return rename
  221. }
  222. //GetSQL returns the generated sql depending on ModifyType
  223. func (m *Migration) GetSQL() (sql string) {
  224. sql = ""
  225. switch m.ModifyType {
  226. case "create":
  227. {
  228. sql += fmt.Sprintf("CREATE TABLE `%s` (", m.TableName)
  229. for index, column := range m.Columns {
  230. sql += fmt.Sprintf("\n `%s` %s %s %s %s %s", column.Name, column.DataType, column.Unsign, column.Null, column.Inc, column.Default)
  231. if len(m.Columns) > index+1 {
  232. sql += ","
  233. }
  234. }
  235. if len(m.Primary) > 0 {
  236. sql += fmt.Sprintf(",\n PRIMARY KEY( ")
  237. }
  238. for index, column := range m.Primary {
  239. sql += fmt.Sprintf(" `%s`", column.Name)
  240. if len(m.Primary) > index+1 {
  241. sql += ","
  242. }
  243. }
  244. if len(m.Primary) > 0 {
  245. sql += fmt.Sprintf(")")
  246. }
  247. for _, unique := range m.Uniques {
  248. sql += fmt.Sprintf(",\n UNIQUE KEY `%s`( ", unique.Definition)
  249. for index, column := range unique.Columns {
  250. sql += fmt.Sprintf(" `%s`", column.Name)
  251. if len(unique.Columns) > index+1 {
  252. sql += ","
  253. }
  254. }
  255. sql += fmt.Sprintf(")")
  256. }
  257. for _, foreign := range m.Foreigns {
  258. sql += fmt.Sprintf(",\n `%s` %s %s %s %s %s", foreign.Name, foreign.DataType, foreign.Unsign, foreign.Null, foreign.Inc, foreign.Default)
  259. sql += fmt.Sprintf(",\n KEY `%s_%s_foreign`(`%s`),", m.TableName, foreign.Column.Name, foreign.Column.Name)
  260. sql += fmt.Sprintf("\n CONSTRAINT `%s_%s_foreign` FOREIGN KEY (`%s`) REFERENCES `%s` (`%s`) %s %s", m.TableName, foreign.Column.Name, foreign.Column.Name, foreign.ForeignTable, foreign.ForeignColumn, foreign.OnDelete, foreign.OnUpdate)
  261. }
  262. sql += fmt.Sprintf(")ENGINE=%s DEFAULT CHARSET=%s;", m.Engine, m.Charset)
  263. break
  264. }
  265. case "alter":
  266. {
  267. sql += fmt.Sprintf("ALTER TABLE `%s` ", m.TableName)
  268. for index, column := range m.Columns {
  269. if !column.remove {
  270. beego.BeeLogger.Info("col")
  271. sql += fmt.Sprintf("\n ADD `%s` %s %s %s %s %s", column.Name, column.DataType, column.Unsign, column.Null, column.Inc, column.Default)
  272. } else {
  273. sql += fmt.Sprintf("\n DROP COLUMN `%s`", column.Name)
  274. }
  275. if len(m.Columns) > index+1 {
  276. sql += ","
  277. }
  278. }
  279. for index, column := range m.Renames {
  280. sql += fmt.Sprintf("CHANGE COLUMN `%s` `%s` %s %s %s %s %s", column.OldName, column.NewName, column.DataType, column.Unsign, column.Null, column.Inc, column.Default)
  281. if len(m.Renames) > index+1 {
  282. sql += ","
  283. }
  284. }
  285. for index, foreign := range m.Foreigns {
  286. sql += fmt.Sprintf("ADD `%s` %s %s %s %s %s", foreign.Name, foreign.DataType, foreign.Unsign, foreign.Null, foreign.Inc, foreign.Default)
  287. sql += fmt.Sprintf(",\n ADD KEY `%s_%s_foreign`(`%s`)", m.TableName, foreign.Column.Name, foreign.Column.Name)
  288. sql += fmt.Sprintf(",\n ADD CONSTRAINT `%s_%s_foreign` FOREIGN KEY (`%s`) REFERENCES `%s` (`%s`) %s %s", m.TableName, foreign.Column.Name, foreign.Column.Name, foreign.ForeignTable, foreign.ForeignColumn, foreign.OnDelete, foreign.OnUpdate)
  289. if len(m.Foreigns) > index+1 {
  290. sql += ","
  291. }
  292. }
  293. sql += ";"
  294. break
  295. }
  296. case "reverse":
  297. {
  298. sql += fmt.Sprintf("ALTER TABLE `%s`", m.TableName)
  299. for index, column := range m.Columns {
  300. if column.remove {
  301. sql += fmt.Sprintf("\n ADD `%s` %s %s %s %s %s", column.Name, column.DataType, column.Unsign, column.Null, column.Inc, column.Default)
  302. } else {
  303. sql += fmt.Sprintf("\n DROP COLUMN `%s`", column.Name)
  304. }
  305. if len(m.Columns) > index+1 {
  306. sql += ","
  307. }
  308. }
  309. if len(m.Primary) > 0 {
  310. sql += fmt.Sprintf("\n DROP PRIMARY KEY,")
  311. }
  312. for index, unique := range m.Uniques {
  313. sql += fmt.Sprintf("\n DROP KEY `%s`", unique.Definition)
  314. if len(m.Uniques) > index+1 {
  315. sql += ","
  316. }
  317. }
  318. for index, column := range m.Renames {
  319. sql += fmt.Sprintf("\n CHANGE COLUMN `%s` `%s` %s %s %s %s", column.NewName, column.OldName, column.OldDataType, column.OldUnsign, column.OldNull, column.OldDefault)
  320. if len(m.Renames) > index+1 {
  321. sql += ","
  322. }
  323. }
  324. for _, foreign := range m.Foreigns {
  325. sql += fmt.Sprintf("\n DROP KEY `%s_%s_foreign`", m.TableName, foreign.Column.Name)
  326. sql += fmt.Sprintf(",\n DROP FOREIGN KEY `%s_%s_foreign`", m.TableName, foreign.Column.Name)
  327. sql += fmt.Sprintf(",\n DROP COLUMN `%s`", foreign.Name)
  328. }
  329. sql += ";"
  330. }
  331. case "delete":
  332. {
  333. sql += fmt.Sprintf("DROP TABLE IF EXISTS `%s`;", m.TableName)
  334. }
  335. }
  336. return
  337. }