/vendor/github.com/influxdb/influxdb/influxql/ast.go

https://gitlab.com/github-cloud-corporation/bootkube · Go · 1743 lines · 1216 code · 250 blank · 277 comment · 232 complexity · b102a21efe61014f0ee1bca4913cbfa2 MD5 · raw file

  1. package influxql
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "regexp"
  7. "sort"
  8. "strconv"
  9. "strings"
  10. "time"
  11. )
  12. // DataType represents the primitive data types available in InfluxQL.
  13. type DataType int
  14. const (
  15. // Unknown primitive data type.
  16. Unknown DataType = 0
  17. // Float means the data type is a float
  18. Float = 1
  19. // Integer means the data type is a integer
  20. Integer = 2
  21. // Boolean means the data type is a boolean.
  22. Boolean = 3
  23. // String means the data type is a string of text.
  24. String = 4
  25. // Time means the data type is a time.
  26. Time = 5
  27. // Duration means the data type is a duration of time.
  28. Duration = 6
  29. )
  30. // InspectDataType returns the data type of a given value.
  31. func InspectDataType(v interface{}) DataType {
  32. switch v.(type) {
  33. case float64:
  34. return Float
  35. case int64, int32, int:
  36. return Integer
  37. case bool:
  38. return Boolean
  39. case string:
  40. return String
  41. case time.Time:
  42. return Time
  43. case time.Duration:
  44. return Duration
  45. default:
  46. return Unknown
  47. }
  48. }
  49. func (d DataType) String() string {
  50. switch d {
  51. case Float:
  52. return "float"
  53. case Integer:
  54. return "integer"
  55. case Boolean:
  56. return "boolean"
  57. case String:
  58. return "string"
  59. case Time:
  60. return "time"
  61. case Duration:
  62. return "duration"
  63. }
  64. return "unknown"
  65. }
  66. // Node represents a node in the InfluxDB abstract syntax tree.
  67. type Node interface {
  68. node()
  69. String() string
  70. }
  71. func (*Query) node() {}
  72. func (Statements) node() {}
  73. func (*AlterRetentionPolicyStatement) node() {}
  74. func (*CreateContinuousQueryStatement) node() {}
  75. func (*CreateDatabaseStatement) node() {}
  76. func (*CreateRetentionPolicyStatement) node() {}
  77. func (*CreateUserStatement) node() {}
  78. func (*Distinct) node() {}
  79. func (*DeleteStatement) node() {}
  80. func (*DropContinuousQueryStatement) node() {}
  81. func (*DropDatabaseStatement) node() {}
  82. func (*DropMeasurementStatement) node() {}
  83. func (*DropRetentionPolicyStatement) node() {}
  84. func (*DropSeriesStatement) node() {}
  85. func (*DropUserStatement) node() {}
  86. func (*GrantStatement) node() {}
  87. func (*GrantAdminStatement) node() {}
  88. func (*RevokeStatement) node() {}
  89. func (*RevokeAdminStatement) node() {}
  90. func (*SelectStatement) node() {}
  91. func (*SetPasswordUserStatement) node() {}
  92. func (*ShowContinuousQueriesStatement) node() {}
  93. func (*ShowGrantsForUserStatement) node() {}
  94. func (*ShowServersStatement) node() {}
  95. func (*ShowDatabasesStatement) node() {}
  96. func (*ShowFieldKeysStatement) node() {}
  97. func (*ShowRetentionPoliciesStatement) node() {}
  98. func (*ShowMeasurementsStatement) node() {}
  99. func (*ShowSeriesStatement) node() {}
  100. func (*ShowStatsStatement) node() {}
  101. func (*ShowDiagnosticsStatement) node() {}
  102. func (*ShowTagKeysStatement) node() {}
  103. func (*ShowTagValuesStatement) node() {}
  104. func (*ShowUsersStatement) node() {}
  105. func (*BinaryExpr) node() {}
  106. func (*BooleanLiteral) node() {}
  107. func (*Call) node() {}
  108. func (*Dimension) node() {}
  109. func (Dimensions) node() {}
  110. func (*DurationLiteral) node() {}
  111. func (*Field) node() {}
  112. func (Fields) node() {}
  113. func (*Measurement) node() {}
  114. func (Measurements) node() {}
  115. func (*nilLiteral) node() {}
  116. func (*NumberLiteral) node() {}
  117. func (*ParenExpr) node() {}
  118. func (*RegexLiteral) node() {}
  119. func (*SortField) node() {}
  120. func (SortFields) node() {}
  121. func (Sources) node() {}
  122. func (*StringLiteral) node() {}
  123. func (*Target) node() {}
  124. func (*TimeLiteral) node() {}
  125. func (*VarRef) node() {}
  126. func (*Wildcard) node() {}
  127. // Query represents a collection of ordered statements.
  128. type Query struct {
  129. Statements Statements
  130. }
  131. // String returns a string representation of the query.
  132. func (q *Query) String() string { return q.Statements.String() }
  133. // Statements represents a list of statements.
  134. type Statements []Statement
  135. // String returns a string representation of the statements.
  136. func (a Statements) String() string {
  137. var str []string
  138. for _, stmt := range a {
  139. str = append(str, stmt.String())
  140. }
  141. return strings.Join(str, ";\n")
  142. }
  143. // Statement represents a single command in InfluxQL.
  144. type Statement interface {
  145. Node
  146. stmt()
  147. RequiredPrivileges() ExecutionPrivileges
  148. }
  149. // HasDefaultDatabase provides an interface to get the default database from a Statement.
  150. type HasDefaultDatabase interface {
  151. Node
  152. stmt()
  153. DefaultDatabase() string
  154. }
  155. // ExecutionPrivilege is a privilege required for a user to execute
  156. // a statement on a database or resource.
  157. type ExecutionPrivilege struct {
  158. // Admin privilege required.
  159. Admin bool
  160. // Name of the database.
  161. Name string
  162. // Database privilege required.
  163. Privilege Privilege
  164. }
  165. // ExecutionPrivileges is a list of privileges required to execute a statement.
  166. type ExecutionPrivileges []ExecutionPrivilege
  167. func (*AlterRetentionPolicyStatement) stmt() {}
  168. func (*CreateContinuousQueryStatement) stmt() {}
  169. func (*CreateDatabaseStatement) stmt() {}
  170. func (*CreateRetentionPolicyStatement) stmt() {}
  171. func (*CreateUserStatement) stmt() {}
  172. func (*DeleteStatement) stmt() {}
  173. func (*DropContinuousQueryStatement) stmt() {}
  174. func (*DropDatabaseStatement) stmt() {}
  175. func (*DropMeasurementStatement) stmt() {}
  176. func (*DropRetentionPolicyStatement) stmt() {}
  177. func (*DropSeriesStatement) stmt() {}
  178. func (*DropUserStatement) stmt() {}
  179. func (*GrantStatement) stmt() {}
  180. func (*GrantAdminStatement) stmt() {}
  181. func (*ShowContinuousQueriesStatement) stmt() {}
  182. func (*ShowGrantsForUserStatement) stmt() {}
  183. func (*ShowServersStatement) stmt() {}
  184. func (*ShowDatabasesStatement) stmt() {}
  185. func (*ShowFieldKeysStatement) stmt() {}
  186. func (*ShowMeasurementsStatement) stmt() {}
  187. func (*ShowRetentionPoliciesStatement) stmt() {}
  188. func (*ShowSeriesStatement) stmt() {}
  189. func (*ShowStatsStatement) stmt() {}
  190. func (*ShowDiagnosticsStatement) stmt() {}
  191. func (*ShowTagKeysStatement) stmt() {}
  192. func (*ShowTagValuesStatement) stmt() {}
  193. func (*ShowUsersStatement) stmt() {}
  194. func (*RevokeStatement) stmt() {}
  195. func (*RevokeAdminStatement) stmt() {}
  196. func (*SelectStatement) stmt() {}
  197. func (*SetPasswordUserStatement) stmt() {}
  198. // Expr represents an expression that can be evaluated to a value.
  199. type Expr interface {
  200. Node
  201. expr()
  202. }
  203. func (*BinaryExpr) expr() {}
  204. func (*BooleanLiteral) expr() {}
  205. func (*Call) expr() {}
  206. func (*Distinct) expr() {}
  207. func (*DurationLiteral) expr() {}
  208. func (*nilLiteral) expr() {}
  209. func (*NumberLiteral) expr() {}
  210. func (*ParenExpr) expr() {}
  211. func (*RegexLiteral) expr() {}
  212. func (*StringLiteral) expr() {}
  213. func (*TimeLiteral) expr() {}
  214. func (*VarRef) expr() {}
  215. func (*Wildcard) expr() {}
  216. // Source represents a source of data for a statement.
  217. type Source interface {
  218. Node
  219. source()
  220. }
  221. func (*Measurement) source() {}
  222. // Sources represents a list of sources.
  223. type Sources []Source
  224. // String returns a string representation of a Sources array.
  225. func (a Sources) String() string {
  226. var buf bytes.Buffer
  227. ubound := len(a) - 1
  228. for i, src := range a {
  229. _, _ = buf.WriteString(src.String())
  230. if i < ubound {
  231. _, _ = buf.WriteString(", ")
  232. }
  233. }
  234. return buf.String()
  235. }
  236. // SortField represents a field to sort results by.
  237. type SortField struct {
  238. // Name of the field
  239. Name string
  240. // Sort order.
  241. Ascending bool
  242. }
  243. // String returns a string representation of a sort field
  244. func (field *SortField) String() string {
  245. var buf bytes.Buffer
  246. if field.Name == "" {
  247. _, _ = buf.WriteString(field.Name)
  248. _, _ = buf.WriteString(" ")
  249. }
  250. if field.Ascending {
  251. _, _ = buf.WriteString("ASC")
  252. } else {
  253. _, _ = buf.WriteString("DESC")
  254. }
  255. return buf.String()
  256. }
  257. // SortFields represents an ordered list of ORDER BY fields
  258. type SortFields []*SortField
  259. // String returns a string representation of sort fields
  260. func (a SortFields) String() string {
  261. fields := make([]string, 0, len(a))
  262. for _, field := range a {
  263. fields = append(fields, field.String())
  264. }
  265. return strings.Join(fields, ", ")
  266. }
  267. // CreateDatabaseStatement represents a command for creating a new database.
  268. type CreateDatabaseStatement struct {
  269. // Name of the database to be created.
  270. Name string
  271. }
  272. // String returns a string representation of the create database statement.
  273. func (s *CreateDatabaseStatement) String() string {
  274. var buf bytes.Buffer
  275. _, _ = buf.WriteString("CREATE DATABASE ")
  276. _, _ = buf.WriteString(s.Name)
  277. return buf.String()
  278. }
  279. // RequiredPrivileges returns the privilege required to execute a CreateDatabaseStatement.
  280. func (s *CreateDatabaseStatement) RequiredPrivileges() ExecutionPrivileges {
  281. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}
  282. }
  283. // DropDatabaseStatement represents a command to drop a database.
  284. type DropDatabaseStatement struct {
  285. // Name of the database to be dropped.
  286. Name string
  287. }
  288. // String returns a string representation of the drop database statement.
  289. func (s *DropDatabaseStatement) String() string {
  290. var buf bytes.Buffer
  291. _, _ = buf.WriteString("DROP DATABASE ")
  292. _, _ = buf.WriteString(s.Name)
  293. return buf.String()
  294. }
  295. // RequiredPrivileges returns the privilege required to execute a DropDatabaseStatement.
  296. func (s *DropDatabaseStatement) RequiredPrivileges() ExecutionPrivileges {
  297. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}
  298. }
  299. // DropRetentionPolicyStatement represents a command to drop a retention policy from a database.
  300. type DropRetentionPolicyStatement struct {
  301. // Name of the policy to drop.
  302. Name string
  303. // Name of the database to drop the policy from.
  304. Database string
  305. }
  306. // String returns a string representation of the drop retention policy statement.
  307. func (s *DropRetentionPolicyStatement) String() string {
  308. var buf bytes.Buffer
  309. _, _ = buf.WriteString("DROP RETENTION POLICY ")
  310. _, _ = buf.WriteString(s.Name)
  311. _, _ = buf.WriteString(" ON ")
  312. _, _ = buf.WriteString(s.Database)
  313. return buf.String()
  314. }
  315. // RequiredPrivileges returns the privilege required to execute a DropRetentionPolicyStatement.
  316. func (s *DropRetentionPolicyStatement) RequiredPrivileges() ExecutionPrivileges {
  317. return ExecutionPrivileges{{Admin: false, Name: s.Database, Privilege: WritePrivilege}}
  318. }
  319. // CreateUserStatement represents a command for creating a new user.
  320. type CreateUserStatement struct {
  321. // Name of the user to be created.
  322. Name string
  323. // User's password.
  324. Password string
  325. // User's admin privilege.
  326. Admin bool
  327. }
  328. // String returns a string representation of the create user statement.
  329. func (s *CreateUserStatement) String() string {
  330. var buf bytes.Buffer
  331. _, _ = buf.WriteString("CREATE USER ")
  332. _, _ = buf.WriteString(s.Name)
  333. _, _ = buf.WriteString(" WITH PASSWORD ")
  334. _, _ = buf.WriteString("[REDACTED]")
  335. if s.Admin {
  336. _, _ = buf.WriteString(" WITH ALL PRIVILEGES")
  337. }
  338. return buf.String()
  339. }
  340. // RequiredPrivileges returns the privilege(s) required to execute a CreateUserStatement.
  341. func (s *CreateUserStatement) RequiredPrivileges() ExecutionPrivileges {
  342. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}
  343. }
  344. // DropUserStatement represents a command for dropping a user.
  345. type DropUserStatement struct {
  346. // Name of the user to drop.
  347. Name string
  348. }
  349. // String returns a string representation of the drop user statement.
  350. func (s *DropUserStatement) String() string {
  351. var buf bytes.Buffer
  352. _, _ = buf.WriteString("DROP USER ")
  353. _, _ = buf.WriteString(s.Name)
  354. return buf.String()
  355. }
  356. // RequiredPrivileges returns the privilege(s) required to execute a DropUserStatement.
  357. func (s *DropUserStatement) RequiredPrivileges() ExecutionPrivileges {
  358. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}
  359. }
  360. // Privilege is a type of action a user can be granted the right to use.
  361. type Privilege int
  362. const (
  363. // NoPrivileges means no privileges required / granted / revoked.
  364. NoPrivileges Privilege = iota
  365. // ReadPrivilege means read privilege required / granted / revoked.
  366. ReadPrivilege
  367. // WritePrivilege means write privilege required / granted / revoked.
  368. WritePrivilege
  369. // AllPrivileges means all privileges required / granted / revoked.
  370. AllPrivileges
  371. )
  372. // NewPrivilege returns an initialized *Privilege.
  373. func NewPrivilege(p Privilege) *Privilege { return &p }
  374. // String returns a string representation of a Privilege.
  375. func (p Privilege) String() string {
  376. switch p {
  377. case NoPrivileges:
  378. return "NO PRIVILEGES"
  379. case ReadPrivilege:
  380. return "READ"
  381. case WritePrivilege:
  382. return "WRITE"
  383. case AllPrivileges:
  384. return "ALL PRIVILEGES"
  385. }
  386. return ""
  387. }
  388. // GrantStatement represents a command for granting a privilege.
  389. type GrantStatement struct {
  390. // The privilege to be granted.
  391. Privilege Privilege
  392. // Database to grant the privilege to.
  393. On string
  394. // Who to grant the privilege to.
  395. User string
  396. }
  397. // String returns a string representation of the grant statement.
  398. func (s *GrantStatement) String() string {
  399. var buf bytes.Buffer
  400. _, _ = buf.WriteString("GRANT ")
  401. _, _ = buf.WriteString(s.Privilege.String())
  402. _, _ = buf.WriteString(" ON ")
  403. _, _ = buf.WriteString(s.On)
  404. _, _ = buf.WriteString(" TO ")
  405. _, _ = buf.WriteString(s.User)
  406. return buf.String()
  407. }
  408. // RequiredPrivileges returns the privilege required to execute a GrantStatement.
  409. func (s *GrantStatement) RequiredPrivileges() ExecutionPrivileges {
  410. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}
  411. }
  412. // GrantAdminStatement represents a command for granting admin privilege.
  413. type GrantAdminStatement struct {
  414. // Who to grant the privilege to.
  415. User string
  416. }
  417. // String returns a string representation of the grant admin statement.
  418. func (s *GrantAdminStatement) String() string {
  419. var buf bytes.Buffer
  420. _, _ = buf.WriteString("GRANT ALL PRIVILEGES TO ")
  421. _, _ = buf.WriteString(s.User)
  422. return buf.String()
  423. }
  424. // RequiredPrivileges returns the privilege required to execute a GrantAdminStatement.
  425. func (s *GrantAdminStatement) RequiredPrivileges() ExecutionPrivileges {
  426. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}
  427. }
  428. // SetPasswordUserStatement represents a command for changing user password.
  429. type SetPasswordUserStatement struct {
  430. // Plain Password
  431. Password string
  432. // Who to grant the privilege to.
  433. Name string
  434. }
  435. // String returns a string representation of the set password statement.
  436. func (s *SetPasswordUserStatement) String() string {
  437. var buf bytes.Buffer
  438. _, _ = buf.WriteString("SET PASSWORD FOR ")
  439. _, _ = buf.WriteString(s.Name)
  440. _, _ = buf.WriteString(" = ")
  441. _, _ = buf.WriteString("[REDACTED]")
  442. return buf.String()
  443. }
  444. // RequiredPrivileges returns the privilege required to execute a SetPasswordUserStatement.
  445. func (s *SetPasswordUserStatement) RequiredPrivileges() ExecutionPrivileges {
  446. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}
  447. }
  448. // RevokeStatement represents a command to revoke a privilege from a user.
  449. type RevokeStatement struct {
  450. // The privilege to be revoked.
  451. Privilege Privilege
  452. // Database to revoke the privilege from.
  453. On string
  454. // Who to revoke privilege from.
  455. User string
  456. }
  457. // String returns a string representation of the revoke statement.
  458. func (s *RevokeStatement) String() string {
  459. var buf bytes.Buffer
  460. _, _ = buf.WriteString("REVOKE ")
  461. _, _ = buf.WriteString(s.Privilege.String())
  462. _, _ = buf.WriteString(" ON ")
  463. _, _ = buf.WriteString(s.On)
  464. _, _ = buf.WriteString(" FROM ")
  465. _, _ = buf.WriteString(s.User)
  466. return buf.String()
  467. }
  468. // RequiredPrivileges returns the privilege required to execute a RevokeStatement.
  469. func (s *RevokeStatement) RequiredPrivileges() ExecutionPrivileges {
  470. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}
  471. }
  472. // RevokeAdminStatement represents a command to revoke admin privilege from a user.
  473. type RevokeAdminStatement struct {
  474. // Who to revoke admin privilege from.
  475. User string
  476. }
  477. // String returns a string representation of the revoke admin statement.
  478. func (s *RevokeAdminStatement) String() string {
  479. var buf bytes.Buffer
  480. _, _ = buf.WriteString("REVOKE ALL PRIVILEGES FROM ")
  481. _, _ = buf.WriteString(s.User)
  482. return buf.String()
  483. }
  484. // RequiredPrivileges returns the privilege required to execute a RevokeAdminStatement.
  485. func (s *RevokeAdminStatement) RequiredPrivileges() ExecutionPrivileges {
  486. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}
  487. }
  488. // CreateRetentionPolicyStatement represents a command to create a retention policy.
  489. type CreateRetentionPolicyStatement struct {
  490. // Name of policy to create.
  491. Name string
  492. // Name of database this policy belongs to.
  493. Database string
  494. // Duration data written to this policy will be retained.
  495. Duration time.Duration
  496. // Replication factor for data written to this policy.
  497. Replication int
  498. // Should this policy be set as default for the database?
  499. Default bool
  500. }
  501. // String returns a string representation of the create retention policy.
  502. func (s *CreateRetentionPolicyStatement) String() string {
  503. var buf bytes.Buffer
  504. _, _ = buf.WriteString("CREATE RETENTION POLICY ")
  505. _, _ = buf.WriteString(s.Name)
  506. _, _ = buf.WriteString(" ON ")
  507. _, _ = buf.WriteString(s.Database)
  508. _, _ = buf.WriteString(" DURATION ")
  509. _, _ = buf.WriteString(FormatDuration(s.Duration))
  510. _, _ = buf.WriteString(" REPLICATION ")
  511. _, _ = buf.WriteString(strconv.Itoa(s.Replication))
  512. if s.Default {
  513. _, _ = buf.WriteString(" DEFAULT")
  514. }
  515. return buf.String()
  516. }
  517. // RequiredPrivileges returns the privilege required to execute a CreateRetentionPolicyStatement.
  518. func (s *CreateRetentionPolicyStatement) RequiredPrivileges() ExecutionPrivileges {
  519. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}
  520. }
  521. // AlterRetentionPolicyStatement represents a command to alter an existing retention policy.
  522. type AlterRetentionPolicyStatement struct {
  523. // Name of policy to alter.
  524. Name string
  525. // Name of the database this policy belongs to.
  526. Database string
  527. // Duration data written to this policy will be retained.
  528. Duration *time.Duration
  529. // Replication factor for data written to this policy.
  530. Replication *int
  531. // Should this policy be set as defalut for the database?
  532. Default bool
  533. }
  534. // String returns a string representation of the alter retention policy statement.
  535. func (s *AlterRetentionPolicyStatement) String() string {
  536. var buf bytes.Buffer
  537. _, _ = buf.WriteString("ALTER RETENTION POLICY ")
  538. _, _ = buf.WriteString(s.Name)
  539. _, _ = buf.WriteString(" ON ")
  540. _, _ = buf.WriteString(s.Database)
  541. if s.Duration != nil {
  542. _, _ = buf.WriteString(" DURATION ")
  543. _, _ = buf.WriteString(FormatDuration(*s.Duration))
  544. }
  545. if s.Replication != nil {
  546. _, _ = buf.WriteString(" REPLICATION ")
  547. _, _ = buf.WriteString(strconv.Itoa(*s.Replication))
  548. }
  549. if s.Default {
  550. _, _ = buf.WriteString(" DEFAULT")
  551. }
  552. return buf.String()
  553. }
  554. // RequiredPrivileges returns the privilege required to execute an AlterRetentionPolicyStatement.
  555. func (s *AlterRetentionPolicyStatement) RequiredPrivileges() ExecutionPrivileges {
  556. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}
  557. }
  558. type FillOption int
  559. const (
  560. // NullFill means that empty aggregate windows will just have null values.
  561. NullFill FillOption = iota
  562. // NoFill means that empty aggregate windows will be purged from the result.
  563. NoFill
  564. // NumberFill means that empty aggregate windows will be filled with the given number
  565. NumberFill
  566. // PreviousFill means that empty aggregate windows will be filled with whatever the previous aggregate window had
  567. PreviousFill
  568. )
  569. // SelectStatement represents a command for extracting data from the database.
  570. type SelectStatement struct {
  571. // Expressions returned from the selection.
  572. Fields Fields
  573. // Target (destination) for the result of the select.
  574. Target *Target
  575. // Expressions used for grouping the selection.
  576. Dimensions Dimensions
  577. // Data sources that fields are extracted from.
  578. Sources Sources
  579. // An expression evaluated on data point.
  580. Condition Expr
  581. // Fields to sort results by
  582. SortFields SortFields
  583. // Maximum number of rows to be returned. Unlimited if zero.
  584. Limit int
  585. // Returns rows starting at an offset from the first row.
  586. Offset int
  587. // Maxiumum number of series to be returned. Unlimited if zero.
  588. SLimit int
  589. // Returns series starting at an offset from the first one.
  590. SOffset int
  591. // memoize the group by interval
  592. groupByInterval time.Duration
  593. // if it's a query for raw data values (i.e. not an aggregate)
  594. IsRawQuery bool
  595. // What fill option the select statement uses, if any
  596. Fill FillOption
  597. // The value to fill empty aggregate buckets with, if any
  598. FillValue interface{}
  599. }
  600. // HasDerivative returns true if one of the function calls in the statement is a
  601. // derivative aggregate
  602. func (s *SelectStatement) HasDerivative() bool {
  603. for _, f := range s.FunctionCalls() {
  604. if strings.HasSuffix(f.Name, "derivative") {
  605. return true
  606. }
  607. }
  608. return false
  609. }
  610. // IsSimpleDerivative return true if one of the function call is a derivative function with a
  611. // variable ref as the first arg
  612. func (s *SelectStatement) IsSimpleDerivative() bool {
  613. for _, f := range s.FunctionCalls() {
  614. if strings.HasSuffix(f.Name, "derivative") {
  615. // it's nested if the first argument is an aggregate function
  616. if _, ok := f.Args[0].(*VarRef); ok {
  617. return true
  618. }
  619. }
  620. }
  621. return false
  622. }
  623. // Clone returns a deep copy of the statement.
  624. func (s *SelectStatement) Clone() *SelectStatement {
  625. clone := &SelectStatement{
  626. Fields: make(Fields, 0, len(s.Fields)),
  627. Dimensions: make(Dimensions, 0, len(s.Dimensions)),
  628. Sources: cloneSources(s.Sources),
  629. SortFields: make(SortFields, 0, len(s.SortFields)),
  630. Condition: CloneExpr(s.Condition),
  631. Limit: s.Limit,
  632. Offset: s.Offset,
  633. SLimit: s.SLimit,
  634. SOffset: s.SOffset,
  635. Fill: s.Fill,
  636. FillValue: s.FillValue,
  637. IsRawQuery: s.IsRawQuery,
  638. }
  639. if s.Target != nil {
  640. clone.Target = &Target{
  641. Measurement: &Measurement{
  642. Database: s.Target.Measurement.Database,
  643. RetentionPolicy: s.Target.Measurement.RetentionPolicy,
  644. Name: s.Target.Measurement.Name,
  645. Regex: CloneRegexLiteral(s.Target.Measurement.Regex),
  646. },
  647. }
  648. }
  649. for _, f := range s.Fields {
  650. clone.Fields = append(clone.Fields, &Field{Expr: CloneExpr(f.Expr), Alias: f.Alias})
  651. }
  652. for _, d := range s.Dimensions {
  653. clone.Dimensions = append(clone.Dimensions, &Dimension{Expr: CloneExpr(d.Expr)})
  654. }
  655. for _, f := range s.SortFields {
  656. clone.SortFields = append(clone.SortFields, &SortField{Name: f.Name, Ascending: f.Ascending})
  657. }
  658. return clone
  659. }
  660. func cloneSources(sources Sources) Sources {
  661. clone := make(Sources, 0, len(sources))
  662. for _, s := range sources {
  663. clone = append(clone, cloneSource(s))
  664. }
  665. return clone
  666. }
  667. func cloneSource(s Source) Source {
  668. if s == nil {
  669. return nil
  670. }
  671. switch s := s.(type) {
  672. case *Measurement:
  673. m := &Measurement{Database: s.Database, RetentionPolicy: s.RetentionPolicy, Name: s.Name}
  674. if s.Regex != nil {
  675. m.Regex = &RegexLiteral{Val: regexp.MustCompile(s.Regex.Val.String())}
  676. }
  677. return m
  678. default:
  679. panic("unreachable")
  680. }
  681. }
  682. // RewriteWildcards returns the re-written form of the select statement. Any wildcard query
  683. // fields are replaced with the supplied fields, and any wildcard GROUP BY fields are replaced
  684. // with the supplied dimensions.
  685. func (s *SelectStatement) RewriteWildcards(fields Fields, dimensions Dimensions) *SelectStatement {
  686. other := s.Clone()
  687. selectWildcard, groupWildcard := false, false
  688. // Rewrite all wildcard query fields
  689. rwFields := make(Fields, 0, len(s.Fields))
  690. for _, f := range s.Fields {
  691. switch f.Expr.(type) {
  692. case *Wildcard:
  693. // Sort wildcard fields for consistent output
  694. sort.Sort(fields)
  695. rwFields = append(rwFields, fields...)
  696. selectWildcard = true
  697. default:
  698. rwFields = append(rwFields, f)
  699. }
  700. }
  701. other.Fields = rwFields
  702. // Rewrite all wildcard GROUP BY fields
  703. rwDimensions := make(Dimensions, 0, len(s.Dimensions))
  704. for _, d := range s.Dimensions {
  705. switch d.Expr.(type) {
  706. case *Wildcard:
  707. rwDimensions = append(rwDimensions, dimensions...)
  708. groupWildcard = true
  709. default:
  710. rwDimensions = append(rwDimensions, d)
  711. }
  712. }
  713. if selectWildcard && !groupWildcard {
  714. rwDimensions = append(rwDimensions, dimensions...)
  715. }
  716. other.Dimensions = rwDimensions
  717. return other
  718. }
  719. // RewriteDistinct rewrites the expression to be a call for map/reduce to work correctly
  720. // This method assumes all validation has passed
  721. func (s *SelectStatement) RewriteDistinct() {
  722. for i, f := range s.Fields {
  723. if d, ok := f.Expr.(*Distinct); ok {
  724. s.Fields[i].Expr = d.NewCall()
  725. s.IsRawQuery = false
  726. }
  727. }
  728. }
  729. // String returns a string representation of the select statement.
  730. func (s *SelectStatement) String() string {
  731. var buf bytes.Buffer
  732. _, _ = buf.WriteString("SELECT ")
  733. _, _ = buf.WriteString(s.Fields.String())
  734. if s.Target != nil {
  735. _, _ = buf.WriteString(" ")
  736. _, _ = buf.WriteString(s.Target.String())
  737. }
  738. if len(s.Sources) > 0 {
  739. _, _ = buf.WriteString(" FROM ")
  740. _, _ = buf.WriteString(s.Sources.String())
  741. }
  742. if s.Condition != nil {
  743. _, _ = buf.WriteString(" WHERE ")
  744. _, _ = buf.WriteString(s.Condition.String())
  745. }
  746. if len(s.Dimensions) > 0 {
  747. _, _ = buf.WriteString(" GROUP BY ")
  748. _, _ = buf.WriteString(s.Dimensions.String())
  749. }
  750. switch s.Fill {
  751. case NoFill:
  752. _, _ = buf.WriteString(" fill(none)")
  753. case NumberFill:
  754. _, _ = buf.WriteString(fmt.Sprintf(" fill(%v)", s.FillValue))
  755. case PreviousFill:
  756. _, _ = buf.WriteString(" fill(previous)")
  757. }
  758. if len(s.SortFields) > 0 {
  759. _, _ = buf.WriteString(" ORDER BY ")
  760. _, _ = buf.WriteString(s.SortFields.String())
  761. }
  762. if s.Limit > 0 {
  763. _, _ = fmt.Fprintf(&buf, " LIMIT %d", s.Limit)
  764. }
  765. if s.Offset > 0 {
  766. _, _ = buf.WriteString(" OFFSET ")
  767. _, _ = buf.WriteString(strconv.Itoa(s.Offset))
  768. }
  769. if s.SLimit > 0 {
  770. _, _ = fmt.Fprintf(&buf, " SLIMIT %d", s.SLimit)
  771. }
  772. if s.SOffset > 0 {
  773. _, _ = fmt.Fprintf(&buf, " SOFFSET %d", s.SOffset)
  774. }
  775. return buf.String()
  776. }
  777. // RequiredPrivileges returns the privilege required to execute the SelectStatement.
  778. func (s *SelectStatement) RequiredPrivileges() ExecutionPrivileges {
  779. ep := ExecutionPrivileges{{Admin: false, Name: "", Privilege: ReadPrivilege}}
  780. if s.Target != nil {
  781. p := ExecutionPrivilege{Admin: false, Name: s.Target.Measurement.Database, Privilege: WritePrivilege}
  782. ep = append(ep, p)
  783. }
  784. return ep
  785. }
  786. // OnlyTimeDimensions returns true if the statement has a where clause with only time constraints
  787. func (s *SelectStatement) OnlyTimeDimensions() bool {
  788. return s.walkForTime(s.Condition)
  789. }
  790. // walkForTime is called by the OnlyTimeDimensions method to walk the where clause to determine if
  791. // the only things specified are based on time
  792. func (s *SelectStatement) walkForTime(node Node) bool {
  793. switch n := node.(type) {
  794. case *BinaryExpr:
  795. if n.Op == AND || n.Op == OR {
  796. return s.walkForTime(n.LHS) && s.walkForTime(n.RHS)
  797. }
  798. if ref, ok := n.LHS.(*VarRef); ok && strings.ToLower(ref.Val) == "time" {
  799. return true
  800. }
  801. return false
  802. case *ParenExpr:
  803. // walk down the tree
  804. return s.walkForTime(n.Expr)
  805. default:
  806. return false
  807. }
  808. }
  809. // HasWildcard returns whether or not the select statement has at least 1 wildcard
  810. func (s *SelectStatement) HasWildcard() bool {
  811. for _, f := range s.Fields {
  812. _, ok := f.Expr.(*Wildcard)
  813. if ok {
  814. return true
  815. }
  816. }
  817. for _, d := range s.Dimensions {
  818. _, ok := d.Expr.(*Wildcard)
  819. if ok {
  820. return true
  821. }
  822. }
  823. return false
  824. }
  825. // hasTimeDimensions returns whether or not the select statement has at least 1
  826. // where condition with time as the condition
  827. func (s *SelectStatement) hasTimeDimensions(node Node) bool {
  828. switch n := node.(type) {
  829. case *BinaryExpr:
  830. if n.Op == AND || n.Op == OR {
  831. return s.hasTimeDimensions(n.LHS) || s.hasTimeDimensions(n.RHS)
  832. }
  833. if ref, ok := n.LHS.(*VarRef); ok && strings.ToLower(ref.Val) == "time" {
  834. return true
  835. }
  836. return false
  837. case *ParenExpr:
  838. // walk down the tree
  839. return s.hasTimeDimensions(n.Expr)
  840. default:
  841. return false
  842. }
  843. }
  844. func (s *SelectStatement) validate(tr targetRequirement) error {
  845. if err := s.validateDistinct(); err != nil {
  846. return err
  847. }
  848. if err := s.validateCountDistinct(); err != nil {
  849. return err
  850. }
  851. if err := s.validateAggregates(tr); err != nil {
  852. return err
  853. }
  854. if err := s.validateDerivative(); err != nil {
  855. return err
  856. }
  857. return nil
  858. }
  859. func (s *SelectStatement) validateAggregates(tr targetRequirement) error {
  860. // First, determine if specific calls have at least one and only one argument
  861. for _, f := range s.Fields {
  862. if c, ok := f.Expr.(*Call); ok {
  863. switch c.Name {
  864. case "derivative", "non_negative_derivative":
  865. if min, max, got := 1, 2, len(c.Args); got > max || got < min {
  866. return fmt.Errorf("invalid number of arguments for %s, expected at least %d but no more than %d, got %d", c.Name, min, max, got)
  867. }
  868. case "percentile":
  869. if exp, got := 2, len(c.Args); got != exp {
  870. return fmt.Errorf("invalid number of arguments for %s, expected %d, got %d", c.Name, exp, got)
  871. }
  872. default:
  873. if exp, got := 1, len(c.Args); got != exp {
  874. return fmt.Errorf("invalid number of arguments for %s, expected %d, got %d", c.Name, exp, got)
  875. }
  876. }
  877. }
  878. }
  879. // Now, check that we have valid duration and where clauses for aggregates
  880. // fetch the group by duration
  881. groupByDuration, _ := s.GroupByInterval()
  882. // If we have a group by interval, but no aggregate function, it's an invalid statement
  883. if s.IsRawQuery && groupByDuration > 0 {
  884. return fmt.Errorf("GROUP BY requires at least one aggregate function")
  885. }
  886. // If we have an aggregate function with a group by time without a where clause, it's an invalid statement
  887. if tr == targetNotRequired { // ignore create continuous query statements
  888. if !s.IsRawQuery && groupByDuration > 0 && !s.hasTimeDimensions(s.Condition) {
  889. return fmt.Errorf("aggregate functions with GROUP BY time require a WHERE time clause")
  890. }
  891. }
  892. return nil
  893. }
  894. func (s *SelectStatement) HasDistinct() bool {
  895. // determine if we have a call named distinct
  896. for _, f := range s.Fields {
  897. switch c := f.Expr.(type) {
  898. case *Call:
  899. if c.Name == "distinct" {
  900. return true
  901. }
  902. case *Distinct:
  903. return true
  904. }
  905. }
  906. return false
  907. }
  908. func (s *SelectStatement) validateDistinct() error {
  909. if !s.HasDistinct() {
  910. return nil
  911. }
  912. if len(s.Fields) > 1 {
  913. return fmt.Errorf("aggregate function distinct() can not be combined with other functions or fields")
  914. }
  915. switch c := s.Fields[0].Expr.(type) {
  916. case *Call:
  917. if len(c.Args) == 0 {
  918. return fmt.Errorf("distinct function requires at least one argument")
  919. }
  920. if len(c.Args) != 1 {
  921. return fmt.Errorf("distinct function can only have one argument")
  922. }
  923. }
  924. return nil
  925. }
  926. func (s *SelectStatement) HasCountDistinct() bool {
  927. for _, f := range s.Fields {
  928. if c, ok := f.Expr.(*Call); ok {
  929. if c.Name == "count" {
  930. for _, a := range c.Args {
  931. if _, ok := a.(*Distinct); ok {
  932. return true
  933. }
  934. if c, ok := a.(*Call); ok {
  935. if c.Name == "distinct" {
  936. return true
  937. }
  938. }
  939. }
  940. }
  941. }
  942. }
  943. return false
  944. }
  945. func (s *SelectStatement) validateCountDistinct() error {
  946. if !s.HasCountDistinct() {
  947. return nil
  948. }
  949. valid := func(e Expr) bool {
  950. c, ok := e.(*Call)
  951. if !ok {
  952. return true
  953. }
  954. if c.Name != "count" {
  955. return true
  956. }
  957. for _, a := range c.Args {
  958. if _, ok := a.(*Distinct); ok {
  959. return len(c.Args) == 1
  960. }
  961. if d, ok := a.(*Call); ok {
  962. if d.Name == "distinct" {
  963. return len(d.Args) == 1
  964. }
  965. }
  966. }
  967. return true
  968. }
  969. for _, f := range s.Fields {
  970. if !valid(f.Expr) {
  971. return fmt.Errorf("count(distinct <field>) can only have one argument")
  972. }
  973. }
  974. return nil
  975. }
  976. func (s *SelectStatement) validateDerivative() error {
  977. if !s.HasDerivative() {
  978. return nil
  979. }
  980. // If a derivative is requested, it must be the only field in the query. We don't support
  981. // multiple fields in combination w/ derivaties yet.
  982. if len(s.Fields) != 1 {
  983. return fmt.Errorf("derivative cannot be used with other fields")
  984. }
  985. aggr := s.FunctionCalls()
  986. if len(aggr) != 1 {
  987. return fmt.Errorf("derivative cannot be used with other fields")
  988. }
  989. // Derivative requires two arguments
  990. derivativeCall := aggr[0]
  991. if len(derivativeCall.Args) == 0 {
  992. return fmt.Errorf("derivative requires a field argument")
  993. }
  994. // First arg must be a field or aggr over a field e.g. (mean(field))
  995. _, callOk := derivativeCall.Args[0].(*Call)
  996. _, varOk := derivativeCall.Args[0].(*VarRef)
  997. if !(callOk || varOk) {
  998. return fmt.Errorf("derivative requires a field argument")
  999. }
  1000. // If a duration arg is pased, make sure it's a duration
  1001. if len(derivativeCall.Args) == 2 {
  1002. // Second must be a duration .e.g (1h)
  1003. if _, ok := derivativeCall.Args[1].(*DurationLiteral); !ok {
  1004. return fmt.Errorf("derivative requires a duration argument")
  1005. }
  1006. }
  1007. return nil
  1008. }
  1009. // GroupByIterval extracts the time interval, if specified.
  1010. func (s *SelectStatement) GroupByInterval() (time.Duration, error) {
  1011. // return if we've already pulled it out
  1012. if s.groupByInterval != 0 {
  1013. return s.groupByInterval, nil
  1014. }
  1015. // Ignore if there are no dimensions.
  1016. if len(s.Dimensions) == 0 {
  1017. return 0, nil
  1018. }
  1019. for _, d := range s.Dimensions {
  1020. if call, ok := d.Expr.(*Call); ok && call.Name == "time" {
  1021. // Make sure there is exactly one argument.
  1022. if len(call.Args) != 1 {
  1023. return 0, errors.New("time dimension expected one argument")
  1024. }
  1025. // Ensure the argument is a duration.
  1026. lit, ok := call.Args[0].(*DurationLiteral)
  1027. if !ok {
  1028. return 0, errors.New("time dimension must have one duration argument")
  1029. }
  1030. s.groupByInterval = lit.Val
  1031. return lit.Val, nil
  1032. }
  1033. }
  1034. return 0, nil
  1035. }
  1036. // SetTimeRange sets the start and end time of the select statement to [start, end). i.e. start inclusive, end exclusive.
  1037. // This is used commonly for continuous queries so the start and end are in buckets.
  1038. func (s *SelectStatement) SetTimeRange(start, end time.Time) error {
  1039. cond := fmt.Sprintf("time >= '%s' AND time < '%s'", start.UTC().Format(time.RFC3339Nano), end.UTC().Format(time.RFC3339Nano))
  1040. if s.Condition != nil {
  1041. cond = fmt.Sprintf("%s AND %s", s.rewriteWithoutTimeDimensions(), cond)
  1042. }
  1043. expr, err := NewParser(strings.NewReader(cond)).ParseExpr()
  1044. if err != nil {
  1045. return err
  1046. }
  1047. // fold out any previously replaced time dimensios and set the condition
  1048. s.Condition = Reduce(expr, nil)
  1049. return nil
  1050. }
  1051. // rewriteWithoutTimeDimensions will remove any WHERE time... clauses from the select statement
  1052. // This is necessary when setting an explicit time range to override any that previously existed.
  1053. func (s *SelectStatement) rewriteWithoutTimeDimensions() string {
  1054. n := RewriteFunc(s.Condition, func(n Node) Node {
  1055. switch n := n.(type) {
  1056. case *BinaryExpr:
  1057. if n.LHS.String() == "time" {
  1058. return &BooleanLiteral{Val: true}
  1059. }
  1060. return n
  1061. case *Call:
  1062. return &BooleanLiteral{Val: true}
  1063. default:
  1064. return n
  1065. }
  1066. })
  1067. return n.String()
  1068. }
  1069. /*
  1070. BinaryExpr
  1071. SELECT mean(xxx.value) + avg(yyy.value) FROM xxx JOIN yyy WHERE xxx.host = 123
  1072. from xxx where host = 123
  1073. select avg(value) from yyy where host = 123
  1074. SELECT xxx.value FROM xxx WHERE xxx.host = 123
  1075. SELECT yyy.value FROM yyy
  1076. ---
  1077. SELECT MEAN(xxx.value) + MEAN(cpu.load.value)
  1078. FROM xxx JOIN yyy
  1079. GROUP BY host
  1080. WHERE (xxx.region == "uswest" OR yyy.region == "uswest") AND xxx.otherfield == "XXX"
  1081. select * from (
  1082. select mean + mean from xxx join yyy
  1083. group by time(5m), host
  1084. ) (xxx.region == "uswest" OR yyy.region == "uswest") AND xxx.otherfield == "XXX"
  1085. (seriesIDS for xxx.region = 'uswest' union seriesIDs for yyy.regnion = 'uswest') | seriesIDS xxx.otherfield = 'XXX'
  1086. WHERE xxx.region == "uswest" AND xxx.otherfield == "XXX"
  1087. WHERE yyy.region == "uswest"
  1088. */
  1089. // Substatement returns a single-series statement for a given variable reference.
  1090. func (s *SelectStatement) Substatement(ref *VarRef) (*SelectStatement, error) {
  1091. // Copy dimensions and properties to new statement.
  1092. other := &SelectStatement{
  1093. Fields: Fields{{Expr: ref}},
  1094. Dimensions: s.Dimensions,
  1095. Limit: s.Limit,
  1096. Offset: s.Offset,
  1097. SortFields: s.SortFields,
  1098. }
  1099. // If there is only one series source then return it with the whole condition.
  1100. if len(s.Sources) == 1 {
  1101. other.Sources = s.Sources
  1102. other.Condition = s.Condition
  1103. return other, nil
  1104. }
  1105. // Find the matching source.
  1106. name := MatchSource(s.Sources, ref.Val)
  1107. if name == "" {
  1108. return nil, fmt.Errorf("field source not found: %s", ref.Val)
  1109. }
  1110. other.Sources = append(other.Sources, &Measurement{Name: name})
  1111. // Filter out conditions.
  1112. if s.Condition != nil {
  1113. other.Condition = filterExprBySource(name, s.Condition)
  1114. }
  1115. return other, nil
  1116. }
  1117. // NamesInWhere returns the field and tag names (idents) referenced in the where clause
  1118. func (s *SelectStatement) NamesInWhere() []string {
  1119. var a []string
  1120. if s.Condition != nil {
  1121. a = walkNames(s.Condition)
  1122. }
  1123. return a
  1124. }
  1125. // NamesInSelect returns the field and tag names (idents) in the select clause
  1126. func (s *SelectStatement) NamesInSelect() []string {
  1127. var a []string
  1128. for _, f := range s.Fields {
  1129. a = append(a, walkNames(f.Expr)...)
  1130. }
  1131. return a
  1132. }
  1133. // walkNames will walk the Expr and return the database fields
  1134. func walkNames(exp Expr) []string {
  1135. switch expr := exp.(type) {
  1136. case *VarRef:
  1137. return []string{expr.Val}
  1138. case *Call:
  1139. if len(expr.Args) == 0 {
  1140. return nil
  1141. }
  1142. lit, ok := expr.Args[0].(*VarRef)
  1143. if !ok {
  1144. return nil
  1145. }
  1146. return []string{lit.Val}
  1147. case *BinaryExpr:
  1148. var ret []string
  1149. ret = append(ret, walkNames(expr.LHS)...)
  1150. ret = append(ret, walkNames(expr.RHS)...)
  1151. return ret
  1152. case *ParenExpr:
  1153. return walkNames(expr.Expr)
  1154. }
  1155. return nil
  1156. }
  1157. // FunctionCalls returns the Call objects from the query
  1158. func (s *SelectStatement) FunctionCalls() []*Call {
  1159. var a []*Call
  1160. for _, f := range s.Fields {
  1161. a = append(a, walkFunctionCalls(f.Expr)...)
  1162. }
  1163. return a
  1164. }
  1165. // walkFunctionCalls walks the Field of a query for any function calls made
  1166. func walkFunctionCalls(exp Expr) []*Call {
  1167. switch expr := exp.(type) {
  1168. case *VarRef:
  1169. return nil
  1170. case *Call:
  1171. return []*Call{expr}
  1172. case *BinaryExpr:
  1173. var ret []*Call
  1174. ret = append(ret, walkFunctionCalls(expr.LHS)...)
  1175. ret = append(ret, walkFunctionCalls(expr.RHS)...)
  1176. return ret
  1177. case *ParenExpr:
  1178. return walkFunctionCalls(expr.Expr)
  1179. }
  1180. return nil
  1181. }
  1182. // filters an expression to exclude expressions unrelated to a source.
  1183. func filterExprBySource(name string, expr Expr) Expr {
  1184. switch expr := expr.(type) {
  1185. case *VarRef:
  1186. if !strings.HasPrefix(expr.Val, name) {
  1187. return nil
  1188. }
  1189. case *BinaryExpr:
  1190. lhs := filterExprBySource(name, expr.LHS)
  1191. rhs := filterExprBySource(name, expr.RHS)
  1192. // If an expr is logical then return either LHS/RHS or both.
  1193. // If an expr is arithmetic or comparative then require both sides.
  1194. if expr.Op == AND || expr.Op == OR {
  1195. if lhs == nil && rhs == nil {
  1196. return nil
  1197. } else if lhs != nil && rhs == nil {
  1198. return lhs
  1199. } else if lhs == nil && rhs != nil {
  1200. return rhs
  1201. }
  1202. } else {
  1203. if lhs == nil || rhs == nil {
  1204. return nil
  1205. }
  1206. }
  1207. return &BinaryExpr{Op: expr.Op, LHS: lhs, RHS: rhs}
  1208. case *ParenExpr:
  1209. exp := filterExprBySource(name, expr.Expr)
  1210. if exp == nil {
  1211. return nil
  1212. }
  1213. return &ParenExpr{Expr: exp}
  1214. }
  1215. return expr
  1216. }
  1217. // MatchSource returns the source name that matches a field name.
  1218. // Returns a blank string if no sources match.
  1219. func MatchSource(sources Sources, name string) string {
  1220. for _, src := range sources {
  1221. switch src := src.(type) {
  1222. case *Measurement:
  1223. if strings.HasPrefix(name, src.Name) {
  1224. return src.Name
  1225. }
  1226. }
  1227. }
  1228. return ""
  1229. }
  1230. // Target represents a target (destination) policy, measurement, and DB.
  1231. type Target struct {
  1232. // Measurement to write into.
  1233. Measurement *Measurement
  1234. }
  1235. // String returns a string representation of the Target.
  1236. func (t *Target) String() string {
  1237. if t == nil {
  1238. return ""
  1239. }
  1240. var buf bytes.Buffer
  1241. _, _ = buf.WriteString("INTO ")
  1242. _, _ = buf.WriteString(t.Measurement.String())
  1243. return buf.String()
  1244. }
  1245. // DeleteStatement represents a command for removing data from the database.
  1246. type DeleteStatement struct {
  1247. // Data source that values are removed from.
  1248. Source Source
  1249. // An expression evaluated on data point.
  1250. Condition Expr
  1251. }
  1252. // String returns a string representation of the delete statement.
  1253. func (s *DeleteStatement) String() string {
  1254. var buf bytes.Buffer
  1255. _, _ = buf.WriteString("DELETE ")
  1256. _, _ = buf.WriteString(s.Source.String())
  1257. if s.Condition != nil {
  1258. _, _ = buf.WriteString(" WHERE ")
  1259. _, _ = buf.WriteString(s.Condition.String())
  1260. }
  1261. return s.String()
  1262. }
  1263. // RequiredPrivileges returns the privilege required to execute a DeleteStatement.
  1264. func (s *DeleteStatement) RequiredPrivileges() ExecutionPrivileges {
  1265. return ExecutionPrivileges{{Admin: false, Name: "", Privilege: WritePrivilege}}
  1266. }
  1267. // ShowSeriesStatement represents a command for listing series in the database.
  1268. type ShowSeriesStatement struct {
  1269. // Measurement(s) the series are listed for.
  1270. Sources Sources
  1271. // An expression evaluated on a series name or tag.
  1272. Condition Expr
  1273. // Fields to sort results by
  1274. SortFields SortFields
  1275. // Maximum number of rows to be returned.
  1276. // Unlimited if zero.
  1277. Limit int
  1278. // Returns rows starting at an offset from the first row.
  1279. Offset int
  1280. }
  1281. // String returns a string representation of the list series statement.
  1282. func (s *ShowSeriesStatement) String() string {
  1283. var buf bytes.Buffer
  1284. _, _ = buf.WriteString("SHOW SERIES")
  1285. if s.Sources != nil {
  1286. _, _ = buf.WriteString(" FROM ")
  1287. _, _ = buf.WriteString(s.Sources.String())
  1288. }
  1289. if s.Condition != nil {
  1290. _, _ = buf.WriteString(" WHERE ")
  1291. _, _ = buf.WriteString(s.Condition.String())
  1292. }
  1293. if len(s.SortFields) > 0 {
  1294. _, _ = buf.WriteString(" ORDER BY ")
  1295. _, _ = buf.WriteString(s.SortFields.String())
  1296. }
  1297. if s.Limit > 0 {
  1298. _, _ = buf.WriteString(" LIMIT ")
  1299. _, _ = buf.WriteString(strconv.Itoa(s.Limit))
  1300. }
  1301. if s.Offset > 0 {
  1302. _, _ = buf.WriteString(" OFFSET ")
  1303. _, _ = buf.WriteString(strconv.Itoa(s.Offset))
  1304. }
  1305. return buf.String()
  1306. }
  1307. // RequiredPrivileges returns the privilege required to execute a ShowSeriesStatement.
  1308. func (s *ShowSeriesStatement) RequiredPrivileges() ExecutionPrivileges {
  1309. return ExecutionPrivileges{{Admin: false, Name: "", Privilege: ReadPrivilege}}
  1310. }
  1311. // DropSeriesStatement represents a command for removing a series from the database.
  1312. type DropSeriesStatement struct {
  1313. // Data source that fields are extracted from (optional)
  1314. Sources Sources
  1315. // An expression evaluated on data point (optional)
  1316. Condition Expr
  1317. }
  1318. // String returns a string representation of the drop series statement.
  1319. func (s *DropSeriesStatement) String() string {
  1320. var buf bytes.Buffer
  1321. buf.WriteString("DROP SERIES")
  1322. if s.Sources != nil {
  1323. buf.WriteString(" FROM ")
  1324. buf.WriteString(s.Sources.String())
  1325. }
  1326. if s.Condition != nil {
  1327. buf.WriteString(" WHERE ")
  1328. buf.WriteString(s.Condition.String())
  1329. }
  1330. return buf.String()
  1331. }
  1332. // RequiredPrivileges returns the privilege required to execute a DropSeriesStatement.
  1333. func (s DropSeriesStatement) RequiredPrivileges() ExecutionPrivileges {
  1334. return ExecutionPrivileges{{Admin: false, Name: "", Privilege: WritePrivilege}}
  1335. }
  1336. // ShowContinuousQueriesStatement represents a command for listing continuous queries.
  1337. type ShowContinuousQueriesStatement struct{}
  1338. // String returns a string representation of the list continuous queries statement.
  1339. func (s *ShowContinuousQueriesStatement) String() string { return "SHOW CONTINUOUS QUERIES" }
  1340. // RequiredPrivileges returns the privilege required to execute a ShowContinuousQueriesStatement.
  1341. func (s *ShowContinuousQueriesStatement) RequiredPrivileges() ExecutionPrivileges {
  1342. return ExecutionPrivileges{{Admin: false, Name: "", Privilege: ReadPrivilege}}
  1343. }
  1344. // ShowGrantsForUserStatement represents a command for listing user privileges.
  1345. type ShowGrantsForUserStatement struct {
  1346. // Name of the user to display privileges.
  1347. Name string
  1348. }
  1349. // String returns a string representation of the show grants for user.
  1350. func (s *ShowGrantsForUserStatement) String() string {
  1351. var buf bytes.Buffer
  1352. _, _ = buf.WriteString("SHOW GRANTS FOR ")
  1353. _, _ = buf.WriteString(s.Name)
  1354. return buf.String()
  1355. }
  1356. // RequiredPrivileges returns the privilege required to execute a ShowGrantsForUserStatement
  1357. func (s *ShowGrantsForUserStatement) RequiredPrivileges() ExecutionPrivileges {
  1358. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}
  1359. }
  1360. // ShowServersStatement represents a command for listing all servers.
  1361. type ShowServersStatement struct{}
  1362. // String returns a string representation of the show servers command.
  1363. func (s *ShowServersStatement) String() string { return "SHOW SERVERS" }
  1364. // RequiredPrivileges returns the privilege required to execute a ShowServersStatement
  1365. func (s *ShowServersStatement) RequiredPrivileges() ExecutionPrivileges {
  1366. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}
  1367. }
  1368. // ShowDatabasesStatement represents a command for listing all databases in the cluster.
  1369. type ShowDatabasesStatement struct{}
  1370. // String returns a string representation of the list databases command.
  1371. func (s *ShowDatabasesStatement) String() string { return "SHOW DATABASES" }
  1372. // RequiredPrivileges returns the privilege required to execute a ShowDatabasesStatement
  1373. func (s *ShowDatabasesStatement) RequiredPrivileges() ExecutionPrivileges {
  1374. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}
  1375. }
  1376. // CreateContinuousQueryStatement represents a command for creating a continuous query.
  1377. type CreateContinuousQueryStatement struct {
  1378. // Name of the continuous query to be created.
  1379. Name string
  1380. // Name of the database to create the continuous query on.
  1381. Database string
  1382. // Source of data (SELECT statement).
  1383. Source *SelectStatement
  1384. }
  1385. // String returns a string representation of the statement.
  1386. func (s *CreateContinuousQueryStatement) String() string {
  1387. return fmt.Sprintf("CREATE CONTINUOUS QUERY %s ON %s BEGIN %s END", QuoteIdent(s.Name), QuoteIdent(s.Database), s.Source.String())
  1388. }
  1389. // DefaultDatabase returns the default database from the statement.
  1390. func (s *CreateContinuousQueryStatement) DefaultDatabase() string {
  1391. return s.Database
  1392. }
  1393. // RequiredPrivileges returns the privilege required to execute a CreateContinuousQueryStatement.
  1394. func (s *CreateContinuousQueryStatement) RequiredPrivileges() ExecutionPrivileges {
  1395. ep := ExecutionPrivileges{{Admin: false, Name: s.Database, Privilege: ReadPrivilege}}
  1396. // Selecting into a database that's different from the source?
  1397. if s.Source.Target.Measurement.Database != "" {
  1398. // Change source database privilege requirement to read.
  1399. ep[0].Privilege = ReadPrivilege
  1400. // Add destination database privilege requirement and set it to write.
  1401. p := ExecutionPrivilege{
  1402. Admin: false,
  1403. Name: s.Source.Target.Measurement.Database,
  1404. Privilege: WritePrivilege,
  1405. }
  1406. ep = append(ep, p)
  1407. }
  1408. return ep
  1409. }
  1410. // DropContinuousQueryStatement represents a command for removing a continuous query.
  1411. type DropContinuousQueryStatement struct {
  1412. Name string
  1413. Database string
  1414. }
  1415. // String returns a string representation of the statement.
  1416. func (s *DropContinuousQueryStatement) String() string {
  1417. return fmt.Sprintf("DROP CONTINUOUS QUERY %s", s.Name)
  1418. }
  1419. // RequiredPrivileges returns the privilege(s) required to execute a DropContinuousQueryStatement
  1420. func (s *DropContinuousQueryStatement) RequiredPrivileges() ExecutionPrivileges {
  1421. return ExecutionPrivileges{{Admin: false, Name: "", Privilege: WritePrivilege}}
  1422. }
  1423. // ShowMeasurementsStatement represents a command for listing measurements.
  1424. type ShowMeasurementsStatement struct {
  1425. // An expression evaluated on data point.
  1426. Condition Expr
  1427. // Fields to sort results by
  1428. SortFields SortFields
  1429. // Maximum number of rows to be returned.
  1430. // Unlimited if zero.
  1431. Limit int
  1432. // Returns rows starting at an offset from the first row.
  1433. Offset int
  1434. }
  1435. // String returns a string representation of the statement.
  1436. func (s *ShowMeasurementsStatement) String() string {
  1437. var buf bytes.Buffer
  1438. _, _ = buf.WriteString("SHOW MEASUREMENTS")
  1439. if s.Condition != nil {
  1440. _, _ = buf.WriteString(" WHERE ")
  1441. _, _ = buf.WriteString(s.Condition.String())
  1442. }
  1443. if len(s.SortFields) > 0 {
  1444. _, _ = buf.WriteString(" ORDER BY ")
  1445. _, _ = buf.WriteString(s.SortFields.String())
  1446. }
  1447. if s.Limit > 0 {
  1448. _, _ = buf.WriteString(" LIMIT ")
  1449. _, _ = buf.WriteString(strconv.Itoa(s.Limit))
  1450. }
  1451. if s.Offset > 0 {
  1452. _, _ = buf.WriteString(" OFFSET ")
  1453. _, _ = buf.WriteString(strconv.Itoa(s.Offset))
  1454. }
  1455. return buf.String()
  1456. }
  1457. // RequiredPrivileges returns the privilege(s) required to execute a ShowMeasurementsStatement
  1458. func (s *ShowMeasurementsStatement) RequiredPrivileges() ExecutionPrivileges {
  1459. return ExecutionPrivileges{{Admin: false, Name: "", Privilege: ReadPrivilege}}
  1460. }
  1461. // DropMeasurementStatement represents a command to drop a measurement.
  1462. type DropMeasurementStatement struct {
  1463. // Name of the measurement to be dropped.
  1464. Name string
  1465. }
  1466. // String returns a string representation of the drop measurement statement.
  1467. func (s *DropMeasurementStatement) String() string {
  1468. var buf bytes.Buffer
  1469. _, _ = buf.WriteString("DROP MEASUREMENT ")
  1470. _, _ = buf.WriteString(s.Name)
  1471. return buf.String()
  1472. }
  1473. // RequiredPrivileges returns the privilege(s) required to execute a DropMeasurementStatement
  1474. func (s *DropMeasurementStatement) RequiredPrivileges() ExecutionPrivileges {
  1475. return ExecutionPrivileges{{Admin: true, Name: "", Privilege: AllPrivileges}}
  1476. }
  1477. // ShowRetentionPoliciesStatement represents a command for listing retention policies.
  1478. type ShowRetentionPoliciesStatement struct {
  1479. // Name of the database to list policies for.
  1480. Database string
  1481. }
  1482. // String returns a string representation of a ShowRetent