misc.go 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273
  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. "bytes"
  16. "fmt"
  17. "net/url"
  18. "strconv"
  19. "strings"
  20. "github.com/pingcap/errors"
  21. "github.com/pingcap/parser/auth"
  22. "github.com/pingcap/parser/format"
  23. "github.com/pingcap/parser/model"
  24. "github.com/pingcap/parser/mysql"
  25. )
  26. var (
  27. _ StmtNode = &AdminStmt{}
  28. _ StmtNode = &AlterUserStmt{}
  29. _ StmtNode = &BeginStmt{}
  30. _ StmtNode = &BinlogStmt{}
  31. _ StmtNode = &CommitStmt{}
  32. _ StmtNode = &CreateUserStmt{}
  33. _ StmtNode = &DeallocateStmt{}
  34. _ StmtNode = &DoStmt{}
  35. _ StmtNode = &ExecuteStmt{}
  36. _ StmtNode = &ExplainStmt{}
  37. _ StmtNode = &GrantStmt{}
  38. _ StmtNode = &PrepareStmt{}
  39. _ StmtNode = &RollbackStmt{}
  40. _ StmtNode = &SetPwdStmt{}
  41. _ StmtNode = &SetRoleStmt{}
  42. _ StmtNode = &SetDefaultRoleStmt{}
  43. _ StmtNode = &SetStmt{}
  44. _ StmtNode = &UseStmt{}
  45. _ StmtNode = &FlushStmt{}
  46. _ StmtNode = &KillStmt{}
  47. _ StmtNode = &CreateBindingStmt{}
  48. _ StmtNode = &DropBindingStmt{}
  49. _ StmtNode = &ShutdownStmt{}
  50. _ StmtNode = &RenameUserStmt{}
  51. _ Node = &PrivElem{}
  52. _ Node = &VariableAssignment{}
  53. )
  54. // Isolation level constants.
  55. const (
  56. ReadCommitted = "READ-COMMITTED"
  57. ReadUncommitted = "READ-UNCOMMITTED"
  58. Serializable = "SERIALIZABLE"
  59. RepeatableRead = "REPEATABLE-READ"
  60. // Valid formats for explain statement.
  61. ExplainFormatROW = "row"
  62. ExplainFormatDOT = "dot"
  63. ExplainFormatJSON = "json"
  64. ExplainFormatHint = "hint"
  65. ExplainFormatVerbose = "verbose"
  66. ExplainFormatBrief = "brief"
  67. PumpType = "PUMP"
  68. DrainerType = "DRAINER"
  69. )
  70. // Transaction mode constants.
  71. const (
  72. Optimistic = "OPTIMISTIC"
  73. Pessimistic = "PESSIMISTIC"
  74. )
  75. var (
  76. // ExplainFormats stores the valid formats for explain statement, used by validator.
  77. ExplainFormats = []string{
  78. ExplainFormatROW,
  79. ExplainFormatDOT,
  80. ExplainFormatJSON,
  81. ExplainFormatHint,
  82. ExplainFormatVerbose,
  83. ExplainFormatBrief,
  84. }
  85. )
  86. // TypeOpt is used for parsing data type option from SQL.
  87. type TypeOpt struct {
  88. IsUnsigned bool
  89. IsZerofill bool
  90. }
  91. // FloatOpt is used for parsing floating-point type option from SQL.
  92. // See http://dev.mysql.com/doc/refman/5.7/en/floating-point-types.html
  93. type FloatOpt struct {
  94. Flen int
  95. Decimal int
  96. }
  97. // AuthOption is used for parsing create use statement.
  98. type AuthOption struct {
  99. // ByAuthString set as true, if AuthString is used for authorization. Otherwise, authorization is done by HashString.
  100. ByAuthString bool
  101. AuthString string
  102. HashString string
  103. // TODO: support auth_plugin
  104. }
  105. // Restore implements Node interface.
  106. func (n *AuthOption) Restore(ctx *format.RestoreCtx) error {
  107. ctx.WriteKeyWord("IDENTIFIED BY ")
  108. if n.ByAuthString {
  109. ctx.WriteString(n.AuthString)
  110. } else {
  111. ctx.WriteKeyWord("PASSWORD ")
  112. ctx.WriteString(n.HashString)
  113. }
  114. return nil
  115. }
  116. // TraceStmt is a statement to trace what sql actually does at background.
  117. type TraceStmt struct {
  118. stmtNode
  119. Stmt StmtNode
  120. Format string
  121. }
  122. // Restore implements Node interface.
  123. func (n *TraceStmt) Restore(ctx *format.RestoreCtx) error {
  124. ctx.WriteKeyWord("TRACE ")
  125. if n.Format != "row" {
  126. ctx.WriteKeyWord("FORMAT")
  127. ctx.WritePlain(" = ")
  128. ctx.WriteString(n.Format)
  129. ctx.WritePlain(" ")
  130. }
  131. if err := n.Stmt.Restore(ctx); err != nil {
  132. return errors.Annotate(err, "An error occurred while restore TraceStmt.Stmt")
  133. }
  134. return nil
  135. }
  136. // Accept implements Node Accept interface.
  137. func (n *TraceStmt) Accept(v Visitor) (Node, bool) {
  138. newNode, skipChildren := v.Enter(n)
  139. if skipChildren {
  140. return v.Leave(newNode)
  141. }
  142. n = newNode.(*TraceStmt)
  143. node, ok := n.Stmt.Accept(v)
  144. if !ok {
  145. return n, false
  146. }
  147. n.Stmt = node.(StmtNode)
  148. return v.Leave(n)
  149. }
  150. // ExplainForStmt is a statement to provite information about how is SQL statement executeing
  151. // in connection #ConnectionID
  152. // See https://dev.mysql.com/doc/refman/5.7/en/explain.html
  153. type ExplainForStmt struct {
  154. stmtNode
  155. Format string
  156. ConnectionID uint64
  157. }
  158. // Restore implements Node interface.
  159. func (n *ExplainForStmt) Restore(ctx *format.RestoreCtx) error {
  160. ctx.WriteKeyWord("EXPLAIN ")
  161. ctx.WriteKeyWord("FORMAT ")
  162. ctx.WritePlain("= ")
  163. ctx.WriteString(n.Format)
  164. ctx.WritePlain(" ")
  165. ctx.WriteKeyWord("FOR ")
  166. ctx.WriteKeyWord("CONNECTION ")
  167. ctx.WritePlain(strconv.FormatUint(n.ConnectionID, 10))
  168. return nil
  169. }
  170. // Accept implements Node Accept interface.
  171. func (n *ExplainForStmt) Accept(v Visitor) (Node, bool) {
  172. newNode, skipChildren := v.Enter(n)
  173. if skipChildren {
  174. return v.Leave(newNode)
  175. }
  176. n = newNode.(*ExplainForStmt)
  177. return v.Leave(n)
  178. }
  179. // ExplainStmt is a statement to provide information about how is SQL statement executed
  180. // or get columns information in a table.
  181. // See https://dev.mysql.com/doc/refman/5.7/en/explain.html
  182. type ExplainStmt struct {
  183. stmtNode
  184. Stmt StmtNode
  185. Format string
  186. Analyze bool
  187. }
  188. // Restore implements Node interface.
  189. func (n *ExplainStmt) Restore(ctx *format.RestoreCtx) error {
  190. if showStmt, ok := n.Stmt.(*ShowStmt); ok {
  191. ctx.WriteKeyWord("DESC ")
  192. if err := showStmt.Table.Restore(ctx); err != nil {
  193. return errors.Annotate(err, "An error occurred while restore ExplainStmt.ShowStmt.Table")
  194. }
  195. if showStmt.Column != nil {
  196. ctx.WritePlain(" ")
  197. if err := showStmt.Column.Restore(ctx); err != nil {
  198. return errors.Annotate(err, "An error occurred while restore ExplainStmt.ShowStmt.Column")
  199. }
  200. }
  201. return nil
  202. }
  203. ctx.WriteKeyWord("EXPLAIN ")
  204. if n.Analyze {
  205. ctx.WriteKeyWord("ANALYZE ")
  206. } else {
  207. ctx.WriteKeyWord("FORMAT ")
  208. ctx.WritePlain("= ")
  209. ctx.WriteString(n.Format)
  210. ctx.WritePlain(" ")
  211. }
  212. if err := n.Stmt.Restore(ctx); err != nil {
  213. return errors.Annotate(err, "An error occurred while restore ExplainStmt.Stmt")
  214. }
  215. return nil
  216. }
  217. // Accept implements Node Accept interface.
  218. func (n *ExplainStmt) Accept(v Visitor) (Node, bool) {
  219. newNode, skipChildren := v.Enter(n)
  220. if skipChildren {
  221. return v.Leave(newNode)
  222. }
  223. n = newNode.(*ExplainStmt)
  224. node, ok := n.Stmt.Accept(v)
  225. if !ok {
  226. return n, false
  227. }
  228. n.Stmt = node.(StmtNode)
  229. return v.Leave(n)
  230. }
  231. // PrepareStmt is a statement to prepares a SQL statement which contains placeholders,
  232. // and it is executed with ExecuteStmt and released with DeallocateStmt.
  233. // See https://dev.mysql.com/doc/refman/5.7/en/prepare.html
  234. type PrepareStmt struct {
  235. stmtNode
  236. Name string
  237. SQLText string
  238. SQLVar *VariableExpr
  239. }
  240. // Restore implements Node interface.
  241. func (n *PrepareStmt) Restore(ctx *format.RestoreCtx) error {
  242. ctx.WriteKeyWord("PREPARE ")
  243. ctx.WriteName(n.Name)
  244. ctx.WriteKeyWord(" FROM ")
  245. if n.SQLText != "" {
  246. ctx.WriteString(n.SQLText)
  247. return nil
  248. }
  249. if n.SQLVar != nil {
  250. if err := n.SQLVar.Restore(ctx); err != nil {
  251. return errors.Annotate(err, "An error occurred while restore PrepareStmt.SQLVar")
  252. }
  253. return nil
  254. }
  255. return errors.New("An error occurred while restore PrepareStmt")
  256. }
  257. // Accept implements Node Accept interface.
  258. func (n *PrepareStmt) Accept(v Visitor) (Node, bool) {
  259. newNode, skipChildren := v.Enter(n)
  260. if skipChildren {
  261. return v.Leave(newNode)
  262. }
  263. n = newNode.(*PrepareStmt)
  264. if n.SQLVar != nil {
  265. node, ok := n.SQLVar.Accept(v)
  266. if !ok {
  267. return n, false
  268. }
  269. n.SQLVar = node.(*VariableExpr)
  270. }
  271. return v.Leave(n)
  272. }
  273. // DeallocateStmt is a statement to release PreparedStmt.
  274. // See https://dev.mysql.com/doc/refman/5.7/en/deallocate-prepare.html
  275. type DeallocateStmt struct {
  276. stmtNode
  277. Name string
  278. }
  279. // Restore implements Node interface.
  280. func (n *DeallocateStmt) Restore(ctx *format.RestoreCtx) error {
  281. ctx.WriteKeyWord("DEALLOCATE PREPARE ")
  282. ctx.WriteName(n.Name)
  283. return nil
  284. }
  285. // Accept implements Node Accept interface.
  286. func (n *DeallocateStmt) Accept(v Visitor) (Node, bool) {
  287. newNode, skipChildren := v.Enter(n)
  288. if skipChildren {
  289. return v.Leave(newNode)
  290. }
  291. n = newNode.(*DeallocateStmt)
  292. return v.Leave(n)
  293. }
  294. // Prepared represents a prepared statement.
  295. type Prepared struct {
  296. Stmt StmtNode
  297. StmtType string
  298. Params []ParamMarkerExpr
  299. SchemaVersion int64
  300. UseCache bool
  301. CachedPlan interface{}
  302. CachedNames interface{}
  303. }
  304. // ExecuteStmt is a statement to execute PreparedStmt.
  305. // See https://dev.mysql.com/doc/refman/5.7/en/execute.html
  306. type ExecuteStmt struct {
  307. stmtNode
  308. Name string
  309. UsingVars []ExprNode
  310. BinaryArgs interface{}
  311. ExecID uint32
  312. IdxInMulti int
  313. }
  314. // Restore implements Node interface.
  315. func (n *ExecuteStmt) Restore(ctx *format.RestoreCtx) error {
  316. ctx.WriteKeyWord("EXECUTE ")
  317. ctx.WriteName(n.Name)
  318. if len(n.UsingVars) > 0 {
  319. ctx.WriteKeyWord(" USING ")
  320. for i, val := range n.UsingVars {
  321. if i != 0 {
  322. ctx.WritePlain(",")
  323. }
  324. if err := val.Restore(ctx); err != nil {
  325. return errors.Annotatef(err, "An error occurred while restore ExecuteStmt.UsingVars index %d", i)
  326. }
  327. }
  328. }
  329. return nil
  330. }
  331. // Accept implements Node Accept interface.
  332. func (n *ExecuteStmt) Accept(v Visitor) (Node, bool) {
  333. newNode, skipChildren := v.Enter(n)
  334. if skipChildren {
  335. return v.Leave(newNode)
  336. }
  337. n = newNode.(*ExecuteStmt)
  338. for i, val := range n.UsingVars {
  339. node, ok := val.Accept(v)
  340. if !ok {
  341. return n, false
  342. }
  343. n.UsingVars[i] = node.(ExprNode)
  344. }
  345. return v.Leave(n)
  346. }
  347. // BeginStmt is a statement to start a new transaction.
  348. // See https://dev.mysql.com/doc/refman/5.7/en/commit.html
  349. type BeginStmt struct {
  350. stmtNode
  351. Mode string
  352. ReadOnly bool
  353. Bound *TimestampBound
  354. CausalConsistencyOnly bool
  355. }
  356. // Restore implements Node interface.
  357. func (n *BeginStmt) Restore(ctx *format.RestoreCtx) error {
  358. if n.Mode == "" {
  359. if n.ReadOnly {
  360. ctx.WriteKeyWord("START TRANSACTION READ ONLY")
  361. if n.Bound != nil {
  362. switch n.Bound.Mode {
  363. case TimestampBoundStrong:
  364. ctx.WriteKeyWord(" WITH TIMESTAMP BOUND STRONG")
  365. case TimestampBoundMaxStaleness:
  366. ctx.WriteKeyWord(" WITH TIMESTAMP BOUND MAX STALENESS ")
  367. return n.Bound.Timestamp.Restore(ctx)
  368. case TimestampBoundExactStaleness:
  369. ctx.WriteKeyWord(" WITH TIMESTAMP BOUND EXACT STALENESS ")
  370. return n.Bound.Timestamp.Restore(ctx)
  371. case TimestampBoundReadTimestamp:
  372. ctx.WriteKeyWord(" WITH TIMESTAMP BOUND READ TIMESTAMP ")
  373. return n.Bound.Timestamp.Restore(ctx)
  374. case TimestampBoundMinReadTimestamp:
  375. ctx.WriteKeyWord(" WITH TIMESTAMP BOUND MIN READ TIMESTAMP ")
  376. return n.Bound.Timestamp.Restore(ctx)
  377. }
  378. }
  379. } else if n.CausalConsistencyOnly {
  380. ctx.WriteKeyWord("START TRANSACTION WITH CAUSAL CONSISTENCY ONLY")
  381. } else {
  382. ctx.WriteKeyWord("START TRANSACTION")
  383. }
  384. } else {
  385. ctx.WriteKeyWord("BEGIN ")
  386. ctx.WriteKeyWord(n.Mode)
  387. }
  388. return nil
  389. }
  390. // Accept implements Node Accept interface.
  391. func (n *BeginStmt) Accept(v Visitor) (Node, bool) {
  392. newNode, skipChildren := v.Enter(n)
  393. if skipChildren {
  394. return v.Leave(newNode)
  395. }
  396. n = newNode.(*BeginStmt)
  397. if n.Bound != nil && n.Bound.Timestamp != nil {
  398. newTimestamp, ok := n.Bound.Timestamp.Accept(v)
  399. if !ok {
  400. return n, false
  401. }
  402. n.Bound.Timestamp = newTimestamp.(ExprNode)
  403. }
  404. return v.Leave(n)
  405. }
  406. // BinlogStmt is an internal-use statement.
  407. // We just parse and ignore it.
  408. // See http://dev.mysql.com/doc/refman/5.7/en/binlog.html
  409. type BinlogStmt struct {
  410. stmtNode
  411. Str string
  412. }
  413. // Restore implements Node interface.
  414. func (n *BinlogStmt) Restore(ctx *format.RestoreCtx) error {
  415. ctx.WriteKeyWord("BINLOG ")
  416. ctx.WriteString(n.Str)
  417. return nil
  418. }
  419. // Accept implements Node Accept interface.
  420. func (n *BinlogStmt) Accept(v Visitor) (Node, bool) {
  421. newNode, skipChildren := v.Enter(n)
  422. if skipChildren {
  423. return v.Leave(newNode)
  424. }
  425. n = newNode.(*BinlogStmt)
  426. return v.Leave(n)
  427. }
  428. // CompletionType defines completion_type used in COMMIT and ROLLBACK statements
  429. type CompletionType int8
  430. const (
  431. // CompletionTypeDefault refers to NO_CHAIN
  432. CompletionTypeDefault CompletionType = iota
  433. CompletionTypeChain
  434. CompletionTypeRelease
  435. )
  436. func (n CompletionType) Restore(ctx *format.RestoreCtx) error {
  437. switch n {
  438. case CompletionTypeDefault:
  439. break
  440. case CompletionTypeChain:
  441. ctx.WriteKeyWord(" AND CHAIN")
  442. case CompletionTypeRelease:
  443. ctx.WriteKeyWord(" RELEASE")
  444. }
  445. return nil
  446. }
  447. // CommitStmt is a statement to commit the current transaction.
  448. // See https://dev.mysql.com/doc/refman/5.7/en/commit.html
  449. type CommitStmt struct {
  450. stmtNode
  451. // CompletionType overwrites system variable `completion_type` within transaction
  452. CompletionType CompletionType
  453. }
  454. // Restore implements Node interface.
  455. func (n *CommitStmt) Restore(ctx *format.RestoreCtx) error {
  456. ctx.WriteKeyWord("COMMIT")
  457. if err := n.CompletionType.Restore(ctx); err != nil {
  458. return errors.Annotate(err, "An error occurred while restore CommitStmt.CompletionType")
  459. }
  460. return nil
  461. }
  462. // Accept implements Node Accept interface.
  463. func (n *CommitStmt) Accept(v Visitor) (Node, bool) {
  464. newNode, skipChildren := v.Enter(n)
  465. if skipChildren {
  466. return v.Leave(newNode)
  467. }
  468. n = newNode.(*CommitStmt)
  469. return v.Leave(n)
  470. }
  471. // RollbackStmt is a statement to roll back the current transaction.
  472. // See https://dev.mysql.com/doc/refman/5.7/en/commit.html
  473. type RollbackStmt struct {
  474. stmtNode
  475. // CompletionType overwrites system variable `completion_type` within transaction
  476. CompletionType CompletionType
  477. }
  478. // Restore implements Node interface.
  479. func (n *RollbackStmt) Restore(ctx *format.RestoreCtx) error {
  480. ctx.WriteKeyWord("ROLLBACK")
  481. if err := n.CompletionType.Restore(ctx); err != nil {
  482. return errors.Annotate(err, "An error occurred while restore RollbackStmt.CompletionType")
  483. }
  484. return nil
  485. }
  486. // Accept implements Node Accept interface.
  487. func (n *RollbackStmt) Accept(v Visitor) (Node, bool) {
  488. newNode, skipChildren := v.Enter(n)
  489. if skipChildren {
  490. return v.Leave(newNode)
  491. }
  492. n = newNode.(*RollbackStmt)
  493. return v.Leave(n)
  494. }
  495. // UseStmt is a statement to use the DBName database as the current database.
  496. // See https://dev.mysql.com/doc/refman/5.7/en/use.html
  497. type UseStmt struct {
  498. stmtNode
  499. DBName string
  500. }
  501. // Restore implements Node interface.
  502. func (n *UseStmt) Restore(ctx *format.RestoreCtx) error {
  503. ctx.WriteKeyWord("USE ")
  504. ctx.WriteName(n.DBName)
  505. return nil
  506. }
  507. // Accept implements Node Accept interface.
  508. func (n *UseStmt) Accept(v Visitor) (Node, bool) {
  509. newNode, skipChildren := v.Enter(n)
  510. if skipChildren {
  511. return v.Leave(newNode)
  512. }
  513. n = newNode.(*UseStmt)
  514. return v.Leave(n)
  515. }
  516. const (
  517. // SetNames is the const for set names stmt.
  518. // If VariableAssignment.Name == Names, it should be set names stmt.
  519. SetNames = "SetNAMES"
  520. // SetCharset is the const for set charset stmt.
  521. SetCharset = "SetCharset"
  522. )
  523. // VariableAssignment is a variable assignment struct.
  524. type VariableAssignment struct {
  525. node
  526. Name string
  527. Value ExprNode
  528. IsGlobal bool
  529. IsSystem bool
  530. // ExtendValue is a way to store extended info.
  531. // VariableAssignment should be able to store information for SetCharset/SetPWD Stmt.
  532. // For SetCharsetStmt, Value is charset, ExtendValue is collation.
  533. // TODO: Use SetStmt to implement set password statement.
  534. ExtendValue ValueExpr
  535. }
  536. // Restore implements Node interface.
  537. func (n *VariableAssignment) Restore(ctx *format.RestoreCtx) error {
  538. if n.IsSystem {
  539. ctx.WritePlain("@@")
  540. if n.IsGlobal {
  541. ctx.WriteKeyWord("GLOBAL")
  542. } else {
  543. ctx.WriteKeyWord("SESSION")
  544. }
  545. ctx.WritePlain(".")
  546. } else if n.Name != SetNames && n.Name != SetCharset {
  547. ctx.WriteKeyWord("@")
  548. }
  549. if n.Name == SetNames {
  550. ctx.WriteKeyWord("NAMES ")
  551. } else if n.Name == SetCharset {
  552. ctx.WriteKeyWord("CHARSET ")
  553. } else {
  554. ctx.WriteName(n.Name)
  555. ctx.WritePlain("=")
  556. }
  557. if err := n.Value.Restore(ctx); err != nil {
  558. return errors.Annotate(err, "An error occurred while restore VariableAssignment.Value")
  559. }
  560. if n.ExtendValue != nil {
  561. ctx.WriteKeyWord(" COLLATE ")
  562. if err := n.ExtendValue.Restore(ctx); err != nil {
  563. return errors.Annotate(err, "An error occurred while restore VariableAssignment.ExtendValue")
  564. }
  565. }
  566. return nil
  567. }
  568. // Accept implements Node interface.
  569. func (n *VariableAssignment) Accept(v Visitor) (Node, bool) {
  570. newNode, skipChildren := v.Enter(n)
  571. if skipChildren {
  572. return v.Leave(newNode)
  573. }
  574. n = newNode.(*VariableAssignment)
  575. node, ok := n.Value.Accept(v)
  576. if !ok {
  577. return n, false
  578. }
  579. n.Value = node.(ExprNode)
  580. return v.Leave(n)
  581. }
  582. // FlushStmtType is the type for FLUSH statement.
  583. type FlushStmtType int
  584. // Flush statement types.
  585. const (
  586. FlushNone FlushStmtType = iota
  587. FlushTables
  588. FlushPrivileges
  589. FlushStatus
  590. FlushTiDBPlugin
  591. FlushHosts
  592. FlushLogs
  593. FlushClientErrorsSummary
  594. )
  595. // LogType is the log type used in FLUSH statement.
  596. type LogType int8
  597. const (
  598. LogTypeDefault LogType = iota
  599. LogTypeBinary
  600. LogTypeEngine
  601. LogTypeError
  602. LogTypeGeneral
  603. LogTypeSlow
  604. )
  605. // FlushStmt is a statement to flush tables/privileges/optimizer costs and so on.
  606. type FlushStmt struct {
  607. stmtNode
  608. Tp FlushStmtType // Privileges/Tables/...
  609. NoWriteToBinLog bool
  610. LogType LogType
  611. Tables []*TableName // For FlushTableStmt, if Tables is empty, it means flush all tables.
  612. ReadLock bool
  613. Plugins []string
  614. }
  615. // Restore implements Node interface.
  616. func (n *FlushStmt) Restore(ctx *format.RestoreCtx) error {
  617. ctx.WriteKeyWord("FLUSH ")
  618. if n.NoWriteToBinLog {
  619. ctx.WriteKeyWord("NO_WRITE_TO_BINLOG ")
  620. }
  621. switch n.Tp {
  622. case FlushTables:
  623. ctx.WriteKeyWord("TABLES")
  624. for i, v := range n.Tables {
  625. if i == 0 {
  626. ctx.WritePlain(" ")
  627. } else {
  628. ctx.WritePlain(", ")
  629. }
  630. if err := v.Restore(ctx); err != nil {
  631. return errors.Annotatef(err, "An error occurred while restore FlushStmt.Tables[%d]", i)
  632. }
  633. }
  634. if n.ReadLock {
  635. ctx.WriteKeyWord(" WITH READ LOCK")
  636. }
  637. case FlushPrivileges:
  638. ctx.WriteKeyWord("PRIVILEGES")
  639. case FlushStatus:
  640. ctx.WriteKeyWord("STATUS")
  641. case FlushTiDBPlugin:
  642. ctx.WriteKeyWord("TIDB PLUGINS")
  643. for i, v := range n.Plugins {
  644. if i == 0 {
  645. ctx.WritePlain(" ")
  646. } else {
  647. ctx.WritePlain(", ")
  648. }
  649. ctx.WritePlain(v)
  650. }
  651. case FlushHosts:
  652. ctx.WriteKeyWord("HOSTS")
  653. case FlushLogs:
  654. var logType string
  655. switch n.LogType {
  656. case LogTypeDefault:
  657. logType = "LOGS"
  658. case LogTypeBinary:
  659. logType = "BINARY LOGS"
  660. case LogTypeEngine:
  661. logType = "ENGINE LOGS"
  662. case LogTypeError:
  663. logType = "ERROR LOGS"
  664. case LogTypeGeneral:
  665. logType = "GENERAL LOGS"
  666. case LogTypeSlow:
  667. logType = "SLOW LOGS"
  668. }
  669. ctx.WriteKeyWord(logType)
  670. case FlushClientErrorsSummary:
  671. ctx.WriteKeyWord("CLIENT_ERRORS_SUMMARY")
  672. default:
  673. return errors.New("Unsupported type of FlushStmt")
  674. }
  675. return nil
  676. }
  677. // Accept implements Node Accept interface.
  678. func (n *FlushStmt) Accept(v Visitor) (Node, bool) {
  679. newNode, skipChildren := v.Enter(n)
  680. if skipChildren {
  681. return v.Leave(newNode)
  682. }
  683. n = newNode.(*FlushStmt)
  684. return v.Leave(n)
  685. }
  686. // KillStmt is a statement to kill a query or connection.
  687. type KillStmt struct {
  688. stmtNode
  689. // Query indicates whether terminate a single query on this connection or the whole connection.
  690. // If Query is true, terminates the statement the connection is currently executing, but leaves the connection itself intact.
  691. // If Query is false, terminates the connection associated with the given ConnectionID, after terminating any statement the connection is executing.
  692. Query bool
  693. ConnectionID uint64
  694. // TiDBExtension is used to indicate whether the user knows he is sending kill statement to the right tidb-server.
  695. // When the SQL grammar is "KILL TIDB [CONNECTION | QUERY] connectionID", TiDBExtension will be set.
  696. // It's a special grammar extension in TiDB. This extension exists because, when the connection is:
  697. // client -> LVS proxy -> TiDB, and type Ctrl+C in client, the following action will be executed:
  698. // new a connection; kill xxx;
  699. // kill command may send to the wrong TiDB, because the exists of LVS proxy, and kill the wrong session.
  700. // So, "KILL TIDB" grammar is introduced, and it REQUIRES DIRECT client -> TiDB TOPOLOGY.
  701. // TODO: The standard KILL grammar will be supported once we have global connectionID.
  702. TiDBExtension bool
  703. }
  704. // Restore implements Node interface.
  705. func (n *KillStmt) Restore(ctx *format.RestoreCtx) error {
  706. ctx.WriteKeyWord("KILL")
  707. if n.TiDBExtension {
  708. ctx.WriteKeyWord(" TIDB")
  709. }
  710. if n.Query {
  711. ctx.WriteKeyWord(" QUERY")
  712. }
  713. ctx.WritePlainf(" %d", n.ConnectionID)
  714. return nil
  715. }
  716. // Accept implements Node Accept interface.
  717. func (n *KillStmt) Accept(v Visitor) (Node, bool) {
  718. newNode, skipChildren := v.Enter(n)
  719. if skipChildren {
  720. return v.Leave(newNode)
  721. }
  722. n = newNode.(*KillStmt)
  723. return v.Leave(n)
  724. }
  725. // SetStmt is the statement to set variables.
  726. type SetStmt struct {
  727. stmtNode
  728. // Variables is the list of variable assignment.
  729. Variables []*VariableAssignment
  730. }
  731. // Restore implements Node interface.
  732. func (n *SetStmt) Restore(ctx *format.RestoreCtx) error {
  733. ctx.WriteKeyWord("SET ")
  734. for i, v := range n.Variables {
  735. if i != 0 {
  736. ctx.WritePlain(", ")
  737. }
  738. if err := v.Restore(ctx); err != nil {
  739. return errors.Annotatef(err, "An error occurred while restore SetStmt.Variables[%d]", i)
  740. }
  741. }
  742. return nil
  743. }
  744. // Accept implements Node Accept interface.
  745. func (n *SetStmt) Accept(v Visitor) (Node, bool) {
  746. newNode, skipChildren := v.Enter(n)
  747. if skipChildren {
  748. return v.Leave(newNode)
  749. }
  750. n = newNode.(*SetStmt)
  751. for i, val := range n.Variables {
  752. node, ok := val.Accept(v)
  753. if !ok {
  754. return n, false
  755. }
  756. n.Variables[i] = node.(*VariableAssignment)
  757. }
  758. return v.Leave(n)
  759. }
  760. // SetConfigStmt is the statement to set cluster configs.
  761. type SetConfigStmt struct {
  762. stmtNode
  763. Type string // TiDB, TiKV, PD
  764. Instance string // '127.0.0.1:3306'
  765. Name string // the variable name
  766. Value ExprNode
  767. }
  768. func (n *SetConfigStmt) Restore(ctx *format.RestoreCtx) error {
  769. ctx.WriteKeyWord("SET CONFIG ")
  770. if n.Type != "" {
  771. ctx.WriteKeyWord(n.Type)
  772. } else {
  773. ctx.WriteString(n.Instance)
  774. }
  775. ctx.WritePlain(" ")
  776. ctx.WriteKeyWord(n.Name)
  777. ctx.WritePlain(" = ")
  778. return n.Value.Restore(ctx)
  779. }
  780. func (n *SetConfigStmt) Accept(v Visitor) (Node, bool) {
  781. newNode, skipChildren := v.Enter(n)
  782. if skipChildren {
  783. return v.Leave(newNode)
  784. }
  785. n = newNode.(*SetConfigStmt)
  786. if node, ok := n.Value.Accept(v); !ok {
  787. return n, false
  788. } else {
  789. n.Value = node.(ExprNode)
  790. }
  791. return v.Leave(n)
  792. }
  793. /*
  794. // SetCharsetStmt is a statement to assign values to character and collation variables.
  795. // See https://dev.mysql.com/doc/refman/5.7/en/set-statement.html
  796. type SetCharsetStmt struct {
  797. stmtNode
  798. Charset string
  799. Collate string
  800. }
  801. // Accept implements Node Accept interface.
  802. func (n *SetCharsetStmt) Accept(v Visitor) (Node, bool) {
  803. newNode, skipChildren := v.Enter(n)
  804. if skipChildren {
  805. return v.Leave(newNode)
  806. }
  807. n = newNode.(*SetCharsetStmt)
  808. return v.Leave(n)
  809. }
  810. */
  811. // SetPwdStmt is a statement to assign a password to user account.
  812. // See https://dev.mysql.com/doc/refman/5.7/en/set-password.html
  813. type SetPwdStmt struct {
  814. stmtNode
  815. User *auth.UserIdentity
  816. Password string
  817. }
  818. // Restore implements Node interface.
  819. func (n *SetPwdStmt) Restore(ctx *format.RestoreCtx) error {
  820. ctx.WriteKeyWord("SET PASSWORD")
  821. if n.User != nil {
  822. ctx.WriteKeyWord(" FOR ")
  823. if err := n.User.Restore(ctx); err != nil {
  824. return errors.Annotate(err, "An error occurred while restore SetPwdStmt.User")
  825. }
  826. }
  827. ctx.WritePlain("=")
  828. ctx.WriteString(n.Password)
  829. return nil
  830. }
  831. // SecureText implements SensitiveStatement interface.
  832. func (n *SetPwdStmt) SecureText() string {
  833. return fmt.Sprintf("set password for user %s", n.User)
  834. }
  835. // Accept implements Node Accept interface.
  836. func (n *SetPwdStmt) Accept(v Visitor) (Node, bool) {
  837. newNode, skipChildren := v.Enter(n)
  838. if skipChildren {
  839. return v.Leave(newNode)
  840. }
  841. n = newNode.(*SetPwdStmt)
  842. return v.Leave(n)
  843. }
  844. type ChangeStmt struct {
  845. stmtNode
  846. NodeType string
  847. State string
  848. NodeID string
  849. }
  850. // Restore implements Node interface.
  851. func (n *ChangeStmt) Restore(ctx *format.RestoreCtx) error {
  852. ctx.WriteKeyWord("CHANGE ")
  853. ctx.WriteKeyWord(n.NodeType)
  854. ctx.WriteKeyWord(" TO NODE_STATE ")
  855. ctx.WritePlain("=")
  856. ctx.WriteString(n.State)
  857. ctx.WriteKeyWord(" FOR NODE_ID ")
  858. ctx.WriteString(n.NodeID)
  859. return nil
  860. }
  861. // SecureText implements SensitiveStatement interface.
  862. func (n *ChangeStmt) SecureText() string {
  863. return fmt.Sprintf("change %s to node_state='%s' for node_id '%s'", strings.ToLower(n.NodeType), n.State, n.NodeID)
  864. }
  865. // Accept implements Node Accept interface.
  866. func (n *ChangeStmt) Accept(v Visitor) (Node, bool) {
  867. newNode, skipChildren := v.Enter(n)
  868. if skipChildren {
  869. return v.Leave(newNode)
  870. }
  871. n = newNode.(*ChangeStmt)
  872. return v.Leave(n)
  873. }
  874. // SetRoleStmtType is the type for FLUSH statement.
  875. type SetRoleStmtType int
  876. // SetRole statement types.
  877. const (
  878. SetRoleDefault SetRoleStmtType = iota
  879. SetRoleNone
  880. SetRoleAll
  881. SetRoleAllExcept
  882. SetRoleRegular
  883. )
  884. type SetRoleStmt struct {
  885. stmtNode
  886. SetRoleOpt SetRoleStmtType
  887. RoleList []*auth.RoleIdentity
  888. }
  889. func (n *SetRoleStmt) Restore(ctx *format.RestoreCtx) error {
  890. ctx.WriteKeyWord("SET ROLE")
  891. switch n.SetRoleOpt {
  892. case SetRoleDefault:
  893. ctx.WriteKeyWord(" DEFAULT")
  894. case SetRoleNone:
  895. ctx.WriteKeyWord(" NONE")
  896. case SetRoleAll:
  897. ctx.WriteKeyWord(" ALL")
  898. case SetRoleAllExcept:
  899. ctx.WriteKeyWord(" ALL EXCEPT")
  900. }
  901. for i, role := range n.RoleList {
  902. ctx.WritePlain(" ")
  903. err := role.Restore(ctx)
  904. if err != nil {
  905. return errors.Annotate(err, "An error occurred while restore SetRoleStmt.RoleList")
  906. }
  907. if i != len(n.RoleList)-1 {
  908. ctx.WritePlain(",")
  909. }
  910. }
  911. return nil
  912. }
  913. // Accept implements Node Accept interface.
  914. func (n *SetRoleStmt) Accept(v Visitor) (Node, bool) {
  915. newNode, skipChildren := v.Enter(n)
  916. if skipChildren {
  917. return v.Leave(newNode)
  918. }
  919. n = newNode.(*SetRoleStmt)
  920. return v.Leave(n)
  921. }
  922. type SetDefaultRoleStmt struct {
  923. stmtNode
  924. SetRoleOpt SetRoleStmtType
  925. RoleList []*auth.RoleIdentity
  926. UserList []*auth.UserIdentity
  927. }
  928. func (n *SetDefaultRoleStmt) Restore(ctx *format.RestoreCtx) error {
  929. ctx.WriteKeyWord("SET DEFAULT ROLE")
  930. switch n.SetRoleOpt {
  931. case SetRoleNone:
  932. ctx.WriteKeyWord(" NONE")
  933. case SetRoleAll:
  934. ctx.WriteKeyWord(" ALL")
  935. default:
  936. }
  937. for i, role := range n.RoleList {
  938. ctx.WritePlain(" ")
  939. err := role.Restore(ctx)
  940. if err != nil {
  941. return errors.Annotate(err, "An error occurred while restore SetDefaultRoleStmt.RoleList")
  942. }
  943. if i != len(n.RoleList)-1 {
  944. ctx.WritePlain(",")
  945. }
  946. }
  947. ctx.WritePlain(" TO")
  948. for i, user := range n.UserList {
  949. ctx.WritePlain(" ")
  950. err := user.Restore(ctx)
  951. if err != nil {
  952. return errors.Annotate(err, "An error occurred while restore SetDefaultRoleStmt.UserList")
  953. }
  954. if i != len(n.UserList)-1 {
  955. ctx.WritePlain(",")
  956. }
  957. }
  958. return nil
  959. }
  960. // Accept implements Node Accept interface.
  961. func (n *SetDefaultRoleStmt) Accept(v Visitor) (Node, bool) {
  962. newNode, skipChildren := v.Enter(n)
  963. if skipChildren {
  964. return v.Leave(newNode)
  965. }
  966. n = newNode.(*SetDefaultRoleStmt)
  967. return v.Leave(n)
  968. }
  969. // UserSpec is used for parsing create user statement.
  970. type UserSpec struct {
  971. User *auth.UserIdentity
  972. AuthOpt *AuthOption
  973. IsRole bool
  974. }
  975. // Restore implements Node interface.
  976. func (n *UserSpec) Restore(ctx *format.RestoreCtx) error {
  977. if err := n.User.Restore(ctx); err != nil {
  978. return errors.Annotate(err, "An error occurred while restore UserSpec.User")
  979. }
  980. if n.AuthOpt != nil {
  981. ctx.WritePlain(" ")
  982. if err := n.AuthOpt.Restore(ctx); err != nil {
  983. return errors.Annotate(err, "An error occurred while restore UserSpec.AuthOpt")
  984. }
  985. }
  986. return nil
  987. }
  988. // SecurityString formats the UserSpec without password information.
  989. func (n *UserSpec) SecurityString() string {
  990. withPassword := false
  991. if opt := n.AuthOpt; opt != nil {
  992. if len(opt.AuthString) > 0 || len(opt.HashString) > 0 {
  993. withPassword = true
  994. }
  995. }
  996. if withPassword {
  997. return fmt.Sprintf("{%s password = ***}", n.User)
  998. }
  999. return n.User.String()
  1000. }
  1001. // EncodedPassword returns the encoded password (which is the real data mysql.user).
  1002. // The boolean value indicates input's password format is legal or not.
  1003. func (n *UserSpec) EncodedPassword() (string, bool) {
  1004. if n.AuthOpt == nil {
  1005. return "", true
  1006. }
  1007. opt := n.AuthOpt
  1008. if opt.ByAuthString {
  1009. return auth.EncodePassword(opt.AuthString), true
  1010. }
  1011. // Not a legal password string.
  1012. if len(opt.HashString) != 41 || !strings.HasPrefix(opt.HashString, "*") {
  1013. return "", false
  1014. }
  1015. return opt.HashString, true
  1016. }
  1017. const (
  1018. TslNone = iota
  1019. Ssl
  1020. X509
  1021. Cipher
  1022. Issuer
  1023. Subject
  1024. SAN
  1025. )
  1026. type TLSOption struct {
  1027. Type int
  1028. Value string
  1029. }
  1030. func (t *TLSOption) Restore(ctx *format.RestoreCtx) error {
  1031. switch t.Type {
  1032. case TslNone:
  1033. ctx.WriteKeyWord("NONE")
  1034. case Ssl:
  1035. ctx.WriteKeyWord("SSL")
  1036. case X509:
  1037. ctx.WriteKeyWord("X509")
  1038. case Cipher:
  1039. ctx.WriteKeyWord("CIPHER ")
  1040. ctx.WriteString(t.Value)
  1041. case Issuer:
  1042. ctx.WriteKeyWord("ISSUER ")
  1043. ctx.WriteString(t.Value)
  1044. case Subject:
  1045. ctx.WriteKeyWord("SUBJECT ")
  1046. ctx.WriteString(t.Value)
  1047. case SAN:
  1048. ctx.WriteKeyWord("SAN ")
  1049. ctx.WriteString(t.Value)
  1050. default:
  1051. return errors.Errorf("Unsupported TLSOption.Type %d", t.Type)
  1052. }
  1053. return nil
  1054. }
  1055. const (
  1056. MaxQueriesPerHour = iota + 1
  1057. MaxUpdatesPerHour
  1058. MaxConnectionsPerHour
  1059. MaxUserConnections
  1060. )
  1061. type ResourceOption struct {
  1062. Type int
  1063. Count int64
  1064. }
  1065. func (r *ResourceOption) Restore(ctx *format.RestoreCtx) error {
  1066. switch r.Type {
  1067. case MaxQueriesPerHour:
  1068. ctx.WriteKeyWord("MAX_QUERIES_PER_HOUR ")
  1069. case MaxUpdatesPerHour:
  1070. ctx.WriteKeyWord("MAX_UPDATES_PER_HOUR ")
  1071. case MaxConnectionsPerHour:
  1072. ctx.WriteKeyWord("MAX_CONNECTIONS_PER_HOUR ")
  1073. case MaxUserConnections:
  1074. ctx.WriteKeyWord("MAX_USER_CONNECTIONS ")
  1075. default:
  1076. return errors.Errorf("Unsupported ResourceOption.Type %d", r.Type)
  1077. }
  1078. ctx.WritePlainf("%d", r.Count)
  1079. return nil
  1080. }
  1081. const (
  1082. PasswordExpire = iota + 1
  1083. PasswordExpireDefault
  1084. PasswordExpireNever
  1085. PasswordExpireInterval
  1086. Lock
  1087. Unlock
  1088. )
  1089. type PasswordOrLockOption struct {
  1090. Type int
  1091. Count int64
  1092. }
  1093. func (p *PasswordOrLockOption) Restore(ctx *format.RestoreCtx) error {
  1094. switch p.Type {
  1095. case PasswordExpire:
  1096. ctx.WriteKeyWord("PASSWORD EXPIRE")
  1097. case PasswordExpireDefault:
  1098. ctx.WriteKeyWord("PASSWORD EXPIRE DEFAULT")
  1099. case PasswordExpireNever:
  1100. ctx.WriteKeyWord("PASSWORD EXPIRE NEVER")
  1101. case PasswordExpireInterval:
  1102. ctx.WriteKeyWord("PASSWORD EXPIRE INTERVAL")
  1103. ctx.WritePlainf(" %d", p.Count)
  1104. ctx.WriteKeyWord(" DAY")
  1105. case Lock:
  1106. ctx.WriteKeyWord("ACCOUNT LOCK")
  1107. case Unlock:
  1108. ctx.WriteKeyWord("ACCOUNT UNLOCK")
  1109. default:
  1110. return errors.Errorf("Unsupported PasswordOrLockOption.Type %d", p.Type)
  1111. }
  1112. return nil
  1113. }
  1114. // CreateUserStmt creates user account.
  1115. // See https://dev.mysql.com/doc/refman/5.7/en/create-user.html
  1116. type CreateUserStmt struct {
  1117. stmtNode
  1118. IsCreateRole bool
  1119. IfNotExists bool
  1120. Specs []*UserSpec
  1121. TLSOptions []*TLSOption
  1122. ResourceOptions []*ResourceOption
  1123. PasswordOrLockOptions []*PasswordOrLockOption
  1124. }
  1125. // Restore implements Node interface.
  1126. func (n *CreateUserStmt) Restore(ctx *format.RestoreCtx) error {
  1127. if n.IsCreateRole {
  1128. ctx.WriteKeyWord("CREATE ROLE ")
  1129. } else {
  1130. ctx.WriteKeyWord("CREATE USER ")
  1131. }
  1132. if n.IfNotExists {
  1133. ctx.WriteKeyWord("IF NOT EXISTS ")
  1134. }
  1135. for i, v := range n.Specs {
  1136. if i != 0 {
  1137. ctx.WritePlain(", ")
  1138. }
  1139. if err := v.Restore(ctx); err != nil {
  1140. return errors.Annotatef(err, "An error occurred while restore CreateUserStmt.Specs[%d]", i)
  1141. }
  1142. }
  1143. if len(n.TLSOptions) != 0 {
  1144. ctx.WriteKeyWord(" REQUIRE ")
  1145. }
  1146. for i, option := range n.TLSOptions {
  1147. if i != 0 {
  1148. ctx.WriteKeyWord(" AND ")
  1149. }
  1150. if err := option.Restore(ctx); err != nil {
  1151. return errors.Annotatef(err, "An error occurred while restore CreateUserStmt.TLSOptions[%d]", i)
  1152. }
  1153. }
  1154. if len(n.ResourceOptions) != 0 {
  1155. ctx.WriteKeyWord(" WITH")
  1156. }
  1157. for i, v := range n.ResourceOptions {
  1158. ctx.WritePlain(" ")
  1159. if err := v.Restore(ctx); err != nil {
  1160. return errors.Annotatef(err, "An error occurred while restore CreateUserStmt.ResourceOptions[%d]", i)
  1161. }
  1162. }
  1163. for i, v := range n.PasswordOrLockOptions {
  1164. ctx.WritePlain(" ")
  1165. if err := v.Restore(ctx); err != nil {
  1166. return errors.Annotatef(err, "An error occurred while restore CreateUserStmt.PasswordOrLockOptions[%d]", i)
  1167. }
  1168. }
  1169. return nil
  1170. }
  1171. // Accept implements Node Accept interface.
  1172. func (n *CreateUserStmt) Accept(v Visitor) (Node, bool) {
  1173. newNode, skipChildren := v.Enter(n)
  1174. if skipChildren {
  1175. return v.Leave(newNode)
  1176. }
  1177. n = newNode.(*CreateUserStmt)
  1178. return v.Leave(n)
  1179. }
  1180. // SecureText implements SensitiveStatement interface.
  1181. func (n *CreateUserStmt) SecureText() string {
  1182. var buf bytes.Buffer
  1183. buf.WriteString("create user")
  1184. for _, user := range n.Specs {
  1185. buf.WriteString(" ")
  1186. buf.WriteString(user.SecurityString())
  1187. }
  1188. return buf.String()
  1189. }
  1190. // AlterUserStmt modifies user account.
  1191. // See https://dev.mysql.com/doc/refman/5.7/en/alter-user.html
  1192. type AlterUserStmt struct {
  1193. stmtNode
  1194. IfExists bool
  1195. CurrentAuth *AuthOption
  1196. Specs []*UserSpec
  1197. TLSOptions []*TLSOption
  1198. ResourceOptions []*ResourceOption
  1199. PasswordOrLockOptions []*PasswordOrLockOption
  1200. }
  1201. // Restore implements Node interface.
  1202. func (n *AlterUserStmt) Restore(ctx *format.RestoreCtx) error {
  1203. ctx.WriteKeyWord("ALTER USER ")
  1204. if n.IfExists {
  1205. ctx.WriteKeyWord("IF EXISTS ")
  1206. }
  1207. if n.CurrentAuth != nil {
  1208. ctx.WriteKeyWord("USER")
  1209. ctx.WritePlain("() ")
  1210. if err := n.CurrentAuth.Restore(ctx); err != nil {
  1211. return errors.Annotate(err, "An error occurred while restore AlterUserStmt.CurrentAuth")
  1212. }
  1213. }
  1214. for i, v := range n.Specs {
  1215. if i != 0 {
  1216. ctx.WritePlain(", ")
  1217. }
  1218. if err := v.Restore(ctx); err != nil {
  1219. return errors.Annotatef(err, "An error occurred while restore AlterUserStmt.Specs[%d]", i)
  1220. }
  1221. }
  1222. if len(n.TLSOptions) != 0 {
  1223. ctx.WriteKeyWord(" REQUIRE ")
  1224. }
  1225. for i, option := range n.TLSOptions {
  1226. if i != 0 {
  1227. ctx.WriteKeyWord(" AND ")
  1228. }
  1229. if err := option.Restore(ctx); err != nil {
  1230. return errors.Annotatef(err, "An error occurred while restore AlterUserStmt.TLSOptions[%d]", i)
  1231. }
  1232. }
  1233. if len(n.ResourceOptions) != 0 {
  1234. ctx.WriteKeyWord(" WITH")
  1235. }
  1236. for i, v := range n.ResourceOptions {
  1237. ctx.WritePlain(" ")
  1238. if err := v.Restore(ctx); err != nil {
  1239. return errors.Annotatef(err, "An error occurred while restore AlterUserStmt.ResourceOptions[%d]", i)
  1240. }
  1241. }
  1242. for i, v := range n.PasswordOrLockOptions {
  1243. ctx.WritePlain(" ")
  1244. if err := v.Restore(ctx); err != nil {
  1245. return errors.Annotatef(err, "An error occurred while restore AlterUserStmt.PasswordOrLockOptions[%d]", i)
  1246. }
  1247. }
  1248. return nil
  1249. }
  1250. // SecureText implements SensitiveStatement interface.
  1251. func (n *AlterUserStmt) SecureText() string {
  1252. var buf bytes.Buffer
  1253. buf.WriteString("alter user")
  1254. for _, user := range n.Specs {
  1255. buf.WriteString(" ")
  1256. buf.WriteString(user.SecurityString())
  1257. }
  1258. return buf.String()
  1259. }
  1260. // Accept implements Node Accept interface.
  1261. func (n *AlterUserStmt) Accept(v Visitor) (Node, bool) {
  1262. newNode, skipChildren := v.Enter(n)
  1263. if skipChildren {
  1264. return v.Leave(newNode)
  1265. }
  1266. n = newNode.(*AlterUserStmt)
  1267. return v.Leave(n)
  1268. }
  1269. // AlterInstanceStmt modifies instance.
  1270. // See https://dev.mysql.com/doc/refman/8.0/en/alter-instance.html
  1271. type AlterInstanceStmt struct {
  1272. stmtNode
  1273. ReloadTLS bool
  1274. NoRollbackOnError bool
  1275. }
  1276. // Restore implements Node interface.
  1277. func (n *AlterInstanceStmt) Restore(ctx *format.RestoreCtx) error {
  1278. ctx.WriteKeyWord("ALTER INSTANCE")
  1279. if n.ReloadTLS {
  1280. ctx.WriteKeyWord(" RELOAD TLS")
  1281. }
  1282. if n.NoRollbackOnError {
  1283. ctx.WriteKeyWord(" NO ROLLBACK ON ERROR")
  1284. }
  1285. return nil
  1286. }
  1287. // Accept implements Node Accept interface.
  1288. func (n *AlterInstanceStmt) Accept(v Visitor) (Node, bool) {
  1289. newNode, skipChildren := v.Enter(n)
  1290. if skipChildren {
  1291. return v.Leave(newNode)
  1292. }
  1293. n = newNode.(*AlterInstanceStmt)
  1294. return v.Leave(n)
  1295. }
  1296. // DropUserStmt creates user account.
  1297. // See http://dev.mysql.com/doc/refman/5.7/en/drop-user.html
  1298. type DropUserStmt struct {
  1299. stmtNode
  1300. IfExists bool
  1301. IsDropRole bool
  1302. UserList []*auth.UserIdentity
  1303. }
  1304. // Restore implements Node interface.
  1305. func (n *DropUserStmt) Restore(ctx *format.RestoreCtx) error {
  1306. if n.IsDropRole {
  1307. ctx.WriteKeyWord("DROP ROLE ")
  1308. } else {
  1309. ctx.WriteKeyWord("DROP USER ")
  1310. }
  1311. if n.IfExists {
  1312. ctx.WriteKeyWord("IF EXISTS ")
  1313. }
  1314. for i, v := range n.UserList {
  1315. if i != 0 {
  1316. ctx.WritePlain(", ")
  1317. }
  1318. if err := v.Restore(ctx); err != nil {
  1319. return errors.Annotatef(err, "An error occurred while restore DropUserStmt.UserList[%d]", i)
  1320. }
  1321. }
  1322. return nil
  1323. }
  1324. // Accept implements Node Accept interface.
  1325. func (n *DropUserStmt) Accept(v Visitor) (Node, bool) {
  1326. newNode, skipChildren := v.Enter(n)
  1327. if skipChildren {
  1328. return v.Leave(newNode)
  1329. }
  1330. n = newNode.(*DropUserStmt)
  1331. return v.Leave(n)
  1332. }
  1333. // CreateBindingStmt creates sql binding hint.
  1334. type CreateBindingStmt struct {
  1335. stmtNode
  1336. GlobalScope bool
  1337. OriginNode StmtNode
  1338. HintedNode StmtNode
  1339. }
  1340. func (n *CreateBindingStmt) Restore(ctx *format.RestoreCtx) error {
  1341. ctx.WriteKeyWord("CREATE ")
  1342. if n.GlobalScope {
  1343. ctx.WriteKeyWord("GLOBAL ")
  1344. } else {
  1345. ctx.WriteKeyWord("SESSION ")
  1346. }
  1347. ctx.WriteKeyWord("BINDING FOR ")
  1348. if err := n.OriginNode.Restore(ctx); err != nil {
  1349. return errors.Trace(err)
  1350. }
  1351. ctx.WriteKeyWord(" USING ")
  1352. if err := n.HintedNode.Restore(ctx); err != nil {
  1353. return errors.Trace(err)
  1354. }
  1355. return nil
  1356. }
  1357. func (n *CreateBindingStmt) Accept(v Visitor) (Node, bool) {
  1358. newNode, skipChildren := v.Enter(n)
  1359. if skipChildren {
  1360. return v.Leave(newNode)
  1361. }
  1362. n = newNode.(*CreateBindingStmt)
  1363. origNode, ok := n.OriginNode.Accept(v)
  1364. if !ok {
  1365. return n, false
  1366. }
  1367. n.OriginNode = origNode.(StmtNode)
  1368. hintedNode, ok := n.HintedNode.Accept(v)
  1369. if !ok {
  1370. return n, false
  1371. }
  1372. n.HintedNode = hintedNode.(StmtNode)
  1373. return v.Leave(n)
  1374. }
  1375. // DropBindingStmt deletes sql binding hint.
  1376. type DropBindingStmt struct {
  1377. stmtNode
  1378. GlobalScope bool
  1379. OriginNode StmtNode
  1380. HintedNode StmtNode
  1381. }
  1382. func (n *DropBindingStmt) Restore(ctx *format.RestoreCtx) error {
  1383. ctx.WriteKeyWord("DROP ")
  1384. if n.GlobalScope {
  1385. ctx.WriteKeyWord("GLOBAL ")
  1386. } else {
  1387. ctx.WriteKeyWord("SESSION ")
  1388. }
  1389. ctx.WriteKeyWord("BINDING FOR ")
  1390. if err := n.OriginNode.Restore(ctx); err != nil {
  1391. return errors.Trace(err)
  1392. }
  1393. if n.HintedNode != nil {
  1394. ctx.WriteKeyWord(" USING ")
  1395. if err := n.HintedNode.Restore(ctx); err != nil {
  1396. return errors.Trace(err)
  1397. }
  1398. }
  1399. return nil
  1400. }
  1401. func (n *DropBindingStmt) Accept(v Visitor) (Node, bool) {
  1402. newNode, skipChildren := v.Enter(n)
  1403. if skipChildren {
  1404. return v.Leave(newNode)
  1405. }
  1406. n = newNode.(*DropBindingStmt)
  1407. origNode, ok := n.OriginNode.Accept(v)
  1408. if !ok {
  1409. return n, false
  1410. }
  1411. n.OriginNode = origNode.(StmtNode)
  1412. if n.HintedNode != nil {
  1413. hintedNode, ok := n.HintedNode.Accept(v)
  1414. if !ok {
  1415. return n, false
  1416. }
  1417. n.HintedNode = hintedNode.(StmtNode)
  1418. }
  1419. return v.Leave(n)
  1420. }
  1421. // Extended statistics types.
  1422. const (
  1423. StatsTypeCardinality uint8 = iota
  1424. StatsTypeDependency
  1425. StatsTypeCorrelation
  1426. )
  1427. // StatisticsSpec is the specification for ADD /DROP STATISTICS.
  1428. type StatisticsSpec struct {
  1429. StatsName string
  1430. StatsType uint8
  1431. Columns []*ColumnName
  1432. }
  1433. // CreateStatisticsStmt is a statement to create extended statistics.
  1434. // Examples:
  1435. // CREATE STATISTICS stats1 (cardinality) ON t(a, b, c);
  1436. // CREATE STATISTICS stats2 (dependency) ON t(a, b);
  1437. // CREATE STATISTICS stats3 (correlation) ON t(a, b);
  1438. type CreateStatisticsStmt struct {
  1439. stmtNode
  1440. IfNotExists bool
  1441. StatsName string
  1442. StatsType uint8
  1443. Table *TableName
  1444. Columns []*ColumnName
  1445. }
  1446. // Restore implements Node interface.
  1447. func (n *CreateStatisticsStmt) Restore(ctx *format.RestoreCtx) error {
  1448. ctx.WriteKeyWord("CREATE STATISTICS ")
  1449. if n.IfNotExists {
  1450. ctx.WriteKeyWord("IF NOT EXISTS ")
  1451. }
  1452. ctx.WriteName(n.StatsName)
  1453. switch n.StatsType {
  1454. case StatsTypeCardinality:
  1455. ctx.WriteKeyWord(" (cardinality) ")
  1456. case StatsTypeDependency:
  1457. ctx.WriteKeyWord(" (dependency) ")
  1458. case StatsTypeCorrelation:
  1459. ctx.WriteKeyWord(" (correlation) ")
  1460. }
  1461. ctx.WriteKeyWord("ON ")
  1462. if err := n.Table.Restore(ctx); err != nil {
  1463. return errors.Annotate(err, "An error occurred while restore CreateStatisticsStmt.Table")
  1464. }
  1465. ctx.WritePlain("(")
  1466. for i, col := range n.Columns {
  1467. if i != 0 {
  1468. ctx.WritePlain(", ")
  1469. }
  1470. if err := col.Restore(ctx); err != nil {
  1471. return errors.Annotatef(err, "An error occurred while restore CreateStatisticsStmt.Columns: [%v]", i)
  1472. }
  1473. }
  1474. ctx.WritePlain(")")
  1475. return nil
  1476. }
  1477. // Accept implements Node Accept interface.
  1478. func (n *CreateStatisticsStmt) Accept(v Visitor) (Node, bool) {
  1479. newNode, skipChildren := v.Enter(n)
  1480. if skipChildren {
  1481. return v.Leave(newNode)
  1482. }
  1483. n = newNode.(*CreateStatisticsStmt)
  1484. node, ok := n.Table.Accept(v)
  1485. if !ok {
  1486. return n, false
  1487. }
  1488. n.Table = node.(*TableName)
  1489. for i, col := range n.Columns {
  1490. node, ok = col.Accept(v)
  1491. if !ok {
  1492. return n, false
  1493. }
  1494. n.Columns[i] = node.(*ColumnName)
  1495. }
  1496. return v.Leave(n)
  1497. }
  1498. // DropStatisticsStmt is a statement to drop extended statistics.
  1499. // Examples:
  1500. // DROP STATISTICS stats1;
  1501. type DropStatisticsStmt struct {
  1502. stmtNode
  1503. StatsName string
  1504. }
  1505. // Restore implements Node interface.
  1506. func (n *DropStatisticsStmt) Restore(ctx *format.RestoreCtx) error {
  1507. ctx.WriteKeyWord("DROP STATISTICS ")
  1508. ctx.WriteName(n.StatsName)
  1509. return nil
  1510. }
  1511. // Accept implements Node Accept interface.
  1512. func (n *DropStatisticsStmt) Accept(v Visitor) (Node, bool) {
  1513. newNode, skipChildren := v.Enter(n)
  1514. if skipChildren {
  1515. return v.Leave(newNode)
  1516. }
  1517. n = newNode.(*DropStatisticsStmt)
  1518. return v.Leave(n)
  1519. }
  1520. // DoStmt is the struct for DO statement.
  1521. type DoStmt struct {
  1522. stmtNode
  1523. Exprs []ExprNode
  1524. }
  1525. // Restore implements Node interface.
  1526. func (n *DoStmt) Restore(ctx *format.RestoreCtx) error {
  1527. ctx.WriteKeyWord("DO ")
  1528. for i, v := range n.Exprs {
  1529. if i != 0 {
  1530. ctx.WritePlain(", ")
  1531. }
  1532. if err := v.Restore(ctx); err != nil {
  1533. return errors.Annotatef(err, "An error occurred while restore DoStmt.Exprs[%d]", i)
  1534. }
  1535. }
  1536. return nil
  1537. }
  1538. // Accept implements Node Accept interface.
  1539. func (n *DoStmt) Accept(v Visitor) (Node, bool) {
  1540. newNode, skipChildren := v.Enter(n)
  1541. if skipChildren {
  1542. return v.Leave(newNode)
  1543. }
  1544. n = newNode.(*DoStmt)
  1545. for i, val := range n.Exprs {
  1546. node, ok := val.Accept(v)
  1547. if !ok {
  1548. return n, false
  1549. }
  1550. n.Exprs[i] = node.(ExprNode)
  1551. }
  1552. return v.Leave(n)
  1553. }
  1554. // AdminStmtType is the type for admin statement.
  1555. type AdminStmtType int
  1556. // Admin statement types.
  1557. const (
  1558. AdminShowDDL = iota + 1
  1559. AdminCheckTable
  1560. AdminShowDDLJobs
  1561. AdminCancelDDLJobs
  1562. AdminCheckIndex
  1563. AdminRecoverIndex
  1564. AdminCleanupIndex
  1565. AdminCheckIndexRange
  1566. AdminShowDDLJobQueries
  1567. AdminChecksumTable
  1568. AdminShowSlow
  1569. AdminShowNextRowID
  1570. AdminReloadExprPushdownBlacklist
  1571. AdminReloadOptRuleBlacklist
  1572. AdminPluginDisable
  1573. AdminPluginEnable
  1574. AdminFlushBindings
  1575. AdminCaptureBindings
  1576. AdminEvolveBindings
  1577. AdminReloadBindings
  1578. AdminShowTelemetry
  1579. AdminResetTelemetryID
  1580. AdminReloadStatistics
  1581. )
  1582. // HandleRange represents a range where handle value >= Begin and < End.
  1583. type HandleRange struct {
  1584. Begin int64
  1585. End int64
  1586. }
  1587. // ShowSlowType defines the type for SlowSlow statement.
  1588. type ShowSlowType int
  1589. const (
  1590. // ShowSlowTop is a ShowSlowType constant.
  1591. ShowSlowTop ShowSlowType = iota
  1592. // ShowSlowRecent is a ShowSlowType constant.
  1593. ShowSlowRecent
  1594. )
  1595. // ShowSlowKind defines the kind for SlowSlow statement when the type is ShowSlowTop.
  1596. type ShowSlowKind int
  1597. const (
  1598. // ShowSlowKindDefault is a ShowSlowKind constant.
  1599. ShowSlowKindDefault ShowSlowKind = iota
  1600. // ShowSlowKindInternal is a ShowSlowKind constant.
  1601. ShowSlowKindInternal
  1602. // ShowSlowKindAll is a ShowSlowKind constant.
  1603. ShowSlowKindAll
  1604. )
  1605. // ShowSlow is used for the following command:
  1606. // admin show slow top [ internal | all] N
  1607. // admin show slow recent N
  1608. type ShowSlow struct {
  1609. Tp ShowSlowType
  1610. Count uint64
  1611. Kind ShowSlowKind
  1612. }
  1613. // Restore implements Node interface.
  1614. func (n *ShowSlow) Restore(ctx *format.RestoreCtx) error {
  1615. switch n.Tp {
  1616. case ShowSlowRecent:
  1617. ctx.WriteKeyWord("RECENT ")
  1618. case ShowSlowTop:
  1619. ctx.WriteKeyWord("TOP ")
  1620. switch n.Kind {
  1621. case ShowSlowKindDefault:
  1622. // do nothing
  1623. case ShowSlowKindInternal:
  1624. ctx.WriteKeyWord("INTERNAL ")
  1625. case ShowSlowKindAll:
  1626. ctx.WriteKeyWord("ALL ")
  1627. default:
  1628. return errors.New("Unsupported kind of ShowSlowTop")
  1629. }
  1630. default:
  1631. return errors.New("Unsupported type of ShowSlow")
  1632. }
  1633. ctx.WritePlainf("%d", n.Count)
  1634. return nil
  1635. }
  1636. // AdminStmt is the struct for Admin statement.
  1637. type AdminStmt struct {
  1638. stmtNode
  1639. Tp AdminStmtType
  1640. Index string
  1641. Tables []*TableName
  1642. JobIDs []int64
  1643. JobNumber int64
  1644. HandleRanges []HandleRange
  1645. ShowSlow *ShowSlow
  1646. Plugins []string
  1647. Where ExprNode
  1648. }
  1649. // Restore implements Node interface.
  1650. func (n *AdminStmt) Restore(ctx *format.RestoreCtx) error {
  1651. restoreTables := func() error {
  1652. for i, v := range n.Tables {
  1653. if i != 0 {
  1654. ctx.WritePlain(", ")
  1655. }
  1656. if err := v.Restore(ctx); err != nil {
  1657. return errors.Annotatef(err, "An error occurred while restore AdminStmt.Tables[%d]", i)
  1658. }
  1659. }
  1660. return nil
  1661. }
  1662. restoreJobIDs := func() {
  1663. for i, v := range n.JobIDs {
  1664. if i != 0 {
  1665. ctx.WritePlain(", ")
  1666. }
  1667. ctx.WritePlainf("%d", v)
  1668. }
  1669. }
  1670. ctx.WriteKeyWord("ADMIN ")
  1671. switch n.Tp {
  1672. case AdminShowDDL:
  1673. ctx.WriteKeyWord("SHOW DDL")
  1674. case AdminShowDDLJobs:
  1675. ctx.WriteKeyWord("SHOW DDL JOBS")
  1676. if n.JobNumber != 0 {
  1677. ctx.WritePlainf(" %d", n.JobNumber)
  1678. }
  1679. if n.Where != nil {
  1680. ctx.WriteKeyWord(" WHERE ")
  1681. if err := n.Where.Restore(ctx); err != nil {
  1682. return errors.Annotate(err, "An error occurred while restore ShowStmt.Where")
  1683. }
  1684. }
  1685. case AdminShowNextRowID:
  1686. ctx.WriteKeyWord("SHOW ")
  1687. if err := restoreTables(); err != nil {
  1688. return err
  1689. }
  1690. ctx.WriteKeyWord(" NEXT_ROW_ID")
  1691. case AdminCheckTable:
  1692. ctx.WriteKeyWord("CHECK TABLE ")
  1693. if err := restoreTables(); err != nil {
  1694. return err
  1695. }
  1696. case AdminCheckIndex:
  1697. ctx.WriteKeyWord("CHECK INDEX ")
  1698. if err := restoreTables(); err != nil {
  1699. return err
  1700. }
  1701. ctx.WritePlainf(" %s", n.Index)
  1702. case AdminRecoverIndex:
  1703. ctx.WriteKeyWord("RECOVER INDEX ")
  1704. if err := restoreTables(); err != nil {
  1705. return err
  1706. }
  1707. ctx.WritePlainf(" %s", n.Index)
  1708. case AdminCleanupIndex:
  1709. ctx.WriteKeyWord("CLEANUP INDEX ")
  1710. if err := restoreTables(); err != nil {
  1711. return err
  1712. }
  1713. ctx.WritePlainf(" %s", n.Index)
  1714. case AdminCheckIndexRange:
  1715. ctx.WriteKeyWord("CHECK INDEX ")
  1716. if err := restoreTables(); err != nil {
  1717. return err
  1718. }
  1719. ctx.WritePlainf(" %s", n.Index)
  1720. if n.HandleRanges != nil {
  1721. ctx.WritePlain(" ")
  1722. for i, v := range n.HandleRanges {
  1723. if i != 0 {
  1724. ctx.WritePlain(", ")
  1725. }
  1726. ctx.WritePlainf("(%d,%d)", v.Begin, v.End)
  1727. }
  1728. }
  1729. case AdminChecksumTable:
  1730. ctx.WriteKeyWord("CHECKSUM TABLE ")
  1731. if err := restoreTables(); err != nil {
  1732. return err
  1733. }
  1734. case AdminCancelDDLJobs:
  1735. ctx.WriteKeyWord("CANCEL DDL JOBS ")
  1736. restoreJobIDs()
  1737. case AdminShowDDLJobQueries:
  1738. ctx.WriteKeyWord("SHOW DDL JOB QUERIES ")
  1739. restoreJobIDs()
  1740. case AdminShowSlow:
  1741. ctx.WriteKeyWord("SHOW SLOW ")
  1742. if err := n.ShowSlow.Restore(ctx); err != nil {
  1743. return errors.Annotate(err, "An error occurred while restore AdminStmt.ShowSlow")
  1744. }
  1745. case AdminReloadExprPushdownBlacklist:
  1746. ctx.WriteKeyWord("RELOAD EXPR_PUSHDOWN_BLACKLIST")
  1747. case AdminReloadOptRuleBlacklist:
  1748. ctx.WriteKeyWord("RELOAD OPT_RULE_BLACKLIST")
  1749. case AdminPluginEnable:
  1750. ctx.WriteKeyWord("PLUGINS ENABLE")
  1751. for i, v := range n.Plugins {
  1752. if i == 0 {
  1753. ctx.WritePlain(" ")
  1754. } else {
  1755. ctx.WritePlain(", ")
  1756. }
  1757. ctx.WritePlain(v)
  1758. }
  1759. case AdminPluginDisable:
  1760. ctx.WriteKeyWord("PLUGINS DISABLE")
  1761. for i, v := range n.Plugins {
  1762. if i == 0 {
  1763. ctx.WritePlain(" ")
  1764. } else {
  1765. ctx.WritePlain(", ")
  1766. }
  1767. ctx.WritePlain(v)
  1768. }
  1769. case AdminFlushBindings:
  1770. ctx.WriteKeyWord("FLUSH BINDINGS")
  1771. case AdminCaptureBindings:
  1772. ctx.WriteKeyWord("CAPTURE BINDINGS")
  1773. case AdminEvolveBindings:
  1774. ctx.WriteKeyWord("EVOLVE BINDINGS")
  1775. case AdminReloadBindings:
  1776. ctx.WriteKeyWord("RELOAD BINDINGS")
  1777. case AdminShowTelemetry:
  1778. ctx.WriteKeyWord("SHOW TELEMETRY")
  1779. case AdminResetTelemetryID:
  1780. ctx.WriteKeyWord("RESET TELEMETRY_ID")
  1781. case AdminReloadStatistics:
  1782. ctx.WriteKeyWord("RELOAD STATS_EXTENDED")
  1783. default:
  1784. return errors.New("Unsupported AdminStmt type")
  1785. }
  1786. return nil
  1787. }
  1788. // Accept implements Node Accept interface.
  1789. func (n *AdminStmt) Accept(v Visitor) (Node, bool) {
  1790. newNode, skipChildren := v.Enter(n)
  1791. if skipChildren {
  1792. return v.Leave(newNode)
  1793. }
  1794. n = newNode.(*AdminStmt)
  1795. for i, val := range n.Tables {
  1796. node, ok := val.Accept(v)
  1797. if !ok {
  1798. return n, false
  1799. }
  1800. n.Tables[i] = node.(*TableName)
  1801. }
  1802. if n.Where != nil {
  1803. node, ok := n.Where.Accept(v)
  1804. if !ok {
  1805. return n, false
  1806. }
  1807. n.Where = node.(ExprNode)
  1808. }
  1809. return v.Leave(n)
  1810. }
  1811. // RoleOrPriv is a temporary structure to be further processed into auth.RoleIdentity or PrivElem
  1812. type RoleOrPriv struct {
  1813. Symbols string // hold undecided symbols
  1814. Node interface{} // hold auth.RoleIdentity or PrivElem that can be sure when parsing
  1815. }
  1816. func (n *RoleOrPriv) ToRole() (*auth.RoleIdentity, error) {
  1817. if n.Node != nil {
  1818. if r, ok := n.Node.(*auth.RoleIdentity); ok {
  1819. return r, nil
  1820. }
  1821. return nil, errors.Errorf("can't convert to RoleIdentity, type %T", n.Node)
  1822. }
  1823. return &auth.RoleIdentity{Username: n.Symbols, Hostname: "%"}, nil
  1824. }
  1825. func (n *RoleOrPriv) ToPriv() (*PrivElem, error) {
  1826. if n.Node != nil {
  1827. if p, ok := n.Node.(*PrivElem); ok {
  1828. return p, nil
  1829. }
  1830. return nil, errors.Errorf("can't convert to PrivElem, type %T", n.Node)
  1831. }
  1832. if len(n.Symbols) == 0 {
  1833. return nil, errors.New("symbols should not be length 0")
  1834. }
  1835. return &PrivElem{Priv: mysql.ExtendedPriv, Name: n.Symbols}, nil
  1836. }
  1837. // PrivElem is the privilege type and optional column list.
  1838. type PrivElem struct {
  1839. node
  1840. Priv mysql.PrivilegeType
  1841. Cols []*ColumnName
  1842. Name string
  1843. }
  1844. // Restore implements Node interface.
  1845. func (n *PrivElem) Restore(ctx *format.RestoreCtx) error {
  1846. if n.Priv == mysql.AllPriv {
  1847. ctx.WriteKeyWord("ALL")
  1848. } else if n.Priv == mysql.ExtendedPriv {
  1849. ctx.WriteKeyWord(n.Name)
  1850. } else {
  1851. str, ok := mysql.Priv2Str[n.Priv]
  1852. if ok {
  1853. ctx.WriteKeyWord(str)
  1854. } else {
  1855. return errors.New("Undefined privilege type")
  1856. }
  1857. }
  1858. if n.Cols != nil {
  1859. ctx.WritePlain(" (")
  1860. for i, v := range n.Cols {
  1861. if i != 0 {
  1862. ctx.WritePlain(",")
  1863. }
  1864. if err := v.Restore(ctx); err != nil {
  1865. return errors.Annotatef(err, "An error occurred while restore PrivElem.Cols[%d]", i)
  1866. }
  1867. }
  1868. ctx.WritePlain(")")
  1869. }
  1870. return nil
  1871. }
  1872. // Accept implements Node Accept interface.
  1873. func (n *PrivElem) Accept(v Visitor) (Node, bool) {
  1874. newNode, skipChildren := v.Enter(n)
  1875. if skipChildren {
  1876. return v.Leave(newNode)
  1877. }
  1878. n = newNode.(*PrivElem)
  1879. for i, val := range n.Cols {
  1880. node, ok := val.Accept(v)
  1881. if !ok {
  1882. return n, false
  1883. }
  1884. n.Cols[i] = node.(*ColumnName)
  1885. }
  1886. return v.Leave(n)
  1887. }
  1888. // ObjectTypeType is the type for object type.
  1889. type ObjectTypeType int
  1890. const (
  1891. // ObjectTypeNone is for empty object type.
  1892. ObjectTypeNone ObjectTypeType = iota + 1
  1893. // ObjectTypeTable means the following object is a table.
  1894. ObjectTypeTable
  1895. // ObjectTypeFunction means the following object is a stored function.
  1896. ObjectTypeFunction
  1897. // ObjectTypeProcedure means the following object is a stored procedure.
  1898. ObjectTypeProcedure
  1899. )
  1900. // Restore implements Node interface.
  1901. func (n ObjectTypeType) Restore(ctx *format.RestoreCtx) error {
  1902. switch n {
  1903. case ObjectTypeNone:
  1904. // do nothing
  1905. case ObjectTypeTable:
  1906. ctx.WriteKeyWord("TABLE")
  1907. case ObjectTypeFunction:
  1908. ctx.WriteKeyWord("FUNCTION")
  1909. case ObjectTypeProcedure:
  1910. ctx.WriteKeyWord("PROCEDURE")
  1911. default:
  1912. return errors.New("Unsupported object type")
  1913. }
  1914. return nil
  1915. }
  1916. // GrantLevelType is the type for grant level.
  1917. type GrantLevelType int
  1918. const (
  1919. // GrantLevelNone is the dummy const for default value.
  1920. GrantLevelNone GrantLevelType = iota + 1
  1921. // GrantLevelGlobal means the privileges are administrative or apply to all databases on a given server.
  1922. GrantLevelGlobal
  1923. // GrantLevelDB means the privileges apply to all objects in a given database.
  1924. GrantLevelDB
  1925. // GrantLevelTable means the privileges apply to all columns in a given table.
  1926. GrantLevelTable
  1927. )
  1928. // GrantLevel is used for store the privilege scope.
  1929. type GrantLevel struct {
  1930. Level GrantLevelType
  1931. DBName string
  1932. TableName string
  1933. }
  1934. // Restore implements Node interface.
  1935. func (n *GrantLevel) Restore(ctx *format.RestoreCtx) error {
  1936. switch n.Level {
  1937. case GrantLevelDB:
  1938. if n.DBName == "" {
  1939. ctx.WritePlain("*")
  1940. } else {
  1941. ctx.WriteName(n.DBName)
  1942. ctx.WritePlain(".*")
  1943. }
  1944. case GrantLevelGlobal:
  1945. ctx.WritePlain("*.*")
  1946. case GrantLevelTable:
  1947. if n.DBName != "" {
  1948. ctx.WriteName(n.DBName)
  1949. ctx.WritePlain(".")
  1950. }
  1951. ctx.WriteName(n.TableName)
  1952. }
  1953. return nil
  1954. }
  1955. // RevokeStmt is the struct for REVOKE statement.
  1956. type RevokeStmt struct {
  1957. stmtNode
  1958. Privs []*PrivElem
  1959. ObjectType ObjectTypeType
  1960. Level *GrantLevel
  1961. Users []*UserSpec
  1962. }
  1963. // Restore implements Node interface.
  1964. func (n *RevokeStmt) Restore(ctx *format.RestoreCtx) error {
  1965. ctx.WriteKeyWord("REVOKE ")
  1966. for i, v := range n.Privs {
  1967. if i != 0 {
  1968. ctx.WritePlain(", ")
  1969. }
  1970. if err := v.Restore(ctx); err != nil {
  1971. return errors.Annotatef(err, "An error occurred while restore RevokeStmt.Privs[%d]", i)
  1972. }
  1973. }
  1974. ctx.WriteKeyWord(" ON ")
  1975. if n.ObjectType != ObjectTypeNone {
  1976. if err := n.ObjectType.Restore(ctx); err != nil {
  1977. return errors.Annotate(err, "An error occurred while restore RevokeStmt.ObjectType")
  1978. }
  1979. ctx.WritePlain(" ")
  1980. }
  1981. if err := n.Level.Restore(ctx); err != nil {
  1982. return errors.Annotate(err, "An error occurred while restore RevokeStmt.Level")
  1983. }
  1984. ctx.WriteKeyWord(" FROM ")
  1985. for i, v := range n.Users {
  1986. if i != 0 {
  1987. ctx.WritePlain(", ")
  1988. }
  1989. if err := v.Restore(ctx); err != nil {
  1990. return errors.Annotatef(err, "An error occurred while restore RevokeStmt.Users[%d]", i)
  1991. }
  1992. }
  1993. return nil
  1994. }
  1995. // Accept implements Node Accept interface.
  1996. func (n *RevokeStmt) Accept(v Visitor) (Node, bool) {
  1997. newNode, skipChildren := v.Enter(n)
  1998. if skipChildren {
  1999. return v.Leave(newNode)
  2000. }
  2001. n = newNode.(*RevokeStmt)
  2002. for i, val := range n.Privs {
  2003. node, ok := val.Accept(v)
  2004. if !ok {
  2005. return n, false
  2006. }
  2007. n.Privs[i] = node.(*PrivElem)
  2008. }
  2009. return v.Leave(n)
  2010. }
  2011. // RevokeStmt is the struct for REVOKE statement.
  2012. type RevokeRoleStmt struct {
  2013. stmtNode
  2014. Roles []*auth.RoleIdentity
  2015. Users []*auth.UserIdentity
  2016. }
  2017. // Restore implements Node interface.
  2018. func (n *RevokeRoleStmt) Restore(ctx *format.RestoreCtx) error {
  2019. ctx.WriteKeyWord("REVOKE ")
  2020. for i, role := range n.Roles {
  2021. if i != 0 {
  2022. ctx.WritePlain(", ")
  2023. }
  2024. if err := role.Restore(ctx); err != nil {
  2025. return errors.Annotatef(err, "An error occurred while restore RevokeRoleStmt.Roles[%d]", i)
  2026. }
  2027. }
  2028. ctx.WriteKeyWord(" FROM ")
  2029. for i, v := range n.Users {
  2030. if i != 0 {
  2031. ctx.WritePlain(", ")
  2032. }
  2033. if err := v.Restore(ctx); err != nil {
  2034. return errors.Annotatef(err, "An error occurred while restore RevokeRoleStmt.Users[%d]", i)
  2035. }
  2036. }
  2037. return nil
  2038. }
  2039. // Accept implements Node Accept interface.
  2040. func (n *RevokeRoleStmt) Accept(v Visitor) (Node, bool) {
  2041. newNode, skipChildren := v.Enter(n)
  2042. if skipChildren {
  2043. return v.Leave(newNode)
  2044. }
  2045. n = newNode.(*RevokeRoleStmt)
  2046. return v.Leave(n)
  2047. }
  2048. // GrantStmt is the struct for GRANT statement.
  2049. type GrantStmt struct {
  2050. stmtNode
  2051. Privs []*PrivElem
  2052. ObjectType ObjectTypeType
  2053. Level *GrantLevel
  2054. Users []*UserSpec
  2055. TLSOptions []*TLSOption
  2056. WithGrant bool
  2057. }
  2058. // Restore implements Node interface.
  2059. func (n *GrantStmt) Restore(ctx *format.RestoreCtx) error {
  2060. ctx.WriteKeyWord("GRANT ")
  2061. for i, v := range n.Privs {
  2062. if i != 0 && v.Priv != 0 {
  2063. ctx.WritePlain(", ")
  2064. } else if v.Priv == 0 {
  2065. ctx.WritePlain(" ")
  2066. }
  2067. if err := v.Restore(ctx); err != nil {
  2068. return errors.Annotatef(err, "An error occurred while restore GrantStmt.Privs[%d]", i)
  2069. }
  2070. }
  2071. ctx.WriteKeyWord(" ON ")
  2072. if n.ObjectType != ObjectTypeNone {
  2073. if err := n.ObjectType.Restore(ctx); err != nil {
  2074. return errors.Annotate(err, "An error occurred while restore GrantStmt.ObjectType")
  2075. }
  2076. ctx.WritePlain(" ")
  2077. }
  2078. if err := n.Level.Restore(ctx); err != nil {
  2079. return errors.Annotate(err, "An error occurred while restore GrantStmt.Level")
  2080. }
  2081. ctx.WriteKeyWord(" TO ")
  2082. for i, v := range n.Users {
  2083. if i != 0 {
  2084. ctx.WritePlain(", ")
  2085. }
  2086. if err := v.Restore(ctx); err != nil {
  2087. return errors.Annotatef(err, "An error occurred while restore GrantStmt.Users[%d]", i)
  2088. }
  2089. }
  2090. if n.TLSOptions != nil {
  2091. if len(n.TLSOptions) != 0 {
  2092. ctx.WriteKeyWord(" REQUIRE ")
  2093. }
  2094. for i, option := range n.TLSOptions {
  2095. if i != 0 {
  2096. ctx.WriteKeyWord(" AND ")
  2097. }
  2098. if err := option.Restore(ctx); err != nil {
  2099. return errors.Annotatef(err, "An error occurred while restore GrantStmt.TLSOptions[%d]", i)
  2100. }
  2101. }
  2102. }
  2103. if n.WithGrant {
  2104. ctx.WriteKeyWord(" WITH GRANT OPTION")
  2105. }
  2106. return nil
  2107. }
  2108. // SecureText implements SensitiveStatement interface.
  2109. func (n *GrantStmt) SecureText() string {
  2110. text := n.text
  2111. // Filter "identified by xxx" because it would expose password information.
  2112. idx := strings.Index(strings.ToLower(text), "identified")
  2113. if idx > 0 {
  2114. text = text[:idx]
  2115. }
  2116. return text
  2117. }
  2118. // Accept implements Node Accept interface.
  2119. func (n *GrantStmt) Accept(v Visitor) (Node, bool) {
  2120. newNode, skipChildren := v.Enter(n)
  2121. if skipChildren {
  2122. return v.Leave(newNode)
  2123. }
  2124. n = newNode.(*GrantStmt)
  2125. for i, val := range n.Privs {
  2126. node, ok := val.Accept(v)
  2127. if !ok {
  2128. return n, false
  2129. }
  2130. n.Privs[i] = node.(*PrivElem)
  2131. }
  2132. return v.Leave(n)
  2133. }
  2134. // GrantProxyStmt is the struct for GRANT PROXY statement.
  2135. type GrantProxyStmt struct {
  2136. stmtNode
  2137. LocalUser *auth.UserIdentity
  2138. ExternalUsers []*auth.UserIdentity
  2139. WithGrant bool
  2140. }
  2141. // Accept implements Node Accept interface.
  2142. func (n *GrantProxyStmt) Accept(v Visitor) (Node, bool) {
  2143. newNode, skipChildren := v.Enter(n)
  2144. if skipChildren {
  2145. return v.Leave(newNode)
  2146. }
  2147. n = newNode.(*GrantProxyStmt)
  2148. return v.Leave(n)
  2149. }
  2150. // Restore implements Node interface.
  2151. func (n *GrantProxyStmt) Restore(ctx *format.RestoreCtx) error {
  2152. ctx.WriteKeyWord("GRANT PROXY ON ")
  2153. if err := n.LocalUser.Restore(ctx); err != nil {
  2154. return errors.Annotatef(err, "An error occurred while restore GrantProxyStmt.LocalUser")
  2155. }
  2156. ctx.WriteKeyWord(" TO ")
  2157. for i, v := range n.ExternalUsers {
  2158. if i != 0 {
  2159. ctx.WritePlain(", ")
  2160. }
  2161. if err := v.Restore(ctx); err != nil {
  2162. return errors.Annotatef(err, "An error occurred while restore GrantProxyStmt.ExternalUsers[%d]", i)
  2163. }
  2164. }
  2165. if n.WithGrant {
  2166. ctx.WriteKeyWord(" WITH GRANT OPTION")
  2167. }
  2168. return nil
  2169. }
  2170. // GrantRoleStmt is the struct for GRANT TO statement.
  2171. type GrantRoleStmt struct {
  2172. stmtNode
  2173. Roles []*auth.RoleIdentity
  2174. Users []*auth.UserIdentity
  2175. }
  2176. // Accept implements Node Accept interface.
  2177. func (n *GrantRoleStmt) Accept(v Visitor) (Node, bool) {
  2178. newNode, skipChildren := v.Enter(n)
  2179. if skipChildren {
  2180. return v.Leave(newNode)
  2181. }
  2182. n = newNode.(*GrantRoleStmt)
  2183. return v.Leave(n)
  2184. }
  2185. // Restore implements Node interface.
  2186. func (n *GrantRoleStmt) Restore(ctx *format.RestoreCtx) error {
  2187. ctx.WriteKeyWord("GRANT ")
  2188. if len(n.Roles) > 0 {
  2189. for i, role := range n.Roles {
  2190. if i != 0 {
  2191. ctx.WritePlain(", ")
  2192. }
  2193. if err := role.Restore(ctx); err != nil {
  2194. return errors.Annotatef(err, "An error occurred while restore GrantRoleStmt.Roles[%d]", i)
  2195. }
  2196. }
  2197. }
  2198. ctx.WriteKeyWord(" TO ")
  2199. for i, v := range n.Users {
  2200. if i != 0 {
  2201. ctx.WritePlain(", ")
  2202. }
  2203. if err := v.Restore(ctx); err != nil {
  2204. return errors.Annotatef(err, "An error occurred while restore GrantStmt.Users[%d]", i)
  2205. }
  2206. }
  2207. return nil
  2208. }
  2209. // SecureText implements SensitiveStatement interface.
  2210. func (n *GrantRoleStmt) SecureText() string {
  2211. text := n.text
  2212. // Filter "identified by xxx" because it would expose password information.
  2213. idx := strings.Index(strings.ToLower(text), "identified")
  2214. if idx > 0 {
  2215. text = text[:idx]
  2216. }
  2217. return text
  2218. }
  2219. // ShutdownStmt is a statement to stop the TiDB server.
  2220. // See https://dev.mysql.com/doc/refman/5.7/en/shutdown.html
  2221. type ShutdownStmt struct {
  2222. stmtNode
  2223. }
  2224. // Restore implements Node interface.
  2225. func (n *ShutdownStmt) Restore(ctx *format.RestoreCtx) error {
  2226. ctx.WriteKeyWord("SHUTDOWN")
  2227. return nil
  2228. }
  2229. // Accept implements Node Accept interface.
  2230. func (n *ShutdownStmt) Accept(v Visitor) (Node, bool) {
  2231. newNode, skipChildren := v.Enter(n)
  2232. if skipChildren {
  2233. return v.Leave(newNode)
  2234. }
  2235. n = newNode.(*ShutdownStmt)
  2236. return v.Leave(n)
  2237. }
  2238. // RenameUserStmt is a statement to rename a user.
  2239. // See http://dev.mysql.com/doc/refman/5.7/en/rename-user.html
  2240. type RenameUserStmt struct {
  2241. stmtNode
  2242. UserToUsers []*UserToUser
  2243. }
  2244. // Restore implements Node interface.
  2245. func (n *RenameUserStmt) Restore(ctx *format.RestoreCtx) error {
  2246. ctx.WriteKeyWord("RENAME USER ")
  2247. for index, user2user := range n.UserToUsers {
  2248. if index != 0 {
  2249. ctx.WritePlain(", ")
  2250. }
  2251. if err := user2user.Restore(ctx); err != nil {
  2252. return errors.Annotate(err, "An error occurred while restore RenameUserStmt.UserToUsers")
  2253. }
  2254. }
  2255. return nil
  2256. }
  2257. // Accept implements Node Accept interface.
  2258. func (n *RenameUserStmt) Accept(v Visitor) (Node, bool) {
  2259. newNode, skipChildren := v.Enter(n)
  2260. if skipChildren {
  2261. return v.Leave(newNode)
  2262. }
  2263. n = newNode.(*RenameUserStmt)
  2264. for i, t := range n.UserToUsers {
  2265. node, ok := t.Accept(v)
  2266. if !ok {
  2267. return n, false
  2268. }
  2269. n.UserToUsers[i] = node.(*UserToUser)
  2270. }
  2271. return v.Leave(n)
  2272. }
  2273. // UserToUser represents renaming old user to new user used in RenameUserStmt.
  2274. type UserToUser struct {
  2275. node
  2276. OldUser *auth.UserIdentity
  2277. NewUser *auth.UserIdentity
  2278. }
  2279. // Restore implements Node interface.
  2280. func (n *UserToUser) Restore(ctx *format.RestoreCtx) error {
  2281. if err := n.OldUser.Restore(ctx); err != nil {
  2282. return errors.Annotate(err, "An error occurred while restore UserToUser.OldUser")
  2283. }
  2284. ctx.WriteKeyWord(" TO ")
  2285. if err := n.NewUser.Restore(ctx); err != nil {
  2286. return errors.Annotate(err, "An error occurred while restore UserToUser.NewUser")
  2287. }
  2288. return nil
  2289. }
  2290. // Accept implements Node Accept interface.
  2291. func (n *UserToUser) Accept(v Visitor) (Node, bool) {
  2292. newNode, skipChildren := v.Enter(n)
  2293. if skipChildren {
  2294. return v.Leave(newNode)
  2295. }
  2296. n = newNode.(*UserToUser)
  2297. return v.Leave(n)
  2298. }
  2299. type BRIEKind uint8
  2300. type BRIEOptionType uint16
  2301. const (
  2302. BRIEKindBackup BRIEKind = iota
  2303. BRIEKindRestore
  2304. // common BRIE options
  2305. BRIEOptionRateLimit BRIEOptionType = iota + 1
  2306. BRIEOptionConcurrency
  2307. BRIEOptionChecksum
  2308. BRIEOptionSendCreds
  2309. BRIEOptionCheckpoint
  2310. // backup options
  2311. BRIEOptionBackupTimeAgo
  2312. BRIEOptionBackupTS
  2313. BRIEOptionBackupTSO
  2314. BRIEOptionLastBackupTS
  2315. BRIEOptionLastBackupTSO
  2316. // restore options
  2317. BRIEOptionOnline
  2318. // import options
  2319. BRIEOptionAnalyze
  2320. BRIEOptionBackend
  2321. BRIEOptionOnDuplicate
  2322. BRIEOptionSkipSchemaFiles
  2323. BRIEOptionStrictFormat
  2324. BRIEOptionTiKVImporter
  2325. BRIEOptionResume
  2326. // CSV options
  2327. BRIEOptionCSVBackslashEscape
  2328. BRIEOptionCSVDelimiter
  2329. BRIEOptionCSVHeader
  2330. BRIEOptionCSVNotNull
  2331. BRIEOptionCSVNull
  2332. BRIEOptionCSVSeparator
  2333. BRIEOptionCSVTrimLastSeparators
  2334. BRIECSVHeaderIsColumns = ^uint64(0)
  2335. )
  2336. type BRIEOptionLevel uint64
  2337. const (
  2338. BRIEOptionLevelOff BRIEOptionLevel = iota // equals FALSE
  2339. BRIEOptionLevelRequired // equals TRUE
  2340. BRIEOptionLevelOptional
  2341. )
  2342. func (kind BRIEKind) String() string {
  2343. switch kind {
  2344. case BRIEKindBackup:
  2345. return "BACKUP"
  2346. case BRIEKindRestore:
  2347. return "RESTORE"
  2348. default:
  2349. return ""
  2350. }
  2351. }
  2352. func (kind BRIEOptionType) String() string {
  2353. switch kind {
  2354. case BRIEOptionRateLimit:
  2355. return "RATE_LIMIT"
  2356. case BRIEOptionConcurrency:
  2357. return "CONCURRENCY"
  2358. case BRIEOptionChecksum:
  2359. return "CHECKSUM"
  2360. case BRIEOptionSendCreds:
  2361. return "SEND_CREDENTIALS_TO_TIKV"
  2362. case BRIEOptionBackupTimeAgo, BRIEOptionBackupTS, BRIEOptionBackupTSO:
  2363. return "SNAPSHOT"
  2364. case BRIEOptionLastBackupTS, BRIEOptionLastBackupTSO:
  2365. return "LAST_BACKUP"
  2366. case BRIEOptionOnline:
  2367. return "ONLINE"
  2368. case BRIEOptionCheckpoint:
  2369. return "CHECKPOINT"
  2370. case BRIEOptionAnalyze:
  2371. return "ANALYZE"
  2372. case BRIEOptionBackend:
  2373. return "BACKEND"
  2374. case BRIEOptionOnDuplicate:
  2375. return "ON_DUPLICATE"
  2376. case BRIEOptionSkipSchemaFiles:
  2377. return "SKIP_SCHEMA_FILES"
  2378. case BRIEOptionStrictFormat:
  2379. return "STRICT_FORMAT"
  2380. case BRIEOptionTiKVImporter:
  2381. return "TIKV_IMPORTER"
  2382. case BRIEOptionResume:
  2383. return "RESUME"
  2384. case BRIEOptionCSVBackslashEscape:
  2385. return "CSV_BACKSLASH_ESCAPE"
  2386. case BRIEOptionCSVDelimiter:
  2387. return "CSV_DELIMITER"
  2388. case BRIEOptionCSVHeader:
  2389. return "CSV_HEADER"
  2390. case BRIEOptionCSVNotNull:
  2391. return "CSV_NOT_NULL"
  2392. case BRIEOptionCSVNull:
  2393. return "CSV_NULL"
  2394. case BRIEOptionCSVSeparator:
  2395. return "CSV_SEPARATOR"
  2396. case BRIEOptionCSVTrimLastSeparators:
  2397. return "CSV_TRIM_LAST_SEPARATORS"
  2398. default:
  2399. return ""
  2400. }
  2401. }
  2402. func (level BRIEOptionLevel) String() string {
  2403. switch level {
  2404. case BRIEOptionLevelOff:
  2405. return "OFF"
  2406. case BRIEOptionLevelOptional:
  2407. return "OPTIONAL"
  2408. case BRIEOptionLevelRequired:
  2409. return "REQUIRED"
  2410. default:
  2411. return ""
  2412. }
  2413. }
  2414. type BRIEOption struct {
  2415. Tp BRIEOptionType
  2416. StrValue string
  2417. UintValue uint64
  2418. }
  2419. func (opt *BRIEOption) Restore(ctx *format.RestoreCtx) error {
  2420. ctx.WriteKeyWord(opt.Tp.String())
  2421. ctx.WritePlain(" = ")
  2422. switch opt.Tp {
  2423. case BRIEOptionBackupTS, BRIEOptionLastBackupTS, BRIEOptionBackend, BRIEOptionOnDuplicate, BRIEOptionTiKVImporter, BRIEOptionCSVDelimiter, BRIEOptionCSVNull, BRIEOptionCSVSeparator:
  2424. ctx.WriteString(opt.StrValue)
  2425. case BRIEOptionBackupTimeAgo:
  2426. ctx.WritePlainf("%d ", opt.UintValue/1000)
  2427. ctx.WriteKeyWord("MICROSECOND AGO")
  2428. case BRIEOptionRateLimit:
  2429. ctx.WritePlainf("%d ", opt.UintValue/1048576)
  2430. ctx.WriteKeyWord("MB")
  2431. ctx.WritePlain("/")
  2432. ctx.WriteKeyWord("SECOND")
  2433. case BRIEOptionCSVHeader:
  2434. if opt.UintValue == BRIECSVHeaderIsColumns {
  2435. ctx.WriteKeyWord("COLUMNS")
  2436. } else {
  2437. ctx.WritePlainf("%d", opt.UintValue)
  2438. }
  2439. case BRIEOptionChecksum, BRIEOptionAnalyze:
  2440. // BACKUP/RESTORE doesn't support OPTIONAL value for now, should warn at executor
  2441. ctx.WriteKeyWord(BRIEOptionLevel(opt.UintValue).String())
  2442. default:
  2443. ctx.WritePlainf("%d", opt.UintValue)
  2444. }
  2445. return nil
  2446. }
  2447. // BRIEStmt is a statement for backup, restore, import and export.
  2448. type BRIEStmt struct {
  2449. stmtNode
  2450. Kind BRIEKind
  2451. Schemas []string
  2452. Tables []*TableName
  2453. Storage string
  2454. Options []*BRIEOption
  2455. }
  2456. func (n *BRIEStmt) Accept(v Visitor) (Node, bool) {
  2457. newNode, skipChildren := v.Enter(n)
  2458. if skipChildren {
  2459. return v.Leave(newNode)
  2460. }
  2461. n = newNode.(*BRIEStmt)
  2462. for i, val := range n.Tables {
  2463. node, ok := val.Accept(v)
  2464. if !ok {
  2465. return n, false
  2466. }
  2467. n.Tables[i] = node.(*TableName)
  2468. }
  2469. return v.Leave(n)
  2470. }
  2471. func (n *BRIEStmt) Restore(ctx *format.RestoreCtx) error {
  2472. ctx.WriteKeyWord(n.Kind.String())
  2473. switch {
  2474. case len(n.Tables) != 0:
  2475. ctx.WriteKeyWord(" TABLE ")
  2476. for index, table := range n.Tables {
  2477. if index != 0 {
  2478. ctx.WritePlain(", ")
  2479. }
  2480. if err := table.Restore(ctx); err != nil {
  2481. return errors.Annotatef(err, "An error occurred while restore BRIEStmt.Tables[%d]", index)
  2482. }
  2483. }
  2484. case len(n.Schemas) != 0:
  2485. ctx.WriteKeyWord(" DATABASE ")
  2486. for index, schema := range n.Schemas {
  2487. if index != 0 {
  2488. ctx.WritePlain(", ")
  2489. }
  2490. ctx.WriteName(schema)
  2491. }
  2492. default:
  2493. ctx.WriteKeyWord(" DATABASE")
  2494. ctx.WritePlain(" *")
  2495. }
  2496. switch n.Kind {
  2497. case BRIEKindBackup:
  2498. ctx.WriteKeyWord(" TO ")
  2499. case BRIEKindRestore:
  2500. ctx.WriteKeyWord(" FROM ")
  2501. }
  2502. ctx.WriteString(n.Storage)
  2503. for _, opt := range n.Options {
  2504. ctx.WritePlain(" ")
  2505. if err := opt.Restore(ctx); err != nil {
  2506. return err
  2507. }
  2508. }
  2509. return nil
  2510. }
  2511. // SecureText implements SensitiveStmtNode
  2512. func (n *BRIEStmt) SecureText() string {
  2513. // FIXME: this solution is not scalable, and duplicates some logic from BR.
  2514. redactedStorage := n.Storage
  2515. u, err := url.Parse(n.Storage)
  2516. if err == nil {
  2517. if u.Scheme == "s3" {
  2518. query := u.Query()
  2519. for key := range query {
  2520. switch strings.ToLower(strings.ReplaceAll(key, "_", "-")) {
  2521. case "access-key", "secret-access-key":
  2522. query[key] = []string{"xxxxxx"}
  2523. }
  2524. }
  2525. u.RawQuery = query.Encode()
  2526. redactedStorage = u.String()
  2527. }
  2528. }
  2529. redactedStmt := &BRIEStmt{
  2530. Kind: n.Kind,
  2531. Schemas: n.Schemas,
  2532. Tables: n.Tables,
  2533. Storage: redactedStorage,
  2534. Options: n.Options,
  2535. }
  2536. var sb strings.Builder
  2537. _ = redactedStmt.Restore(format.NewRestoreCtx(format.DefaultRestoreFlags, &sb))
  2538. return sb.String()
  2539. }
  2540. type PurgeImportStmt struct {
  2541. stmtNode
  2542. TaskID uint64
  2543. }
  2544. func (n *PurgeImportStmt) Accept(v Visitor) (Node, bool) {
  2545. newNode, _ := v.Enter(n)
  2546. n = newNode.(*PurgeImportStmt)
  2547. return v.Leave(n)
  2548. }
  2549. func (n *PurgeImportStmt) Restore(ctx *format.RestoreCtx) error {
  2550. ctx.WritePlainf("PURGE IMPORT %d", n.TaskID)
  2551. return nil
  2552. }
  2553. // ErrorHandlingOption is used in async IMPORT related stmt
  2554. type ErrorHandlingOption uint64
  2555. const (
  2556. ErrorHandleError ErrorHandlingOption = iota
  2557. ErrorHandleReplace
  2558. ErrorHandleSkipAll
  2559. ErrorHandleSkipConstraint
  2560. ErrorHandleSkipDuplicate
  2561. ErrorHandleSkipStrict
  2562. )
  2563. func (o ErrorHandlingOption) String() string {
  2564. switch o {
  2565. case ErrorHandleError:
  2566. return ""
  2567. case ErrorHandleReplace:
  2568. return "REPLACE"
  2569. case ErrorHandleSkipAll:
  2570. return "SKIP ALL"
  2571. case ErrorHandleSkipConstraint:
  2572. return "SKIP CONSTRAINT"
  2573. case ErrorHandleSkipDuplicate:
  2574. return "SKIP DUPLICATE"
  2575. case ErrorHandleSkipStrict:
  2576. return "SKIP STRICT"
  2577. default:
  2578. return ""
  2579. }
  2580. }
  2581. type CreateImportStmt struct {
  2582. stmtNode
  2583. IfNotExists bool
  2584. Name string
  2585. Storage string
  2586. ErrorHandling ErrorHandlingOption
  2587. Options []*BRIEOption
  2588. }
  2589. func (n *CreateImportStmt) Accept(v Visitor) (Node, bool) {
  2590. newNode, _ := v.Enter(n)
  2591. n = newNode.(*CreateImportStmt)
  2592. return v.Leave(n)
  2593. }
  2594. func (n *CreateImportStmt) Restore(ctx *format.RestoreCtx) error {
  2595. ctx.WriteKeyWord("CREATE IMPORT ")
  2596. if n.IfNotExists {
  2597. ctx.WriteKeyWord("IF NOT EXISTS ")
  2598. }
  2599. ctx.WriteName(n.Name)
  2600. ctx.WriteKeyWord(" FROM ")
  2601. ctx.WriteString(n.Storage)
  2602. if n.ErrorHandling != ErrorHandleError {
  2603. ctx.WritePlain(" ")
  2604. ctx.WriteKeyWord(n.ErrorHandling.String())
  2605. }
  2606. for _, opt := range n.Options {
  2607. ctx.WritePlain(" ")
  2608. if err := opt.Restore(ctx); err != nil {
  2609. return err
  2610. }
  2611. }
  2612. return nil
  2613. }
  2614. // SecureText implements SensitiveStmtNode
  2615. func (n *CreateImportStmt) SecureText() string {
  2616. // FIXME: this solution is not scalable, and duplicates some logic from BR.
  2617. redactedStorage := n.Storage
  2618. u, err := url.Parse(n.Storage)
  2619. if err == nil {
  2620. if u.Scheme == "s3" {
  2621. query := u.Query()
  2622. for key := range query {
  2623. switch strings.ToLower(strings.ReplaceAll(key, "_", "-")) {
  2624. case "access-key", "secret-access-key":
  2625. query[key] = []string{"xxxxxx"}
  2626. }
  2627. }
  2628. u.RawQuery = query.Encode()
  2629. redactedStorage = u.String()
  2630. }
  2631. }
  2632. redactedStmt := &CreateImportStmt{
  2633. IfNotExists: n.IfNotExists,
  2634. Name: n.Name,
  2635. Storage: redactedStorage,
  2636. ErrorHandling: n.ErrorHandling,
  2637. Options: n.Options,
  2638. }
  2639. var sb strings.Builder
  2640. _ = redactedStmt.Restore(format.NewRestoreCtx(format.DefaultRestoreFlags, &sb))
  2641. return sb.String()
  2642. }
  2643. type StopImportStmt struct {
  2644. stmtNode
  2645. IfRunning bool
  2646. Name string
  2647. }
  2648. func (n *StopImportStmt) Accept(v Visitor) (Node, bool) {
  2649. newNode, _ := v.Enter(n)
  2650. n = newNode.(*StopImportStmt)
  2651. return v.Leave(n)
  2652. }
  2653. func (n *StopImportStmt) Restore(ctx *format.RestoreCtx) error {
  2654. ctx.WriteKeyWord("STOP IMPORT ")
  2655. if n.IfRunning {
  2656. ctx.WriteKeyWord("IF RUNNING ")
  2657. }
  2658. ctx.WriteName(n.Name)
  2659. return nil
  2660. }
  2661. type ResumeImportStmt struct {
  2662. stmtNode
  2663. IfNotRunning bool
  2664. Name string
  2665. }
  2666. func (n *ResumeImportStmt) Accept(v Visitor) (Node, bool) {
  2667. newNode, _ := v.Enter(n)
  2668. n = newNode.(*ResumeImportStmt)
  2669. return v.Leave(n)
  2670. }
  2671. func (n *ResumeImportStmt) Restore(ctx *format.RestoreCtx) error {
  2672. ctx.WriteKeyWord("RESUME IMPORT ")
  2673. if n.IfNotRunning {
  2674. ctx.WriteKeyWord("IF NOT RUNNING ")
  2675. }
  2676. ctx.WriteName(n.Name)
  2677. return nil
  2678. }
  2679. type ImportTruncate struct {
  2680. IsErrorsOnly bool
  2681. TableNames []*TableName
  2682. }
  2683. type AlterImportStmt struct {
  2684. stmtNode
  2685. Name string
  2686. ErrorHandling ErrorHandlingOption
  2687. Options []*BRIEOption
  2688. Truncate *ImportTruncate
  2689. }
  2690. func (n *AlterImportStmt) Accept(v Visitor) (Node, bool) {
  2691. newNode, _ := v.Enter(n)
  2692. n = newNode.(*AlterImportStmt)
  2693. return v.Leave(n)
  2694. }
  2695. func (n *AlterImportStmt) Restore(ctx *format.RestoreCtx) error {
  2696. ctx.WriteKeyWord("ALTER IMPORT ")
  2697. ctx.WriteName(n.Name)
  2698. if n.ErrorHandling != ErrorHandleError {
  2699. ctx.WritePlain(" ")
  2700. ctx.WriteKeyWord(n.ErrorHandling.String())
  2701. }
  2702. for _, opt := range n.Options {
  2703. ctx.WritePlain(" ")
  2704. if err := opt.Restore(ctx); err != nil {
  2705. return err
  2706. }
  2707. }
  2708. if n.Truncate != nil {
  2709. if n.Truncate.IsErrorsOnly {
  2710. ctx.WriteKeyWord(" TRUNCATE ERRORS")
  2711. } else {
  2712. ctx.WriteKeyWord(" TRUNCATE ALL")
  2713. }
  2714. if len(n.Truncate.TableNames) != 0 {
  2715. ctx.WriteKeyWord(" TABLE")
  2716. }
  2717. for i := range n.Truncate.TableNames {
  2718. if i == 0 {
  2719. ctx.WritePlain(" ")
  2720. } else {
  2721. ctx.WritePlain(", ")
  2722. }
  2723. if err := n.Truncate.TableNames[i].Restore(ctx); err != nil {
  2724. return err
  2725. }
  2726. }
  2727. }
  2728. return nil
  2729. }
  2730. type DropImportStmt struct {
  2731. stmtNode
  2732. IfExists bool
  2733. Name string
  2734. }
  2735. func (n *DropImportStmt) Accept(v Visitor) (Node, bool) {
  2736. newNode, _ := v.Enter(n)
  2737. n = newNode.(*DropImportStmt)
  2738. return v.Leave(n)
  2739. }
  2740. func (n *DropImportStmt) Restore(ctx *format.RestoreCtx) error {
  2741. ctx.WriteKeyWord("DROP IMPORT ")
  2742. if n.IfExists {
  2743. ctx.WriteKeyWord("IF EXISTS ")
  2744. }
  2745. ctx.WriteName(n.Name)
  2746. return nil
  2747. }
  2748. type ShowImportStmt struct {
  2749. stmtNode
  2750. Name string
  2751. ErrorsOnly bool
  2752. TableNames []*TableName
  2753. }
  2754. func (n *ShowImportStmt) Accept(v Visitor) (Node, bool) {
  2755. newNode, _ := v.Enter(n)
  2756. n = newNode.(*ShowImportStmt)
  2757. return v.Leave(n)
  2758. }
  2759. func (n *ShowImportStmt) Restore(ctx *format.RestoreCtx) error {
  2760. ctx.WriteKeyWord("SHOW IMPORT ")
  2761. ctx.WriteName(n.Name)
  2762. if n.ErrorsOnly {
  2763. ctx.WriteKeyWord(" ERRORS")
  2764. }
  2765. if len(n.TableNames) != 0 {
  2766. ctx.WriteKeyWord(" TABLE")
  2767. }
  2768. for i := range n.TableNames {
  2769. if i == 0 {
  2770. ctx.WritePlain(" ")
  2771. } else {
  2772. ctx.WritePlain(", ")
  2773. }
  2774. if err := n.TableNames[i].Restore(ctx); err != nil {
  2775. return err
  2776. }
  2777. }
  2778. return nil
  2779. }
  2780. // Ident is the table identifier composed of schema name and table name.
  2781. type Ident struct {
  2782. Schema model.CIStr
  2783. Name model.CIStr
  2784. }
  2785. // String implements fmt.Stringer interface.
  2786. func (i Ident) String() string {
  2787. if i.Schema.O == "" {
  2788. return i.Name.O
  2789. }
  2790. return fmt.Sprintf("%s.%s", i.Schema, i.Name)
  2791. }
  2792. // SelectStmtOpts wrap around select hints and switches
  2793. type SelectStmtOpts struct {
  2794. Distinct bool
  2795. SQLBigResult bool
  2796. SQLBufferResult bool
  2797. SQLCache bool
  2798. SQLSmallResult bool
  2799. CalcFoundRows bool
  2800. StraightJoin bool
  2801. Priority mysql.PriorityEnum
  2802. TableHints []*TableOptimizerHint
  2803. ExplicitAll bool
  2804. }
  2805. // TableOptimizerHint is Table level optimizer hint
  2806. type TableOptimizerHint struct {
  2807. node
  2808. // HintName is the name or alias of the table(s) which the hint will affect.
  2809. // Table hints has no schema info
  2810. // It allows only table name or alias (if table has an alias)
  2811. HintName model.CIStr
  2812. // HintData is the payload of the hint. The actual type of this field
  2813. // is defined differently as according `HintName`. Define as following:
  2814. //
  2815. // Statement Execution Time Optimizer Hints
  2816. // See https://dev.mysql.com/doc/refman/5.7/en/optimizer-hints.html#optimizer-hints-execution-time
  2817. // - MAX_EXECUTION_TIME => uint64
  2818. // - MEMORY_QUOTA => int64
  2819. // - QUERY_TYPE => model.CIStr
  2820. //
  2821. // Time Range is used to hint the time range of inspection tables
  2822. // e.g: select /*+ time_range('','') */ * from information_schema.inspection_result.
  2823. // - TIME_RANGE => ast.HintTimeRange
  2824. // - READ_FROM_STORAGE => model.CIStr
  2825. // - USE_TOJA => bool
  2826. // - NTH_PLAN => int64
  2827. HintData interface{}
  2828. // QBName is the default effective query block of this hint.
  2829. QBName model.CIStr
  2830. Tables []HintTable
  2831. Indexes []model.CIStr
  2832. }
  2833. // HintTimeRange is the payload of `TIME_RANGE` hint
  2834. type HintTimeRange struct {
  2835. From string
  2836. To string
  2837. }
  2838. // HintSetVar is the payload of `SET_VAR` hint
  2839. type HintSetVar struct {
  2840. VarName string
  2841. Value string
  2842. }
  2843. // HintTable is table in the hint. It may have query block info.
  2844. type HintTable struct {
  2845. DBName model.CIStr
  2846. TableName model.CIStr
  2847. QBName model.CIStr
  2848. PartitionList []model.CIStr
  2849. }
  2850. func (ht *HintTable) Restore(ctx *format.RestoreCtx) {
  2851. if ht.DBName.L != "" {
  2852. ctx.WriteName(ht.DBName.String())
  2853. ctx.WriteKeyWord(".")
  2854. }
  2855. ctx.WriteName(ht.TableName.String())
  2856. if ht.QBName.L != "" {
  2857. ctx.WriteKeyWord("@")
  2858. ctx.WriteName(ht.QBName.String())
  2859. }
  2860. if len(ht.PartitionList) > 0 {
  2861. ctx.WriteKeyWord(" PARTITION")
  2862. ctx.WritePlain("(")
  2863. for i, p := range ht.PartitionList {
  2864. if i > 0 {
  2865. ctx.WritePlain(", ")
  2866. }
  2867. ctx.WriteName(p.String())
  2868. }
  2869. ctx.WritePlain(")")
  2870. }
  2871. }
  2872. // Restore implements Node interface.
  2873. func (n *TableOptimizerHint) Restore(ctx *format.RestoreCtx) error {
  2874. ctx.WriteKeyWord(n.HintName.String())
  2875. ctx.WritePlain("(")
  2876. if n.QBName.L != "" {
  2877. if n.HintName.L != "qb_name" {
  2878. ctx.WriteKeyWord("@")
  2879. }
  2880. ctx.WriteName(n.QBName.String())
  2881. }
  2882. // Hints without args except query block.
  2883. switch n.HintName.L {
  2884. case "hash_agg", "stream_agg", "agg_to_cop", "read_consistent_replica", "no_index_merge", "qb_name", "ignore_plan_cache", "limit_to_cop":
  2885. ctx.WritePlain(")")
  2886. return nil
  2887. }
  2888. if n.QBName.L != "" {
  2889. ctx.WritePlain(" ")
  2890. }
  2891. // Hints with args except query block.
  2892. switch n.HintName.L {
  2893. case "max_execution_time":
  2894. ctx.WritePlainf("%d", n.HintData.(uint64))
  2895. case "nth_plan":
  2896. ctx.WritePlainf("%d", n.HintData.(int64))
  2897. case "tidb_hj", "tidb_smj", "tidb_inlj", "hash_join", "merge_join", "inl_join", "broadcast_join", "broadcast_join_local", "inl_hash_join", "inl_merge_join":
  2898. for i, table := range n.Tables {
  2899. if i != 0 {
  2900. ctx.WritePlain(", ")
  2901. }
  2902. table.Restore(ctx)
  2903. }
  2904. case "use_index", "ignore_index", "use_index_merge", "force_index":
  2905. n.Tables[0].Restore(ctx)
  2906. ctx.WritePlain(" ")
  2907. for i, index := range n.Indexes {
  2908. if i != 0 {
  2909. ctx.WritePlain(", ")
  2910. }
  2911. ctx.WriteName(index.String())
  2912. }
  2913. case "use_toja", "use_cascades":
  2914. if n.HintData.(bool) {
  2915. ctx.WritePlain("TRUE")
  2916. } else {
  2917. ctx.WritePlain("FALSE")
  2918. }
  2919. case "query_type":
  2920. ctx.WriteKeyWord(n.HintData.(model.CIStr).String())
  2921. case "memory_quota":
  2922. ctx.WritePlainf("%d MB", n.HintData.(int64)/1024/1024)
  2923. case "read_from_storage":
  2924. ctx.WriteKeyWord(n.HintData.(model.CIStr).String())
  2925. for i, table := range n.Tables {
  2926. if i == 0 {
  2927. ctx.WritePlain("[")
  2928. }
  2929. table.Restore(ctx)
  2930. if i == len(n.Tables)-1 {
  2931. ctx.WritePlain("]")
  2932. } else {
  2933. ctx.WritePlain(", ")
  2934. }
  2935. }
  2936. case "time_range":
  2937. hintData := n.HintData.(HintTimeRange)
  2938. ctx.WriteString(hintData.From)
  2939. ctx.WritePlain(", ")
  2940. ctx.WriteString(hintData.To)
  2941. case "set_var":
  2942. hintData := n.HintData.(HintSetVar)
  2943. ctx.WriteString(hintData.VarName)
  2944. ctx.WritePlain(", ")
  2945. ctx.WriteString(hintData.Value)
  2946. }
  2947. ctx.WritePlain(")")
  2948. return nil
  2949. }
  2950. // Accept implements Node Accept interface.
  2951. func (n *TableOptimizerHint) Accept(v Visitor) (Node, bool) {
  2952. newNode, skipChildren := v.Enter(n)
  2953. if skipChildren {
  2954. return v.Leave(newNode)
  2955. }
  2956. n = newNode.(*TableOptimizerHint)
  2957. return v.Leave(n)
  2958. }
  2959. type BinaryLiteral interface {
  2960. ToString() string
  2961. }
  2962. // NewDecimal creates a types.Decimal value, it's provided by parser driver.
  2963. var NewDecimal func(string) (interface{}, error)
  2964. // NewHexLiteral creates a types.HexLiteral value, it's provided by parser driver.
  2965. var NewHexLiteral func(string) (interface{}, error)
  2966. // NewBitLiteral creates a types.BitLiteral value, it's provided by parser driver.
  2967. var NewBitLiteral func(string) (interface{}, error)