functions.go 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  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. "fmt"
  16. "io"
  17. "strings"
  18. "time"
  19. "github.com/pingcap/errors"
  20. "github.com/pingcap/parser/format"
  21. "github.com/pingcap/parser/model"
  22. "github.com/pingcap/parser/types"
  23. )
  24. var (
  25. _ FuncNode = &AggregateFuncExpr{}
  26. _ FuncNode = &FuncCallExpr{}
  27. _ FuncNode = &FuncCastExpr{}
  28. _ FuncNode = &WindowFuncExpr{}
  29. )
  30. // List scalar function names.
  31. const (
  32. LogicAnd = "and"
  33. Cast = "cast"
  34. LeftShift = "leftshift"
  35. RightShift = "rightshift"
  36. LogicOr = "or"
  37. GE = "ge"
  38. LE = "le"
  39. EQ = "eq"
  40. NE = "ne"
  41. LT = "lt"
  42. GT = "gt"
  43. Plus = "plus"
  44. Minus = "minus"
  45. And = "bitand"
  46. Or = "bitor"
  47. Mod = "mod"
  48. Xor = "bitxor"
  49. Div = "div"
  50. Mul = "mul"
  51. UnaryNot = "not" // Avoid name conflict with Not in github/pingcap/check.
  52. BitNeg = "bitneg"
  53. IntDiv = "intdiv"
  54. LogicXor = "xor"
  55. NullEQ = "nulleq"
  56. UnaryPlus = "unaryplus"
  57. UnaryMinus = "unaryminus"
  58. In = "in"
  59. Like = "like"
  60. Case = "case"
  61. Regexp = "regexp"
  62. IsNull = "isnull"
  63. IsTruthWithoutNull = "istrue" // Avoid name conflict with IsTrue in github/pingcap/check.
  64. IsTruthWithNull = "istrue_with_null"
  65. IsFalsity = "isfalse" // Avoid name conflict with IsFalse in github/pingcap/check.
  66. RowFunc = "row"
  67. SetVar = "setvar"
  68. GetVar = "getvar"
  69. Values = "values"
  70. BitCount = "bit_count"
  71. GetParam = "getparam"
  72. // common functions
  73. Coalesce = "coalesce"
  74. Greatest = "greatest"
  75. Least = "least"
  76. Interval = "interval"
  77. // math functions
  78. Abs = "abs"
  79. Acos = "acos"
  80. Asin = "asin"
  81. Atan = "atan"
  82. Atan2 = "atan2"
  83. Ceil = "ceil"
  84. Ceiling = "ceiling"
  85. Conv = "conv"
  86. Cos = "cos"
  87. Cot = "cot"
  88. CRC32 = "crc32"
  89. Degrees = "degrees"
  90. Exp = "exp"
  91. Floor = "floor"
  92. Ln = "ln"
  93. Log = "log"
  94. Log2 = "log2"
  95. Log10 = "log10"
  96. PI = "pi"
  97. Pow = "pow"
  98. Power = "power"
  99. Radians = "radians"
  100. Rand = "rand"
  101. Round = "round"
  102. Sign = "sign"
  103. Sin = "sin"
  104. Sqrt = "sqrt"
  105. Tan = "tan"
  106. Truncate = "truncate"
  107. // time functions
  108. AddDate = "adddate"
  109. AddTime = "addtime"
  110. ConvertTz = "convert_tz"
  111. Curdate = "curdate"
  112. CurrentDate = "current_date"
  113. CurrentTime = "current_time"
  114. CurrentTimestamp = "current_timestamp"
  115. Curtime = "curtime"
  116. Date = "date"
  117. DateLiteral = "'tidb`.(dateliteral"
  118. DateAdd = "date_add"
  119. DateFormat = "date_format"
  120. DateSub = "date_sub"
  121. DateDiff = "datediff"
  122. Day = "day"
  123. DayName = "dayname"
  124. DayOfMonth = "dayofmonth"
  125. DayOfWeek = "dayofweek"
  126. DayOfYear = "dayofyear"
  127. Extract = "extract"
  128. FromDays = "from_days"
  129. FromUnixTime = "from_unixtime"
  130. GetFormat = "get_format"
  131. Hour = "hour"
  132. LocalTime = "localtime"
  133. LocalTimestamp = "localtimestamp"
  134. MakeDate = "makedate"
  135. MakeTime = "maketime"
  136. MicroSecond = "microsecond"
  137. Minute = "minute"
  138. Month = "month"
  139. MonthName = "monthname"
  140. Now = "now"
  141. PeriodAdd = "period_add"
  142. PeriodDiff = "period_diff"
  143. Quarter = "quarter"
  144. SecToTime = "sec_to_time"
  145. Second = "second"
  146. StrToDate = "str_to_date"
  147. SubDate = "subdate"
  148. SubTime = "subtime"
  149. Sysdate = "sysdate"
  150. Time = "time"
  151. TimeLiteral = "'tidb`.(timeliteral"
  152. TimeFormat = "time_format"
  153. TimeToSec = "time_to_sec"
  154. TimeDiff = "timediff"
  155. Timestamp = "timestamp"
  156. TimestampLiteral = "'tidb`.(timestampliteral"
  157. TimestampAdd = "timestampadd"
  158. TimestampDiff = "timestampdiff"
  159. ToDays = "to_days"
  160. ToSeconds = "to_seconds"
  161. UnixTimestamp = "unix_timestamp"
  162. UTCDate = "utc_date"
  163. UTCTime = "utc_time"
  164. UTCTimestamp = "utc_timestamp"
  165. Week = "week"
  166. Weekday = "weekday"
  167. WeekOfYear = "weekofyear"
  168. Year = "year"
  169. YearWeek = "yearweek"
  170. LastDay = "last_day"
  171. TiDBParseTso = "tidb_parse_tso"
  172. // string functions
  173. ASCII = "ascii"
  174. Bin = "bin"
  175. Concat = "concat"
  176. ConcatWS = "concat_ws"
  177. Convert = "convert"
  178. Elt = "elt"
  179. ExportSet = "export_set"
  180. Field = "field"
  181. Format = "format"
  182. FromBase64 = "from_base64"
  183. InsertFunc = "insert_func"
  184. Instr = "instr"
  185. Lcase = "lcase"
  186. Left = "left"
  187. Length = "length"
  188. LoadFile = "load_file"
  189. Locate = "locate"
  190. Lower = "lower"
  191. Lpad = "lpad"
  192. LTrim = "ltrim"
  193. MakeSet = "make_set"
  194. Mid = "mid"
  195. Oct = "oct"
  196. OctetLength = "octet_length"
  197. Ord = "ord"
  198. Position = "position"
  199. Quote = "quote"
  200. Repeat = "repeat"
  201. Replace = "replace"
  202. Reverse = "reverse"
  203. Right = "right"
  204. RTrim = "rtrim"
  205. Space = "space"
  206. Strcmp = "strcmp"
  207. Substring = "substring"
  208. Substr = "substr"
  209. SubstringIndex = "substring_index"
  210. ToBase64 = "to_base64"
  211. Trim = "trim"
  212. Upper = "upper"
  213. Ucase = "ucase"
  214. Hex = "hex"
  215. Unhex = "unhex"
  216. Rpad = "rpad"
  217. BitLength = "bit_length"
  218. CharFunc = "char_func"
  219. CharLength = "char_length"
  220. CharacterLength = "character_length"
  221. FindInSet = "find_in_set"
  222. WeightString = "weight_string"
  223. Soundex = "soundex"
  224. // information functions
  225. Benchmark = "benchmark"
  226. Charset = "charset"
  227. Coercibility = "coercibility"
  228. Collation = "collation"
  229. ConnectionID = "connection_id"
  230. CurrentUser = "current_user"
  231. CurrentRole = "current_role"
  232. Database = "database"
  233. FoundRows = "found_rows"
  234. LastInsertId = "last_insert_id"
  235. RowCount = "row_count"
  236. Schema = "schema"
  237. SessionUser = "session_user"
  238. SystemUser = "system_user"
  239. User = "user"
  240. Version = "version"
  241. TiDBVersion = "tidb_version"
  242. TiDBIsDDLOwner = "tidb_is_ddl_owner"
  243. TiDBDecodePlan = "tidb_decode_plan"
  244. FormatBytes = "format_bytes"
  245. FormatNanoTime = "format_nano_time"
  246. // control functions
  247. If = "if"
  248. Ifnull = "ifnull"
  249. Nullif = "nullif"
  250. // miscellaneous functions
  251. AnyValue = "any_value"
  252. DefaultFunc = "default_func"
  253. InetAton = "inet_aton"
  254. InetNtoa = "inet_ntoa"
  255. Inet6Aton = "inet6_aton"
  256. Inet6Ntoa = "inet6_ntoa"
  257. IsFreeLock = "is_free_lock"
  258. IsIPv4 = "is_ipv4"
  259. IsIPv4Compat = "is_ipv4_compat"
  260. IsIPv4Mapped = "is_ipv4_mapped"
  261. IsIPv6 = "is_ipv6"
  262. IsUsedLock = "is_used_lock"
  263. MasterPosWait = "master_pos_wait"
  264. NameConst = "name_const"
  265. ReleaseAllLocks = "release_all_locks"
  266. Sleep = "sleep"
  267. UUID = "uuid"
  268. UUIDShort = "uuid_short"
  269. UUIDToBin = "uuid_to_bin"
  270. BinToUUID = "bin_to_uuid"
  271. VitessHash = "vitess_hash"
  272. // get_lock() and release_lock() is parsed but do nothing.
  273. // It is used for preventing error in Ruby's activerecord migrations.
  274. GetLock = "get_lock"
  275. ReleaseLock = "release_lock"
  276. // encryption and compression functions
  277. AesDecrypt = "aes_decrypt"
  278. AesEncrypt = "aes_encrypt"
  279. Compress = "compress"
  280. Decode = "decode"
  281. DesDecrypt = "des_decrypt"
  282. DesEncrypt = "des_encrypt"
  283. Encode = "encode"
  284. Encrypt = "encrypt"
  285. MD5 = "md5"
  286. OldPassword = "old_password"
  287. PasswordFunc = "password_func"
  288. RandomBytes = "random_bytes"
  289. SHA1 = "sha1"
  290. SHA = "sha"
  291. SHA2 = "sha2"
  292. Uncompress = "uncompress"
  293. UncompressedLength = "uncompressed_length"
  294. ValidatePasswordStrength = "validate_password_strength"
  295. // json functions
  296. JSONType = "json_type"
  297. JSONExtract = "json_extract"
  298. JSONUnquote = "json_unquote"
  299. JSONArray = "json_array"
  300. JSONObject = "json_object"
  301. JSONMerge = "json_merge"
  302. JSONSet = "json_set"
  303. JSONInsert = "json_insert"
  304. JSONReplace = "json_replace"
  305. JSONRemove = "json_remove"
  306. JSONContains = "json_contains"
  307. JSONContainsPath = "json_contains_path"
  308. JSONValid = "json_valid"
  309. JSONArrayAppend = "json_array_append"
  310. JSONArrayInsert = "json_array_insert"
  311. JSONMergePatch = "json_merge_patch"
  312. JSONMergePreserve = "json_merge_preserve"
  313. JSONPretty = "json_pretty"
  314. JSONQuote = "json_quote"
  315. JSONSearch = "json_search"
  316. JSONStorageSize = "json_storage_size"
  317. JSONDepth = "json_depth"
  318. JSONKeys = "json_keys"
  319. JSONLength = "json_length"
  320. // TiDB internal function.
  321. TiDBDecodeKey = "tidb_decode_key"
  322. TiDBDecodeBase64Key = "tidb_decode_base64_key"
  323. // MVCC information fetching function.
  324. GetMvccInfo = "get_mvcc_info"
  325. // Sequence function.
  326. NextVal = "nextval"
  327. LastVal = "lastval"
  328. SetVal = "setval"
  329. )
  330. type FuncCallExprType int8
  331. const (
  332. FuncCallExprTypeKeyword FuncCallExprType = iota
  333. FuncCallExprTypeGeneric
  334. )
  335. // FuncCallExpr is for function expression.
  336. type FuncCallExpr struct {
  337. funcNode
  338. Tp FuncCallExprType
  339. Schema model.CIStr
  340. // FnName is the function name.
  341. FnName model.CIStr
  342. // Args is the function args.
  343. Args []ExprNode
  344. }
  345. // Restore implements Node interface.
  346. func (n *FuncCallExpr) Restore(ctx *format.RestoreCtx) error {
  347. var specialLiteral string
  348. switch n.FnName.L {
  349. case DateLiteral:
  350. specialLiteral = "DATE "
  351. case TimeLiteral:
  352. specialLiteral = "TIME "
  353. case TimestampLiteral:
  354. specialLiteral = "TIMESTAMP "
  355. }
  356. if specialLiteral != "" {
  357. ctx.WritePlain(specialLiteral)
  358. if err := n.Args[0].Restore(ctx); err != nil {
  359. return errors.Annotatef(err, "An error occurred while restore FuncCastExpr.Expr")
  360. }
  361. return nil
  362. }
  363. if len(n.Schema.String()) != 0 {
  364. ctx.WriteName(n.Schema.O)
  365. ctx.WritePlain(".")
  366. }
  367. if n.Tp == FuncCallExprTypeGeneric {
  368. ctx.WriteName(n.FnName.O)
  369. } else {
  370. ctx.WriteKeyWord(n.FnName.O)
  371. }
  372. ctx.WritePlain("(")
  373. switch n.FnName.L {
  374. case "convert":
  375. if err := n.Args[0].Restore(ctx); err != nil {
  376. return errors.Annotatef(err, "An error occurred while restore FuncCastExpr.Expr")
  377. }
  378. ctx.WriteKeyWord(" USING ")
  379. if err := n.Args[1].Restore(ctx); err != nil {
  380. return errors.Annotatef(err, "An error occurred while restore FuncCastExpr.Expr")
  381. }
  382. case "adddate", "subdate", "date_add", "date_sub":
  383. if err := n.Args[0].Restore(ctx); err != nil {
  384. return errors.Annotatef(err, "An error occurred while restore FuncCallExpr.Args[0]")
  385. }
  386. ctx.WritePlain(", ")
  387. ctx.WriteKeyWord("INTERVAL ")
  388. if err := n.Args[1].Restore(ctx); err != nil {
  389. return errors.Annotatef(err, "An error occurred while restore FuncCallExpr.Args[1]")
  390. }
  391. ctx.WritePlain(" ")
  392. if err := n.Args[2].Restore(ctx); err != nil {
  393. return errors.Annotatef(err, "An error occurred while restore FuncCallExpr.Args[2]")
  394. }
  395. case "extract":
  396. if err := n.Args[0].Restore(ctx); err != nil {
  397. return errors.Annotatef(err, "An error occurred while restore FuncCallExpr.Args[0]")
  398. }
  399. ctx.WriteKeyWord(" FROM ")
  400. if err := n.Args[1].Restore(ctx); err != nil {
  401. return errors.Annotatef(err, "An error occurred while restore FuncCallExpr.Args[1]")
  402. }
  403. case "position":
  404. if err := n.Args[0].Restore(ctx); err != nil {
  405. return errors.Annotatef(err, "An error occurred while restore FuncCallExpr")
  406. }
  407. ctx.WriteKeyWord(" IN ")
  408. if err := n.Args[1].Restore(ctx); err != nil {
  409. return errors.Annotatef(err, "An error occurred while restore FuncCallExpr")
  410. }
  411. case "trim":
  412. switch len(n.Args) {
  413. case 3:
  414. if err := n.Args[2].Restore(ctx); err != nil {
  415. return errors.Annotatef(err, "An error occurred while restore FuncCallExpr.Args[2]")
  416. }
  417. ctx.WritePlain(" ")
  418. fallthrough
  419. case 2:
  420. if expr, isValue := n.Args[1].(ValueExpr); !isValue || expr.GetValue() != nil {
  421. if err := n.Args[1].Restore(ctx); err != nil {
  422. return errors.Annotatef(err, "An error occurred while restore FuncCallExpr.Args[1]")
  423. }
  424. ctx.WritePlain(" ")
  425. }
  426. ctx.WriteKeyWord("FROM ")
  427. fallthrough
  428. case 1:
  429. if err := n.Args[0].Restore(ctx); err != nil {
  430. return errors.Annotatef(err, "An error occurred while restore FuncCallExpr.Args[0]")
  431. }
  432. }
  433. case WeightString:
  434. if err := n.Args[0].Restore(ctx); err != nil {
  435. return errors.Annotatef(err, "An error occurred while restore FuncCallExpr.(WEIGHT_STRING).Args[0]")
  436. }
  437. if len(n.Args) == 3 {
  438. ctx.WriteKeyWord(" AS ")
  439. ctx.WriteKeyWord(n.Args[1].(ValueExpr).GetValue().(string))
  440. ctx.WritePlain("(")
  441. if err := n.Args[2].Restore(ctx); err != nil {
  442. return errors.Annotatef(err, "An error occurred while restore FuncCallExpr.(WEIGHT_STRING).Args[2]")
  443. }
  444. ctx.WritePlain(")")
  445. }
  446. default:
  447. for i, argv := range n.Args {
  448. if i != 0 {
  449. ctx.WritePlain(", ")
  450. }
  451. if err := argv.Restore(ctx); err != nil {
  452. return errors.Annotatef(err, "An error occurred while restore FuncCallExpr.Args %d", i)
  453. }
  454. }
  455. }
  456. ctx.WritePlain(")")
  457. return nil
  458. }
  459. // Format the ExprNode into a Writer.
  460. func (n *FuncCallExpr) Format(w io.Writer) {
  461. fmt.Fprintf(w, "%s(", n.FnName.L)
  462. if !n.specialFormatArgs(w) {
  463. for i, arg := range n.Args {
  464. arg.Format(w)
  465. if i != len(n.Args)-1 {
  466. fmt.Fprint(w, ", ")
  467. }
  468. }
  469. }
  470. fmt.Fprint(w, ")")
  471. }
  472. // specialFormatArgs formats argument list for some special functions.
  473. func (n *FuncCallExpr) specialFormatArgs(w io.Writer) bool {
  474. switch n.FnName.L {
  475. case DateAdd, DateSub, AddDate, SubDate:
  476. n.Args[0].Format(w)
  477. fmt.Fprint(w, ", INTERVAL ")
  478. n.Args[1].Format(w)
  479. fmt.Fprint(w, " ")
  480. n.Args[2].Format(w)
  481. return true
  482. }
  483. return false
  484. }
  485. // Accept implements Node interface.
  486. func (n *FuncCallExpr) Accept(v Visitor) (Node, bool) {
  487. newNode, skipChildren := v.Enter(n)
  488. if skipChildren {
  489. return v.Leave(newNode)
  490. }
  491. n = newNode.(*FuncCallExpr)
  492. for i, val := range n.Args {
  493. node, ok := val.Accept(v)
  494. if !ok {
  495. return n, false
  496. }
  497. n.Args[i] = node.(ExprNode)
  498. }
  499. return v.Leave(n)
  500. }
  501. // CastFunctionType is the type for cast function.
  502. type CastFunctionType int
  503. // CastFunction types
  504. const (
  505. CastFunction CastFunctionType = iota + 1
  506. CastConvertFunction
  507. CastBinaryOperator
  508. )
  509. // FuncCastExpr is the cast function converting value to another type, e.g, cast(expr AS signed).
  510. // See https://dev.mysql.com/doc/refman/5.7/en/cast-functions.html
  511. type FuncCastExpr struct {
  512. funcNode
  513. // Expr is the expression to be converted.
  514. Expr ExprNode
  515. // Tp is the conversion type.
  516. Tp *types.FieldType
  517. // FunctionType is either Cast, Convert or Binary.
  518. FunctionType CastFunctionType
  519. // ExplicitCharSet is true when charset is explicit indicated.
  520. ExplicitCharSet bool
  521. }
  522. // Restore implements Node interface.
  523. func (n *FuncCastExpr) Restore(ctx *format.RestoreCtx) error {
  524. switch n.FunctionType {
  525. case CastFunction:
  526. ctx.WriteKeyWord("CAST")
  527. ctx.WritePlain("(")
  528. if err := n.Expr.Restore(ctx); err != nil {
  529. return errors.Annotatef(err, "An error occurred while restore FuncCastExpr.Expr")
  530. }
  531. ctx.WriteKeyWord(" AS ")
  532. n.Tp.RestoreAsCastType(ctx, n.ExplicitCharSet)
  533. ctx.WritePlain(")")
  534. case CastConvertFunction:
  535. ctx.WriteKeyWord("CONVERT")
  536. ctx.WritePlain("(")
  537. if err := n.Expr.Restore(ctx); err != nil {
  538. return errors.Annotatef(err, "An error occurred while restore FuncCastExpr.Expr")
  539. }
  540. ctx.WritePlain(", ")
  541. n.Tp.RestoreAsCastType(ctx, n.ExplicitCharSet)
  542. ctx.WritePlain(")")
  543. case CastBinaryOperator:
  544. ctx.WriteKeyWord("BINARY ")
  545. if err := n.Expr.Restore(ctx); err != nil {
  546. return errors.Annotatef(err, "An error occurred while restore FuncCastExpr.Expr")
  547. }
  548. }
  549. return nil
  550. }
  551. // Format the ExprNode into a Writer.
  552. func (n *FuncCastExpr) Format(w io.Writer) {
  553. switch n.FunctionType {
  554. case CastFunction:
  555. fmt.Fprint(w, "CAST(")
  556. n.Expr.Format(w)
  557. fmt.Fprint(w, " AS ")
  558. n.Tp.FormatAsCastType(w, n.ExplicitCharSet)
  559. fmt.Fprint(w, ")")
  560. case CastConvertFunction:
  561. fmt.Fprint(w, "CONVERT(")
  562. n.Expr.Format(w)
  563. fmt.Fprint(w, ", ")
  564. n.Tp.FormatAsCastType(w, n.ExplicitCharSet)
  565. fmt.Fprint(w, ")")
  566. case CastBinaryOperator:
  567. fmt.Fprint(w, "BINARY ")
  568. n.Expr.Format(w)
  569. }
  570. }
  571. // Accept implements Node Accept interface.
  572. func (n *FuncCastExpr) Accept(v Visitor) (Node, bool) {
  573. newNode, skipChildren := v.Enter(n)
  574. if skipChildren {
  575. return v.Leave(newNode)
  576. }
  577. n = newNode.(*FuncCastExpr)
  578. node, ok := n.Expr.Accept(v)
  579. if !ok {
  580. return n, false
  581. }
  582. n.Expr = node.(ExprNode)
  583. return v.Leave(n)
  584. }
  585. // TrimDirectionType is the type for trim direction.
  586. type TrimDirectionType int
  587. const (
  588. // TrimBothDefault trims from both direction by default.
  589. TrimBothDefault TrimDirectionType = iota
  590. // TrimBoth trims from both direction with explicit notation.
  591. TrimBoth
  592. // TrimLeading trims from left.
  593. TrimLeading
  594. // TrimTrailing trims from right.
  595. TrimTrailing
  596. )
  597. // String implements fmt.Stringer interface.
  598. func (direction TrimDirectionType) String() string {
  599. switch direction {
  600. case TrimBoth, TrimBothDefault:
  601. return "BOTH"
  602. case TrimLeading:
  603. return "LEADING"
  604. case TrimTrailing:
  605. return "TRAILING"
  606. default:
  607. return ""
  608. }
  609. }
  610. // TrimDirectionExpr is an expression representing the trim direction used in the TRIM() function.
  611. type TrimDirectionExpr struct {
  612. exprNode
  613. // Direction is the trim direction
  614. Direction TrimDirectionType
  615. }
  616. // Restore implements Node interface.
  617. func (n *TrimDirectionExpr) Restore(ctx *format.RestoreCtx) error {
  618. ctx.WriteKeyWord(n.Direction.String())
  619. return nil
  620. }
  621. // Format the ExprNode into a Writer.
  622. func (n *TrimDirectionExpr) Format(w io.Writer) {
  623. fmt.Fprint(w, n.Direction.String())
  624. }
  625. // Accept implements Node Accept interface.
  626. func (n *TrimDirectionExpr) Accept(v Visitor) (Node, bool) {
  627. newNode, skipChildren := v.Enter(n)
  628. if skipChildren {
  629. return v.Leave(newNode)
  630. }
  631. return v.Leave(n)
  632. }
  633. // DateArithType is type for DateArith type.
  634. type DateArithType byte
  635. const (
  636. // DateArithAdd is to run adddate or date_add function option.
  637. // See https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_adddate
  638. // See https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-add
  639. DateArithAdd DateArithType = iota + 1
  640. // DateArithSub is to run subdate or date_sub function option.
  641. // See https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_subdate
  642. // See https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-sub
  643. DateArithSub
  644. )
  645. const (
  646. // AggFuncCount is the name of Count function.
  647. AggFuncCount = "count"
  648. // AggFuncSum is the name of Sum function.
  649. AggFuncSum = "sum"
  650. // AggFuncAvg is the name of Avg function.
  651. AggFuncAvg = "avg"
  652. // AggFuncFirstRow is the name of FirstRowColumn function.
  653. AggFuncFirstRow = "firstrow"
  654. // AggFuncMax is the name of max function.
  655. AggFuncMax = "max"
  656. // AggFuncMin is the name of min function.
  657. AggFuncMin = "min"
  658. // AggFuncGroupConcat is the name of group_concat function.
  659. AggFuncGroupConcat = "group_concat"
  660. // AggFuncBitOr is the name of bit_or function.
  661. AggFuncBitOr = "bit_or"
  662. // AggFuncBitXor is the name of bit_xor function.
  663. AggFuncBitXor = "bit_xor"
  664. // AggFuncBitAnd is the name of bit_and function.
  665. AggFuncBitAnd = "bit_and"
  666. // AggFuncVarPop is the name of var_pop function
  667. AggFuncVarPop = "var_pop"
  668. // AggFuncVarSamp is the name of var_samp function
  669. AggFuncVarSamp = "var_samp"
  670. // AggFuncStddevPop is the name of stddev_pop/std/stddev function
  671. AggFuncStddevPop = "stddev_pop"
  672. // AggFuncStddevSamp is the name of stddev_samp function
  673. AggFuncStddevSamp = "stddev_samp"
  674. // AggFuncJsonArrayagg is the name of json_arrayagg function
  675. AggFuncJsonArrayagg = "json_arrayagg"
  676. // AggFuncJsonObjectAgg is the name of json_objectagg function
  677. AggFuncJsonObjectAgg = "json_objectagg"
  678. // AggFuncApproxCountDistinct is the name of approx_count_distinct function.
  679. AggFuncApproxCountDistinct = "approx_count_distinct"
  680. // AggFuncApproxPercentile is the name of approx_percentile function.
  681. AggFuncApproxPercentile = "approx_percentile"
  682. )
  683. // AggregateFuncExpr represents aggregate function expression.
  684. type AggregateFuncExpr struct {
  685. funcNode
  686. // F is the function name.
  687. F string
  688. // Args is the function args.
  689. Args []ExprNode
  690. // Distinct is true, function hence only aggregate distinct values.
  691. // For example, column c1 values are "1", "2", "2", "sum(c1)" is "5",
  692. // but "sum(distinct c1)" is "3".
  693. Distinct bool
  694. // Order is only used in GROUP_CONCAT
  695. Order *OrderByClause
  696. }
  697. // Restore implements Node interface.
  698. func (n *AggregateFuncExpr) Restore(ctx *format.RestoreCtx) error {
  699. ctx.WriteKeyWord(n.F)
  700. ctx.WritePlain("(")
  701. if n.Distinct {
  702. ctx.WriteKeyWord("DISTINCT ")
  703. }
  704. switch strings.ToLower(n.F) {
  705. case "group_concat":
  706. for i := 0; i < len(n.Args)-1; i++ {
  707. if i != 0 {
  708. ctx.WritePlain(", ")
  709. }
  710. if err := n.Args[i].Restore(ctx); err != nil {
  711. return errors.Annotatef(err, "An error occurred while restore AggregateFuncExpr.Args[%d]", i)
  712. }
  713. }
  714. if n.Order != nil {
  715. ctx.WritePlain(" ")
  716. if err := n.Order.Restore(ctx); err != nil {
  717. return errors.Annotate(err, "An error occur while restore AggregateFuncExpr.Args Order")
  718. }
  719. }
  720. ctx.WriteKeyWord(" SEPARATOR ")
  721. if err := n.Args[len(n.Args)-1].Restore(ctx); err != nil {
  722. return errors.Annotate(err, "An error occurred while restore AggregateFuncExpr.Args SEPARATOR")
  723. }
  724. default:
  725. for i, argv := range n.Args {
  726. if i != 0 {
  727. ctx.WritePlain(", ")
  728. }
  729. if err := argv.Restore(ctx); err != nil {
  730. return errors.Annotatef(err, "An error occurred while restore AggregateFuncExpr.Args[%d]", i)
  731. }
  732. }
  733. }
  734. ctx.WritePlain(")")
  735. return nil
  736. }
  737. // Format the ExprNode into a Writer.
  738. func (n *AggregateFuncExpr) Format(w io.Writer) {
  739. panic("Not implemented")
  740. }
  741. // Accept implements Node Accept interface.
  742. func (n *AggregateFuncExpr) Accept(v Visitor) (Node, bool) {
  743. newNode, skipChildren := v.Enter(n)
  744. if skipChildren {
  745. return v.Leave(newNode)
  746. }
  747. n = newNode.(*AggregateFuncExpr)
  748. for i, val := range n.Args {
  749. node, ok := val.Accept(v)
  750. if !ok {
  751. return n, false
  752. }
  753. n.Args[i] = node.(ExprNode)
  754. }
  755. if n.Order != nil {
  756. node, ok := n.Order.Accept(v)
  757. if !ok {
  758. return n, false
  759. }
  760. n.Order = node.(*OrderByClause)
  761. }
  762. return v.Leave(n)
  763. }
  764. const (
  765. // WindowFuncRowNumber is the name of row_number function.
  766. WindowFuncRowNumber = "row_number"
  767. // WindowFuncRank is the name of rank function.
  768. WindowFuncRank = "rank"
  769. // WindowFuncDenseRank is the name of dense_rank function.
  770. WindowFuncDenseRank = "dense_rank"
  771. // WindowFuncCumeDist is the name of cume_dist function.
  772. WindowFuncCumeDist = "cume_dist"
  773. // WindowFuncPercentRank is the name of percent_rank function.
  774. WindowFuncPercentRank = "percent_rank"
  775. // WindowFuncNtile is the name of ntile function.
  776. WindowFuncNtile = "ntile"
  777. // WindowFuncLead is the name of lead function.
  778. WindowFuncLead = "lead"
  779. // WindowFuncLag is the name of lag function.
  780. WindowFuncLag = "lag"
  781. // WindowFuncFirstValue is the name of first_value function.
  782. WindowFuncFirstValue = "first_value"
  783. // WindowFuncLastValue is the name of last_value function.
  784. WindowFuncLastValue = "last_value"
  785. // WindowFuncNthValue is the name of nth_value function.
  786. WindowFuncNthValue = "nth_value"
  787. )
  788. // WindowFuncExpr represents window function expression.
  789. type WindowFuncExpr struct {
  790. funcNode
  791. // F is the function name.
  792. F string
  793. // Args is the function args.
  794. Args []ExprNode
  795. // Distinct cannot be true for most window functions, except `max` and `min`.
  796. // We need to raise error if it is not allowed to be true.
  797. Distinct bool
  798. // IgnoreNull indicates how to handle null value.
  799. // MySQL only supports `RESPECT NULLS`, so we need to raise error if it is true.
  800. IgnoreNull bool
  801. // FromLast indicates the calculation direction of this window function.
  802. // MySQL only supports calculation from first, so we need to raise error if it is true.
  803. FromLast bool
  804. // Spec is the specification of this window.
  805. Spec WindowSpec
  806. }
  807. // Restore implements Node interface.
  808. func (n *WindowFuncExpr) Restore(ctx *format.RestoreCtx) error {
  809. ctx.WriteKeyWord(n.F)
  810. ctx.WritePlain("(")
  811. for i, v := range n.Args {
  812. if i != 0 {
  813. ctx.WritePlain(", ")
  814. } else if n.Distinct {
  815. ctx.WriteKeyWord("DISTINCT ")
  816. }
  817. if err := v.Restore(ctx); err != nil {
  818. return errors.Annotatef(err, "An error occurred while restore WindowFuncExpr.Args[%d]", i)
  819. }
  820. }
  821. ctx.WritePlain(")")
  822. if n.FromLast {
  823. ctx.WriteKeyWord(" FROM LAST")
  824. }
  825. if n.IgnoreNull {
  826. ctx.WriteKeyWord(" IGNORE NULLS")
  827. }
  828. ctx.WriteKeyWord(" OVER ")
  829. if err := n.Spec.Restore(ctx); err != nil {
  830. return errors.Annotate(err, "An error occurred while restore WindowFuncExpr.Spec")
  831. }
  832. return nil
  833. }
  834. // Format formats the window function expression into a Writer.
  835. func (n *WindowFuncExpr) Format(w io.Writer) {
  836. panic("Not implemented")
  837. }
  838. // Accept implements Node Accept interface.
  839. func (n *WindowFuncExpr) Accept(v Visitor) (Node, bool) {
  840. newNode, skipChildren := v.Enter(n)
  841. if skipChildren {
  842. return v.Leave(newNode)
  843. }
  844. n = newNode.(*WindowFuncExpr)
  845. for i, val := range n.Args {
  846. node, ok := val.Accept(v)
  847. if !ok {
  848. return n, false
  849. }
  850. n.Args[i] = node.(ExprNode)
  851. }
  852. node, ok := n.Spec.Accept(v)
  853. if !ok {
  854. return n, false
  855. }
  856. n.Spec = *node.(*WindowSpec)
  857. return v.Leave(n)
  858. }
  859. // TimeUnitType is the type for time and timestamp units.
  860. type TimeUnitType int
  861. const (
  862. // TimeUnitInvalid is a placeholder for an invalid time or timestamp unit
  863. TimeUnitInvalid TimeUnitType = iota
  864. // TimeUnitMicrosecond is the time or timestamp unit MICROSECOND.
  865. TimeUnitMicrosecond
  866. // TimeUnitSecond is the time or timestamp unit SECOND.
  867. TimeUnitSecond
  868. // TimeUnitMinute is the time or timestamp unit MINUTE.
  869. TimeUnitMinute
  870. // TimeUnitHour is the time or timestamp unit HOUR.
  871. TimeUnitHour
  872. // TimeUnitDay is the time or timestamp unit DAY.
  873. TimeUnitDay
  874. // TimeUnitWeek is the time or timestamp unit WEEK.
  875. TimeUnitWeek
  876. // TimeUnitMonth is the time or timestamp unit MONTH.
  877. TimeUnitMonth
  878. // TimeUnitQuarter is the time or timestamp unit QUARTER.
  879. TimeUnitQuarter
  880. // TimeUnitYear is the time or timestamp unit YEAR.
  881. TimeUnitYear
  882. // TimeUnitSecondMicrosecond is the time unit SECOND_MICROSECOND.
  883. TimeUnitSecondMicrosecond
  884. // TimeUnitMinuteMicrosecond is the time unit MINUTE_MICROSECOND.
  885. TimeUnitMinuteMicrosecond
  886. // TimeUnitMinuteSecond is the time unit MINUTE_SECOND.
  887. TimeUnitMinuteSecond
  888. // TimeUnitHourMicrosecond is the time unit HOUR_MICROSECOND.
  889. TimeUnitHourMicrosecond
  890. // TimeUnitHourSecond is the time unit HOUR_SECOND.
  891. TimeUnitHourSecond
  892. // TimeUnitHourMinute is the time unit HOUR_MINUTE.
  893. TimeUnitHourMinute
  894. // TimeUnitDayMicrosecond is the time unit DAY_MICROSECOND.
  895. TimeUnitDayMicrosecond
  896. // TimeUnitDaySecond is the time unit DAY_SECOND.
  897. TimeUnitDaySecond
  898. // TimeUnitDayMinute is the time unit DAY_MINUTE.
  899. TimeUnitDayMinute
  900. // TimeUnitDayHour is the time unit DAY_HOUR.
  901. TimeUnitDayHour
  902. // TimeUnitYearMonth is the time unit YEAR_MONTH.
  903. TimeUnitYearMonth
  904. )
  905. // String implements fmt.Stringer interface.
  906. func (unit TimeUnitType) String() string {
  907. switch unit {
  908. case TimeUnitMicrosecond:
  909. return "MICROSECOND"
  910. case TimeUnitSecond:
  911. return "SECOND"
  912. case TimeUnitMinute:
  913. return "MINUTE"
  914. case TimeUnitHour:
  915. return "HOUR"
  916. case TimeUnitDay:
  917. return "DAY"
  918. case TimeUnitWeek:
  919. return "WEEK"
  920. case TimeUnitMonth:
  921. return "MONTH"
  922. case TimeUnitQuarter:
  923. return "QUARTER"
  924. case TimeUnitYear:
  925. return "YEAR"
  926. case TimeUnitSecondMicrosecond:
  927. return "SECOND_MICROSECOND"
  928. case TimeUnitMinuteMicrosecond:
  929. return "MINUTE_MICROSECOND"
  930. case TimeUnitMinuteSecond:
  931. return "MINUTE_SECOND"
  932. case TimeUnitHourMicrosecond:
  933. return "HOUR_MICROSECOND"
  934. case TimeUnitHourSecond:
  935. return "HOUR_SECOND"
  936. case TimeUnitHourMinute:
  937. return "HOUR_MINUTE"
  938. case TimeUnitDayMicrosecond:
  939. return "DAY_MICROSECOND"
  940. case TimeUnitDaySecond:
  941. return "DAY_SECOND"
  942. case TimeUnitDayMinute:
  943. return "DAY_MINUTE"
  944. case TimeUnitDayHour:
  945. return "DAY_HOUR"
  946. case TimeUnitYearMonth:
  947. return "YEAR_MONTH"
  948. default:
  949. return ""
  950. }
  951. }
  952. // Duration represented by this unit.
  953. // Returns error if the time unit is not a fixed time interval (such as MONTH)
  954. // or a composite unit (such as MINUTE_SECOND).
  955. func (unit TimeUnitType) Duration() (time.Duration, error) {
  956. switch unit {
  957. case TimeUnitMicrosecond:
  958. return time.Microsecond, nil
  959. case TimeUnitSecond:
  960. return time.Second, nil
  961. case TimeUnitMinute:
  962. return time.Minute, nil
  963. case TimeUnitHour:
  964. return time.Hour, nil
  965. case TimeUnitDay:
  966. return time.Hour * 24, nil
  967. case TimeUnitWeek:
  968. return time.Hour * 24 * 7, nil
  969. case TimeUnitMonth, TimeUnitQuarter, TimeUnitYear:
  970. return 0, errors.Errorf("%s is not a constant time interval and cannot be used here", unit)
  971. default:
  972. return 0, errors.Errorf("%s is a composite time unit and is not supported yet", unit)
  973. }
  974. }
  975. // TimeUnitExpr is an expression representing a time or timestamp unit.
  976. type TimeUnitExpr struct {
  977. exprNode
  978. // Unit is the time or timestamp unit.
  979. Unit TimeUnitType
  980. }
  981. // Restore implements Node interface.
  982. func (n *TimeUnitExpr) Restore(ctx *format.RestoreCtx) error {
  983. ctx.WriteKeyWord(n.Unit.String())
  984. return nil
  985. }
  986. // Format the ExprNode into a Writer.
  987. func (n *TimeUnitExpr) Format(w io.Writer) {
  988. fmt.Fprint(w, n.Unit.String())
  989. }
  990. // Accept implements Node Accept interface.
  991. func (n *TimeUnitExpr) Accept(v Visitor) (Node, bool) {
  992. newNode, skipChildren := v.Enter(n)
  993. if skipChildren {
  994. return v.Leave(newNode)
  995. }
  996. return v.Leave(n)
  997. }
  998. // GetFormatSelectorType is the type for the first argument of GET_FORMAT() function.
  999. type GetFormatSelectorType int
  1000. const (
  1001. // GetFormatSelectorDate is the GET_FORMAT selector DATE.
  1002. GetFormatSelectorDate GetFormatSelectorType = iota + 1
  1003. // GetFormatSelectorTime is the GET_FORMAT selector TIME.
  1004. GetFormatSelectorTime
  1005. // GetFormatSelectorDatetime is the GET_FORMAT selector DATETIME and TIMESTAMP.
  1006. GetFormatSelectorDatetime
  1007. )
  1008. // GetFormatSelectorExpr is an expression used as the first argument of GET_FORMAT() function.
  1009. type GetFormatSelectorExpr struct {
  1010. exprNode
  1011. // Selector is the GET_FORMAT() selector.
  1012. Selector GetFormatSelectorType
  1013. }
  1014. // String implements fmt.Stringer interface.
  1015. func (selector GetFormatSelectorType) String() string {
  1016. switch selector {
  1017. case GetFormatSelectorDate:
  1018. return "DATE"
  1019. case GetFormatSelectorTime:
  1020. return "TIME"
  1021. case GetFormatSelectorDatetime:
  1022. return "DATETIME"
  1023. default:
  1024. return ""
  1025. }
  1026. }
  1027. // Restore implements Node interface.
  1028. func (n *GetFormatSelectorExpr) Restore(ctx *format.RestoreCtx) error {
  1029. ctx.WriteKeyWord(n.Selector.String())
  1030. return nil
  1031. }
  1032. // Format the ExprNode into a Writer.
  1033. func (n *GetFormatSelectorExpr) Format(w io.Writer) {
  1034. fmt.Fprint(w, n.Selector.String())
  1035. }
  1036. // Accept implements Node Accept interface.
  1037. func (n *GetFormatSelectorExpr) Accept(v Visitor) (Node, bool) {
  1038. newNode, skipChildren := v.Enter(n)
  1039. if skipChildren {
  1040. return v.Leave(newNode)
  1041. }
  1042. return v.Leave(n)
  1043. }