ddl.go 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666
  1. // Copyright 2015 PingCAP, Inc.
  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. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. package ast
  14. import (
  15. "github.com/pingcap/errors"
  16. "github.com/pingcap/parser/auth"
  17. "github.com/pingcap/parser/format"
  18. "github.com/pingcap/parser/model"
  19. "github.com/pingcap/parser/mysql"
  20. "github.com/pingcap/parser/terror"
  21. "github.com/pingcap/parser/types"
  22. )
  23. var (
  24. _ DDLNode = &AlterTableStmt{}
  25. _ DDLNode = &AlterSequenceStmt{}
  26. _ DDLNode = &CreateDatabaseStmt{}
  27. _ DDLNode = &CreateIndexStmt{}
  28. _ DDLNode = &CreateTableStmt{}
  29. _ DDLNode = &CreateViewStmt{}
  30. _ DDLNode = &CreateSequenceStmt{}
  31. _ DDLNode = &DropDatabaseStmt{}
  32. _ DDLNode = &DropIndexStmt{}
  33. _ DDLNode = &DropTableStmt{}
  34. _ DDLNode = &DropSequenceStmt{}
  35. _ DDLNode = &RenameTableStmt{}
  36. _ DDLNode = &TruncateTableStmt{}
  37. _ DDLNode = &RepairTableStmt{}
  38. _ Node = &AlterTableSpec{}
  39. _ Node = &ColumnDef{}
  40. _ Node = &ColumnOption{}
  41. _ Node = &ColumnPosition{}
  42. _ Node = &Constraint{}
  43. _ Node = &IndexPartSpecification{}
  44. _ Node = &ReferenceDef{}
  45. )
  46. // CharsetOpt is used for parsing charset option from SQL.
  47. type CharsetOpt struct {
  48. Chs string
  49. Col string
  50. }
  51. // NullString represents a string that may be nil.
  52. type NullString struct {
  53. String string
  54. Empty bool // Empty is true if String is empty backtick.
  55. }
  56. // DatabaseOptionType is the type for database options.
  57. type DatabaseOptionType int
  58. // Database option types.
  59. const (
  60. DatabaseOptionNone DatabaseOptionType = iota
  61. DatabaseOptionCharset
  62. DatabaseOptionCollate
  63. DatabaseOptionEncryption
  64. )
  65. // DatabaseOption represents database option.
  66. type DatabaseOption struct {
  67. Tp DatabaseOptionType
  68. Value string
  69. }
  70. // Restore implements Node interface.
  71. func (n *DatabaseOption) Restore(ctx *format.RestoreCtx) error {
  72. switch n.Tp {
  73. case DatabaseOptionCharset:
  74. ctx.WriteKeyWord("CHARACTER SET")
  75. ctx.WritePlain(" = ")
  76. ctx.WritePlain(n.Value)
  77. case DatabaseOptionCollate:
  78. ctx.WriteKeyWord("COLLATE")
  79. ctx.WritePlain(" = ")
  80. ctx.WritePlain(n.Value)
  81. case DatabaseOptionEncryption:
  82. ctx.WriteKeyWord("ENCRYPTION")
  83. ctx.WritePlain(" = ")
  84. ctx.WriteString(n.Value)
  85. default:
  86. return errors.Errorf("invalid DatabaseOptionType: %d", n.Tp)
  87. }
  88. return nil
  89. }
  90. // CreateDatabaseStmt is a statement to create a database.
  91. // See https://dev.mysql.com/doc/refman/5.7/en/create-database.html
  92. type CreateDatabaseStmt struct {
  93. ddlNode
  94. IfNotExists bool
  95. Name string
  96. Options []*DatabaseOption
  97. }
  98. // Restore implements Node interface.
  99. func (n *CreateDatabaseStmt) Restore(ctx *format.RestoreCtx) error {
  100. ctx.WriteKeyWord("CREATE DATABASE ")
  101. if n.IfNotExists {
  102. ctx.WriteKeyWord("IF NOT EXISTS ")
  103. }
  104. ctx.WriteName(n.Name)
  105. for i, option := range n.Options {
  106. ctx.WritePlain(" ")
  107. err := option.Restore(ctx)
  108. if err != nil {
  109. return errors.Annotatef(err, "An error occurred while splicing CreateDatabaseStmt DatabaseOption: [%v]", i)
  110. }
  111. }
  112. return nil
  113. }
  114. // Accept implements Node Accept interface.
  115. func (n *CreateDatabaseStmt) Accept(v Visitor) (Node, bool) {
  116. newNode, skipChildren := v.Enter(n)
  117. if skipChildren {
  118. return v.Leave(newNode)
  119. }
  120. n = newNode.(*CreateDatabaseStmt)
  121. return v.Leave(n)
  122. }
  123. // AlterDatabaseStmt is a statement to change the structure of a database.
  124. // See https://dev.mysql.com/doc/refman/5.7/en/alter-database.html
  125. type AlterDatabaseStmt struct {
  126. ddlNode
  127. Name string
  128. AlterDefaultDatabase bool
  129. Options []*DatabaseOption
  130. }
  131. // Restore implements Node interface.
  132. func (n *AlterDatabaseStmt) Restore(ctx *format.RestoreCtx) error {
  133. ctx.WriteKeyWord("ALTER DATABASE")
  134. if !n.AlterDefaultDatabase {
  135. ctx.WritePlain(" ")
  136. ctx.WriteName(n.Name)
  137. }
  138. for i, option := range n.Options {
  139. ctx.WritePlain(" ")
  140. err := option.Restore(ctx)
  141. if err != nil {
  142. return errors.Annotatef(err, "An error occurred while splicing AlterDatabaseStmt DatabaseOption: [%v]", i)
  143. }
  144. }
  145. return nil
  146. }
  147. // Accept implements Node Accept interface.
  148. func (n *AlterDatabaseStmt) Accept(v Visitor) (Node, bool) {
  149. newNode, skipChildren := v.Enter(n)
  150. if skipChildren {
  151. return v.Leave(newNode)
  152. }
  153. n = newNode.(*AlterDatabaseStmt)
  154. return v.Leave(n)
  155. }
  156. // DropDatabaseStmt is a statement to drop a database and all tables in the database.
  157. // See https://dev.mysql.com/doc/refman/5.7/en/drop-database.html
  158. type DropDatabaseStmt struct {
  159. ddlNode
  160. IfExists bool
  161. Name string
  162. }
  163. // Restore implements Node interface.
  164. func (n *DropDatabaseStmt) Restore(ctx *format.RestoreCtx) error {
  165. ctx.WriteKeyWord("DROP DATABASE ")
  166. if n.IfExists {
  167. ctx.WriteKeyWord("IF EXISTS ")
  168. }
  169. ctx.WriteName(n.Name)
  170. return nil
  171. }
  172. // Accept implements Node Accept interface.
  173. func (n *DropDatabaseStmt) Accept(v Visitor) (Node, bool) {
  174. newNode, skipChildren := v.Enter(n)
  175. if skipChildren {
  176. return v.Leave(newNode)
  177. }
  178. n = newNode.(*DropDatabaseStmt)
  179. return v.Leave(n)
  180. }
  181. // IndexPartSpecifications is used for parsing index column name or index expression from SQL.
  182. type IndexPartSpecification struct {
  183. node
  184. Column *ColumnName
  185. Length int
  186. Expr ExprNode
  187. }
  188. // Restore implements Node interface.
  189. func (n *IndexPartSpecification) Restore(ctx *format.RestoreCtx) error {
  190. if n.Expr != nil {
  191. ctx.WritePlain("(")
  192. if err := n.Expr.Restore(ctx); err != nil {
  193. return errors.Annotate(err, "An error occurred while splicing IndexPartSpecifications")
  194. }
  195. ctx.WritePlain(")")
  196. return nil
  197. }
  198. if err := n.Column.Restore(ctx); err != nil {
  199. return errors.Annotate(err, "An error occurred while splicing IndexPartSpecifications")
  200. }
  201. if n.Length > 0 {
  202. ctx.WritePlainf("(%d)", n.Length)
  203. }
  204. return nil
  205. }
  206. // Accept implements Node Accept interface.
  207. func (n *IndexPartSpecification) Accept(v Visitor) (Node, bool) {
  208. newNode, skipChildren := v.Enter(n)
  209. if skipChildren {
  210. return v.Leave(newNode)
  211. }
  212. n = newNode.(*IndexPartSpecification)
  213. if n.Expr != nil {
  214. node, ok := n.Expr.Accept(v)
  215. if !ok {
  216. return n, false
  217. }
  218. n.Expr = node.(ExprNode)
  219. return v.Leave(n)
  220. }
  221. node, ok := n.Column.Accept(v)
  222. if !ok {
  223. return n, false
  224. }
  225. n.Column = node.(*ColumnName)
  226. return v.Leave(n)
  227. }
  228. // MatchType is the type for reference match type.
  229. type MatchType int
  230. // match type
  231. const (
  232. MatchNone MatchType = iota
  233. MatchFull
  234. MatchPartial
  235. MatchSimple
  236. )
  237. // ReferenceDef is used for parsing foreign key reference option from SQL.
  238. // See http://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html
  239. type ReferenceDef struct {
  240. node
  241. Table *TableName
  242. IndexPartSpecifications []*IndexPartSpecification
  243. OnDelete *OnDeleteOpt
  244. OnUpdate *OnUpdateOpt
  245. Match MatchType
  246. }
  247. // Restore implements Node interface.
  248. func (n *ReferenceDef) Restore(ctx *format.RestoreCtx) error {
  249. if n.Table != nil {
  250. ctx.WriteKeyWord("REFERENCES ")
  251. if err := n.Table.Restore(ctx); err != nil {
  252. return errors.Annotate(err, "An error occurred while splicing ReferenceDef")
  253. }
  254. }
  255. if n.IndexPartSpecifications != nil {
  256. ctx.WritePlain("(")
  257. for i, indexColNames := range n.IndexPartSpecifications {
  258. if i > 0 {
  259. ctx.WritePlain(", ")
  260. }
  261. if err := indexColNames.Restore(ctx); err != nil {
  262. return errors.Annotatef(err, "An error occurred while splicing IndexPartSpecifications: [%v]", i)
  263. }
  264. }
  265. ctx.WritePlain(")")
  266. }
  267. if n.Match != MatchNone {
  268. ctx.WriteKeyWord(" MATCH ")
  269. switch n.Match {
  270. case MatchFull:
  271. ctx.WriteKeyWord("FULL")
  272. case MatchPartial:
  273. ctx.WriteKeyWord("PARTIAL")
  274. case MatchSimple:
  275. ctx.WriteKeyWord("SIMPLE")
  276. }
  277. }
  278. if n.OnDelete.ReferOpt != ReferOptionNoOption {
  279. ctx.WritePlain(" ")
  280. if err := n.OnDelete.Restore(ctx); err != nil {
  281. return errors.Annotate(err, "An error occurred while splicing OnDelete")
  282. }
  283. }
  284. if n.OnUpdate.ReferOpt != ReferOptionNoOption {
  285. ctx.WritePlain(" ")
  286. if err := n.OnUpdate.Restore(ctx); err != nil {
  287. return errors.Annotate(err, "An error occurred while splicing OnUpdate")
  288. }
  289. }
  290. return nil
  291. }
  292. // Accept implements Node Accept interface.
  293. func (n *ReferenceDef) Accept(v Visitor) (Node, bool) {
  294. newNode, skipChildren := v.Enter(n)
  295. if skipChildren {
  296. return v.Leave(newNode)
  297. }
  298. n = newNode.(*ReferenceDef)
  299. if n.Table != nil {
  300. node, ok := n.Table.Accept(v)
  301. if !ok {
  302. return n, false
  303. }
  304. n.Table = node.(*TableName)
  305. }
  306. for i, val := range n.IndexPartSpecifications {
  307. node, ok := val.Accept(v)
  308. if !ok {
  309. return n, false
  310. }
  311. n.IndexPartSpecifications[i] = node.(*IndexPartSpecification)
  312. }
  313. onDelete, ok := n.OnDelete.Accept(v)
  314. if !ok {
  315. return n, false
  316. }
  317. n.OnDelete = onDelete.(*OnDeleteOpt)
  318. onUpdate, ok := n.OnUpdate.Accept(v)
  319. if !ok {
  320. return n, false
  321. }
  322. n.OnUpdate = onUpdate.(*OnUpdateOpt)
  323. return v.Leave(n)
  324. }
  325. // ReferOptionType is the type for refer options.
  326. type ReferOptionType int
  327. // Refer option types.
  328. const (
  329. ReferOptionNoOption ReferOptionType = iota
  330. ReferOptionRestrict
  331. ReferOptionCascade
  332. ReferOptionSetNull
  333. ReferOptionNoAction
  334. ReferOptionSetDefault
  335. )
  336. // String implements fmt.Stringer interface.
  337. func (r ReferOptionType) String() string {
  338. switch r {
  339. case ReferOptionRestrict:
  340. return "RESTRICT"
  341. case ReferOptionCascade:
  342. return "CASCADE"
  343. case ReferOptionSetNull:
  344. return "SET NULL"
  345. case ReferOptionNoAction:
  346. return "NO ACTION"
  347. case ReferOptionSetDefault:
  348. return "SET DEFAULT"
  349. }
  350. return ""
  351. }
  352. // OnDeleteOpt is used for optional on delete clause.
  353. type OnDeleteOpt struct {
  354. node
  355. ReferOpt ReferOptionType
  356. }
  357. // Restore implements Node interface.
  358. func (n *OnDeleteOpt) Restore(ctx *format.RestoreCtx) error {
  359. if n.ReferOpt != ReferOptionNoOption {
  360. ctx.WriteKeyWord("ON DELETE ")
  361. ctx.WriteKeyWord(n.ReferOpt.String())
  362. }
  363. return nil
  364. }
  365. // Accept implements Node Accept interface.
  366. func (n *OnDeleteOpt) Accept(v Visitor) (Node, bool) {
  367. newNode, skipChildren := v.Enter(n)
  368. if skipChildren {
  369. return v.Leave(newNode)
  370. }
  371. n = newNode.(*OnDeleteOpt)
  372. return v.Leave(n)
  373. }
  374. // OnUpdateOpt is used for optional on update clause.
  375. type OnUpdateOpt struct {
  376. node
  377. ReferOpt ReferOptionType
  378. }
  379. // Restore implements Node interface.
  380. func (n *OnUpdateOpt) Restore(ctx *format.RestoreCtx) error {
  381. if n.ReferOpt != ReferOptionNoOption {
  382. ctx.WriteKeyWord("ON UPDATE ")
  383. ctx.WriteKeyWord(n.ReferOpt.String())
  384. }
  385. return nil
  386. }
  387. // Accept implements Node Accept interface.
  388. func (n *OnUpdateOpt) Accept(v Visitor) (Node, bool) {
  389. newNode, skipChildren := v.Enter(n)
  390. if skipChildren {
  391. return v.Leave(newNode)
  392. }
  393. n = newNode.(*OnUpdateOpt)
  394. return v.Leave(n)
  395. }
  396. // ColumnOptionType is the type for ColumnOption.
  397. type ColumnOptionType int
  398. // ColumnOption types.
  399. const (
  400. ColumnOptionNoOption ColumnOptionType = iota
  401. ColumnOptionPrimaryKey
  402. ColumnOptionNotNull
  403. ColumnOptionAutoIncrement
  404. ColumnOptionDefaultValue
  405. ColumnOptionUniqKey
  406. ColumnOptionNull
  407. ColumnOptionOnUpdate // For Timestamp and Datetime only.
  408. ColumnOptionFulltext
  409. ColumnOptionComment
  410. ColumnOptionGenerated
  411. ColumnOptionReference
  412. ColumnOptionCollate
  413. ColumnOptionCheck
  414. ColumnOptionColumnFormat
  415. ColumnOptionStorage
  416. ColumnOptionAutoRandom
  417. )
  418. var (
  419. invalidOptionForGeneratedColumn = map[ColumnOptionType]struct{}{
  420. ColumnOptionAutoIncrement: {},
  421. ColumnOptionOnUpdate: {},
  422. ColumnOptionDefaultValue: {},
  423. }
  424. )
  425. // ColumnOption is used for parsing column constraint info from SQL.
  426. type ColumnOption struct {
  427. node
  428. Tp ColumnOptionType
  429. // Expr is used for ColumnOptionDefaultValue/ColumnOptionOnUpdateColumnOptionGenerated.
  430. // For ColumnOptionDefaultValue or ColumnOptionOnUpdate, it's the target value.
  431. // For ColumnOptionGenerated, it's the target expression.
  432. Expr ExprNode
  433. // Stored is only for ColumnOptionGenerated, default is false.
  434. Stored bool
  435. // Refer is used for foreign key.
  436. Refer *ReferenceDef
  437. StrValue string
  438. AutoRandomBitLength int
  439. // Enforced is only for Check, default is true.
  440. Enforced bool
  441. // Name is only used for Check Constraint name.
  442. ConstraintName string
  443. PrimaryKeyTp model.PrimaryKeyType
  444. }
  445. // Restore implements Node interface.
  446. func (n *ColumnOption) Restore(ctx *format.RestoreCtx) error {
  447. switch n.Tp {
  448. case ColumnOptionNoOption:
  449. return nil
  450. case ColumnOptionPrimaryKey:
  451. ctx.WriteKeyWord("PRIMARY KEY")
  452. pkTp := n.PrimaryKeyTp.String()
  453. if len(pkTp) != 0 {
  454. ctx.WritePlain(" ")
  455. ctx.WriteKeyWord(pkTp)
  456. }
  457. case ColumnOptionNotNull:
  458. ctx.WriteKeyWord("NOT NULL")
  459. case ColumnOptionAutoIncrement:
  460. ctx.WriteKeyWord("AUTO_INCREMENT")
  461. case ColumnOptionDefaultValue:
  462. ctx.WriteKeyWord("DEFAULT ")
  463. if err := n.Expr.Restore(ctx); err != nil {
  464. return errors.Annotate(err, "An error occurred while splicing ColumnOption DefaultValue Expr")
  465. }
  466. case ColumnOptionUniqKey:
  467. ctx.WriteKeyWord("UNIQUE KEY")
  468. case ColumnOptionNull:
  469. ctx.WriteKeyWord("NULL")
  470. case ColumnOptionOnUpdate:
  471. ctx.WriteKeyWord("ON UPDATE ")
  472. if err := n.Expr.Restore(ctx); err != nil {
  473. return errors.Annotate(err, "An error occurred while splicing ColumnOption ON UPDATE Expr")
  474. }
  475. case ColumnOptionFulltext:
  476. return errors.New("TiDB Parser ignore the `ColumnOptionFulltext` type now")
  477. case ColumnOptionComment:
  478. ctx.WriteKeyWord("COMMENT ")
  479. if err := n.Expr.Restore(ctx); err != nil {
  480. return errors.Annotate(err, "An error occurred while splicing ColumnOption COMMENT Expr")
  481. }
  482. case ColumnOptionGenerated:
  483. ctx.WriteKeyWord("GENERATED ALWAYS AS")
  484. ctx.WritePlain("(")
  485. if err := n.Expr.Restore(ctx); err != nil {
  486. return errors.Annotate(err, "An error occurred while splicing ColumnOption GENERATED ALWAYS Expr")
  487. }
  488. ctx.WritePlain(")")
  489. if n.Stored {
  490. ctx.WriteKeyWord(" STORED")
  491. } else {
  492. ctx.WriteKeyWord(" VIRTUAL")
  493. }
  494. case ColumnOptionReference:
  495. if err := n.Refer.Restore(ctx); err != nil {
  496. return errors.Annotate(err, "An error occurred while splicing ColumnOption ReferenceDef")
  497. }
  498. case ColumnOptionCollate:
  499. if n.StrValue == "" {
  500. return errors.New("Empty ColumnOption COLLATE")
  501. }
  502. ctx.WriteKeyWord("COLLATE ")
  503. ctx.WritePlain(n.StrValue)
  504. case ColumnOptionCheck:
  505. if n.ConstraintName != "" {
  506. ctx.WriteKeyWord("CONSTRAINT ")
  507. ctx.WriteName(n.ConstraintName)
  508. ctx.WritePlain(" ")
  509. }
  510. ctx.WriteKeyWord("CHECK")
  511. ctx.WritePlain("(")
  512. if err := n.Expr.Restore(ctx); err != nil {
  513. return errors.Trace(err)
  514. }
  515. ctx.WritePlain(")")
  516. if n.Enforced {
  517. ctx.WriteKeyWord(" ENFORCED")
  518. } else {
  519. ctx.WriteKeyWord(" NOT ENFORCED")
  520. }
  521. case ColumnOptionColumnFormat:
  522. ctx.WriteKeyWord("COLUMN_FORMAT ")
  523. ctx.WriteKeyWord(n.StrValue)
  524. case ColumnOptionStorage:
  525. ctx.WriteKeyWord("STORAGE ")
  526. ctx.WriteKeyWord(n.StrValue)
  527. case ColumnOptionAutoRandom:
  528. ctx.WriteKeyWord("AUTO_RANDOM")
  529. if n.AutoRandomBitLength != types.UnspecifiedLength {
  530. ctx.WritePlainf("(%d)", n.AutoRandomBitLength)
  531. }
  532. default:
  533. return errors.New("An error occurred while splicing ColumnOption")
  534. }
  535. return nil
  536. }
  537. // Accept implements Node Accept interface.
  538. func (n *ColumnOption) Accept(v Visitor) (Node, bool) {
  539. newNode, skipChildren := v.Enter(n)
  540. if skipChildren {
  541. return v.Leave(newNode)
  542. }
  543. n = newNode.(*ColumnOption)
  544. if n.Expr != nil {
  545. node, ok := n.Expr.Accept(v)
  546. if !ok {
  547. return n, false
  548. }
  549. n.Expr = node.(ExprNode)
  550. }
  551. return v.Leave(n)
  552. }
  553. // IndexVisibility is the option for index visibility.
  554. type IndexVisibility int
  555. // IndexVisibility options.
  556. const (
  557. IndexVisibilityDefault IndexVisibility = iota
  558. IndexVisibilityVisible
  559. IndexVisibilityInvisible
  560. )
  561. // IndexOption is the index options.
  562. // KEY_BLOCK_SIZE [=] value
  563. // | index_type
  564. // | WITH PARSER parser_name
  565. // | COMMENT 'string'
  566. // See http://dev.mysql.com/doc/refman/5.7/en/create-table.html
  567. type IndexOption struct {
  568. node
  569. KeyBlockSize uint64
  570. Tp model.IndexType
  571. Comment string
  572. ParserName model.CIStr
  573. Visibility IndexVisibility
  574. PrimaryKeyTp model.PrimaryKeyType
  575. }
  576. // Restore implements Node interface.
  577. func (n *IndexOption) Restore(ctx *format.RestoreCtx) error {
  578. hasPrevOption := false
  579. if n.PrimaryKeyTp != model.PrimaryKeyTypeDefault {
  580. ctx.WriteKeyWord(n.PrimaryKeyTp.String())
  581. hasPrevOption = true
  582. }
  583. if n.KeyBlockSize > 0 {
  584. if hasPrevOption {
  585. ctx.WritePlain(" ")
  586. }
  587. ctx.WriteKeyWord("KEY_BLOCK_SIZE")
  588. ctx.WritePlainf("=%d", n.KeyBlockSize)
  589. hasPrevOption = true
  590. }
  591. if n.Tp != model.IndexTypeInvalid {
  592. if hasPrevOption {
  593. ctx.WritePlain(" ")
  594. }
  595. ctx.WriteKeyWord("USING ")
  596. ctx.WritePlain(n.Tp.String())
  597. hasPrevOption = true
  598. }
  599. if len(n.ParserName.O) > 0 {
  600. if hasPrevOption {
  601. ctx.WritePlain(" ")
  602. }
  603. ctx.WriteKeyWord("WITH PARSER ")
  604. ctx.WriteName(n.ParserName.O)
  605. hasPrevOption = true
  606. }
  607. if n.Comment != "" {
  608. if hasPrevOption {
  609. ctx.WritePlain(" ")
  610. }
  611. ctx.WriteKeyWord("COMMENT ")
  612. ctx.WriteString(n.Comment)
  613. hasPrevOption = true
  614. }
  615. if n.Visibility != IndexVisibilityDefault {
  616. if hasPrevOption {
  617. ctx.WritePlain(" ")
  618. }
  619. switch n.Visibility {
  620. case IndexVisibilityVisible:
  621. ctx.WriteKeyWord("VISIBLE")
  622. case IndexVisibilityInvisible:
  623. ctx.WriteKeyWord("INVISIBLE")
  624. }
  625. }
  626. return nil
  627. }
  628. // Accept implements Node Accept interface.
  629. func (n *IndexOption) Accept(v Visitor) (Node, bool) {
  630. newNode, skipChildren := v.Enter(n)
  631. if skipChildren {
  632. return v.Leave(newNode)
  633. }
  634. n = newNode.(*IndexOption)
  635. return v.Leave(n)
  636. }
  637. // ConstraintType is the type for Constraint.
  638. type ConstraintType int
  639. // ConstraintTypes
  640. const (
  641. ConstraintNoConstraint ConstraintType = iota
  642. ConstraintPrimaryKey
  643. ConstraintKey
  644. ConstraintIndex
  645. ConstraintUniq
  646. ConstraintUniqKey
  647. ConstraintUniqIndex
  648. ConstraintForeignKey
  649. ConstraintFulltext
  650. ConstraintCheck
  651. )
  652. // Constraint is constraint for table definition.
  653. type Constraint struct {
  654. node
  655. // only supported by MariaDB 10.0.2+ (ADD {INDEX|KEY}, ADD FOREIGN KEY),
  656. // see https://mariadb.com/kb/en/library/alter-table/
  657. IfNotExists bool
  658. Tp ConstraintType
  659. Name string
  660. Keys []*IndexPartSpecification // Used for PRIMARY KEY, UNIQUE, ......
  661. Refer *ReferenceDef // Used for foreign key.
  662. Option *IndexOption // Index Options
  663. Expr ExprNode // Used for Check
  664. Enforced bool // Used for Check
  665. InColumn bool // Used for Check
  666. InColumnName string // Used for Check
  667. IsEmptyIndex bool // Used for Check
  668. }
  669. // Restore implements Node interface.
  670. func (n *Constraint) Restore(ctx *format.RestoreCtx) error {
  671. switch n.Tp {
  672. case ConstraintNoConstraint:
  673. return nil
  674. case ConstraintPrimaryKey:
  675. ctx.WriteKeyWord("PRIMARY KEY")
  676. case ConstraintKey:
  677. ctx.WriteKeyWord("KEY")
  678. if n.IfNotExists {
  679. ctx.WriteKeyWord(" IF NOT EXISTS")
  680. }
  681. case ConstraintIndex:
  682. ctx.WriteKeyWord("INDEX")
  683. if n.IfNotExists {
  684. ctx.WriteKeyWord(" IF NOT EXISTS")
  685. }
  686. case ConstraintUniq:
  687. ctx.WriteKeyWord("UNIQUE")
  688. case ConstraintUniqKey:
  689. ctx.WriteKeyWord("UNIQUE KEY")
  690. case ConstraintUniqIndex:
  691. ctx.WriteKeyWord("UNIQUE INDEX")
  692. case ConstraintFulltext:
  693. ctx.WriteKeyWord("FULLTEXT")
  694. case ConstraintCheck:
  695. if n.Name != "" {
  696. ctx.WriteKeyWord("CONSTRAINT ")
  697. ctx.WriteName(n.Name)
  698. ctx.WritePlain(" ")
  699. }
  700. ctx.WriteKeyWord("CHECK")
  701. ctx.WritePlain("(")
  702. if err := n.Expr.Restore(ctx); err != nil {
  703. return errors.Trace(err)
  704. }
  705. ctx.WritePlain(") ")
  706. if n.Enforced {
  707. ctx.WriteKeyWord("ENFORCED")
  708. } else {
  709. ctx.WriteKeyWord("NOT ENFORCED")
  710. }
  711. return nil
  712. }
  713. if n.Tp == ConstraintForeignKey {
  714. ctx.WriteKeyWord("CONSTRAINT ")
  715. if n.Name != "" {
  716. ctx.WriteName(n.Name)
  717. ctx.WritePlain(" ")
  718. }
  719. ctx.WriteKeyWord("FOREIGN KEY ")
  720. if n.IfNotExists {
  721. ctx.WriteKeyWord("IF NOT EXISTS ")
  722. }
  723. } else if n.Name != "" || n.IsEmptyIndex {
  724. ctx.WritePlain(" ")
  725. ctx.WriteName(n.Name)
  726. }
  727. ctx.WritePlain("(")
  728. for i, keys := range n.Keys {
  729. if i > 0 {
  730. ctx.WritePlain(", ")
  731. }
  732. if err := keys.Restore(ctx); err != nil {
  733. return errors.Annotatef(err, "An error occurred while splicing Constraint Keys: [%v]", i)
  734. }
  735. }
  736. ctx.WritePlain(")")
  737. if n.Refer != nil {
  738. ctx.WritePlain(" ")
  739. if err := n.Refer.Restore(ctx); err != nil {
  740. return errors.Annotate(err, "An error occurred while splicing Constraint Refer")
  741. }
  742. }
  743. if n.Option != nil {
  744. ctx.WritePlain(" ")
  745. if err := n.Option.Restore(ctx); err != nil {
  746. return errors.Annotate(err, "An error occurred while splicing Constraint Option")
  747. }
  748. }
  749. return nil
  750. }
  751. // Accept implements Node Accept interface.
  752. func (n *Constraint) Accept(v Visitor) (Node, bool) {
  753. newNode, skipChildren := v.Enter(n)
  754. if skipChildren {
  755. return v.Leave(newNode)
  756. }
  757. n = newNode.(*Constraint)
  758. for i, val := range n.Keys {
  759. node, ok := val.Accept(v)
  760. if !ok {
  761. return n, false
  762. }
  763. n.Keys[i] = node.(*IndexPartSpecification)
  764. }
  765. if n.Refer != nil {
  766. node, ok := n.Refer.Accept(v)
  767. if !ok {
  768. return n, false
  769. }
  770. n.Refer = node.(*ReferenceDef)
  771. }
  772. if n.Option != nil {
  773. node, ok := n.Option.Accept(v)
  774. if !ok {
  775. return n, false
  776. }
  777. n.Option = node.(*IndexOption)
  778. }
  779. if n.Expr != nil {
  780. node, ok := n.Expr.Accept(v)
  781. if !ok {
  782. return n, false
  783. }
  784. n.Expr = node.(ExprNode)
  785. }
  786. return v.Leave(n)
  787. }
  788. // ColumnDef is used for parsing column definition from SQL.
  789. type ColumnDef struct {
  790. node
  791. Name *ColumnName
  792. Tp *types.FieldType
  793. Options []*ColumnOption
  794. }
  795. // Restore implements Node interface.
  796. func (n *ColumnDef) Restore(ctx *format.RestoreCtx) error {
  797. if err := n.Name.Restore(ctx); err != nil {
  798. return errors.Annotate(err, "An error occurred while splicing ColumnDef Name")
  799. }
  800. if n.Tp != nil {
  801. ctx.WritePlain(" ")
  802. if err := n.Tp.Restore(ctx); err != nil {
  803. return errors.Annotate(err, "An error occurred while splicing ColumnDef Type")
  804. }
  805. }
  806. for i, options := range n.Options {
  807. ctx.WritePlain(" ")
  808. if err := options.Restore(ctx); err != nil {
  809. return errors.Annotatef(err, "An error occurred while splicing ColumnDef ColumnOption: [%v]", i)
  810. }
  811. }
  812. return nil
  813. }
  814. // Accept implements Node Accept interface.
  815. func (n *ColumnDef) Accept(v Visitor) (Node, bool) {
  816. newNode, skipChildren := v.Enter(n)
  817. if skipChildren {
  818. return v.Leave(newNode)
  819. }
  820. n = newNode.(*ColumnDef)
  821. node, ok := n.Name.Accept(v)
  822. if !ok {
  823. return n, false
  824. }
  825. n.Name = node.(*ColumnName)
  826. for i, val := range n.Options {
  827. node, ok := val.Accept(v)
  828. if !ok {
  829. return n, false
  830. }
  831. n.Options[i] = node.(*ColumnOption)
  832. }
  833. return v.Leave(n)
  834. }
  835. // Validate checks if a column definition is legal.
  836. // For example, generated column definitions that contain such
  837. // column options as `ON UPDATE`, `AUTO_INCREMENT`, `DEFAULT`
  838. // are illegal.
  839. func (n *ColumnDef) Validate() bool {
  840. generatedCol := false
  841. illegalOpt4gc := false
  842. for _, opt := range n.Options {
  843. if opt.Tp == ColumnOptionGenerated {
  844. generatedCol = true
  845. }
  846. _, found := invalidOptionForGeneratedColumn[opt.Tp]
  847. illegalOpt4gc = illegalOpt4gc || found
  848. }
  849. return !(generatedCol && illegalOpt4gc)
  850. }
  851. // CreateTableStmt is a statement to create a table.
  852. // See https://dev.mysql.com/doc/refman/5.7/en/create-table.html
  853. type CreateTableStmt struct {
  854. ddlNode
  855. IfNotExists bool
  856. IsTemporary bool
  857. Table *TableName
  858. ReferTable *TableName
  859. Cols []*ColumnDef
  860. Constraints []*Constraint
  861. Options []*TableOption
  862. Partition *PartitionOptions
  863. OnDuplicate OnDuplicateKeyHandlingType
  864. Select ResultSetNode
  865. }
  866. // Restore implements Node interface.
  867. func (n *CreateTableStmt) Restore(ctx *format.RestoreCtx) error {
  868. if n.IsTemporary {
  869. ctx.WriteKeyWord("CREATE TEMPORARY TABLE ")
  870. } else {
  871. ctx.WriteKeyWord("CREATE TABLE ")
  872. }
  873. if n.IfNotExists {
  874. ctx.WriteKeyWord("IF NOT EXISTS ")
  875. }
  876. if err := n.Table.Restore(ctx); err != nil {
  877. return errors.Annotate(err, "An error occurred while splicing CreateTableStmt Table")
  878. }
  879. if n.ReferTable != nil {
  880. ctx.WriteKeyWord(" LIKE ")
  881. if err := n.ReferTable.Restore(ctx); err != nil {
  882. return errors.Annotate(err, "An error occurred while splicing CreateTableStmt ReferTable")
  883. }
  884. }
  885. lenCols := len(n.Cols)
  886. lenConstraints := len(n.Constraints)
  887. if lenCols+lenConstraints > 0 {
  888. ctx.WritePlain(" (")
  889. for i, col := range n.Cols {
  890. if i > 0 {
  891. ctx.WritePlain(",")
  892. }
  893. if err := col.Restore(ctx); err != nil {
  894. return errors.Annotatef(err, "An error occurred while splicing CreateTableStmt ColumnDef: [%v]", i)
  895. }
  896. }
  897. for i, constraint := range n.Constraints {
  898. if i > 0 || lenCols >= 1 {
  899. ctx.WritePlain(",")
  900. }
  901. if err := constraint.Restore(ctx); err != nil {
  902. return errors.Annotatef(err, "An error occurred while splicing CreateTableStmt Constraints: [%v]", i)
  903. }
  904. }
  905. ctx.WritePlain(")")
  906. }
  907. for i, option := range n.Options {
  908. ctx.WritePlain(" ")
  909. if err := option.Restore(ctx); err != nil {
  910. return errors.Annotatef(err, "An error occurred while splicing CreateTableStmt TableOption: [%v]", i)
  911. }
  912. }
  913. if n.Partition != nil {
  914. ctx.WritePlain(" ")
  915. if err := n.Partition.Restore(ctx); err != nil {
  916. return errors.Annotate(err, "An error occurred while splicing CreateTableStmt Partition")
  917. }
  918. }
  919. if n.Select != nil {
  920. switch n.OnDuplicate {
  921. case OnDuplicateKeyHandlingError:
  922. ctx.WriteKeyWord(" AS ")
  923. case OnDuplicateKeyHandlingIgnore:
  924. ctx.WriteKeyWord(" IGNORE AS ")
  925. case OnDuplicateKeyHandlingReplace:
  926. ctx.WriteKeyWord(" REPLACE AS ")
  927. }
  928. if err := n.Select.Restore(ctx); err != nil {
  929. return errors.Annotate(err, "An error occurred while splicing CreateTableStmt Select")
  930. }
  931. }
  932. return nil
  933. }
  934. // Accept implements Node Accept interface.
  935. func (n *CreateTableStmt) Accept(v Visitor) (Node, bool) {
  936. newNode, skipChildren := v.Enter(n)
  937. if skipChildren {
  938. return v.Leave(newNode)
  939. }
  940. n = newNode.(*CreateTableStmt)
  941. node, ok := n.Table.Accept(v)
  942. if !ok {
  943. return n, false
  944. }
  945. n.Table = node.(*TableName)
  946. if n.ReferTable != nil {
  947. node, ok = n.ReferTable.Accept(v)
  948. if !ok {
  949. return n, false
  950. }
  951. n.ReferTable = node.(*TableName)
  952. }
  953. for i, val := range n.Cols {
  954. node, ok = val.Accept(v)
  955. if !ok {
  956. return n, false
  957. }
  958. n.Cols[i] = node.(*ColumnDef)
  959. }
  960. for i, val := range n.Constraints {
  961. node, ok = val.Accept(v)
  962. if !ok {
  963. return n, false
  964. }
  965. n.Constraints[i] = node.(*Constraint)
  966. }
  967. if n.Select != nil {
  968. node, ok := n.Select.Accept(v)
  969. if !ok {
  970. return n, false
  971. }
  972. n.Select = node.(ResultSetNode)
  973. }
  974. if n.Partition != nil {
  975. node, ok := n.Partition.Accept(v)
  976. if !ok {
  977. return n, false
  978. }
  979. n.Partition = node.(*PartitionOptions)
  980. }
  981. return v.Leave(n)
  982. }
  983. // DropTableStmt is a statement to drop one or more tables.
  984. // See https://dev.mysql.com/doc/refman/5.7/en/drop-table.html
  985. type DropTableStmt struct {
  986. ddlNode
  987. IfExists bool
  988. Tables []*TableName
  989. IsView bool
  990. IsTemporary bool // make sense ONLY if/when IsView == false
  991. }
  992. // Restore implements Node interface.
  993. func (n *DropTableStmt) Restore(ctx *format.RestoreCtx) error {
  994. if n.IsView {
  995. ctx.WriteKeyWord("DROP VIEW ")
  996. } else {
  997. if n.IsTemporary {
  998. ctx.WriteKeyWord("DROP TEMPORARY TABLE ")
  999. } else {
  1000. ctx.WriteKeyWord("DROP TABLE ")
  1001. }
  1002. }
  1003. if n.IfExists {
  1004. ctx.WriteKeyWord("IF EXISTS ")
  1005. }
  1006. for index, table := range n.Tables {
  1007. if index != 0 {
  1008. ctx.WritePlain(", ")
  1009. }
  1010. if err := table.Restore(ctx); err != nil {
  1011. return errors.Annotatef(err, "An error occurred while restore DropTableStmt.Tables[%d]", index)
  1012. }
  1013. }
  1014. return nil
  1015. }
  1016. // Accept implements Node Accept interface.
  1017. func (n *DropTableStmt) Accept(v Visitor) (Node, bool) {
  1018. newNode, skipChildren := v.Enter(n)
  1019. if skipChildren {
  1020. return v.Leave(newNode)
  1021. }
  1022. n = newNode.(*DropTableStmt)
  1023. for i, val := range n.Tables {
  1024. node, ok := val.Accept(v)
  1025. if !ok {
  1026. return n, false
  1027. }
  1028. n.Tables[i] = node.(*TableName)
  1029. }
  1030. return v.Leave(n)
  1031. }
  1032. // DropSequenceStmt is a statement to drop a Sequence.
  1033. type DropSequenceStmt struct {
  1034. ddlNode
  1035. IfExists bool
  1036. Sequences []*TableName
  1037. }
  1038. // Restore implements Node interface.
  1039. func (n *DropSequenceStmt) Restore(ctx *format.RestoreCtx) error {
  1040. ctx.WriteKeyWord("DROP SEQUENCE ")
  1041. if n.IfExists {
  1042. ctx.WriteKeyWord("IF EXISTS ")
  1043. }
  1044. for i, sequence := range n.Sequences {
  1045. if i != 0 {
  1046. ctx.WritePlain(", ")
  1047. }
  1048. if err := sequence.Restore(ctx); err != nil {
  1049. return errors.Annotatef(err, "An error occurred while restore DropSequenceStmt.Sequences[%d]", i)
  1050. }
  1051. }
  1052. return nil
  1053. }
  1054. // Accept implements Node Accept interface.
  1055. func (n *DropSequenceStmt) Accept(v Visitor) (Node, bool) {
  1056. newNode, skipChildren := v.Enter(n)
  1057. if skipChildren {
  1058. return v.Leave(newNode)
  1059. }
  1060. n = newNode.(*DropSequenceStmt)
  1061. for i, val := range n.Sequences {
  1062. node, ok := val.Accept(v)
  1063. if !ok {
  1064. return n, false
  1065. }
  1066. n.Sequences[i] = node.(*TableName)
  1067. }
  1068. return v.Leave(n)
  1069. }
  1070. // RenameTableStmt is a statement to rename a table.
  1071. // See http://dev.mysql.com/doc/refman/5.7/en/rename-table.html
  1072. type RenameTableStmt struct {
  1073. ddlNode
  1074. TableToTables []*TableToTable
  1075. }
  1076. // Restore implements Node interface.
  1077. func (n *RenameTableStmt) Restore(ctx *format.RestoreCtx) error {
  1078. ctx.WriteKeyWord("RENAME TABLE ")
  1079. for index, table2table := range n.TableToTables {
  1080. if index != 0 {
  1081. ctx.WritePlain(", ")
  1082. }
  1083. if err := table2table.Restore(ctx); err != nil {
  1084. return errors.Annotate(err, "An error occurred while restore RenameTableStmt.TableToTables")
  1085. }
  1086. }
  1087. return nil
  1088. }
  1089. // Accept implements Node Accept interface.
  1090. func (n *RenameTableStmt) Accept(v Visitor) (Node, bool) {
  1091. newNode, skipChildren := v.Enter(n)
  1092. if skipChildren {
  1093. return v.Leave(newNode)
  1094. }
  1095. n = newNode.(*RenameTableStmt)
  1096. for i, t := range n.TableToTables {
  1097. node, ok := t.Accept(v)
  1098. if !ok {
  1099. return n, false
  1100. }
  1101. n.TableToTables[i] = node.(*TableToTable)
  1102. }
  1103. return v.Leave(n)
  1104. }
  1105. // TableToTable represents renaming old table to new table used in RenameTableStmt.
  1106. type TableToTable struct {
  1107. node
  1108. OldTable *TableName
  1109. NewTable *TableName
  1110. }
  1111. // Restore implements Node interface.
  1112. func (n *TableToTable) Restore(ctx *format.RestoreCtx) error {
  1113. if err := n.OldTable.Restore(ctx); err != nil {
  1114. return errors.Annotate(err, "An error occurred while restore TableToTable.OldTable")
  1115. }
  1116. ctx.WriteKeyWord(" TO ")
  1117. if err := n.NewTable.Restore(ctx); err != nil {
  1118. return errors.Annotate(err, "An error occurred while restore TableToTable.NewTable")
  1119. }
  1120. return nil
  1121. }
  1122. // Accept implements Node Accept interface.
  1123. func (n *TableToTable) Accept(v Visitor) (Node, bool) {
  1124. newNode, skipChildren := v.Enter(n)
  1125. if skipChildren {
  1126. return v.Leave(newNode)
  1127. }
  1128. n = newNode.(*TableToTable)
  1129. node, ok := n.OldTable.Accept(v)
  1130. if !ok {
  1131. return n, false
  1132. }
  1133. n.OldTable = node.(*TableName)
  1134. node, ok = n.NewTable.Accept(v)
  1135. if !ok {
  1136. return n, false
  1137. }
  1138. n.NewTable = node.(*TableName)
  1139. return v.Leave(n)
  1140. }
  1141. // CreateViewStmt is a statement to create a View.
  1142. // See https://dev.mysql.com/doc/refman/5.7/en/create-view.html
  1143. type CreateViewStmt struct {
  1144. ddlNode
  1145. OrReplace bool
  1146. ViewName *TableName
  1147. Cols []model.CIStr
  1148. Select StmtNode
  1149. SchemaCols []model.CIStr
  1150. Algorithm model.ViewAlgorithm
  1151. Definer *auth.UserIdentity
  1152. Security model.ViewSecurity
  1153. CheckOption model.ViewCheckOption
  1154. }
  1155. // Restore implements Node interface.
  1156. func (n *CreateViewStmt) Restore(ctx *format.RestoreCtx) error {
  1157. ctx.WriteKeyWord("CREATE ")
  1158. if n.OrReplace {
  1159. ctx.WriteKeyWord("OR REPLACE ")
  1160. }
  1161. ctx.WriteKeyWord("ALGORITHM")
  1162. ctx.WritePlain(" = ")
  1163. ctx.WriteKeyWord(n.Algorithm.String())
  1164. ctx.WriteKeyWord(" DEFINER")
  1165. ctx.WritePlain(" = ")
  1166. // todo Use n.Definer.Restore(ctx) to replace this part
  1167. if n.Definer.CurrentUser {
  1168. ctx.WriteKeyWord("current_user")
  1169. } else {
  1170. ctx.WriteName(n.Definer.Username)
  1171. if n.Definer.Hostname != "" {
  1172. ctx.WritePlain("@")
  1173. ctx.WriteName(n.Definer.Hostname)
  1174. }
  1175. }
  1176. ctx.WriteKeyWord(" SQL SECURITY ")
  1177. ctx.WriteKeyWord(n.Security.String())
  1178. ctx.WriteKeyWord(" VIEW ")
  1179. if err := n.ViewName.Restore(ctx); err != nil {
  1180. return errors.Annotate(err, "An error occurred while create CreateViewStmt.ViewName")
  1181. }
  1182. for i, col := range n.Cols {
  1183. if i == 0 {
  1184. ctx.WritePlain(" (")
  1185. } else {
  1186. ctx.WritePlain(",")
  1187. }
  1188. ctx.WriteName(col.O)
  1189. if i == len(n.Cols)-1 {
  1190. ctx.WritePlain(")")
  1191. }
  1192. }
  1193. ctx.WriteKeyWord(" AS ")
  1194. if err := n.Select.Restore(ctx); err != nil {
  1195. return errors.Annotate(err, "An error occurred while create CreateViewStmt.Select")
  1196. }
  1197. if n.CheckOption != model.CheckOptionCascaded {
  1198. ctx.WriteKeyWord(" WITH ")
  1199. ctx.WriteKeyWord(n.CheckOption.String())
  1200. ctx.WriteKeyWord(" CHECK OPTION")
  1201. }
  1202. return nil
  1203. }
  1204. // Accept implements Node Accept interface.
  1205. func (n *CreateViewStmt) Accept(v Visitor) (Node, bool) {
  1206. newNode, skipChildren := v.Enter(n)
  1207. if skipChildren {
  1208. return v.Leave(newNode)
  1209. }
  1210. n = newNode.(*CreateViewStmt)
  1211. node, ok := n.ViewName.Accept(v)
  1212. if !ok {
  1213. return n, false
  1214. }
  1215. n.ViewName = node.(*TableName)
  1216. selnode, ok := n.Select.Accept(v)
  1217. if !ok {
  1218. return n, false
  1219. }
  1220. n.Select = selnode.(StmtNode)
  1221. return v.Leave(n)
  1222. }
  1223. // CreateSequenceStmt is a statement to create a Sequence.
  1224. type CreateSequenceStmt struct {
  1225. ddlNode
  1226. // TODO : support or replace if need : care for it will conflict on temporaryOpt.
  1227. IfNotExists bool
  1228. Name *TableName
  1229. SeqOptions []*SequenceOption
  1230. TblOptions []*TableOption
  1231. }
  1232. // Restore implements Node interface.
  1233. func (n *CreateSequenceStmt) Restore(ctx *format.RestoreCtx) error {
  1234. ctx.WriteKeyWord("CREATE ")
  1235. ctx.WriteKeyWord("SEQUENCE ")
  1236. if n.IfNotExists {
  1237. ctx.WriteKeyWord("IF NOT EXISTS ")
  1238. }
  1239. if err := n.Name.Restore(ctx); err != nil {
  1240. return errors.Annotate(err, "An error occurred while create CreateSequenceStmt.Name")
  1241. }
  1242. for i, option := range n.SeqOptions {
  1243. ctx.WritePlain(" ")
  1244. if err := option.Restore(ctx); err != nil {
  1245. return errors.Annotatef(err, "An error occurred while splicing CreateSequenceStmt SequenceOption: [%v]", i)
  1246. }
  1247. }
  1248. for i, option := range n.TblOptions {
  1249. ctx.WritePlain(" ")
  1250. if err := option.Restore(ctx); err != nil {
  1251. return errors.Annotatef(err, "An error occurred while splicing CreateSequenceStmt TableOption: [%v]", i)
  1252. }
  1253. }
  1254. return nil
  1255. }
  1256. // Accept implements Node Accept interface.
  1257. func (n *CreateSequenceStmt) Accept(v Visitor) (Node, bool) {
  1258. newNode, skipChildren := v.Enter(n)
  1259. if skipChildren {
  1260. return v.Leave(newNode)
  1261. }
  1262. n = newNode.(*CreateSequenceStmt)
  1263. node, ok := n.Name.Accept(v)
  1264. if !ok {
  1265. return n, false
  1266. }
  1267. n.Name = node.(*TableName)
  1268. return v.Leave(n)
  1269. }
  1270. // IndexLockAndAlgorithm stores the algorithm option and the lock option.
  1271. type IndexLockAndAlgorithm struct {
  1272. node
  1273. LockTp LockType
  1274. AlgorithmTp AlgorithmType
  1275. }
  1276. // Restore implements Node interface.
  1277. func (n *IndexLockAndAlgorithm) Restore(ctx *format.RestoreCtx) error {
  1278. hasPrevOption := false
  1279. if n.AlgorithmTp != AlgorithmTypeDefault {
  1280. ctx.WriteKeyWord("ALGORITHM")
  1281. ctx.WritePlain(" = ")
  1282. ctx.WriteKeyWord(n.AlgorithmTp.String())
  1283. hasPrevOption = true
  1284. }
  1285. if n.LockTp != LockTypeDefault {
  1286. if hasPrevOption {
  1287. ctx.WritePlain(" ")
  1288. }
  1289. ctx.WriteKeyWord("LOCK")
  1290. ctx.WritePlain(" = ")
  1291. ctx.WriteKeyWord(n.LockTp.String())
  1292. }
  1293. return nil
  1294. }
  1295. // Accept implements Node Accept interface.
  1296. func (n *IndexLockAndAlgorithm) Accept(v Visitor) (Node, bool) {
  1297. newNode, skipChildren := v.Enter(n)
  1298. if skipChildren {
  1299. return v.Leave(newNode)
  1300. }
  1301. n = newNode.(*IndexLockAndAlgorithm)
  1302. return v.Leave(n)
  1303. }
  1304. // IndexKeyType is the type for index key.
  1305. type IndexKeyType int
  1306. // Index key types.
  1307. const (
  1308. IndexKeyTypeNone IndexKeyType = iota
  1309. IndexKeyTypeUnique
  1310. IndexKeyTypeSpatial
  1311. IndexKeyTypeFullText
  1312. )
  1313. // CreateIndexStmt is a statement to create an index.
  1314. // See https://dev.mysql.com/doc/refman/5.7/en/create-index.html
  1315. type CreateIndexStmt struct {
  1316. ddlNode
  1317. // only supported by MariaDB 10.0.2+,
  1318. // see https://mariadb.com/kb/en/library/create-index/
  1319. IfNotExists bool
  1320. IndexName string
  1321. Table *TableName
  1322. IndexPartSpecifications []*IndexPartSpecification
  1323. IndexOption *IndexOption
  1324. KeyType IndexKeyType
  1325. LockAlg *IndexLockAndAlgorithm
  1326. }
  1327. // Restore implements Node interface.
  1328. func (n *CreateIndexStmt) Restore(ctx *format.RestoreCtx) error {
  1329. ctx.WriteKeyWord("CREATE ")
  1330. switch n.KeyType {
  1331. case IndexKeyTypeUnique:
  1332. ctx.WriteKeyWord("UNIQUE ")
  1333. case IndexKeyTypeSpatial:
  1334. ctx.WriteKeyWord("SPATIAL ")
  1335. case IndexKeyTypeFullText:
  1336. ctx.WriteKeyWord("FULLTEXT ")
  1337. }
  1338. ctx.WriteKeyWord("INDEX ")
  1339. if n.IfNotExists {
  1340. ctx.WriteKeyWord("IF NOT EXISTS ")
  1341. }
  1342. ctx.WriteName(n.IndexName)
  1343. ctx.WriteKeyWord(" ON ")
  1344. if err := n.Table.Restore(ctx); err != nil {
  1345. return errors.Annotate(err, "An error occurred while restore CreateIndexStmt.Table")
  1346. }
  1347. ctx.WritePlain(" (")
  1348. for i, indexColName := range n.IndexPartSpecifications {
  1349. if i != 0 {
  1350. ctx.WritePlain(", ")
  1351. }
  1352. if err := indexColName.Restore(ctx); err != nil {
  1353. return errors.Annotatef(err, "An error occurred while restore CreateIndexStmt.IndexPartSpecifications: [%v]", i)
  1354. }
  1355. }
  1356. ctx.WritePlain(")")
  1357. if n.IndexOption.Tp != model.IndexTypeInvalid || n.IndexOption.KeyBlockSize > 0 || n.IndexOption.Comment != "" || len(n.IndexOption.ParserName.O) > 0 || n.IndexOption.Visibility != IndexVisibilityDefault {
  1358. ctx.WritePlain(" ")
  1359. if err := n.IndexOption.Restore(ctx); err != nil {
  1360. return errors.Annotate(err, "An error occurred while restore CreateIndexStmt.IndexOption")
  1361. }
  1362. }
  1363. if n.LockAlg != nil {
  1364. ctx.WritePlain(" ")
  1365. if err := n.LockAlg.Restore(ctx); err != nil {
  1366. return errors.Annotate(err, "An error occurred while restore CreateIndexStmt.LockAlg")
  1367. }
  1368. }
  1369. return nil
  1370. }
  1371. // Accept implements Node Accept interface.
  1372. func (n *CreateIndexStmt) Accept(v Visitor) (Node, bool) {
  1373. newNode, skipChildren := v.Enter(n)
  1374. if skipChildren {
  1375. return v.Leave(newNode)
  1376. }
  1377. n = newNode.(*CreateIndexStmt)
  1378. node, ok := n.Table.Accept(v)
  1379. if !ok {
  1380. return n, false
  1381. }
  1382. n.Table = node.(*TableName)
  1383. for i, val := range n.IndexPartSpecifications {
  1384. node, ok = val.Accept(v)
  1385. if !ok {
  1386. return n, false
  1387. }
  1388. n.IndexPartSpecifications[i] = node.(*IndexPartSpecification)
  1389. }
  1390. if n.IndexOption != nil {
  1391. node, ok := n.IndexOption.Accept(v)
  1392. if !ok {
  1393. return n, false
  1394. }
  1395. n.IndexOption = node.(*IndexOption)
  1396. }
  1397. if n.LockAlg != nil {
  1398. node, ok := n.LockAlg.Accept(v)
  1399. if !ok {
  1400. return n, false
  1401. }
  1402. n.LockAlg = node.(*IndexLockAndAlgorithm)
  1403. }
  1404. return v.Leave(n)
  1405. }
  1406. // DropIndexStmt is a statement to drop the index.
  1407. // See https://dev.mysql.com/doc/refman/5.7/en/drop-index.html
  1408. type DropIndexStmt struct {
  1409. ddlNode
  1410. IfExists bool
  1411. IndexName string
  1412. Table *TableName
  1413. LockAlg *IndexLockAndAlgorithm
  1414. }
  1415. // Restore implements Node interface.
  1416. func (n *DropIndexStmt) Restore(ctx *format.RestoreCtx) error {
  1417. ctx.WriteKeyWord("DROP INDEX ")
  1418. if n.IfExists {
  1419. ctx.WriteKeyWord("IF EXISTS ")
  1420. }
  1421. ctx.WriteName(n.IndexName)
  1422. ctx.WriteKeyWord(" ON ")
  1423. if err := n.Table.Restore(ctx); err != nil {
  1424. return errors.Annotate(err, "An error occurred while add index")
  1425. }
  1426. if n.LockAlg != nil {
  1427. ctx.WritePlain(" ")
  1428. if err := n.LockAlg.Restore(ctx); err != nil {
  1429. return errors.Annotate(err, "An error occurred while restore CreateIndexStmt.LockAlg")
  1430. }
  1431. }
  1432. return nil
  1433. }
  1434. // Accept implements Node Accept interface.
  1435. func (n *DropIndexStmt) Accept(v Visitor) (Node, bool) {
  1436. newNode, skipChildren := v.Enter(n)
  1437. if skipChildren {
  1438. return v.Leave(newNode)
  1439. }
  1440. n = newNode.(*DropIndexStmt)
  1441. node, ok := n.Table.Accept(v)
  1442. if !ok {
  1443. return n, false
  1444. }
  1445. n.Table = node.(*TableName)
  1446. if n.LockAlg != nil {
  1447. node, ok := n.LockAlg.Accept(v)
  1448. if !ok {
  1449. return n, false
  1450. }
  1451. n.LockAlg = node.(*IndexLockAndAlgorithm)
  1452. }
  1453. return v.Leave(n)
  1454. }
  1455. // LockTablesStmt is a statement to lock tables.
  1456. type LockTablesStmt struct {
  1457. ddlNode
  1458. TableLocks []TableLock
  1459. }
  1460. // TableLock contains the table name and lock type.
  1461. type TableLock struct {
  1462. Table *TableName
  1463. Type model.TableLockType
  1464. }
  1465. // Accept implements Node Accept interface.
  1466. func (n *LockTablesStmt) Accept(v Visitor) (Node, bool) {
  1467. newNode, skipChildren := v.Enter(n)
  1468. if skipChildren {
  1469. return v.Leave(newNode)
  1470. }
  1471. n = newNode.(*LockTablesStmt)
  1472. for i := range n.TableLocks {
  1473. node, ok := n.TableLocks[i].Table.Accept(v)
  1474. if !ok {
  1475. return n, false
  1476. }
  1477. n.TableLocks[i].Table = node.(*TableName)
  1478. }
  1479. return v.Leave(n)
  1480. }
  1481. // Restore implements Node interface.
  1482. func (n *LockTablesStmt) Restore(ctx *format.RestoreCtx) error {
  1483. ctx.WriteKeyWord("LOCK TABLES ")
  1484. for i, tl := range n.TableLocks {
  1485. if i != 0 {
  1486. ctx.WritePlain(", ")
  1487. }
  1488. if err := tl.Table.Restore(ctx); err != nil {
  1489. return errors.Annotate(err, "An error occurred while add index")
  1490. }
  1491. ctx.WriteKeyWord(" " + tl.Type.String())
  1492. }
  1493. return nil
  1494. }
  1495. // UnlockTablesStmt is a statement to unlock tables.
  1496. type UnlockTablesStmt struct {
  1497. ddlNode
  1498. }
  1499. // Accept implements Node Accept interface.
  1500. func (n *UnlockTablesStmt) Accept(v Visitor) (Node, bool) {
  1501. _, _ = v.Enter(n)
  1502. return v.Leave(n)
  1503. }
  1504. // Restore implements Node interface.
  1505. func (n *UnlockTablesStmt) Restore(ctx *format.RestoreCtx) error {
  1506. ctx.WriteKeyWord("UNLOCK TABLES")
  1507. return nil
  1508. }
  1509. // CleanupTableLockStmt is a statement to cleanup table lock.
  1510. type CleanupTableLockStmt struct {
  1511. ddlNode
  1512. Tables []*TableName
  1513. }
  1514. // Accept implements Node Accept interface.
  1515. func (n *CleanupTableLockStmt) Accept(v Visitor) (Node, bool) {
  1516. newNode, skipChildren := v.Enter(n)
  1517. if skipChildren {
  1518. return v.Leave(newNode)
  1519. }
  1520. n = newNode.(*CleanupTableLockStmt)
  1521. for i := range n.Tables {
  1522. node, ok := n.Tables[i].Accept(v)
  1523. if !ok {
  1524. return n, false
  1525. }
  1526. n.Tables[i] = node.(*TableName)
  1527. }
  1528. return v.Leave(n)
  1529. }
  1530. // Restore implements Node interface.
  1531. func (n *CleanupTableLockStmt) Restore(ctx *format.RestoreCtx) error {
  1532. ctx.WriteKeyWord("ADMIN CLEANUP TABLE LOCK ")
  1533. for i, v := range n.Tables {
  1534. if i != 0 {
  1535. ctx.WritePlain(", ")
  1536. }
  1537. if err := v.Restore(ctx); err != nil {
  1538. return errors.Annotatef(err, "An error occurred while restore CleanupTableLockStmt.Tables[%d]", i)
  1539. }
  1540. }
  1541. return nil
  1542. }
  1543. // RepairTableStmt is a statement to repair tableInfo.
  1544. type RepairTableStmt struct {
  1545. ddlNode
  1546. Table *TableName
  1547. CreateStmt *CreateTableStmt
  1548. }
  1549. // Accept implements Node Accept interface.
  1550. func (n *RepairTableStmt) Accept(v Visitor) (Node, bool) {
  1551. newNode, skipChildren := v.Enter(n)
  1552. if skipChildren {
  1553. return v.Leave(newNode)
  1554. }
  1555. n = newNode.(*RepairTableStmt)
  1556. node, ok := n.Table.Accept(v)
  1557. if !ok {
  1558. return n, false
  1559. }
  1560. n.Table = node.(*TableName)
  1561. node, ok = n.CreateStmt.Accept(v)
  1562. if !ok {
  1563. return n, false
  1564. }
  1565. n.CreateStmt = node.(*CreateTableStmt)
  1566. return v.Leave(n)
  1567. }
  1568. // Restore implements Node interface.
  1569. func (n *RepairTableStmt) Restore(ctx *format.RestoreCtx) error {
  1570. ctx.WriteKeyWord("ADMIN REPAIR TABLE ")
  1571. if err := n.Table.Restore(ctx); err != nil {
  1572. return errors.Annotatef(err, "An error occurred while restore RepairTableStmt.table : [%v]", n.Table)
  1573. }
  1574. ctx.WritePlain(" ")
  1575. if err := n.CreateStmt.Restore(ctx); err != nil {
  1576. return errors.Annotatef(err, "An error occurred while restore RepairTableStmt.createStmt : [%v]", n.CreateStmt)
  1577. }
  1578. return nil
  1579. }
  1580. // TableOptionType is the type for TableOption
  1581. type TableOptionType int
  1582. // TableOption types.
  1583. const (
  1584. TableOptionNone TableOptionType = iota
  1585. TableOptionEngine
  1586. TableOptionCharset
  1587. TableOptionCollate
  1588. TableOptionAutoIdCache
  1589. TableOptionAutoIncrement
  1590. TableOptionAutoRandomBase
  1591. TableOptionComment
  1592. TableOptionAvgRowLength
  1593. TableOptionCheckSum
  1594. TableOptionCompression
  1595. TableOptionConnection
  1596. TableOptionPassword
  1597. TableOptionKeyBlockSize
  1598. TableOptionMaxRows
  1599. TableOptionMinRows
  1600. TableOptionDelayKeyWrite
  1601. TableOptionRowFormat
  1602. TableOptionStatsPersistent
  1603. TableOptionStatsAutoRecalc
  1604. TableOptionShardRowID
  1605. TableOptionPreSplitRegion
  1606. TableOptionPackKeys
  1607. TableOptionTablespace
  1608. TableOptionNodegroup
  1609. TableOptionDataDirectory
  1610. TableOptionIndexDirectory
  1611. TableOptionStorageMedia
  1612. TableOptionStatsSamplePages
  1613. TableOptionSecondaryEngine
  1614. TableOptionSecondaryEngineNull
  1615. TableOptionInsertMethod
  1616. TableOptionTableCheckSum
  1617. TableOptionUnion
  1618. TableOptionEncryption
  1619. )
  1620. // RowFormat types
  1621. const (
  1622. RowFormatDefault uint64 = iota + 1
  1623. RowFormatDynamic
  1624. RowFormatFixed
  1625. RowFormatCompressed
  1626. RowFormatRedundant
  1627. RowFormatCompact
  1628. TokuDBRowFormatDefault
  1629. TokuDBRowFormatFast
  1630. TokuDBRowFormatSmall
  1631. TokuDBRowFormatZlib
  1632. TokuDBRowFormatQuickLZ
  1633. TokuDBRowFormatLzma
  1634. TokuDBRowFormatSnappy
  1635. TokuDBRowFormatUncompressed
  1636. )
  1637. // OnDuplicateKeyHandlingType is the option that handle unique key values in 'CREATE TABLE ... SELECT' or `LOAD DATA`.
  1638. // See https://dev.mysql.com/doc/refman/5.7/en/create-table-select.html
  1639. // See https://dev.mysql.com/doc/refman/5.7/en/load-data.html
  1640. type OnDuplicateKeyHandlingType int
  1641. // OnDuplicateKeyHandling types
  1642. const (
  1643. OnDuplicateKeyHandlingError OnDuplicateKeyHandlingType = iota
  1644. OnDuplicateKeyHandlingIgnore
  1645. OnDuplicateKeyHandlingReplace
  1646. )
  1647. const (
  1648. TableOptionCharsetWithoutConvertTo uint64 = 0
  1649. TableOptionCharsetWithConvertTo uint64 = 1
  1650. )
  1651. // TableOption is used for parsing table option from SQL.
  1652. type TableOption struct {
  1653. Tp TableOptionType
  1654. Default bool
  1655. StrValue string
  1656. UintValue uint64
  1657. TableNames []*TableName
  1658. }
  1659. func (n *TableOption) Restore(ctx *format.RestoreCtx) error {
  1660. switch n.Tp {
  1661. case TableOptionEngine:
  1662. ctx.WriteKeyWord("ENGINE ")
  1663. ctx.WritePlain("= ")
  1664. if n.StrValue != "" {
  1665. ctx.WritePlain(n.StrValue)
  1666. } else {
  1667. ctx.WritePlain("''")
  1668. }
  1669. case TableOptionCharset:
  1670. if n.UintValue == TableOptionCharsetWithConvertTo {
  1671. ctx.WriteKeyWord("CONVERT TO ")
  1672. } else {
  1673. ctx.WriteKeyWord("DEFAULT ")
  1674. }
  1675. ctx.WriteKeyWord("CHARACTER SET ")
  1676. if n.UintValue == TableOptionCharsetWithoutConvertTo {
  1677. ctx.WriteKeyWord("= ")
  1678. }
  1679. if n.Default {
  1680. ctx.WriteKeyWord("DEFAULT")
  1681. } else {
  1682. ctx.WriteKeyWord(n.StrValue)
  1683. }
  1684. case TableOptionCollate:
  1685. ctx.WriteKeyWord("DEFAULT COLLATE ")
  1686. ctx.WritePlain("= ")
  1687. ctx.WriteKeyWord(n.StrValue)
  1688. case TableOptionAutoIncrement:
  1689. ctx.WriteKeyWord("AUTO_INCREMENT ")
  1690. ctx.WritePlain("= ")
  1691. ctx.WritePlainf("%d", n.UintValue)
  1692. case TableOptionAutoIdCache:
  1693. ctx.WriteKeyWord("AUTO_ID_CACHE ")
  1694. ctx.WritePlain("= ")
  1695. ctx.WritePlainf("%d", n.UintValue)
  1696. case TableOptionAutoRandomBase:
  1697. ctx.WriteKeyWord("AUTO_RANDOM_BASE ")
  1698. ctx.WritePlain("= ")
  1699. ctx.WritePlainf("%d", n.UintValue)
  1700. case TableOptionComment:
  1701. ctx.WriteKeyWord("COMMENT ")
  1702. ctx.WritePlain("= ")
  1703. ctx.WriteString(n.StrValue)
  1704. case TableOptionAvgRowLength:
  1705. ctx.WriteKeyWord("AVG_ROW_LENGTH ")
  1706. ctx.WritePlain("= ")
  1707. ctx.WritePlainf("%d", n.UintValue)
  1708. case TableOptionCheckSum:
  1709. ctx.WriteKeyWord("CHECKSUM ")
  1710. ctx.WritePlain("= ")
  1711. ctx.WritePlainf("%d", n.UintValue)
  1712. case TableOptionCompression:
  1713. ctx.WriteKeyWord("COMPRESSION ")
  1714. ctx.WritePlain("= ")
  1715. ctx.WriteString(n.StrValue)
  1716. case TableOptionConnection:
  1717. ctx.WriteKeyWord("CONNECTION ")
  1718. ctx.WritePlain("= ")
  1719. ctx.WriteString(n.StrValue)
  1720. case TableOptionPassword:
  1721. ctx.WriteKeyWord("PASSWORD ")
  1722. ctx.WritePlain("= ")
  1723. ctx.WriteString(n.StrValue)
  1724. case TableOptionKeyBlockSize:
  1725. ctx.WriteKeyWord("KEY_BLOCK_SIZE ")
  1726. ctx.WritePlain("= ")
  1727. ctx.WritePlainf("%d", n.UintValue)
  1728. case TableOptionMaxRows:
  1729. ctx.WriteKeyWord("MAX_ROWS ")
  1730. ctx.WritePlain("= ")
  1731. ctx.WritePlainf("%d", n.UintValue)
  1732. case TableOptionMinRows:
  1733. ctx.WriteKeyWord("MIN_ROWS ")
  1734. ctx.WritePlain("= ")
  1735. ctx.WritePlainf("%d", n.UintValue)
  1736. case TableOptionDelayKeyWrite:
  1737. ctx.WriteKeyWord("DELAY_KEY_WRITE ")
  1738. ctx.WritePlain("= ")
  1739. ctx.WritePlainf("%d", n.UintValue)
  1740. case TableOptionRowFormat:
  1741. ctx.WriteKeyWord("ROW_FORMAT ")
  1742. ctx.WritePlain("= ")
  1743. switch n.UintValue {
  1744. case RowFormatDefault:
  1745. ctx.WriteKeyWord("DEFAULT")
  1746. case RowFormatDynamic:
  1747. ctx.WriteKeyWord("DYNAMIC")
  1748. case RowFormatFixed:
  1749. ctx.WriteKeyWord("FIXED")
  1750. case RowFormatCompressed:
  1751. ctx.WriteKeyWord("COMPRESSED")
  1752. case RowFormatRedundant:
  1753. ctx.WriteKeyWord("REDUNDANT")
  1754. case RowFormatCompact:
  1755. ctx.WriteKeyWord("COMPACT")
  1756. case TokuDBRowFormatDefault:
  1757. ctx.WriteKeyWord("TOKUDB_DEFAULT")
  1758. case TokuDBRowFormatFast:
  1759. ctx.WriteKeyWord("TOKUDB_FAST")
  1760. case TokuDBRowFormatSmall:
  1761. ctx.WriteKeyWord("TOKUDB_SMALL")
  1762. case TokuDBRowFormatZlib:
  1763. ctx.WriteKeyWord("TOKUDB_ZLIB")
  1764. case TokuDBRowFormatQuickLZ:
  1765. ctx.WriteKeyWord("TOKUDB_QUICKLZ")
  1766. case TokuDBRowFormatLzma:
  1767. ctx.WriteKeyWord("TOKUDB_LZMA")
  1768. case TokuDBRowFormatSnappy:
  1769. ctx.WriteKeyWord("TOKUDB_SNAPPY")
  1770. case TokuDBRowFormatUncompressed:
  1771. ctx.WriteKeyWord("TOKUDB_UNCOMPRESSED")
  1772. default:
  1773. return errors.Errorf("invalid TableOption: TableOptionRowFormat: %d", n.UintValue)
  1774. }
  1775. case TableOptionStatsPersistent:
  1776. // TODO: not support
  1777. ctx.WriteKeyWord("STATS_PERSISTENT ")
  1778. ctx.WritePlain("= ")
  1779. ctx.WriteKeyWord("DEFAULT")
  1780. ctx.WritePlain(" /* TableOptionStatsPersistent is not supported */ ")
  1781. case TableOptionStatsAutoRecalc:
  1782. ctx.WriteKeyWord("STATS_AUTO_RECALC ")
  1783. ctx.WritePlain("= ")
  1784. if n.Default {
  1785. ctx.WriteKeyWord("DEFAULT")
  1786. } else {
  1787. ctx.WritePlainf("%d", n.UintValue)
  1788. }
  1789. case TableOptionShardRowID:
  1790. ctx.WriteKeyWord("SHARD_ROW_ID_BITS ")
  1791. ctx.WritePlainf("= %d", n.UintValue)
  1792. case TableOptionPreSplitRegion:
  1793. ctx.WriteKeyWord("PRE_SPLIT_REGIONS ")
  1794. ctx.WritePlainf("= %d", n.UintValue)
  1795. case TableOptionPackKeys:
  1796. // TODO: not support
  1797. ctx.WriteKeyWord("PACK_KEYS ")
  1798. ctx.WritePlain("= ")
  1799. ctx.WriteKeyWord("DEFAULT")
  1800. ctx.WritePlain(" /* TableOptionPackKeys is not supported */ ")
  1801. case TableOptionTablespace:
  1802. ctx.WriteKeyWord("TABLESPACE ")
  1803. ctx.WritePlain("= ")
  1804. ctx.WriteName(n.StrValue)
  1805. case TableOptionNodegroup:
  1806. ctx.WriteKeyWord("NODEGROUP ")
  1807. ctx.WritePlainf("= %d", n.UintValue)
  1808. case TableOptionDataDirectory:
  1809. ctx.WriteKeyWord("DATA DIRECTORY ")
  1810. ctx.WritePlain("= ")
  1811. ctx.WriteString(n.StrValue)
  1812. case TableOptionIndexDirectory:
  1813. ctx.WriteKeyWord("INDEX DIRECTORY ")
  1814. ctx.WritePlain("= ")
  1815. ctx.WriteString(n.StrValue)
  1816. case TableOptionStorageMedia:
  1817. ctx.WriteKeyWord("STORAGE ")
  1818. ctx.WriteKeyWord(n.StrValue)
  1819. case TableOptionStatsSamplePages:
  1820. ctx.WriteKeyWord("STATS_SAMPLE_PAGES ")
  1821. ctx.WritePlain("= ")
  1822. if n.Default {
  1823. ctx.WriteKeyWord("DEFAULT")
  1824. } else {
  1825. ctx.WritePlainf("%d", n.UintValue)
  1826. }
  1827. case TableOptionSecondaryEngine:
  1828. ctx.WriteKeyWord("SECONDARY_ENGINE ")
  1829. ctx.WritePlain("= ")
  1830. ctx.WriteString(n.StrValue)
  1831. case TableOptionSecondaryEngineNull:
  1832. ctx.WriteKeyWord("SECONDARY_ENGINE ")
  1833. ctx.WritePlain("= ")
  1834. ctx.WriteKeyWord("NULL")
  1835. case TableOptionInsertMethod:
  1836. ctx.WriteKeyWord("INSERT_METHOD ")
  1837. ctx.WritePlain("= ")
  1838. ctx.WriteString(n.StrValue)
  1839. case TableOptionTableCheckSum:
  1840. ctx.WriteKeyWord("TABLE_CHECKSUM ")
  1841. ctx.WritePlain("= ")
  1842. ctx.WritePlainf("%d", n.UintValue)
  1843. case TableOptionUnion:
  1844. ctx.WriteKeyWord("UNION ")
  1845. ctx.WritePlain("= (")
  1846. for i, tableName := range n.TableNames {
  1847. if i != 0 {
  1848. ctx.WritePlain(",")
  1849. }
  1850. tableName.Restore(ctx)
  1851. }
  1852. ctx.WritePlain(")")
  1853. case TableOptionEncryption:
  1854. ctx.WriteKeyWord("ENCRYPTION ")
  1855. ctx.WritePlain("= ")
  1856. ctx.WriteString(n.StrValue)
  1857. default:
  1858. return errors.Errorf("invalid TableOption: %d", n.Tp)
  1859. }
  1860. return nil
  1861. }
  1862. // SequenceOptionType is the type for SequenceOption
  1863. type SequenceOptionType int
  1864. // SequenceOption types.
  1865. const (
  1866. SequenceOptionNone SequenceOptionType = iota
  1867. SequenceOptionIncrementBy
  1868. SequenceStartWith
  1869. SequenceNoMinValue
  1870. SequenceMinValue
  1871. SequenceNoMaxValue
  1872. SequenceMaxValue
  1873. SequenceNoCache
  1874. SequenceCache
  1875. SequenceNoCycle
  1876. SequenceCycle
  1877. // SequenceRestart is only used in alter sequence statement.
  1878. SequenceRestart
  1879. SequenceRestartWith
  1880. )
  1881. // SequenceOption is used for parsing sequence option from SQL.
  1882. type SequenceOption struct {
  1883. Tp SequenceOptionType
  1884. IntValue int64
  1885. }
  1886. func (n *SequenceOption) Restore(ctx *format.RestoreCtx) error {
  1887. switch n.Tp {
  1888. case SequenceOptionIncrementBy:
  1889. ctx.WriteKeyWord("INCREMENT BY ")
  1890. ctx.WritePlainf("%d", n.IntValue)
  1891. case SequenceStartWith:
  1892. ctx.WriteKeyWord("START WITH ")
  1893. ctx.WritePlainf("%d", n.IntValue)
  1894. case SequenceNoMinValue:
  1895. ctx.WriteKeyWord("NO MINVALUE")
  1896. case SequenceMinValue:
  1897. ctx.WriteKeyWord("MINVALUE ")
  1898. ctx.WritePlainf("%d", n.IntValue)
  1899. case SequenceNoMaxValue:
  1900. ctx.WriteKeyWord("NO MAXVALUE")
  1901. case SequenceMaxValue:
  1902. ctx.WriteKeyWord("MAXVALUE ")
  1903. ctx.WritePlainf("%d", n.IntValue)
  1904. case SequenceNoCache:
  1905. ctx.WriteKeyWord("NOCACHE")
  1906. case SequenceCache:
  1907. ctx.WriteKeyWord("CACHE ")
  1908. ctx.WritePlainf("%d", n.IntValue)
  1909. case SequenceNoCycle:
  1910. ctx.WriteKeyWord("NOCYCLE")
  1911. case SequenceCycle:
  1912. ctx.WriteKeyWord("CYCLE")
  1913. case SequenceRestart:
  1914. ctx.WriteKeyWord("RESTART")
  1915. case SequenceRestartWith:
  1916. ctx.WriteKeyWord("RESTART WITH ")
  1917. ctx.WritePlainf("%d", n.IntValue)
  1918. default:
  1919. return errors.Errorf("invalid SequenceOption: %d", n.Tp)
  1920. }
  1921. return nil
  1922. }
  1923. // ColumnPositionType is the type for ColumnPosition.
  1924. type ColumnPositionType int
  1925. // ColumnPosition Types
  1926. const (
  1927. ColumnPositionNone ColumnPositionType = iota
  1928. ColumnPositionFirst
  1929. ColumnPositionAfter
  1930. )
  1931. // ColumnPosition represent the position of the newly added column
  1932. type ColumnPosition struct {
  1933. node
  1934. // Tp is either ColumnPositionNone, ColumnPositionFirst or ColumnPositionAfter.
  1935. Tp ColumnPositionType
  1936. // RelativeColumn is the column the newly added column after if type is ColumnPositionAfter
  1937. RelativeColumn *ColumnName
  1938. }
  1939. // Restore implements Node interface.
  1940. func (n *ColumnPosition) Restore(ctx *format.RestoreCtx) error {
  1941. switch n.Tp {
  1942. case ColumnPositionNone:
  1943. // do nothing
  1944. case ColumnPositionFirst:
  1945. ctx.WriteKeyWord("FIRST")
  1946. case ColumnPositionAfter:
  1947. ctx.WriteKeyWord("AFTER ")
  1948. if err := n.RelativeColumn.Restore(ctx); err != nil {
  1949. return errors.Annotate(err, "An error occurred while restore ColumnPosition.RelativeColumn")
  1950. }
  1951. default:
  1952. return errors.Errorf("invalid ColumnPositionType: %d", n.Tp)
  1953. }
  1954. return nil
  1955. }
  1956. // Accept implements Node Accept interface.
  1957. func (n *ColumnPosition) Accept(v Visitor) (Node, bool) {
  1958. newNode, skipChildren := v.Enter(n)
  1959. if skipChildren {
  1960. return v.Leave(newNode)
  1961. }
  1962. n = newNode.(*ColumnPosition)
  1963. if n.RelativeColumn != nil {
  1964. node, ok := n.RelativeColumn.Accept(v)
  1965. if !ok {
  1966. return n, false
  1967. }
  1968. n.RelativeColumn = node.(*ColumnName)
  1969. }
  1970. return v.Leave(n)
  1971. }
  1972. // AlterTableType is the type for AlterTableSpec.
  1973. type AlterTableType int
  1974. // AlterTable types.
  1975. const (
  1976. AlterTableOption AlterTableType = iota + 1
  1977. AlterTableAddColumns
  1978. AlterTableAddConstraint
  1979. AlterTableDropColumn
  1980. AlterTableDropPrimaryKey
  1981. AlterTableDropIndex
  1982. AlterTableDropForeignKey
  1983. AlterTableModifyColumn
  1984. AlterTableChangeColumn
  1985. AlterTableRenameColumn
  1986. AlterTableRenameTable
  1987. AlterTableAlterColumn
  1988. AlterTableLock
  1989. AlterTableWriteable
  1990. AlterTableAlgorithm
  1991. AlterTableRenameIndex
  1992. AlterTableForce
  1993. AlterTableAddPartitions
  1994. AlterTableAlterPartition
  1995. AlterTableCoalescePartitions
  1996. AlterTableDropPartition
  1997. AlterTableTruncatePartition
  1998. AlterTablePartition
  1999. AlterTableEnableKeys
  2000. AlterTableDisableKeys
  2001. AlterTableRemovePartitioning
  2002. AlterTableWithValidation
  2003. AlterTableWithoutValidation
  2004. AlterTableSecondaryLoad
  2005. AlterTableSecondaryUnload
  2006. AlterTableRebuildPartition
  2007. AlterTableReorganizePartition
  2008. AlterTableCheckPartitions
  2009. AlterTableExchangePartition
  2010. AlterTableOptimizePartition
  2011. AlterTableRepairPartition
  2012. AlterTableImportPartitionTablespace
  2013. AlterTableDiscardPartitionTablespace
  2014. AlterTableAlterCheck
  2015. AlterTableDropCheck
  2016. AlterTableImportTablespace
  2017. AlterTableDiscardTablespace
  2018. AlterTableIndexInvisible
  2019. // TODO: Add more actions
  2020. AlterTableOrderByColumns
  2021. // AlterTableSetTiFlashReplica uses to set the table TiFlash replica.
  2022. AlterTableSetTiFlashReplica
  2023. AlterTablePlacement
  2024. AlterTableAddStatistics
  2025. AlterTableDropStatistics
  2026. )
  2027. // LockType is the type for AlterTableSpec.
  2028. // See https://dev.mysql.com/doc/refman/5.7/en/alter-table.html#alter-table-concurrency
  2029. type LockType byte
  2030. func (n LockType) String() string {
  2031. switch n {
  2032. case LockTypeNone:
  2033. return "NONE"
  2034. case LockTypeDefault:
  2035. return "DEFAULT"
  2036. case LockTypeShared:
  2037. return "SHARED"
  2038. case LockTypeExclusive:
  2039. return "EXCLUSIVE"
  2040. }
  2041. return ""
  2042. }
  2043. // Lock Types.
  2044. const (
  2045. LockTypeNone LockType = iota + 1
  2046. LockTypeDefault
  2047. LockTypeShared
  2048. LockTypeExclusive
  2049. )
  2050. // AlgorithmType is the algorithm of the DDL operations.
  2051. // See https://dev.mysql.com/doc/refman/8.0/en/alter-table.html#alter-table-performance.
  2052. type AlgorithmType byte
  2053. // DDL algorithms.
  2054. // For now, TiDB only supported inplace and instance algorithms. If the user specify `copy`,
  2055. // will get an error.
  2056. const (
  2057. AlgorithmTypeDefault AlgorithmType = iota
  2058. AlgorithmTypeCopy
  2059. AlgorithmTypeInplace
  2060. AlgorithmTypeInstant
  2061. )
  2062. func (a AlgorithmType) String() string {
  2063. switch a {
  2064. case AlgorithmTypeDefault:
  2065. return "DEFAULT"
  2066. case AlgorithmTypeCopy:
  2067. return "COPY"
  2068. case AlgorithmTypeInplace:
  2069. return "INPLACE"
  2070. case AlgorithmTypeInstant:
  2071. return "INSTANT"
  2072. default:
  2073. return "DEFAULT"
  2074. }
  2075. }
  2076. // AlterTableSpec represents alter table specification.
  2077. type AlterTableSpec struct {
  2078. node
  2079. // only supported by MariaDB 10.0.2+ (DROP COLUMN, CHANGE COLUMN, MODIFY COLUMN, DROP INDEX, DROP FOREIGN KEY, DROP PARTITION)
  2080. // see https://mariadb.com/kb/en/library/alter-table/
  2081. IfExists bool
  2082. // only supported by MariaDB 10.0.2+ (ADD COLUMN, ADD PARTITION)
  2083. // see https://mariadb.com/kb/en/library/alter-table/
  2084. IfNotExists bool
  2085. NoWriteToBinlog bool
  2086. OnAllPartitions bool
  2087. Tp AlterTableType
  2088. Name string
  2089. IndexName model.CIStr
  2090. Constraint *Constraint
  2091. Options []*TableOption
  2092. OrderByList []*AlterOrderItem
  2093. NewTable *TableName
  2094. NewColumns []*ColumnDef
  2095. NewConstraints []*Constraint
  2096. OldColumnName *ColumnName
  2097. NewColumnName *ColumnName
  2098. Position *ColumnPosition
  2099. LockType LockType
  2100. Algorithm AlgorithmType
  2101. Comment string
  2102. FromKey model.CIStr
  2103. ToKey model.CIStr
  2104. Partition *PartitionOptions
  2105. PartitionNames []model.CIStr
  2106. PartDefinitions []*PartitionDefinition
  2107. WithValidation bool
  2108. Num uint64
  2109. Visibility IndexVisibility
  2110. TiFlashReplica *TiFlashReplicaSpec
  2111. PlacementSpecs []*PlacementSpec
  2112. Writeable bool
  2113. Statistics *StatisticsSpec
  2114. }
  2115. type TiFlashReplicaSpec struct {
  2116. Count uint64
  2117. Labels []string
  2118. }
  2119. // AlterOrderItem represents an item in order by at alter table stmt.
  2120. type AlterOrderItem struct {
  2121. node
  2122. Column *ColumnName
  2123. Desc bool
  2124. }
  2125. // Restore implements Node interface.
  2126. func (n *AlterOrderItem) Restore(ctx *format.RestoreCtx) error {
  2127. if err := n.Column.Restore(ctx); err != nil {
  2128. return errors.Annotate(err, "An error occurred while restore AlterOrderItem.Column")
  2129. }
  2130. if n.Desc {
  2131. ctx.WriteKeyWord(" DESC")
  2132. }
  2133. return nil
  2134. }
  2135. // Restore implements Node interface.
  2136. func (n *AlterTableSpec) Restore(ctx *format.RestoreCtx) error {
  2137. switch n.Tp {
  2138. case AlterTableSetTiFlashReplica:
  2139. ctx.WriteKeyWord("SET TIFLASH REPLICA ")
  2140. ctx.WritePlainf("%d", n.TiFlashReplica.Count)
  2141. if len(n.TiFlashReplica.Labels) == 0 {
  2142. break
  2143. }
  2144. ctx.WriteKeyWord(" LOCATION LABELS ")
  2145. for i, v := range n.TiFlashReplica.Labels {
  2146. if i > 0 {
  2147. ctx.WritePlain(", ")
  2148. }
  2149. ctx.WriteString(v)
  2150. }
  2151. case AlterTableAddStatistics:
  2152. ctx.WriteKeyWord("ADD STATS_EXTENDED ")
  2153. if n.IfNotExists {
  2154. ctx.WriteKeyWord("IF NOT EXISTS ")
  2155. }
  2156. ctx.WriteName(n.Statistics.StatsName)
  2157. switch n.Statistics.StatsType {
  2158. case StatsTypeCardinality:
  2159. ctx.WriteKeyWord(" CARDINALITY(")
  2160. case StatsTypeDependency:
  2161. ctx.WriteKeyWord(" DEPENDENCY(")
  2162. case StatsTypeCorrelation:
  2163. ctx.WriteKeyWord(" CORRELATION(")
  2164. }
  2165. for i, col := range n.Statistics.Columns {
  2166. if i != 0 {
  2167. ctx.WritePlain(", ")
  2168. }
  2169. if err := col.Restore(ctx); err != nil {
  2170. return errors.Annotatef(err, "An error occurred while restore AddStatisticsSpec.Columns: [%v]", i)
  2171. }
  2172. }
  2173. ctx.WritePlain(")")
  2174. case AlterTableDropStatistics:
  2175. ctx.WriteKeyWord("DROP STATS_EXTENDED ")
  2176. if n.IfExists {
  2177. ctx.WriteKeyWord("IF EXISTS ")
  2178. }
  2179. ctx.WriteName(n.Statistics.StatsName)
  2180. case AlterTableOption:
  2181. switch {
  2182. case len(n.Options) == 2 && n.Options[0].Tp == TableOptionCharset && n.Options[1].Tp == TableOptionCollate:
  2183. if n.Options[0].UintValue == TableOptionCharsetWithConvertTo {
  2184. ctx.WriteKeyWord("CONVERT TO ")
  2185. }
  2186. ctx.WriteKeyWord("CHARACTER SET ")
  2187. if n.Options[0].Default {
  2188. ctx.WriteKeyWord("DEFAULT")
  2189. } else {
  2190. ctx.WriteKeyWord(n.Options[0].StrValue)
  2191. }
  2192. ctx.WriteKeyWord(" COLLATE ")
  2193. ctx.WriteKeyWord(n.Options[1].StrValue)
  2194. case n.Options[0].Tp == TableOptionCharset && n.Options[0].Default:
  2195. if n.Options[0].UintValue == TableOptionCharsetWithConvertTo {
  2196. ctx.WriteKeyWord("CONVERT TO ")
  2197. }
  2198. ctx.WriteKeyWord("CHARACTER SET DEFAULT")
  2199. default:
  2200. for i, opt := range n.Options {
  2201. if i != 0 {
  2202. ctx.WritePlain(" ")
  2203. }
  2204. if err := opt.Restore(ctx); err != nil {
  2205. return errors.Annotatef(err, "An error occurred while restore AlterTableSpec.Options[%d]", i)
  2206. }
  2207. }
  2208. }
  2209. case AlterTableAddColumns:
  2210. ctx.WriteKeyWord("ADD COLUMN ")
  2211. if n.IfNotExists {
  2212. ctx.WriteKeyWord("IF NOT EXISTS ")
  2213. }
  2214. if n.Position != nil && len(n.NewColumns) == 1 {
  2215. if err := n.NewColumns[0].Restore(ctx); err != nil {
  2216. return errors.Annotatef(err, "An error occurred while restore AlterTableSpec.NewColumns[%d]", 0)
  2217. }
  2218. if n.Position.Tp != ColumnPositionNone {
  2219. ctx.WritePlain(" ")
  2220. }
  2221. if err := n.Position.Restore(ctx); err != nil {
  2222. return errors.Annotate(err, "An error occurred while restore AlterTableSpec.Position")
  2223. }
  2224. } else {
  2225. lenCols := len(n.NewColumns)
  2226. ctx.WritePlain("(")
  2227. for i, col := range n.NewColumns {
  2228. if i != 0 {
  2229. ctx.WritePlain(", ")
  2230. }
  2231. if err := col.Restore(ctx); err != nil {
  2232. return errors.Annotatef(err, "An error occurred while restore AlterTableSpec.NewColumns[%d]", i)
  2233. }
  2234. }
  2235. for i, constraint := range n.NewConstraints {
  2236. if i != 0 || lenCols >= 1 {
  2237. ctx.WritePlain(", ")
  2238. }
  2239. if err := constraint.Restore(ctx); err != nil {
  2240. return errors.Annotatef(err, "An error occurred while restore AlterTableSpec.NewConstraints[%d]", i)
  2241. }
  2242. }
  2243. ctx.WritePlain(")")
  2244. }
  2245. case AlterTableAddConstraint:
  2246. ctx.WriteKeyWord("ADD ")
  2247. if err := n.Constraint.Restore(ctx); err != nil {
  2248. return errors.Annotate(err, "An error occurred while restore AlterTableSpec.Constraint")
  2249. }
  2250. case AlterTableDropColumn:
  2251. ctx.WriteKeyWord("DROP COLUMN ")
  2252. if n.IfExists {
  2253. ctx.WriteKeyWord("IF EXISTS ")
  2254. }
  2255. if err := n.OldColumnName.Restore(ctx); err != nil {
  2256. return errors.Annotate(err, "An error occurred while restore AlterTableSpec.OldColumnName")
  2257. }
  2258. // TODO: RestrictOrCascadeOpt not support
  2259. case AlterTableDropPrimaryKey:
  2260. ctx.WriteKeyWord("DROP PRIMARY KEY")
  2261. case AlterTableDropIndex:
  2262. ctx.WriteKeyWord("DROP INDEX ")
  2263. if n.IfExists {
  2264. ctx.WriteKeyWord("IF EXISTS ")
  2265. }
  2266. ctx.WriteName(n.Name)
  2267. case AlterTableDropForeignKey:
  2268. ctx.WriteKeyWord("DROP FOREIGN KEY ")
  2269. if n.IfExists {
  2270. ctx.WriteKeyWord("IF EXISTS ")
  2271. }
  2272. ctx.WriteName(n.Name)
  2273. case AlterTableModifyColumn:
  2274. ctx.WriteKeyWord("MODIFY COLUMN ")
  2275. if n.IfExists {
  2276. ctx.WriteKeyWord("IF EXISTS ")
  2277. }
  2278. if err := n.NewColumns[0].Restore(ctx); err != nil {
  2279. return errors.Annotate(err, "An error occurred while restore AlterTableSpec.NewColumns[0]")
  2280. }
  2281. if n.Position.Tp != ColumnPositionNone {
  2282. ctx.WritePlain(" ")
  2283. }
  2284. if err := n.Position.Restore(ctx); err != nil {
  2285. return errors.Annotate(err, "An error occurred while restore AlterTableSpec.Position")
  2286. }
  2287. case AlterTableChangeColumn:
  2288. ctx.WriteKeyWord("CHANGE COLUMN ")
  2289. if n.IfExists {
  2290. ctx.WriteKeyWord("IF EXISTS ")
  2291. }
  2292. if err := n.OldColumnName.Restore(ctx); err != nil {
  2293. return errors.Annotate(err, "An error occurred while restore AlterTableSpec.OldColumnName")
  2294. }
  2295. ctx.WritePlain(" ")
  2296. if err := n.NewColumns[0].Restore(ctx); err != nil {
  2297. return errors.Annotate(err, "An error occurred while restore AlterTableSpec.NewColumns[0]")
  2298. }
  2299. if n.Position.Tp != ColumnPositionNone {
  2300. ctx.WritePlain(" ")
  2301. }
  2302. if err := n.Position.Restore(ctx); err != nil {
  2303. return errors.Annotate(err, "An error occurred while restore AlterTableSpec.Position")
  2304. }
  2305. case AlterTableRenameColumn:
  2306. ctx.WriteKeyWord("RENAME COLUMN ")
  2307. if err := n.OldColumnName.Restore(ctx); err != nil {
  2308. return errors.Annotate(err, "An error occurred while restore AlterTableSpec.OldColumnName")
  2309. }
  2310. ctx.WriteKeyWord(" TO ")
  2311. if err := n.NewColumnName.Restore(ctx); err != nil {
  2312. return errors.Annotate(err, "An error occurred while restore AlterTableSpec.NewColumnName")
  2313. }
  2314. case AlterTableRenameTable:
  2315. ctx.WriteKeyWord("RENAME AS ")
  2316. if err := n.NewTable.Restore(ctx); err != nil {
  2317. return errors.Annotate(err, "An error occurred while restore AlterTableSpec.NewTable")
  2318. }
  2319. case AlterTableAlterColumn:
  2320. ctx.WriteKeyWord("ALTER COLUMN ")
  2321. if err := n.NewColumns[0].Restore(ctx); err != nil {
  2322. return errors.Annotate(err, "An error occurred while restore AlterTableSpec.NewColumns[0]")
  2323. }
  2324. if len(n.NewColumns[0].Options) == 1 {
  2325. ctx.WriteKeyWord("SET DEFAULT ")
  2326. expr := n.NewColumns[0].Options[0].Expr
  2327. if valueExpr, ok := expr.(ValueExpr); ok {
  2328. if err := valueExpr.Restore(ctx); err != nil {
  2329. return errors.Annotate(err, "An error occurred while restore AlterTableSpec.NewColumns[0].Options[0].Expr")
  2330. }
  2331. } else {
  2332. ctx.WritePlain("(")
  2333. if err := expr.Restore(ctx); err != nil {
  2334. return errors.Annotate(err, "An error occurred while restore AlterTableSpec.NewColumns[0].Options[0].Expr")
  2335. }
  2336. ctx.WritePlain(")")
  2337. }
  2338. } else {
  2339. ctx.WriteKeyWord(" DROP DEFAULT")
  2340. }
  2341. case AlterTableLock:
  2342. ctx.WriteKeyWord("LOCK ")
  2343. ctx.WritePlain("= ")
  2344. ctx.WriteKeyWord(n.LockType.String())
  2345. case AlterTableWriteable:
  2346. ctx.WriteKeyWord("READ ")
  2347. if n.Writeable {
  2348. ctx.WriteKeyWord("WRITE")
  2349. } else {
  2350. ctx.WriteKeyWord("ONLY")
  2351. }
  2352. case AlterTableOrderByColumns:
  2353. ctx.WriteKeyWord("ORDER BY ")
  2354. for i, alterOrderItem := range n.OrderByList {
  2355. if i != 0 {
  2356. ctx.WritePlain(",")
  2357. }
  2358. if err := alterOrderItem.Restore(ctx); err != nil {
  2359. return errors.Annotatef(err, "An error occurred while restore AlterTableSpec.OrderByList[%d]", i)
  2360. }
  2361. }
  2362. case AlterTableAlgorithm:
  2363. ctx.WriteKeyWord("ALGORITHM ")
  2364. ctx.WritePlain("= ")
  2365. ctx.WriteKeyWord(n.Algorithm.String())
  2366. case AlterTableRenameIndex:
  2367. ctx.WriteKeyWord("RENAME INDEX ")
  2368. ctx.WriteName(n.FromKey.O)
  2369. ctx.WriteKeyWord(" TO ")
  2370. ctx.WriteName(n.ToKey.O)
  2371. case AlterTableForce:
  2372. // TODO: not support
  2373. ctx.WriteKeyWord("FORCE")
  2374. ctx.WritePlain(" /* AlterTableForce is not supported */ ")
  2375. case AlterTableAddPartitions:
  2376. ctx.WriteKeyWord("ADD PARTITION")
  2377. if n.IfNotExists {
  2378. ctx.WriteKeyWord(" IF NOT EXISTS")
  2379. }
  2380. if n.NoWriteToBinlog {
  2381. ctx.WriteKeyWord(" NO_WRITE_TO_BINLOG")
  2382. }
  2383. if n.PartDefinitions != nil {
  2384. ctx.WritePlain(" (")
  2385. for i, def := range n.PartDefinitions {
  2386. if i != 0 {
  2387. ctx.WritePlain(", ")
  2388. }
  2389. if err := def.Restore(ctx); err != nil {
  2390. return errors.Annotatef(err, "An error occurred while restore AlterTableSpec.PartDefinitions[%d]", i)
  2391. }
  2392. }
  2393. ctx.WritePlain(")")
  2394. } else if n.Num != 0 {
  2395. ctx.WriteKeyWord(" PARTITIONS ")
  2396. ctx.WritePlainf("%d", n.Num)
  2397. }
  2398. case AlterTableAlterPartition:
  2399. if len(n.PartitionNames) != 1 {
  2400. return errors.Errorf("Maybe partition options are combined.")
  2401. }
  2402. ctx.WriteKeyWord("ALTER PARTITION ")
  2403. ctx.WriteName(n.PartitionNames[0].O)
  2404. ctx.WritePlain(" ")
  2405. for i, spec := range n.PlacementSpecs {
  2406. if i != 0 {
  2407. ctx.WritePlain(", ")
  2408. }
  2409. if err := spec.Restore(ctx); err != nil {
  2410. return errors.Annotatef(err, "An error occurred while restore AlterTableSpec.PlacementSpecs[%d]", i)
  2411. }
  2412. }
  2413. case AlterTableCoalescePartitions:
  2414. ctx.WriteKeyWord("COALESCE PARTITION ")
  2415. if n.NoWriteToBinlog {
  2416. ctx.WriteKeyWord("NO_WRITE_TO_BINLOG ")
  2417. }
  2418. ctx.WritePlainf("%d", n.Num)
  2419. case AlterTableDropPartition:
  2420. ctx.WriteKeyWord("DROP PARTITION ")
  2421. if n.IfExists {
  2422. ctx.WriteKeyWord("IF EXISTS ")
  2423. }
  2424. for i, name := range n.PartitionNames {
  2425. if i != 0 {
  2426. ctx.WritePlain(",")
  2427. }
  2428. ctx.WriteName(name.O)
  2429. }
  2430. case AlterTableTruncatePartition:
  2431. ctx.WriteKeyWord("TRUNCATE PARTITION ")
  2432. if n.OnAllPartitions {
  2433. ctx.WriteKeyWord("ALL")
  2434. return nil
  2435. }
  2436. for i, name := range n.PartitionNames {
  2437. if i != 0 {
  2438. ctx.WritePlain(",")
  2439. }
  2440. ctx.WriteName(name.O)
  2441. }
  2442. case AlterTableCheckPartitions:
  2443. ctx.WriteKeyWord("CHECK PARTITION ")
  2444. if n.OnAllPartitions {
  2445. ctx.WriteKeyWord("ALL")
  2446. return nil
  2447. }
  2448. for i, name := range n.PartitionNames {
  2449. if i != 0 {
  2450. ctx.WritePlain(",")
  2451. }
  2452. ctx.WriteName(name.O)
  2453. }
  2454. case AlterTableOptimizePartition:
  2455. ctx.WriteKeyWord("OPTIMIZE PARTITION ")
  2456. if n.NoWriteToBinlog {
  2457. ctx.WriteKeyWord("NO_WRITE_TO_BINLOG ")
  2458. }
  2459. if n.OnAllPartitions {
  2460. ctx.WriteKeyWord("ALL")
  2461. return nil
  2462. }
  2463. for i, name := range n.PartitionNames {
  2464. if i != 0 {
  2465. ctx.WritePlain(",")
  2466. }
  2467. ctx.WriteName(name.O)
  2468. }
  2469. case AlterTableRepairPartition:
  2470. ctx.WriteKeyWord("REPAIR PARTITION ")
  2471. if n.NoWriteToBinlog {
  2472. ctx.WriteKeyWord("NO_WRITE_TO_BINLOG ")
  2473. }
  2474. if n.OnAllPartitions {
  2475. ctx.WriteKeyWord("ALL")
  2476. return nil
  2477. }
  2478. for i, name := range n.PartitionNames {
  2479. if i != 0 {
  2480. ctx.WritePlain(",")
  2481. }
  2482. ctx.WriteName(name.O)
  2483. }
  2484. case AlterTableImportPartitionTablespace:
  2485. ctx.WriteKeyWord("IMPORT PARTITION ")
  2486. if n.OnAllPartitions {
  2487. ctx.WriteKeyWord("ALL")
  2488. } else {
  2489. for i, name := range n.PartitionNames {
  2490. if i != 0 {
  2491. ctx.WritePlain(",")
  2492. }
  2493. ctx.WriteName(name.O)
  2494. }
  2495. }
  2496. ctx.WriteKeyWord(" TABLESPACE")
  2497. case AlterTableDiscardPartitionTablespace:
  2498. ctx.WriteKeyWord("DISCARD PARTITION ")
  2499. if n.OnAllPartitions {
  2500. ctx.WriteKeyWord("ALL")
  2501. } else {
  2502. for i, name := range n.PartitionNames {
  2503. if i != 0 {
  2504. ctx.WritePlain(",")
  2505. }
  2506. ctx.WriteName(name.O)
  2507. }
  2508. }
  2509. ctx.WriteKeyWord(" TABLESPACE")
  2510. case AlterTablePartition:
  2511. if err := n.Partition.Restore(ctx); err != nil {
  2512. return errors.Annotate(err, "An error occurred while restore AlterTableSpec.Partition")
  2513. }
  2514. case AlterTableEnableKeys:
  2515. ctx.WriteKeyWord("ENABLE KEYS")
  2516. case AlterTableDisableKeys:
  2517. ctx.WriteKeyWord("DISABLE KEYS")
  2518. case AlterTableRemovePartitioning:
  2519. ctx.WriteKeyWord("REMOVE PARTITIONING")
  2520. case AlterTableWithValidation:
  2521. ctx.WriteKeyWord("WITH VALIDATION")
  2522. case AlterTableWithoutValidation:
  2523. ctx.WriteKeyWord("WITHOUT VALIDATION")
  2524. case AlterTableRebuildPartition:
  2525. ctx.WriteKeyWord("REBUILD PARTITION ")
  2526. if n.NoWriteToBinlog {
  2527. ctx.WriteKeyWord("NO_WRITE_TO_BINLOG ")
  2528. }
  2529. if n.OnAllPartitions {
  2530. ctx.WriteKeyWord("ALL")
  2531. return nil
  2532. }
  2533. for i, name := range n.PartitionNames {
  2534. if i != 0 {
  2535. ctx.WritePlain(",")
  2536. }
  2537. ctx.WriteName(name.O)
  2538. }
  2539. case AlterTableReorganizePartition:
  2540. ctx.WriteKeyWord("REORGANIZE PARTITION")
  2541. if n.NoWriteToBinlog {
  2542. ctx.WriteKeyWord(" NO_WRITE_TO_BINLOG")
  2543. }
  2544. if n.OnAllPartitions {
  2545. return nil
  2546. }
  2547. for i, name := range n.PartitionNames {
  2548. if i != 0 {
  2549. ctx.WritePlain(",")
  2550. } else {
  2551. ctx.WritePlain(" ")
  2552. }
  2553. ctx.WriteName(name.O)
  2554. }
  2555. ctx.WriteKeyWord(" INTO ")
  2556. if n.PartDefinitions != nil {
  2557. ctx.WritePlain("(")
  2558. for i, def := range n.PartDefinitions {
  2559. if i != 0 {
  2560. ctx.WritePlain(", ")
  2561. }
  2562. if err := def.Restore(ctx); err != nil {
  2563. return errors.Annotatef(err, "An error occurred while restore AlterTableSpec.PartDefinitions[%d]", i)
  2564. }
  2565. }
  2566. ctx.WritePlain(")")
  2567. }
  2568. case AlterTableExchangePartition:
  2569. ctx.WriteKeyWord("EXCHANGE PARTITION ")
  2570. ctx.WriteName(n.PartitionNames[0].O)
  2571. ctx.WriteKeyWord(" WITH TABLE ")
  2572. n.NewTable.Restore(ctx)
  2573. if !n.WithValidation {
  2574. ctx.WriteKeyWord(" WITHOUT VALIDATION")
  2575. }
  2576. case AlterTableSecondaryLoad:
  2577. ctx.WriteKeyWord("SECONDARY_LOAD")
  2578. case AlterTableSecondaryUnload:
  2579. ctx.WriteKeyWord("SECONDARY_UNLOAD")
  2580. case AlterTableAlterCheck:
  2581. ctx.WriteKeyWord("ALTER CHECK ")
  2582. ctx.WriteName(n.Constraint.Name)
  2583. if !n.Constraint.Enforced {
  2584. ctx.WriteKeyWord(" NOT")
  2585. }
  2586. ctx.WriteKeyWord(" ENFORCED")
  2587. case AlterTableDropCheck:
  2588. ctx.WriteKeyWord("DROP CHECK ")
  2589. ctx.WriteName(n.Constraint.Name)
  2590. case AlterTableImportTablespace:
  2591. ctx.WriteKeyWord("IMPORT TABLESPACE")
  2592. case AlterTableDiscardTablespace:
  2593. ctx.WriteKeyWord("DISCARD TABLESPACE")
  2594. case AlterTableIndexInvisible:
  2595. ctx.WriteKeyWord("ALTER INDEX ")
  2596. ctx.WriteName(n.IndexName.O)
  2597. switch n.Visibility {
  2598. case IndexVisibilityVisible:
  2599. ctx.WriteKeyWord(" VISIBLE")
  2600. case IndexVisibilityInvisible:
  2601. ctx.WriteKeyWord(" INVISIBLE")
  2602. }
  2603. case AlterTablePlacement:
  2604. for i, spec := range n.PlacementSpecs {
  2605. if i != 0 {
  2606. ctx.WritePlain(", ")
  2607. }
  2608. if err := spec.Restore(ctx); err != nil {
  2609. return errors.Annotatef(err, "An error occurred while restore AlterTableSpec.PlacementSpecs[%d]", i)
  2610. }
  2611. }
  2612. default:
  2613. // TODO: not support
  2614. ctx.WritePlainf(" /* AlterTableType(%d) is not supported */ ", n.Tp)
  2615. }
  2616. return nil
  2617. }
  2618. // Accept implements Node Accept interface.
  2619. func (n *AlterTableSpec) Accept(v Visitor) (Node, bool) {
  2620. newNode, skipChildren := v.Enter(n)
  2621. if skipChildren {
  2622. return v.Leave(newNode)
  2623. }
  2624. n = newNode.(*AlterTableSpec)
  2625. if n.Constraint != nil {
  2626. node, ok := n.Constraint.Accept(v)
  2627. if !ok {
  2628. return n, false
  2629. }
  2630. n.Constraint = node.(*Constraint)
  2631. }
  2632. if n.NewTable != nil {
  2633. node, ok := n.NewTable.Accept(v)
  2634. if !ok {
  2635. return n, false
  2636. }
  2637. n.NewTable = node.(*TableName)
  2638. }
  2639. for i, col := range n.NewColumns {
  2640. node, ok := col.Accept(v)
  2641. if !ok {
  2642. return n, false
  2643. }
  2644. n.NewColumns[i] = node.(*ColumnDef)
  2645. }
  2646. for i, constraint := range n.NewConstraints {
  2647. node, ok := constraint.Accept(v)
  2648. if !ok {
  2649. return n, false
  2650. }
  2651. n.NewConstraints[i] = node.(*Constraint)
  2652. }
  2653. if n.OldColumnName != nil {
  2654. node, ok := n.OldColumnName.Accept(v)
  2655. if !ok {
  2656. return n, false
  2657. }
  2658. n.OldColumnName = node.(*ColumnName)
  2659. }
  2660. if n.Position != nil {
  2661. node, ok := n.Position.Accept(v)
  2662. if !ok {
  2663. return n, false
  2664. }
  2665. n.Position = node.(*ColumnPosition)
  2666. }
  2667. if n.Partition != nil {
  2668. node, ok := n.Partition.Accept(v)
  2669. if !ok {
  2670. return n, false
  2671. }
  2672. n.Partition = node.(*PartitionOptions)
  2673. }
  2674. for _, def := range n.PartDefinitions {
  2675. if !def.acceptInPlace(v) {
  2676. return n, false
  2677. }
  2678. }
  2679. for i, spec := range n.PlacementSpecs {
  2680. node, ok := spec.Accept(v)
  2681. if !ok {
  2682. return n, false
  2683. }
  2684. n.PlacementSpecs[i] = node.(*PlacementSpec)
  2685. }
  2686. return v.Leave(n)
  2687. }
  2688. // AlterTableStmt is a statement to change the structure of a table.
  2689. // See https://dev.mysql.com/doc/refman/5.7/en/alter-table.html
  2690. type AlterTableStmt struct {
  2691. ddlNode
  2692. Table *TableName
  2693. Specs []*AlterTableSpec
  2694. }
  2695. // Restore implements Node interface.
  2696. func (n *AlterTableStmt) Restore(ctx *format.RestoreCtx) error {
  2697. ctx.WriteKeyWord("ALTER TABLE ")
  2698. if err := n.Table.Restore(ctx); err != nil {
  2699. return errors.Annotate(err, "An error occurred while restore AlterTableStmt.Table")
  2700. }
  2701. for i, spec := range n.Specs {
  2702. if i == 0 || spec.Tp == AlterTablePartition || spec.Tp == AlterTableRemovePartitioning || spec.Tp == AlterTableImportTablespace || spec.Tp == AlterTableDiscardTablespace {
  2703. ctx.WritePlain(" ")
  2704. } else {
  2705. ctx.WritePlain(", ")
  2706. }
  2707. if err := spec.Restore(ctx); err != nil {
  2708. return errors.Annotatef(err, "An error occurred while restore AlterTableStmt.Specs[%d]", i)
  2709. }
  2710. }
  2711. return nil
  2712. }
  2713. // Accept implements Node Accept interface.
  2714. func (n *AlterTableStmt) Accept(v Visitor) (Node, bool) {
  2715. newNode, skipChildren := v.Enter(n)
  2716. if skipChildren {
  2717. return v.Leave(newNode)
  2718. }
  2719. n = newNode.(*AlterTableStmt)
  2720. node, ok := n.Table.Accept(v)
  2721. if !ok {
  2722. return n, false
  2723. }
  2724. n.Table = node.(*TableName)
  2725. for i, val := range n.Specs {
  2726. node, ok = val.Accept(v)
  2727. if !ok {
  2728. return n, false
  2729. }
  2730. n.Specs[i] = node.(*AlterTableSpec)
  2731. }
  2732. return v.Leave(n)
  2733. }
  2734. // TruncateTableStmt is a statement to empty a table completely.
  2735. // See https://dev.mysql.com/doc/refman/5.7/en/truncate-table.html
  2736. type TruncateTableStmt struct {
  2737. ddlNode
  2738. Table *TableName
  2739. }
  2740. // Restore implements Node interface.
  2741. func (n *TruncateTableStmt) Restore(ctx *format.RestoreCtx) error {
  2742. ctx.WriteKeyWord("TRUNCATE TABLE ")
  2743. if err := n.Table.Restore(ctx); err != nil {
  2744. return errors.Annotate(err, "An error occurred while restore TruncateTableStmt.Table")
  2745. }
  2746. return nil
  2747. }
  2748. // Accept implements Node Accept interface.
  2749. func (n *TruncateTableStmt) Accept(v Visitor) (Node, bool) {
  2750. newNode, skipChildren := v.Enter(n)
  2751. if skipChildren {
  2752. return v.Leave(newNode)
  2753. }
  2754. n = newNode.(*TruncateTableStmt)
  2755. node, ok := n.Table.Accept(v)
  2756. if !ok {
  2757. return n, false
  2758. }
  2759. n.Table = node.(*TableName)
  2760. return v.Leave(n)
  2761. }
  2762. var (
  2763. ErrNoParts = terror.ClassDDL.NewStd(mysql.ErrNoParts)
  2764. ErrPartitionColumnList = terror.ClassDDL.NewStd(mysql.ErrPartitionColumnList)
  2765. ErrPartitionRequiresValues = terror.ClassDDL.NewStd(mysql.ErrPartitionRequiresValues)
  2766. ErrPartitionsMustBeDefined = terror.ClassDDL.NewStd(mysql.ErrPartitionsMustBeDefined)
  2767. ErrPartitionWrongNoPart = terror.ClassDDL.NewStd(mysql.ErrPartitionWrongNoPart)
  2768. ErrPartitionWrongNoSubpart = terror.ClassDDL.NewStd(mysql.ErrPartitionWrongNoSubpart)
  2769. ErrPartitionWrongValues = terror.ClassDDL.NewStd(mysql.ErrPartitionWrongValues)
  2770. ErrRowSinglePartitionField = terror.ClassDDL.NewStd(mysql.ErrRowSinglePartitionField)
  2771. ErrSubpartition = terror.ClassDDL.NewStd(mysql.ErrSubpartition)
  2772. ErrSystemVersioningWrongPartitions = terror.ClassDDL.NewStd(mysql.ErrSystemVersioningWrongPartitions)
  2773. ErrTooManyValues = terror.ClassDDL.NewStd(mysql.ErrTooManyValues)
  2774. ErrWrongPartitionTypeExpectedSystemTime = terror.ClassDDL.NewStd(mysql.ErrWrongPartitionTypeExpectedSystemTime)
  2775. )
  2776. type SubPartitionDefinition struct {
  2777. Name model.CIStr
  2778. Options []*TableOption
  2779. }
  2780. func (spd *SubPartitionDefinition) Restore(ctx *format.RestoreCtx) error {
  2781. ctx.WriteKeyWord("SUBPARTITION ")
  2782. ctx.WriteName(spd.Name.O)
  2783. for i, opt := range spd.Options {
  2784. ctx.WritePlain(" ")
  2785. if err := opt.Restore(ctx); err != nil {
  2786. return errors.Annotatef(err, "An error occurred while restore SubPartitionDefinition.Options[%d]", i)
  2787. }
  2788. }
  2789. return nil
  2790. }
  2791. type PartitionDefinitionClause interface {
  2792. restore(ctx *format.RestoreCtx) error
  2793. acceptInPlace(v Visitor) bool
  2794. // Validate checks if the clause is consistent with the given options.
  2795. // `pt` can be 0 and `columns` can be -1 to skip checking the clause against
  2796. // the partition type or number of columns in the expression list.
  2797. Validate(pt model.PartitionType, columns int) error
  2798. }
  2799. type PartitionDefinitionClauseNone struct{}
  2800. func (n *PartitionDefinitionClauseNone) restore(ctx *format.RestoreCtx) error {
  2801. return nil
  2802. }
  2803. func (n *PartitionDefinitionClauseNone) acceptInPlace(v Visitor) bool {
  2804. return true
  2805. }
  2806. func (n *PartitionDefinitionClauseNone) Validate(pt model.PartitionType, columns int) error {
  2807. switch pt {
  2808. case 0:
  2809. case model.PartitionTypeRange:
  2810. return ErrPartitionRequiresValues.GenWithStackByArgs("RANGE", "LESS THAN")
  2811. case model.PartitionTypeList:
  2812. return ErrPartitionRequiresValues.GenWithStackByArgs("LIST", "IN")
  2813. case model.PartitionTypeSystemTime:
  2814. return ErrSystemVersioningWrongPartitions
  2815. }
  2816. return nil
  2817. }
  2818. type PartitionDefinitionClauseLessThan struct {
  2819. Exprs []ExprNode
  2820. }
  2821. func (n *PartitionDefinitionClauseLessThan) restore(ctx *format.RestoreCtx) error {
  2822. ctx.WriteKeyWord(" VALUES LESS THAN ")
  2823. ctx.WritePlain("(")
  2824. for i, expr := range n.Exprs {
  2825. if i != 0 {
  2826. ctx.WritePlain(", ")
  2827. }
  2828. if err := expr.Restore(ctx); err != nil {
  2829. return errors.Annotatef(err, "An error occurred while restore PartitionDefinitionClauseLessThan.Exprs[%d]", i)
  2830. }
  2831. }
  2832. ctx.WritePlain(")")
  2833. return nil
  2834. }
  2835. func (n *PartitionDefinitionClauseLessThan) acceptInPlace(v Visitor) bool {
  2836. for i, expr := range n.Exprs {
  2837. newExpr, ok := expr.Accept(v)
  2838. if !ok {
  2839. return false
  2840. }
  2841. n.Exprs[i] = newExpr.(ExprNode)
  2842. }
  2843. return true
  2844. }
  2845. func (n *PartitionDefinitionClauseLessThan) Validate(pt model.PartitionType, columns int) error {
  2846. switch pt {
  2847. case model.PartitionTypeRange, 0:
  2848. default:
  2849. return ErrPartitionWrongValues.GenWithStackByArgs("RANGE", "LESS THAN")
  2850. }
  2851. switch {
  2852. case columns == 0 && len(n.Exprs) != 1:
  2853. return ErrTooManyValues.GenWithStackByArgs("RANGE")
  2854. case columns > 0 && len(n.Exprs) != columns:
  2855. return ErrPartitionColumnList
  2856. }
  2857. return nil
  2858. }
  2859. type PartitionDefinitionClauseIn struct {
  2860. Values [][]ExprNode
  2861. }
  2862. func (n *PartitionDefinitionClauseIn) restore(ctx *format.RestoreCtx) error {
  2863. // we special-case an empty list of values to mean MariaDB's "DEFAULT" clause.
  2864. if len(n.Values) == 0 {
  2865. ctx.WriteKeyWord(" DEFAULT")
  2866. return nil
  2867. }
  2868. ctx.WriteKeyWord(" VALUES IN ")
  2869. ctx.WritePlain("(")
  2870. for i, valList := range n.Values {
  2871. if i != 0 {
  2872. ctx.WritePlain(", ")
  2873. }
  2874. if len(valList) == 1 {
  2875. if err := valList[0].Restore(ctx); err != nil {
  2876. return errors.Annotatef(err, "An error occurred while restore PartitionDefinitionClauseIn.Values[%d][0]", i)
  2877. }
  2878. } else {
  2879. ctx.WritePlain("(")
  2880. for j, val := range valList {
  2881. if j != 0 {
  2882. ctx.WritePlain(", ")
  2883. }
  2884. if err := val.Restore(ctx); err != nil {
  2885. return errors.Annotatef(err, "An error occurred while restore PartitionDefinitionClauseIn.Values[%d][%d]", i, j)
  2886. }
  2887. }
  2888. ctx.WritePlain(")")
  2889. }
  2890. }
  2891. ctx.WritePlain(")")
  2892. return nil
  2893. }
  2894. func (n *PartitionDefinitionClauseIn) acceptInPlace(v Visitor) bool {
  2895. for _, valList := range n.Values {
  2896. for j, val := range valList {
  2897. newVal, ok := val.Accept(v)
  2898. if !ok {
  2899. return false
  2900. }
  2901. valList[j] = newVal.(ExprNode)
  2902. }
  2903. }
  2904. return true
  2905. }
  2906. func (n *PartitionDefinitionClauseIn) Validate(pt model.PartitionType, columns int) error {
  2907. switch pt {
  2908. case model.PartitionTypeList, 0:
  2909. default:
  2910. return ErrPartitionWrongValues.GenWithStackByArgs("LIST", "IN")
  2911. }
  2912. if len(n.Values) == 0 {
  2913. return nil
  2914. }
  2915. expectedColCount := len(n.Values[0])
  2916. for _, val := range n.Values[1:] {
  2917. if len(val) != expectedColCount {
  2918. return ErrPartitionColumnList
  2919. }
  2920. }
  2921. switch {
  2922. case columns == 0 && expectedColCount != 1:
  2923. return ErrRowSinglePartitionField
  2924. case columns > 0 && expectedColCount != columns:
  2925. return ErrPartitionColumnList
  2926. }
  2927. return nil
  2928. }
  2929. type PartitionDefinitionClauseHistory struct {
  2930. Current bool
  2931. }
  2932. func (n *PartitionDefinitionClauseHistory) restore(ctx *format.RestoreCtx) error {
  2933. if n.Current {
  2934. ctx.WriteKeyWord(" CURRENT")
  2935. } else {
  2936. ctx.WriteKeyWord(" HISTORY")
  2937. }
  2938. return nil
  2939. }
  2940. func (n *PartitionDefinitionClauseHistory) acceptInPlace(v Visitor) bool {
  2941. return true
  2942. }
  2943. func (n *PartitionDefinitionClauseHistory) Validate(pt model.PartitionType, columns int) error {
  2944. switch pt {
  2945. case 0, model.PartitionTypeSystemTime:
  2946. default:
  2947. return ErrWrongPartitionTypeExpectedSystemTime
  2948. }
  2949. return nil
  2950. }
  2951. // PartitionDefinition defines a single partition.
  2952. type PartitionDefinition struct {
  2953. Name model.CIStr
  2954. Clause PartitionDefinitionClause
  2955. Options []*TableOption
  2956. Sub []*SubPartitionDefinition
  2957. }
  2958. // Comment returns the comment option given to this definition.
  2959. // The second return value indicates if the comment option exists.
  2960. func (n *PartitionDefinition) Comment() (string, bool) {
  2961. for _, opt := range n.Options {
  2962. if opt.Tp == TableOptionComment {
  2963. return opt.StrValue, true
  2964. }
  2965. }
  2966. return "", false
  2967. }
  2968. func (n *PartitionDefinition) acceptInPlace(v Visitor) bool {
  2969. return n.Clause.acceptInPlace(v)
  2970. }
  2971. // Restore implements Node interface.
  2972. func (n *PartitionDefinition) Restore(ctx *format.RestoreCtx) error {
  2973. ctx.WriteKeyWord("PARTITION ")
  2974. ctx.WriteName(n.Name.O)
  2975. if err := n.Clause.restore(ctx); err != nil {
  2976. return errors.Annotate(err, "An error occurred while restore PartitionDefinition.Clause")
  2977. }
  2978. for i, opt := range n.Options {
  2979. ctx.WritePlain(" ")
  2980. if err := opt.Restore(ctx); err != nil {
  2981. return errors.Annotatef(err, "An error occurred while restore PartitionDefinition.Options[%d]", i)
  2982. }
  2983. }
  2984. if len(n.Sub) > 0 {
  2985. ctx.WritePlain(" (")
  2986. for i, spd := range n.Sub {
  2987. if i != 0 {
  2988. ctx.WritePlain(",")
  2989. }
  2990. if err := spd.Restore(ctx); err != nil {
  2991. return errors.Annotatef(err, "An error occurred while restore PartitionDefinition.Sub[%d]", i)
  2992. }
  2993. }
  2994. ctx.WritePlain(")")
  2995. }
  2996. return nil
  2997. }
  2998. // PartitionMethod describes how partitions or subpartitions are constructed.
  2999. type PartitionMethod struct {
  3000. // Tp is the type of the partition function
  3001. Tp model.PartitionType
  3002. // Linear is a modifier to the HASH and KEY type for choosing a different
  3003. // algorithm
  3004. Linear bool
  3005. // Expr is an expression used as argument of HASH, RANGE, LIST and
  3006. // SYSTEM_TIME types
  3007. Expr ExprNode
  3008. // ColumnNames is a list of column names used as argument of KEY,
  3009. // RANGE COLUMNS and LIST COLUMNS types
  3010. ColumnNames []*ColumnName
  3011. // Unit is a time unit used as argument of SYSTEM_TIME type
  3012. Unit TimeUnitType
  3013. // Limit is a row count used as argument of the SYSTEM_TIME type
  3014. Limit uint64
  3015. // Num is the number of (sub)partitions required by the method.
  3016. Num uint64
  3017. }
  3018. // Restore implements the Node interface
  3019. func (n *PartitionMethod) Restore(ctx *format.RestoreCtx) error {
  3020. if n.Linear {
  3021. ctx.WriteKeyWord("LINEAR ")
  3022. }
  3023. ctx.WriteKeyWord(n.Tp.String())
  3024. switch {
  3025. case n.Tp == model.PartitionTypeSystemTime:
  3026. if n.Expr != nil && n.Unit != TimeUnitInvalid {
  3027. ctx.WriteKeyWord(" INTERVAL ")
  3028. if err := n.Expr.Restore(ctx); err != nil {
  3029. return errors.Annotate(err, "An error occurred while restore PartitionMethod.Expr")
  3030. }
  3031. ctx.WritePlain(" ")
  3032. ctx.WriteKeyWord(n.Unit.String())
  3033. }
  3034. case n.Expr != nil:
  3035. ctx.WritePlain(" (")
  3036. if err := n.Expr.Restore(ctx); err != nil {
  3037. return errors.Annotate(err, "An error occurred while restore PartitionMethod.Expr")
  3038. }
  3039. ctx.WritePlain(")")
  3040. default:
  3041. if n.Tp == model.PartitionTypeRange || n.Tp == model.PartitionTypeList {
  3042. ctx.WriteKeyWord(" COLUMNS")
  3043. }
  3044. ctx.WritePlain(" (")
  3045. for i, col := range n.ColumnNames {
  3046. if i > 0 {
  3047. ctx.WritePlain(",")
  3048. }
  3049. if err := col.Restore(ctx); err != nil {
  3050. return errors.Annotatef(err, "An error occurred while splicing PartitionMethod.ColumnName[%d]", i)
  3051. }
  3052. }
  3053. ctx.WritePlain(")")
  3054. }
  3055. if n.Limit > 0 {
  3056. ctx.WriteKeyWord(" LIMIT ")
  3057. ctx.WritePlainf("%d", n.Limit)
  3058. }
  3059. return nil
  3060. }
  3061. // acceptInPlace is like Node.Accept but does not allow replacing the node itself.
  3062. func (n *PartitionMethod) acceptInPlace(v Visitor) bool {
  3063. if n.Expr != nil {
  3064. expr, ok := n.Expr.Accept(v)
  3065. if !ok {
  3066. return false
  3067. }
  3068. n.Expr = expr.(ExprNode)
  3069. }
  3070. for i, colName := range n.ColumnNames {
  3071. newColName, ok := colName.Accept(v)
  3072. if !ok {
  3073. return false
  3074. }
  3075. n.ColumnNames[i] = newColName.(*ColumnName)
  3076. }
  3077. return true
  3078. }
  3079. // PartitionOptions specifies the partition options.
  3080. type PartitionOptions struct {
  3081. node
  3082. PartitionMethod
  3083. Sub *PartitionMethod
  3084. Definitions []*PartitionDefinition
  3085. }
  3086. // Validate checks if the partition is well-formed.
  3087. func (n *PartitionOptions) Validate() error {
  3088. // if both a partition list and the partition numbers are specified, their values must match
  3089. if n.Num != 0 && len(n.Definitions) != 0 && n.Num != uint64(len(n.Definitions)) {
  3090. return ErrPartitionWrongNoPart
  3091. }
  3092. // now check the subpartition count
  3093. if len(n.Definitions) > 0 {
  3094. // ensure the subpartition count for every partitions are the same
  3095. // then normalize n.Num and n.Sub.Num so equality comparison works.
  3096. n.Num = uint64(len(n.Definitions))
  3097. subDefCount := len(n.Definitions[0].Sub)
  3098. for _, pd := range n.Definitions[1:] {
  3099. if len(pd.Sub) != subDefCount {
  3100. return ErrPartitionWrongNoSubpart
  3101. }
  3102. }
  3103. if n.Sub != nil {
  3104. if n.Sub.Num != 0 && subDefCount != 0 && n.Sub.Num != uint64(subDefCount) {
  3105. return ErrPartitionWrongNoSubpart
  3106. }
  3107. if subDefCount != 0 {
  3108. n.Sub.Num = uint64(subDefCount)
  3109. }
  3110. } else if subDefCount != 0 {
  3111. return ErrSubpartition
  3112. }
  3113. }
  3114. switch n.Tp {
  3115. case model.PartitionTypeHash, model.PartitionTypeKey:
  3116. if n.Num == 0 {
  3117. n.Num = 1
  3118. }
  3119. case model.PartitionTypeRange, model.PartitionTypeList:
  3120. if len(n.Definitions) == 0 {
  3121. return ErrPartitionsMustBeDefined.GenWithStackByArgs(n.Tp)
  3122. }
  3123. case model.PartitionTypeSystemTime:
  3124. if len(n.Definitions) < 2 {
  3125. return ErrSystemVersioningWrongPartitions
  3126. }
  3127. }
  3128. for _, pd := range n.Definitions {
  3129. // ensure the partition definition types match the methods,
  3130. // e.g. RANGE partitions only allows VALUES LESS THAN
  3131. if err := pd.Clause.Validate(n.Tp, len(n.ColumnNames)); err != nil {
  3132. return err
  3133. }
  3134. }
  3135. return nil
  3136. }
  3137. func (n *PartitionOptions) Restore(ctx *format.RestoreCtx) error {
  3138. ctx.WriteKeyWord("PARTITION BY ")
  3139. if err := n.PartitionMethod.Restore(ctx); err != nil {
  3140. return errors.Annotate(err, "An error occurred while restore PartitionOptions.PartitionMethod")
  3141. }
  3142. if n.Num > 0 && len(n.Definitions) == 0 {
  3143. ctx.WriteKeyWord(" PARTITIONS ")
  3144. ctx.WritePlainf("%d", n.Num)
  3145. }
  3146. if n.Sub != nil {
  3147. ctx.WriteKeyWord(" SUBPARTITION BY ")
  3148. if err := n.Sub.Restore(ctx); err != nil {
  3149. return errors.Annotate(err, "An error occurred while restore PartitionOptions.Sub")
  3150. }
  3151. if n.Sub.Num > 0 {
  3152. ctx.WriteKeyWord(" SUBPARTITIONS ")
  3153. ctx.WritePlainf("%d", n.Sub.Num)
  3154. }
  3155. }
  3156. if len(n.Definitions) > 0 {
  3157. ctx.WritePlain(" (")
  3158. for i, def := range n.Definitions {
  3159. if i > 0 {
  3160. ctx.WritePlain(",")
  3161. }
  3162. if err := def.Restore(ctx); err != nil {
  3163. return errors.Annotatef(err, "An error occurred while restore PartitionOptions.Definitions[%d]", i)
  3164. }
  3165. }
  3166. ctx.WritePlain(")")
  3167. }
  3168. return nil
  3169. }
  3170. func (n *PartitionOptions) Accept(v Visitor) (Node, bool) {
  3171. newNode, skipChildren := v.Enter(n)
  3172. if skipChildren {
  3173. return v.Leave(newNode)
  3174. }
  3175. n = newNode.(*PartitionOptions)
  3176. if !n.PartitionMethod.acceptInPlace(v) {
  3177. return n, false
  3178. }
  3179. if n.Sub != nil && !n.Sub.acceptInPlace(v) {
  3180. return n, false
  3181. }
  3182. for _, def := range n.Definitions {
  3183. if !def.acceptInPlace(v) {
  3184. return n, false
  3185. }
  3186. }
  3187. return v.Leave(n)
  3188. }
  3189. // RecoverTableStmt is a statement to recover dropped table.
  3190. type RecoverTableStmt struct {
  3191. ddlNode
  3192. JobID int64
  3193. Table *TableName
  3194. JobNum int64
  3195. }
  3196. // Restore implements Node interface.
  3197. func (n *RecoverTableStmt) Restore(ctx *format.RestoreCtx) error {
  3198. ctx.WriteKeyWord("RECOVER TABLE ")
  3199. if n.JobID != 0 {
  3200. ctx.WriteKeyWord("BY JOB ")
  3201. ctx.WritePlainf("%d", n.JobID)
  3202. } else {
  3203. if err := n.Table.Restore(ctx); err != nil {
  3204. return errors.Annotate(err, "An error occurred while splicing RecoverTableStmt Table")
  3205. }
  3206. if n.JobNum > 0 {
  3207. ctx.WritePlainf(" %d", n.JobNum)
  3208. }
  3209. }
  3210. return nil
  3211. }
  3212. // Accept implements Node Accept interface.
  3213. func (n *RecoverTableStmt) Accept(v Visitor) (Node, bool) {
  3214. newNode, skipChildren := v.Enter(n)
  3215. if skipChildren {
  3216. return v.Leave(newNode)
  3217. }
  3218. n = newNode.(*RecoverTableStmt)
  3219. if n.Table != nil {
  3220. node, ok := n.Table.Accept(v)
  3221. if !ok {
  3222. return n, false
  3223. }
  3224. n.Table = node.(*TableName)
  3225. }
  3226. return v.Leave(n)
  3227. }
  3228. // FlashBackTableStmt is a statement to restore a dropped/truncate table.
  3229. type FlashBackTableStmt struct {
  3230. ddlNode
  3231. Table *TableName
  3232. NewName string
  3233. }
  3234. // Restore implements Node interface.
  3235. func (n *FlashBackTableStmt) Restore(ctx *format.RestoreCtx) error {
  3236. ctx.WriteKeyWord("FLASHBACK TABLE ")
  3237. if err := n.Table.Restore(ctx); err != nil {
  3238. return errors.Annotate(err, "An error occurred while splicing RecoverTableStmt Table")
  3239. }
  3240. if len(n.NewName) > 0 {
  3241. ctx.WriteKeyWord(" TO ")
  3242. ctx.WriteName(n.NewName)
  3243. }
  3244. return nil
  3245. }
  3246. // Accept implements Node Accept interface.
  3247. func (n *FlashBackTableStmt) Accept(v Visitor) (Node, bool) {
  3248. newNode, skipChildren := v.Enter(n)
  3249. if skipChildren {
  3250. return v.Leave(newNode)
  3251. }
  3252. n = newNode.(*FlashBackTableStmt)
  3253. if n.Table != nil {
  3254. node, ok := n.Table.Accept(v)
  3255. if !ok {
  3256. return n, false
  3257. }
  3258. n.Table = node.(*TableName)
  3259. }
  3260. return v.Leave(n)
  3261. }
  3262. type PlacementActionType int
  3263. const (
  3264. PlacementAdd PlacementActionType = iota + 1
  3265. PlacementAlter
  3266. PlacementDrop
  3267. )
  3268. type PlacementRole int
  3269. const (
  3270. PlacementRoleNone PlacementRole = iota
  3271. PlacementRoleLeader
  3272. PlacementRoleFollower
  3273. PlacementRoleLearner
  3274. PlacementRoleVoter
  3275. )
  3276. type PlacementSpec struct {
  3277. node
  3278. Tp PlacementActionType
  3279. Constraints string
  3280. Role PlacementRole
  3281. Replicas uint64
  3282. }
  3283. func (n *PlacementSpec) restoreRole(ctx *format.RestoreCtx) error {
  3284. ctx.WriteKeyWord(" ROLE")
  3285. ctx.WritePlain("=")
  3286. switch n.Role {
  3287. case PlacementRoleFollower:
  3288. ctx.WriteKeyWord("FOLLOWER")
  3289. case PlacementRoleLeader:
  3290. ctx.WriteKeyWord("LEADER")
  3291. case PlacementRoleLearner:
  3292. ctx.WriteKeyWord("LEARNER")
  3293. case PlacementRoleVoter:
  3294. ctx.WriteKeyWord("VOTER")
  3295. default:
  3296. return errors.Errorf("invalid PlacementRole: %d", n.Role)
  3297. }
  3298. return nil
  3299. }
  3300. func (n *PlacementSpec) Restore(ctx *format.RestoreCtx) error {
  3301. switch n.Tp {
  3302. case PlacementAdd:
  3303. ctx.WriteKeyWord("ADD PLACEMENT POLICY ")
  3304. case PlacementAlter:
  3305. ctx.WriteKeyWord("ALTER PLACEMENT POLICY ")
  3306. case PlacementDrop:
  3307. ctx.WriteKeyWord("DROP PLACEMENT POLICY")
  3308. if n.Role != PlacementRoleNone {
  3309. return n.restoreRole(ctx)
  3310. }
  3311. return nil
  3312. default:
  3313. return errors.Errorf("invalid PlacementActionType: %d", n.Tp)
  3314. }
  3315. ctx.WriteKeyWord("CONSTRAINTS")
  3316. ctx.WritePlain("=")
  3317. ctx.WriteString(n.Constraints)
  3318. if err := n.restoreRole(ctx); err != nil {
  3319. return err
  3320. }
  3321. ctx.WriteKeyWord(" REPLICAS")
  3322. ctx.WritePlainf("=%d", n.Replicas)
  3323. return nil
  3324. }
  3325. func (n *PlacementSpec) Accept(v Visitor) (Node, bool) {
  3326. newNode, skipChildren := v.Enter(n)
  3327. if skipChildren {
  3328. return v.Leave(newNode)
  3329. }
  3330. n = newNode.(*PlacementSpec)
  3331. return v.Leave(n)
  3332. }
  3333. // AlterSequenceStmt is a statement to alter sequence option.
  3334. type AlterSequenceStmt struct {
  3335. ddlNode
  3336. // sequence name
  3337. Name *TableName
  3338. IfExists bool
  3339. SeqOptions []*SequenceOption
  3340. }
  3341. func (n *AlterSequenceStmt) Restore(ctx *format.RestoreCtx) error {
  3342. ctx.WriteKeyWord("ALTER SEQUENCE ")
  3343. if n.IfExists {
  3344. ctx.WriteKeyWord("IF EXISTS ")
  3345. }
  3346. if err := n.Name.Restore(ctx); err != nil {
  3347. return errors.Annotate(err, "An error occurred while restore AlterSequenceStmt.Table")
  3348. }
  3349. for i, option := range n.SeqOptions {
  3350. ctx.WritePlain(" ")
  3351. if err := option.Restore(ctx); err != nil {
  3352. return errors.Annotatef(err, "An error occurred while splicing AlterSequenceStmt SequenceOption: [%v]", i)
  3353. }
  3354. }
  3355. return nil
  3356. }
  3357. func (n *AlterSequenceStmt) Accept(v Visitor) (Node, bool) {
  3358. newNode, skipChildren := v.Enter(n)
  3359. if skipChildren {
  3360. return v.Leave(newNode)
  3361. }
  3362. n = newNode.(*AlterSequenceStmt)
  3363. node, ok := n.Name.Accept(v)
  3364. if !ok {
  3365. return n, false
  3366. }
  3367. n.Name = node.(*TableName)
  3368. return v.Leave(n)
  3369. }