influxql

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 7, 2022 License: Apache-2.0, MIT, MIT Imports: 15 Imported by: 0

README

The Influx Query Language Specification

Introduction

This is a reference for the Influx Query Language ("InfluxQL").

InfluxQL is a SQL-like query language for interacting with InfluxDB. It has been lovingly crafted to feel familiar to those coming from other SQL or SQL-like environments while providing features specific to storing and analyzing time series data.

Notation

The syntax is specified using Extended Backus-Naur Form ("EBNF"). EBNF is the same notation used in the Go programming language specification, which can be found here. Not so coincidentally, InfluxDB is written in Go.

Production  = production_name "=" [ Expression ] "." .
Expression  = Alternative { "|" Alternative } .
Alternative = Term { Term } .
Term        = production_name | token [ "…" token ] | Group | Option | Repetition .
Group       = "(" Expression ")" .
Option      = "[" Expression "]" .
Repetition  = "{" Expression "}" .

Notation operators in order of increasing precedence:

|   alternation
()  grouping
[]  option (0 or 1 times)
{}  repetition (0 to n times)

Comments

Both single and multiline comments are supported. A comment is treated the same as whitespace by the parser.

-- single line comment
/*
    multiline comment
*/

Single line comments will skip all text until the scanner hits a newline. Multiline comments will skip all text until the end comment marker is hit. Nested multiline comments are not supported so the following does not work:

/* /* this does not work */ */

Query representation

Characters

InfluxQL is Unicode text encoded in UTF-8.

newline             = /* the Unicode code point U+000A */ .
unicode_char        = /* an arbitrary Unicode code point except newline */ .

Letters and digits

Letters are the set of ASCII characters plus the underscore character _ (U+005F) is considered a letter.

Only decimal digits are supported.

letter              = ascii_letter | "_" .
ascii_letter        = "A" … "Z" | "a" … "z" .
digit               = "0" … "9" .

Identifiers

Identifiers are tokens which refer to database names, retention policy names, user names, measurement names, tag keys, and field keys.

The rules:

  • double quoted identifiers can contain any unicode character other than a new line
  • double quoted identifiers can contain escaped " characters (i.e., \")
  • double quoted identifiers can contain InfluxQL keywords
  • unquoted identifiers must start with an upper or lowercase ASCII character or "_"
  • unquoted identifiers may contain only ASCII letters, decimal digits, and "_"
identifier          = unquoted_identifier | quoted_identifier .
unquoted_identifier = ( letter ) { letter | digit } .
quoted_identifier   = `"` unicode_char { unicode_char } `"` .
Examples:
cpu
_cpu_stats
"1h"
"anything really"
"1_Crazy-1337.identifier>NAME👍"

Keywords

ALL           ALTER         ANALYZE       ANY           AS            ASC
BEGIN         BY            CREATE        CONTINUOUS    DATABASE      DATABASES
DEFAULT       DELETE        DESC          DESTINATIONS  DIAGNOSTICS   DISTINCT
DROP          DURATION      END           EVERY         EXPLAIN       FIELD
FOR           FROM          GRANT         GRANTS        GROUP         GROUPS
IN            INF           INSERT        INTO          KEY           KEYS
KILL          LIMIT         SHOW          MEASUREMENT   MEASUREMENTS  NAME
OFFSET        ON            ORDER         PASSWORD      POLICY        POLICIES
PRIVILEGES    QUERIES       QUERY         READ          REPLICATION   RESAMPLE
RETENTION     REVOKE        SELECT        SERIES        SET           SHARD
SHARDS        SLIMIT        SOFFSET       STATS         SUBSCRIPTION  SUBSCRIPTIONS
TAG           TO            USER          USERS         VALUES        WHERE
WITH          WRITE

Literals

Integers

InfluxQL supports decimal integer literals. Hexadecimal and octal literals are not currently supported.

int_lit             = [ "+" | "-" ] ( "1" … "9" ) { digit } .
Floats

InfluxQL supports floating-point literals. Exponents are not currently supported.

float_lit           = [ "+" | "-" ] ( "." digit { digit } | digit { digit } "." { digit } ) .
Strings

String literals must be surrounded by single quotes. Strings may contain ' characters as long as they are escaped (i.e., \').

string_lit          = `'` { unicode_char } `'` .
Durations

Duration literals specify a length of time. An integer literal followed immediately (with no spaces) by a duration unit listed below is interpreted as a duration literal.

Duration units
Units Meaning
u or µ microseconds (1 millionth of a second)
ms milliseconds (1 thousandth of a second)
s second
m minute
h hour
d day
w week
duration_lit        = int_lit duration_unit .
duration_unit       = "u" | "µ" | "ms" | "s" | "m" | "h" | "d" | "w" .
Dates & Times

The date and time literal format is not specified in EBNF like the rest of this document. It is specified using Go's date / time parsing format, which is a reference date written in the format required by InfluxQL. The reference date time is:

InfluxQL reference date time: January 2nd, 2006 at 3:04:05 PM

time_lit            = "2006-01-02 15:04:05.999999" | "2006-01-02" .
Booleans
bool_lit            = TRUE | FALSE .
Regular Expressions
regex_lit           = "/" { unicode_char } "/" .

Comparators: =~ matches against !~ doesn't match against

Note: Use regular expressions to match measurements and tags. You cannot use regular expressions to match databases, retention policies, or fields.

Queries

A query is composed of one or more statements separated by a semicolon.

query               = statement { ";" statement } .

statement           = alter_retention_policy_stmt |
                      create_continuous_query_stmt |
                      create_database_stmt |
                      create_retention_policy_stmt |
                      create_subscription_stmt |
                      create_user_stmt |
                      delete_stmt |
                      drop_continuous_query_stmt |
                      drop_database_stmt |
                      drop_measurement_stmt |
                      drop_retention_policy_stmt |
                      drop_series_stmt |
                      drop_shard_stmt |
                      drop_subscription_stmt |
                      drop_user_stmt |
                      explain_stmt |
                      grant_stmt |
                      kill_query_statement |
                      show_continuous_queries_stmt |
                      show_databases_stmt |
                      show_field_keys_stmt |
                      show_grants_stmt |
                      show_measurements_stmt |
                      show_queries_stmt |
                      show_retention_policies |
                      show_series_stmt |
                      show_shard_groups_stmt |
                      show_shards_stmt |
                      show_subscriptions_stmt|
                      show_tag_keys_stmt |
                      show_tag_values_stmt |
                      show_users_stmt |
                      revoke_stmt |
                      select_stmt .

Statements

ALTER RETENTION POLICY
alter_retention_policy_stmt  = "ALTER RETENTION POLICY" policy_name on_clause
                               retention_policy_option
                               [ retention_policy_option ]
                               [ retention_policy_option ]
                               [ retention_policy_option ] .

Replication factors do not serve a purpose with single node instances.

Examples:
-- Set default retention policy for mydb to 1h.cpu.
ALTER RETENTION POLICY "1h.cpu" ON "mydb" DEFAULT

-- Change duration and replication factor.
ALTER RETENTION POLICY "policy1" ON "somedb" DURATION 1h REPLICATION 4
CREATE CONTINUOUS QUERY
create_continuous_query_stmt = "CREATE CONTINUOUS QUERY" query_name on_clause
                               [ "RESAMPLE" resample_opts ]
                               "BEGIN" select_stmt "END" .

query_name                   = identifier .

resample_opts                = (every_stmt for_stmt | every_stmt | for_stmt) .
every_stmt                   = "EVERY" duration_lit
for_stmt                     = "FOR" duration_lit
Examples:
-- selects from DEFAULT retention policy and writes into 6_months retention policy
CREATE CONTINUOUS QUERY "10m_event_count"
ON "db_name"
BEGIN
  SELECT count("value")
  INTO "6_months"."events"
  FROM "events"
  GROUP BY time(10m)
END;

-- this selects from the output of one continuous query in one retention policy and outputs to another series in another retention policy
CREATE CONTINUOUS QUERY "1h_event_count"
ON "db_name"
BEGIN
  SELECT sum("count") as "count"
  INTO "2_years"."events"
  FROM "6_months"."events"
  GROUP BY time(1h)
END;

-- this customizes the resample interval so the interval is queried every 10s and intervals are resampled until 2m after their start time
-- when resample is used, at least one of "EVERY" or "FOR" must be used
CREATE CONTINUOUS QUERY "cpu_mean"
ON "db_name"
RESAMPLE EVERY 10s FOR 2m
BEGIN
  SELECT mean("value")
  INTO "cpu_mean"
  FROM "cpu"
  GROUP BY time(1m)
END;
CREATE DATABASE
create_database_stmt = "CREATE DATABASE" db_name
                       [ WITH
                           [ retention_policy_duration ]
                           [ retention_policy_replication ]
                           [ retention_policy_shard_group_duration ]
                           [ retention_policy_name ]
                       ] .

Replication factors do not serve a purpose with single node instances.

Examples:
-- Create a database called foo
CREATE DATABASE "foo"

-- Create a database called bar with a new DEFAULT retention policy and specify the duration, replication, shard group duration, and name of that retention policy
CREATE DATABASE "bar" WITH DURATION 1d REPLICATION 1 SHARD DURATION 30m NAME "myrp"

-- Create a database called mydb with a new DEFAULT retention policy and specify the name of that retention policy
CREATE DATABASE "mydb" WITH NAME "myrp"
CREATE RETENTION POLICY
create_retention_policy_stmt = "CREATE RETENTION POLICY" policy_name on_clause
                               retention_policy_duration
                               retention_policy_replication
                               [ retention_policy_shard_group_duration ]
                               [ "DEFAULT" ] .

Replication factors do not serve a purpose with single node instances.

Examples
-- Create a retention policy.
CREATE RETENTION POLICY "10m.events" ON "somedb" DURATION 60m REPLICATION 2

-- Create a retention policy and set it as the DEFAULT.
CREATE RETENTION POLICY "10m.events" ON "somedb" DURATION 60m REPLICATION 2 DEFAULT

-- Create a retention policy and specify the shard group duration.
CREATE RETENTION POLICY "10m.events" ON "somedb" DURATION 60m REPLICATION 2 SHARD DURATION 30m
CREATE SUBSCRIPTION

Subscriptions tell InfluxDB to send all the data it receives to Kapacitor or other third parties.

create_subscription_stmt = "CREATE SUBSCRIPTION" subscription_name "ON" db_name "." retention_policy "DESTINATIONS" ("ANY"|"ALL") host { "," host} .
Examples:
-- Create a SUBSCRIPTION on database 'mydb' and retention policy 'autogen' that send data to 'example.com:9090' via UDP.
CREATE SUBSCRIPTION "sub0" ON "mydb"."autogen" DESTINATIONS ALL 'udp://example.com:9090'

-- Create a SUBSCRIPTION on database 'mydb' and retention policy 'autogen' that round robins the data to 'h1.example.com:9090' and 'h2.example.com:9090'.
CREATE SUBSCRIPTION "sub0" ON "mydb"."autogen" DESTINATIONS ANY 'udp://h1.example.com:9090', 'udp://h2.example.com:9090'
CREATE USER
create_user_stmt = "CREATE USER" user_name "WITH PASSWORD" password
                   [ "WITH ALL PRIVILEGES" ] .
Examples:
-- Create a normal database user.
CREATE USER "jdoe" WITH PASSWORD '1337password'

-- Create an admin user.
-- Note: Unlike the GRANT statement, the "PRIVILEGES" keyword is required here.
CREATE USER "jdoe" WITH PASSWORD '1337password' WITH ALL PRIVILEGES

Note: The password string must be wrapped in single quotes.

DELETE
delete_stmt = "DELETE" ( from_clause | where_clause | from_clause where_clause ) .
Examples:
DELETE FROM "cpu"
DELETE FROM "cpu" WHERE time < '2000-01-01T00:00:00Z'
DELETE WHERE time < '2000-01-01T00:00:00Z'
DROP CONTINUOUS QUERY
drop_continuous_query_stmt = "DROP CONTINUOUS QUERY" query_name on_clause .
Example:
DROP CONTINUOUS QUERY "myquery" ON "mydb"
DROP DATABASE
drop_database_stmt = "DROP DATABASE" db_name .
Example:
DROP DATABASE "mydb"
DROP MEASUREMENT
drop_measurement_stmt = "DROP MEASUREMENT" measurement .
Examples:
-- drop the cpu measurement
DROP MEASUREMENT "cpu"
DROP RETENTION POLICY
drop_retention_policy_stmt = "DROP RETENTION POLICY" policy_name on_clause .
Example:
-- drop the retention policy named 1h.cpu from mydb
DROP RETENTION POLICY "1h.cpu" ON "mydb"
DROP SERIES
drop_series_stmt = "DROP SERIES" ( from_clause | where_clause | from_clause where_clause ) .
Example:
DROP SERIES FROM "telegraf"."autogen"."cpu" WHERE cpu = 'cpu8'

DROP SHARD
drop_shard_stmt = "DROP SHARD" ( shard_id ) .
Example:
DROP SHARD 1
DROP SUBSCRIPTION
drop_subscription_stmt = "DROP SUBSCRIPTION" subscription_name "ON" db_name "." retention_policy .
Example:
DROP SUBSCRIPTION "sub0" ON "mydb"."autogen"
DROP USER
drop_user_stmt = "DROP USER" user_name .
Example:
DROP USER "jdoe"
EXPLAIN

NOTE: This functionality is unimplemented.

explain_stmt = "EXPLAIN" [ "ANALYZE" ] select_stmt .
GRANT

NOTE: Users can be granted privileges on databases that do not exist.

grant_stmt = "GRANT" privilege [ on_clause ] to_clause .
Examples:
-- grant admin privileges
GRANT ALL TO "jdoe"

-- grant read access to a database
GRANT READ ON "mydb" TO "jdoe"
KILL QUERY
kill_query_statement = "KILL QUERY" query_id .
Examples:
--- kill a query with the query_id 36
KILL QUERY 36

NOTE: Identify the query_id from the SHOW QUERIES output.

SHOW CONTINUOUS QUERIES
show_continuous_queries_stmt = "SHOW CONTINUOUS QUERIES" .
Example:
-- show all continuous queries
SHOW CONTINUOUS QUERIES
SHOW DATABASES
show_databases_stmt = "SHOW DATABASES" .
Example:
-- show all databases
SHOW DATABASES
SHOW FIELD KEYS
show_field_keys_stmt = "SHOW FIELD KEYS" [ from_clause ] .
Examples:
-- show field keys and field value data types from all measurements
SHOW FIELD KEYS

-- show field keys and field value data types from specified measurement
SHOW FIELD KEYS FROM "cpu"
SHOW GRANTS
show_grants_stmt = "SHOW GRANTS FOR" user_name .
Example:
-- show grants for jdoe
SHOW GRANTS FOR "jdoe"
SHOW MEASUREMENTS
show_measurements_stmt = "SHOW MEASUREMENTS" [ with_measurement_clause ] [ where_clause ] [ limit_clause ] [ offset_clause ] .
Examples:
-- show all measurements
SHOW MEASUREMENTS

-- show measurements where region tag = 'uswest' AND host tag = 'serverA'
SHOW MEASUREMENTS WHERE "region" = 'uswest' AND "host" = 'serverA'

-- show measurements that start with 'h2o'
SHOW MEASUREMENTS WITH MEASUREMENT =~ /h2o.*/
SHOW QUERIES
show_queries_stmt = "SHOW QUERIES" .
Example:
-- show all currently-running queries
SHOW QUERIES
SHOW RETENTION POLICIES
show_retention_policies = "SHOW RETENTION POLICIES" on_clause .
Example:
-- show all retention policies on a database
SHOW RETENTION POLICIES ON "mydb"
SHOW SERIES
show_series_stmt = "SHOW SERIES" [ from_clause ] [ where_clause ] [ limit_clause ] [ offset_clause ] .
Example:
SHOW SERIES FROM "telegraf"."autogen"."cpu" WHERE cpu = 'cpu8'
SHOW SHARD GROUPS
show_shard_groups_stmt = "SHOW SHARD GROUPS" .
Example:
SHOW SHARD GROUPS
SHOW SHARDS
show_shards_stmt = "SHOW SHARDS" .
Example:
SHOW SHARDS
SHOW SUBSCRIPTIONS
show_subscriptions_stmt = "SHOW SUBSCRIPTIONS" .
Example:
SHOW SUBSCRIPTIONS
SHOW TAG KEYS
show_tag_keys_stmt = "SHOW TAG KEYS" [ from_clause ] [ where_clause ] [ group_by_clause ]
                     [ limit_clause ] [ offset_clause ] .
Examples:
-- show all tag keys
SHOW TAG KEYS

-- show all tag keys from the cpu measurement
SHOW TAG KEYS FROM "cpu"

-- show all tag keys from the cpu measurement where the region key = 'uswest'
SHOW TAG KEYS FROM "cpu" WHERE "region" = 'uswest'

-- show all tag keys where the host key = 'serverA'
SHOW TAG KEYS WHERE "host" = 'serverA'
SHOW TAG VALUES
show_tag_values_stmt = "SHOW TAG VALUES" [ from_clause ] with_tag_clause [ where_clause ]
                       [ group_by_clause ] [ limit_clause ] [ offset_clause ] .
Examples:
-- show all tag values across all measurements for the region tag
SHOW TAG VALUES WITH KEY = "region"

-- show tag values from the cpu measurement for the region tag
SHOW TAG VALUES FROM "cpu" WITH KEY = "region"

-- show tag values across all measurements for all tag keys that do not include the letter c
SHOW TAG VALUES WITH KEY !~ /.*c.*/

-- show tag values from the cpu measurement for region & host tag keys where service = 'redis'
SHOW TAG VALUES FROM "cpu" WITH KEY IN ("region", "host") WHERE "service" = 'redis'
SHOW USERS
show_users_stmt = "SHOW USERS" .
Example:
-- show all users
SHOW USERS
REVOKE
revoke_stmt = "REVOKE" privilege [ on_clause ] "FROM" user_name .
Examples:
-- revoke admin privileges from jdoe
REVOKE ALL PRIVILEGES FROM "jdoe"

-- revoke read privileges from jdoe on mydb
REVOKE READ ON "mydb" FROM "jdoe"
SELECT
select_stmt = "SELECT" fields from_clause [ into_clause ] [ where_clause ]
              [ group_by_clause ] [ order_by_clause ] [ limit_clause ]
              [ offset_clause ] [ slimit_clause ] [ soffset_clause ]
              [ timezone_clause ] .
Examples:
-- select mean value from the cpu measurement where region = 'uswest' grouped by 10 minute intervals
SELECT mean("value") FROM "cpu" WHERE "region" = 'uswest' GROUP BY time(10m) fill(0)

-- select from all measurements beginning with cpu into the same measurement name in the cpu_1h retention policy
SELECT mean("value") INTO "cpu_1h".:MEASUREMENT FROM /cpu.*/

-- select from measurements grouped by the day with a timezone
SELECT mean("value") FROM "cpu" GROUP BY region, time(1d) fill(0) tz("America/Chicago")

Clauses

from_clause     = "FROM" measurements .

group_by_clause = "GROUP BY" dimensions fill(fill_option).

into_clause     = "INTO" ( measurement | back_ref ).

limit_clause    = "LIMIT" int_lit .

offset_clause   = "OFFSET" int_lit .

slimit_clause   = "SLIMIT" int_lit .

soffset_clause  = "SOFFSET" int_lit .

timezone_clause = tz(string_lit) .

on_clause       = "ON" db_name .

order_by_clause = "ORDER BY" sort_fields .

to_clause       = "TO" user_name .

where_clause    = "WHERE" expr .

with_measurement_clause = "WITH MEASUREMENT" ( "=" measurement | "=~" regex_lit ) .

with_tag_clause = "WITH KEY" ( "=" tag_key | "!=" tag_key | "=~" regex_lit | "IN (" tag_keys ")"  ) .

Expressions

binary_op        = "+" | "-" | "*" | "/" | "%" | "&" | "|" | "^" | "AND" |
                   "OR" | "=" | "!=" | "<>" | "<" | "<=" | ">" | ">=" .

expr             = unary_expr { binary_op unary_expr } .

unary_expr       = "(" expr ")" | var_ref | time_lit | string_lit | int_lit |
                   float_lit | bool_lit | duration_lit | regex_lit .

Other

alias            = "AS" identifier .

back_ref         = ( policy_name ".:MEASUREMENT" ) |
                   ( db_name "." [ policy_name ] ".:MEASUREMENT" ) .

db_name          = identifier .

dimension        = expr .

dimensions       = dimension { "," dimension } .

field_key        = identifier .

field            = expr [ alias ] .

fields           = field { "," field } .

fill_option      = "null" | "none" | "previous" | "linear" | int_lit | float_lit .

host             = string_lit .

measurement      = measurement_name |
                   ( policy_name "." measurement_name ) |
                   ( db_name "." [ policy_name ] "." measurement_name ) .

measurements     = measurement { "," measurement } .

measurement_name = identifier | regex_lit .

password         = string_lit .

policy_name      = identifier .

privilege        = "ALL" [ "PRIVILEGES" ] | "READ" | "WRITE" .

query_id         = int_lit .

query_name       = identifier .

retention_policy = identifier .

retention_policy_option      = retention_policy_duration |
                               retention_policy_replication |
                               retention_policy_shard_group_duration |
                               "DEFAULT" .

retention_policy_duration    = "DURATION" duration_lit .

retention_policy_replication = "REPLICATION" int_lit .

retention_policy_shard_group_duration = "SHARD DURATION" duration_lit .

retention_policy_name = "NAME" identifier .

series_id        = int_lit .

shard_id         = int_lit .

sort_field       = field_key [ ASC | DESC ] .

sort_fields      = sort_field { "," sort_field } .

subscription_name = identifier .

tag_key          = identifier .

tag_keys         = tag_key { "," tag_key } .

user_name        = identifier .

var_ref          = measurement .

Query Engine Internals

Once you understand the language itself, it's important to know how these language constructs are implemented in the query engine. This gives you an intuitive sense for how results will be processed and how to create efficient queries.

The life cycle of a query looks like this:

  1. InfluxQL query string is tokenized and then parsed into an abstract syntax tree (AST). This is the code representation of the query itself.

  2. The AST is passed to the QueryExecutor which directs queries to the appropriate handlers. For example, queries related to meta data are executed by the meta service and SELECT statements are executed by the shards themselves.

  3. The query engine then determines the shards that match the SELECT statement's time range. From these shards, iterators are created for each field in the statement.

  4. Iterators are passed to the emitter which drains them and joins the resulting points. The emitter's job is to convert simple time/value points into the more complex result objects that are returned to the client.

Understanding Iterators

Iterators are at the heart of the query engine. They provide a simple interface for looping over a set of points. For example, this is an iterator over Float points:

type FloatIterator interface {
    Next() (*FloatPoint, error)
}

These iterators are created through the IteratorCreator interface:

type IteratorCreator interface {
    CreateIterator(m *Measurement, opt IteratorOptions) (Iterator, error)
}

The IteratorOptions provide arguments about field selection, time ranges, and dimensions that the iterator creator can use when planning an iterator. The IteratorCreator interface is used at many levels such as the Shards, Shard, and Engine. This allows optimizations to be performed when applicable such as returning a precomputed COUNT().

Iterators aren't just for reading raw data from storage though. Iterators can be composed so that they provided additional functionality around an input iterator. For example, a DistinctIterator can compute the distinct values for each time window for an input iterator. Or a FillIterator can generate additional points that are missing from an input iterator.

This composition also lends itself well to aggregation. For example, a statement such as this:

SELECT MEAN(value) FROM cpu GROUP BY time(10m)

In this case, MEAN(value) is a MeanIterator wrapping an iterator from the underlying shards. However, if we can add an additional iterator to determine the derivative of the mean:

SELECT DERIVATIVE(MEAN(value), 20m) FROM cpu GROUP BY time(10m)
Understanding Auxiliary Fields

Because InfluxQL allows users to use selector functions such as FIRST(), LAST(), MIN(), and MAX(), the engine must provide a way to return related data at the same time with the selected point.

For example, in this query:

SELECT FIRST(value), host FROM cpu GROUP BY time(1h)

We are selecting the first value that occurs every hour but we also want to retrieve the host associated with that point. Since the Point types only specify a single typed Value for efficiency, we push the host into the auxiliary fields of the point. These auxiliary fields are attached to the point until it is passed to the emitter where the fields get split off to their own iterator.

Built-in Iterators

There are many helper iterators that let us build queries:

  • Merge Iterator - This iterator combines one or more iterators into a single new iterator of the same type. This iterator guarantees that all points within a window will be output before starting the next window but does not provide ordering guarantees within the window. This allows for fast access for aggregate queries which do not need stronger sorting guarantees.

  • Sorted Merge Iterator - This iterator also combines one or more iterators into a new iterator of the same type. However, this iterator guarantees time ordering of every point. This makes it slower than the MergeIterator but this ordering guarantee is required for non-aggregate queries which return the raw data points.

  • Limit Iterator - This iterator limits the number of points per name/tag group. This is the implementation of the LIMIT & OFFSET syntax.

  • Fill Iterator - This iterator injects extra points if they are missing from the input iterator. It can provide null points, points with the previous value, or points with a specific value.

  • Buffered Iterator - This iterator provides the ability to "unread" a point back onto a buffer so it can be read again next time. This is used extensively to provide lookahead for windowing.

  • Reduce Iterator - This iterator calls a reduction function for each point in a window. When the window is complete then all points for that window are output. This is used for simple aggregate functions such as COUNT().

  • Reduce Slice Iterator - This iterator collects all points for a window first and then passes them all to a reduction function at once. The results are returned from the iterator. This is used for aggregate functions such as DERIVATIVE().

  • Transform Iterator - This iterator calls a transform function for each point from an input iterator. This is used for executing binary expressions.

  • Dedupe Iterator - This iterator only outputs unique points. It is resource intensive so it is only used for small queries such as meta query statements.

Call Iterators

Function calls in InfluxQL are implemented at two levels. Some calls can be wrapped at multiple layers to improve efficiency. For example, a COUNT() can be performed at the shard level and then multiple CountIterators can be wrapped with another CountIterator to compute the count of all shards. These iterators can be created using NewCallIterator().

Some iterators are more complex or need to be implemented at a higher level. For example, the DERIVATIVE() needs to retrieve all points for a window first before performing the calculation. This iterator is created by the engine itself and is never requested to be created by the lower levels.

Subqueries

Subqueries are built on top of iterators. Most of the work involved in supporting subqueries is in organizing how data is streamed to the iterators that will process the data.

The final ordering of the stream has to output all points from one series before moving to the next series and it also needs to ensure those points are printed in order. So there are two separate concepts we need to consider when creating an iterator: ordering and grouping.

When an inner query has a different grouping than the outermost query, we still need to group together related points into buckets, but we do not have to ensure that all points from one buckets are output before the points in another bucket. In fact, if we do that, we will be unable to perform the grouping for the outer query correctly. Instead, we group all points by the outermost query for an interval and then, within that interval, we group the points for the inner query. For example, here are series keys and times in seconds (fields are omitted since they don't matter in this example):

cpu,host=server01 0
cpu,host=server01 10
cpu,host=server01 20
cpu,host=server01 30
cpu,host=server02 0
cpu,host=server02 10
cpu,host=server02 20
cpu,host=server02 30

With the following query:

SELECT mean(max) FROM (SELECT max(value) FROM cpu GROUP BY host, time(20s)) GROUP BY time(20s)

The final grouping keeps all of the points together which means we need to group server01 with server02. That means we output the points from the underlying engine like this:

cpu,host=server01 0
cpu,host=server01 10
cpu,host=server02 0
cpu,host=server02 10
cpu,host=server01 20
cpu,host=server01 30
cpu,host=server02 20
cpu,host=server02 30

Within each one of those time buckets, we calculate the max() value for each unique host so the output stream gets transformed to look like this:

cpu,host=server01 0
cpu,host=server02 0
cpu,host=server01 20
cpu,host=server02 20

Then we can process the mean() on this stream of data instead and it will be output in the correct order. This is true of any order of grouping since grouping can only go from more specific to less specific.

When it comes to ordering, unordered data is faster to process, but we always need to produce ordered data. When processing a raw query with no aggregates, we need to ensure data coming from the engine is ordered so the output is ordered. When we have an aggregate, we know one point is being emitted for each interval and will always produce ordered output. So for aggregates, we can take unordered data as the input and get ordered output. Any ordered data as input will always result in ordered data so we just need to look at how an iterator processes unordered data.

raw query selector (without group by time) selector (with group by time) aggregator
ordered input ordered output ordered output ordered output ordered output
unordered input unordered output unordered output ordered output ordered output

Since we always need ordered output, we just need to work backwards and determine which pattern of input gives us ordered output. If both ordered and unordered input produce ordered output, we prefer unordered input since it is faster.

There are also certain aggregates that require ordered input like median() and percentile(). These functions will explicitly request ordered input. It is also important to realize that selectors that are grouped by time are the equivalent of an aggregator. It is only selectors without a group by time that are different.

Documentation

Overview

Copyright (c) 2018 InfluxData This code is originally from: https://github.com/influxdata/influxql/blob/v1.1.0/ast.go

2022.01.23 changed. Add statement cases: AlterShardKeyStatement ShowFieldKeysStatement ShowFieldKeyCardinalityStatement ShowTagKeyCardinalityStatement ShowSeriesStatement ShowTagValuesCardinalityStatement PrepareSnapshotStatement EndPrepareSnapshotStatement GetRuntimeInfoStatement Copyright 2022 Huawei Cloud Computing Technologies Co., Ltd.

Package influxql implements a parser for the InfluxDB query language.

InfluxQL is a DML and DDL language for the InfluxDB time series database. It provides the ability to query for aggregate statistics as well as create and configure the InfluxDB server.

See https://docs.influxdata.com/influxdb/latest/query_language/ for a reference on using InfluxQL.

Index

Constants

View Source
const (
	// MinTime is the minumum time that can be represented.
	//
	// 1677-09-21 00:12:43.145224194 +0000 UTC
	//
	// The two lowest minimum integers are used as sentinel values.  The
	// minimum value needs to be used as a value lower than any other value for
	// comparisons and another separate value is needed to act as a sentinel
	// default value that is unusable by the user, but usable internally.
	// Because these two values need to be used for a special purpose, we do
	// not allow users to write points at these two times.
	MinTime = int64(math.MinInt64) + 2

	// MaxTime is the maximum time that can be represented.
	//
	// 2262-04-11 23:47:16.854775806 +0000 UTC
	//
	// The highest time represented by a nanosecond needs to be used for an
	// exclusive range in the shard group, so the maximum time needs to be one
	// less than the possible maximum number of nanoseconds representable by an
	// int64 so that we don't lose a point at that one time.
	MaxTime = int64(math.MaxInt64) - 1

	HASH  = "hash"
	RANGE = "range"
)
View Source
const (
	// DateFormat represents the format for date literals.
	DateFormat = "2006-01-02"

	// DateTimeFormat represents the format for date time literals.
	DateTimeFormat = "2006-01-02 15:04:05.999999"

	// if the tag is full, the index get the SID based on seriesKey, otherwise, the index work as normal procedure.
	SpecificSeriesQuery = "specific_series"

	// Whether the tag is full or not, the index get the SID based on seriesKey.
	FullSeriesQuery = "full_series"

	FilterNullColumn = "filter_null_column"

	ExactStatisticQuery = "exact_statistic_query"
)
View Source
const ADD = 57455
View Source
const ALL = 57373
View Source
const ALTER = 57377
View Source
const ANALYZE = 57413
View Source
const AND = 57453
View Source
const AS = 57351
View Source
const ASC = 57431
View Source
const BITWISE_AND = 57462
View Source
const BITWISE_OR = 57457
View Source
const BITWISE_XOR = 57458
View Source
const BY = 57353
View Source
const CARDINALITY = 57415
View Source
const CASE = 57400
View Source
const COMMA = 57432
View Source
const CONTINUOUS = 57417
View Source
const CREATE = 57360
View Source
const DATABASE = 57381
View Source
const DATABASES = 57380
View Source
const DEFAULT = 57387
View Source
const DELETE = 57371
View Source
const DESC = 57430
View Source
const DIAGNOSTICS = 57418
View Source
const DIV = 57460
View Source
const DOT = 57443
View Source
const DOUBLECOLON = 57444
View Source
const DROP = 57399
View Source
const DURATION = 57386
View Source
const DURATIONVAL = 57449
View Source
const ELSE = 57403
View Source
const END = 57404
View Source
const EQ = 57437
View Source
const EQREGEX = 57446
View Source
const EXACT = 57414
View Source
const EXISTS = 57368
View Source
const EXPLAIN = 57412
View Source
const FALSE = 57406
View Source
const FIELD = 57408
View Source
const FILL = 57370
View Source
const FOR = 57395
View Source
const FROM = 57346
View Source
const FULL = 57361
View Source
const GRANT = 57390
View Source
const GRANTS = 57396
View Source
const GROUP = 57352
View Source
const GROUPS = 57425
View Source
const GT = 57441
View Source
const GTE = 57442
View Source
const HINT = 57452
View Source
const HOT = 57391
View Source
const IDENT = 57447
View Source
const IN = 57366
View Source
const INDEX = 57389
View Source
const INDEXLIST = 57427
View Source
const INDEXTYPE = 57426
View Source
const INTEGER = 57448
View Source
const JOIN = 57364
View Source
const KEY = 57411
View Source
const KEYS = 57409
View Source
const LIMIT = 57355
View Source
const LPAREN = 57434
View Source
const LT = 57439
View Source
const LTE = 57440
View Source
const MEASUREMENT = 57347
View Source
const MEASUREMENTS = 57382
View Source
const MOD = 57461
View Source
const MUL = 57459
View Source
const NAME = 57375
View Source
const NEQ = 57438
View Source
const NEQREGEX = 57445
View Source
const NOT = 57367
View Source
const NUMBER = 57451
View Source
const OFFSET = 57356
View Source
const ON = 57348
View Source
const OR = 57454
View Source
const ORDER = 57354
View Source
const OUTER = 57363
View Source
const PARTITION = 57429
View Source
const PASSWORD = 57374
View Source
const POLICIES = 57384
View Source
const POLICY = 57385
View Source
const PRIVILEGES = 57362
View Source
const QUERIE = 57420
View Source
const QUERIES = 57419
View Source
const QUERY = 57428
View Source
const REGEX = 57436
View Source
const REPLICANUM = 57376
View Source
const REPLICATION = 57397
View Source
const RETENTION = 57383
View Source
const REVOKE = 57369
View Source
const RPAREN = 57435
View Source
const SELECT = 57349
View Source
const SEMICOLON = 57433
View Source
const SERIES = 57398
View Source
const SET = 57394
View Source
const SHARD = 57388
View Source
const SHARDKEY = 57416
View Source
const SHARDS = 57421
View Source
const SHOW = 57359
View Source
const SLIMIT = 57357
View Source
const SOFFSET = 57358
View Source
const STATS = 57422
View Source
const STRING = 57450
View Source
const SUB = 57456
View Source
const SUBSCRIPTION = 57424
View Source
const SUBSCRIPTIONS = 57423
View Source
const TAG = 57407
View Source
const THEN = 57402
View Source
const TO = 57365
View Source
const TRUE = 57405
View Source
const TYPE = 57393
View Source
const UMINUS = 57463
View Source
const USER = 57378
View Source
const USERS = 57379
View Source
const VALUES = 57410
View Source
const WARM = 57392
View Source
const WHEN = 57401
View Source
const WHERE = 57350
View Source
const WITH = 57372

Variables

View Source
var (
	// ErrInvalidTime is returned when the timestamp string used to
	// compare against time field is invalid.
	ErrInvalidTime            = errors.New("invalid timestamp string")
	ErrNeedBatchMap           = errors.New("try batch map later")
	ErrUnsupportBatchMap      = errors.New("remote node unsupport batch map type")
	ErrDeclareEmptyCollection = errors.New("declare empty collection")
)
View Source
var ErrInvalidDuration = errors.New("invalid duration")

ErrInvalidDuration is returned when parsing a malformed duration.

View Source
var Language = &ParseTree{}

Functions

func BinaryExprName

func BinaryExprName(expr *BinaryExpr) string

BinaryExprName returns the name of a binary expression by concatenating the variables in the binary expression with underscores.

func ConditionExpr

func ConditionExpr(cond Expr, valuer Valuer) (Expr, TimeRange, error)

ConditionExpr extracts the time range and the condition from an expression. We only support simple time ranges that are constrained with AND and are not nested. This throws an error when we encounter a time condition that is combined with OR to prevent returning unexpected results that we do not support.

func ContainsVarRef

func ContainsVarRef(expr Expr) bool

ContainsVarRef returns true if expr is a VarRef or contains one.

func Eval

func Eval(expr Expr, m map[string]interface{}) interface{}

Eval evaluates expr against a map.

func EvalBool

func EvalBool(expr Expr, m map[string]interface{}) bool

EvalBool evaluates expr and returns true if result is a boolean true. Otherwise returns false.

func EvalTypeBatch

func EvalTypeBatch(exprs map[string]Expr, sources Sources, typmap TypeMapper, schema *Schema, batchEn bool) error

EvalType evaluates the expression's type.

func FieldDimensions

func FieldDimensions(sources Sources, m FieldMapper, schema *Schema) (fields map[string]DataType, dimensions map[string]struct{}, err error)

func FormatDuration

func FormatDuration(d time.Duration) string

FormatDuration formats a duration to a string.

func HasTimeExpr

func HasTimeExpr(expr Expr) bool

HasTimeExpr returns true if the expression has a time term.

func IdentNeedsQuotes

func IdentNeedsQuotes(ident string) bool

IdentNeedsQuotes returns true if the ident string given would require quotes.

func IsDOT

func IsDOT(ch rune) bool

func IsRegexOp

func IsRegexOp(t Token) bool

IsRegexOp returns true if the operator accepts a regex operand.

func IsSelector

func IsSelector(expr Expr) bool

func IsSystemName

func IsSystemName(name string) bool

IsSystemName returns true if name is an data system name.

func ParseDuration

func ParseDuration(s string) (time.Duration, error)

ParseDuration parses a time duration from a string. This is needed instead of time.ParseDuration because this will support the full syntax that InfluxQL supports for specifying durations including weeks and days.

func QuoteIdent

func QuoteIdent(segments ...string) string

QuoteIdent returns a quoted identifier from multiple bare identifiers.

func QuoteString

func QuoteString(s string) string

QuoteString returns a quoted string.

func RemoveExtraSpace

func RemoveExtraSpace(s string) string

func Sanitize

func Sanitize(query string) string

Sanitize attempts to sanitize passwords out of a raw query. It looks for patterns that may be related to the SET PASSWORD and CREATE USER statements and will redact the password that should be there. It will attempt to redact information from common invalid queries too, but it's not guaranteed to succeed on improper queries.

This function works on the raw query and attempts to retain the original input as much as possible.

func ScanBareIdent

func ScanBareIdent(r io.RuneScanner, checkDOT bool) string

ScanBareIdent reads bare identifier from a rune reader.

func ScanDelimited

func ScanDelimited(r io.RuneScanner, start, end rune, escapes map[rune]rune, escapesPassThru bool) ([]byte, error)

ScanDelimited reads a delimited set of runes

func ScanString

func ScanString(r io.RuneScanner) (string, error)

ScanString reads a quoted string from a rune reader.

func Walk

func Walk(v Visitor, node Node)

Walk traverses a node hierarchy in depth-first order.

func WalkFunc

func WalkFunc(node Node, fn func(Node))

WalkFunc traverses a node hierarchy in depth-first order.

Types

type AlterRetentionPolicyStatement

type AlterRetentionPolicyStatement struct {
	// Name of policy to alter.
	Name string

	// Name of the database this policy belongs to.
	Database string

	// Duration data written to this policy will be retained.
	Duration *time.Duration

	// Replication factor for data written to this policy.
	Replication *int

	// Should this policy be set as defalut for the database?
	Default bool

	// Duration of the Shard.
	ShardGroupDuration *time.Duration

	// Hot Duration
	HotDuration *time.Duration

	// Warm Duration
	WarmDuration *time.Duration

	// Index Duration
	IndexGroupDuration *time.Duration
}

AlterRetentionPolicyStatement represents a command to alter an existing retention policy.

func (*AlterRetentionPolicyStatement) DefaultDatabase

func (s *AlterRetentionPolicyStatement) DefaultDatabase() string

DefaultDatabase returns the default database from the statement.

func (*AlterRetentionPolicyStatement) RequiredPrivileges

func (s *AlterRetentionPolicyStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute an AlterRetentionPolicyStatement.

func (*AlterRetentionPolicyStatement) String

String returns a string representation of the alter retention policy statement.

type AlterShardKeyStatement

type AlterShardKeyStatement struct {
	Database        string
	RetentionPolicy string
	Name            string
	ShardKey        []string
	Type            string
}

func (*AlterShardKeyStatement) RequiredPrivileges

func (s *AlterShardKeyStatement) RequiredPrivileges() (ExecutionPrivileges, error)

func (*AlterShardKeyStatement) String

func (s *AlterShardKeyStatement) String() string

type BinaryExpr

type BinaryExpr struct {
	Op  Token
	LHS Expr
	RHS Expr
}

BinaryExpr represents an operation between two expressions.

func (*BinaryExpr) String

func (e *BinaryExpr) String() string

String returns a string representation of the binary expression.

type BooleanLiteral

type BooleanLiteral struct {
	Val bool
}

BooleanLiteral represents a boolean literal.

func (*BooleanLiteral) String

func (l *BooleanLiteral) String() string

String returns a string representation of the literal.

type BoundParameter

type BoundParameter struct {
	Name string
}

BoundParameter represents a bound parameter literal. This is not available to the query language itself, but can be used when constructing a query string from an AST.

func (*BoundParameter) String

func (bp *BoundParameter) String() string

String returns a string representation of the bound parameter.

type Call

type Call struct {
	Name string
	Args []Expr
}

Call represents a function call.

func (*Call) String

func (c *Call) String() string

String returns a string representation of the call.

type CallTypeMapper

type CallTypeMapper interface {
	TypeMapper

	CallType(name string, args []DataType) (DataType, error)
}

CallTypeMapper maps a data type to the function call.

type CallValuer

type CallValuer interface {
	Valuer

	// Call is invoked to evaluate a function call (if possible).
	Call(name string, args []interface{}) (interface{}, bool)
}

CallValuer implements the Call method for evaluating function calls.

type CaseWhenExpr

type CaseWhenExpr struct {
	Conditions []Expr
	Assigners  []Expr
	Args       []Expr
}

func (*CaseWhenExpr) String

func (p *CaseWhenExpr) String() string

type CreateContinuousQueryStatement

type CreateContinuousQueryStatement struct {
	// Name of the continuous query to be created.
	Name string

	// Name of the database to create the continuous query on.
	Database string

	// Source of data (SELECT statement).
	Source *SelectStatement

	// Interval to resample previous queries.
	ResampleEvery time.Duration

	// Maximum duration to resample previous queries.
	ResampleFor time.Duration
}

CreateContinuousQueryStatement represents a command for creating a continuous query.

func (*CreateContinuousQueryStatement) DefaultDatabase

func (s *CreateContinuousQueryStatement) DefaultDatabase() string

DefaultDatabase returns the default database from the statement.

func (*CreateContinuousQueryStatement) RequiredPrivileges

func (s *CreateContinuousQueryStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a CreateContinuousQueryStatement.

func (*CreateContinuousQueryStatement) String

String returns a string representation of the statement.

type CreateDatabaseStatement

type CreateDatabaseStatement struct {
	// Name of the database to be created.
	Name string

	// RetentionPolicyCreate indicates whether the user explicitly wants to create a retention policy.
	RetentionPolicyCreate bool

	// RetentionPolicyDuration indicates retention duration for the new database.
	RetentionPolicyDuration *time.Duration

	// RetentionPolicyReplication indicates retention replication for the new database.
	RetentionPolicyReplication *int

	// RetentionPolicyName indicates retention name for the new database.
	RetentionPolicyName string

	// RetentionPolicyShardGroupDuration indicates shard group duration for the new database.
	RetentionPolicyShardGroupDuration time.Duration

	ReplicaNum uint32

	RetentionPolicyHotDuration time.Duration

	RetentionPolicyWarmDuration time.Duration

	RetentionPolicyIndexGroupDuration time.Duration

	ShardKey []string
}

CreateDatabaseStatement represents a command for creating a new database.

func (*CreateDatabaseStatement) RequiredPrivileges

func (s *CreateDatabaseStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a CreateDatabaseStatement.

func (*CreateDatabaseStatement) String

func (s *CreateDatabaseStatement) String() string

String returns a string representation of the create database statement.

type CreateMeasurementStatement

type CreateMeasurementStatement struct {
	Database        string
	RetentionPolicy string
	Name            string
	ShardKey        []string
	Type            string
	IndexType       []string
	IndexList       [][]string
}

func (*CreateMeasurementStatement) RequiredPrivileges

func (s *CreateMeasurementStatement) RequiredPrivileges() (ExecutionPrivileges, error)

func (*CreateMeasurementStatement) String

func (s *CreateMeasurementStatement) String() string

type CreateRetentionPolicyStatement

type CreateRetentionPolicyStatement struct {
	// Name of policy to create.
	Name string

	// Name of database this policy belongs to.
	Database string

	// Duration data written to this policy will be retained.
	Duration time.Duration

	// Replication factor for data written to this policy.
	Replication int

	// Should this policy be set as default for the database?
	Default bool

	// Shard Duration.
	ShardGroupDuration time.Duration

	// Hot Duration
	HotDuration time.Duration

	// Warm Duration
	WarmDuration time.Duration

	// Index Duration
	IndexGroupDuration time.Duration
}

CreateRetentionPolicyStatement represents a command to create a retention policy.

func (*CreateRetentionPolicyStatement) DefaultDatabase

func (s *CreateRetentionPolicyStatement) DefaultDatabase() string

DefaultDatabase returns the default database from the statement.

func (*CreateRetentionPolicyStatement) RequiredPrivileges

func (s *CreateRetentionPolicyStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a CreateRetentionPolicyStatement.

func (*CreateRetentionPolicyStatement) String

String returns a string representation of the create retention policy.

type CreateSubscriptionStatement

type CreateSubscriptionStatement struct {
	Name            string
	Database        string
	RetentionPolicy string
	Destinations    []string
	Mode            string
}

CreateSubscriptionStatement represents a command to add a subscription to the incoming data stream.

func (*CreateSubscriptionStatement) DefaultDatabase

func (s *CreateSubscriptionStatement) DefaultDatabase() string

DefaultDatabase returns the default database from the statement.

func (*CreateSubscriptionStatement) RequiredPrivileges

func (s *CreateSubscriptionStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a CreateSubscriptionStatement.

func (*CreateSubscriptionStatement) String

func (s *CreateSubscriptionStatement) String() string

String returns a string representation of the CreateSubscriptionStatement.

type CreateUserStatement

type CreateUserStatement struct {
	// Name of the user to be created.
	Name string

	// User's password.
	Password string

	// User's admin privilege.
	Admin bool

	//rwuser
	Rwuser bool
}

CreateUserStatement represents a command for creating a new user.

func (*CreateUserStatement) RequiredPrivileges

func (s *CreateUserStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege(s) required to execute a CreateUserStatement.

func (*CreateUserStatement) String

func (s *CreateUserStatement) String() string

String returns a string representation of the create user statement.

type DataType

type DataType int

DataType represents the primitive data types available in InfluxQL.

const (
	// Unknown primitive data type.
	Unknown DataType = 0
	// Float means the data type is a float.
	Float DataType = 1
	// Integer means the data type is an integer.
	Integer DataType = 2
	// String means the data type is a string of text.
	String DataType = 3
	// Boolean means the data type is a boolean.
	Boolean DataType = 4
	// Time means the data type is a time.
	Time DataType = 5
	// Duration means the data type is a duration of time.
	Duration DataType = 6
	// Tag means the data type is a tag.
	Tag DataType = 7
	// AnyField means the data type is any field.
	AnyField DataType = 8
	// Unsigned means the data type is an unsigned integer.
	Unsigned DataType = 9
)

func DataTypeFromString

func DataTypeFromString(s string) DataType

DataTypeFromString returns a data type given the string representation of that data type.

func EvalType

func EvalType(expr Expr, sources Sources, typmap TypeMapper) DataType

EvalType evaluates the expression's type.

func InspectDataType

func InspectDataType(v interface{}) DataType

InspectDataType returns the data type of a given value.

func (DataType) LessThan

func (d DataType) LessThan(other DataType) bool

LessThan returns true if the other DataType has greater precedence than the current data type. Unknown has the lowest precedence.

NOTE: This is not the same as using the `<` or `>` operator because the integers used decrease with higher precedence, but Unknown is the lowest precedence at the zero value.

func (DataType) String

func (d DataType) String() string

String returns the human-readable string representation of the DataType.

func (DataType) Zero

func (d DataType) Zero() interface{}

Zero returns the zero value for the DataType. The return value of this method, when sent back to InspectDataType, may not produce the same value.

type DeleteSeriesStatement

type DeleteSeriesStatement struct {
	// Data source that fields are extracted from (optional)
	Sources Sources

	// An expression evaluated on data point (optional)
	Condition Expr
}

DeleteSeriesStatement represents a command for deleting all or part of a series from a database.

func (DeleteSeriesStatement) RequiredPrivileges

func (s DeleteSeriesStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a DeleteSeriesStatement.

func (*DeleteSeriesStatement) String

func (s *DeleteSeriesStatement) String() string

String returns a string representation of the delete series statement.

type DeleteStatement

type DeleteStatement struct {
	// Data source that values are removed from.
	Source Source

	// An expression evaluated on data point.
	Condition Expr
}

DeleteStatement represents a command for deleting data from the database.

func (*DeleteStatement) DefaultDatabase

func (s *DeleteStatement) DefaultDatabase() string

DefaultDatabase returns the default database from the statement.

func (*DeleteStatement) RequiredPrivileges

func (s *DeleteStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a DeleteStatement.

func (*DeleteStatement) String

func (s *DeleteStatement) String() string

String returns a string representation of the delete statement.

type Dimension

type Dimension struct {
	Expr Expr
}

Dimension represents an expression that a select statement is grouped by.

func (*Dimension) String

func (d *Dimension) String() string

String returns a string representation of the dimension.

type Dimensions

type Dimensions []*Dimension

Dimensions represents a list of dimensions.

func (Dimensions) Normalize

func (a Dimensions) Normalize() (time.Duration, []string)

Normalize returns the interval and tag dimensions separately. Returns 0 if no time interval is specified.

func (Dimensions) String

func (a Dimensions) String() string

String returns a string representation of the dimensions.

type Distinct

type Distinct struct {
	// Identifier following DISTINCT
	Val string
}

Distinct represents a DISTINCT expression.

func (*Distinct) NewCall

func (d *Distinct) NewCall() *Call

NewCall returns a new call expression from this expressions.

func (*Distinct) String

func (d *Distinct) String() string

String returns a string representation of the expression.

type DropContinuousQueryStatement

type DropContinuousQueryStatement struct {
	Name     string
	Database string
}

DropContinuousQueryStatement represents a command for removing a continuous query.

func (*DropContinuousQueryStatement) DefaultDatabase

func (s *DropContinuousQueryStatement) DefaultDatabase() string

DefaultDatabase returns the default database from the statement.

func (*DropContinuousQueryStatement) RequiredPrivileges

func (s *DropContinuousQueryStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege(s) required to execute a DropContinuousQueryStatement

func (*DropContinuousQueryStatement) String

String returns a string representation of the statement.

type DropDatabaseStatement

type DropDatabaseStatement struct {
	// Name of the database to be dropped.
	Name string
}

DropDatabaseStatement represents a command to drop a database.

func (*DropDatabaseStatement) RequiredPrivileges

func (s *DropDatabaseStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a DropDatabaseStatement.

func (*DropDatabaseStatement) String

func (s *DropDatabaseStatement) String() string

String returns a string representation of the drop database statement.

type DropMeasurementStatement

type DropMeasurementStatement struct {
	// Name of the measurement to be dropped.
	Name string
}

DropMeasurementStatement represents a command to drop a measurement.

func (*DropMeasurementStatement) RequiredPrivileges

func (s *DropMeasurementStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege(s) required to execute a DropMeasurementStatement

func (*DropMeasurementStatement) String

func (s *DropMeasurementStatement) String() string

String returns a string representation of the drop measurement statement.

type DropRetentionPolicyStatement

type DropRetentionPolicyStatement struct {
	// Name of the policy to drop.
	Name string

	// Name of the database to drop the policy from.
	Database string
}

DropRetentionPolicyStatement represents a command to drop a retention policy from a database.

func (*DropRetentionPolicyStatement) DefaultDatabase

func (s *DropRetentionPolicyStatement) DefaultDatabase() string

DefaultDatabase returns the default database from the statement.

func (*DropRetentionPolicyStatement) RequiredPrivileges

func (s *DropRetentionPolicyStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a DropRetentionPolicyStatement.

func (*DropRetentionPolicyStatement) String

String returns a string representation of the drop retention policy statement.

type DropSeriesStatement

type DropSeriesStatement struct {
	// Data source that fields are extracted from (optional)
	Sources Sources

	// An expression evaluated on data point (optional)
	Condition Expr
}

DropSeriesStatement represents a command for removing a series from the database.

func (DropSeriesStatement) RequiredPrivileges

func (s DropSeriesStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a DropSeriesStatement.

func (*DropSeriesStatement) String

func (s *DropSeriesStatement) String() string

String returns a string representation of the drop series statement.

type DropShardStatement

type DropShardStatement struct {
	// ID of the shard to be dropped.
	ID uint64
}

DropShardStatement represents a command for removing a shard from the node.

func (*DropShardStatement) RequiredPrivileges

func (s *DropShardStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a DropShardStatement.

func (*DropShardStatement) String

func (s *DropShardStatement) String() string

String returns a string representation of the drop series statement.

type DropSubscriptionStatement

type DropSubscriptionStatement struct {
	Name            string
	Database        string
	RetentionPolicy string
}

DropSubscriptionStatement represents a command to drop a subscription to the incoming data stream.

func (*DropSubscriptionStatement) DefaultDatabase

func (s *DropSubscriptionStatement) DefaultDatabase() string

DefaultDatabase returns the default database from the statement.

func (*DropSubscriptionStatement) RequiredPrivileges

func (s *DropSubscriptionStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a DropSubscriptionStatement

func (*DropSubscriptionStatement) String

func (s *DropSubscriptionStatement) String() string

String returns a string representation of the DropSubscriptionStatement.

type DropUserStatement

type DropUserStatement struct {
	// Name of the user to drop.
	Name string
}

DropUserStatement represents a command for dropping a user.

func (*DropUserStatement) RequiredPrivileges

func (s *DropUserStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege(s) required to execute a DropUserStatement.

func (*DropUserStatement) String

func (s *DropUserStatement) String() string

String returns a string representation of the drop user statement.

type DurationLiteral

type DurationLiteral struct {
	Val time.Duration
}

DurationLiteral represents a duration literal.

func (*DurationLiteral) String

func (l *DurationLiteral) String() string

String returns a string representation of the literal.

type EndPrepareSnapshotStatement

type EndPrepareSnapshotStatement struct{}

EndPrepareSnapshotStatement represents a command for preparing preparing.

func (*EndPrepareSnapshotStatement) RequiredPrivileges

func (s *EndPrepareSnapshotStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a EndPrepareSnapshotStatement.

func (*EndPrepareSnapshotStatement) String

func (s *EndPrepareSnapshotStatement) String() string

String returns a string representation of the end prepare preparing command.

type ExecutionPrivilege

type ExecutionPrivilege struct {
	// Admin privilege required.
	Admin bool

	// Name of the database.
	Name string

	//flag the stmt can be executed by rwuser
	Rwuser bool

	// Database privilege required.
	Privilege Privilege
}

ExecutionPrivilege is a privilege required for a user to execute a statement on a database or resource.

type ExecutionPrivileges

type ExecutionPrivileges []ExecutionPrivilege

ExecutionPrivileges is a list of privileges required to execute a statement.

type ExplainStatement

type ExplainStatement struct {
	Statement *SelectStatement

	Analyze bool
}

ExplainStatement represents a command for explaining a select statement.

func (*ExplainStatement) RequiredPrivileges

func (e *ExplainStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a ExplainStatement.

func (*ExplainStatement) String

func (e *ExplainStatement) String() string

String returns a string representation of the explain statement.

type Expr

type Expr interface {
	Node
	// contains filtered or unexported methods
}

Expr represents an expression that can be evaluated to a value.

func CloneExpr

func CloneExpr(expr Expr) Expr

CloneExpr returns a deep copy of the expression.

func MustParseExpr

func MustParseExpr(s string) Expr

MustParseExpr parses an expression string and returns its AST. Panic on error.

func ParseExpr

func ParseExpr(s string) (Expr, error)

ParseExpr parses an expression string and returns its AST representation.

func Reduce

func Reduce(expr Expr, valuer Valuer) Expr

Reduce evaluates expr using the available values in valuer. References that don't exist in valuer are ignored.

func RewriteExpr

func RewriteExpr(expr Expr, fn func(Expr) Expr) Expr

RewriteExpr recursively invokes the function to replace each expr. Nodes are traversed depth-first and rewritten from leaf to root.

type Field

type Field struct {
	Expr  Expr
	Alias string
}

Field represents an expression retrieved from a select statement.

func (*Field) Name

func (f *Field) Name() string

Name returns the name of the field. Returns alias, if set. Otherwise uses the function name or variable name.

func (*Field) String

func (f *Field) String() string

String returns a string representation of the field.

type FieldMapper

type FieldMapper interface {
	FieldDimensions(m *Measurement) (fields map[string]DataType, dimensions map[string]struct{}, schema *Schema, err error)

	TypeMapper
}

FieldMapper returns the data type for the field inside of the measurement.

type Fields

type Fields []*Field

Fields represents a list of fields.

func (Fields) AliasNames

func (a Fields) AliasNames() []string

AliasNames returns a list of calculated field names in order of alias, function name, then field.

func (Fields) Len

func (a Fields) Len() int

Len implements sort.Interface.

func (Fields) Less

func (a Fields) Less(i, j int) bool

Less implements sort.Interface.

func (Fields) Names

func (a Fields) Names() []string

Names returns a list of field names.

func (Fields) String

func (a Fields) String() string

String returns a string representation of the fields.

func (Fields) Swap

func (a Fields) Swap(i, j int)

Swap implements sort.Interface.

type FillOption

type FillOption int

FillOption represents different options for filling aggregate windows.

const (
	// NullFill means that empty aggregate windows will just have null values.
	NullFill FillOption = iota
	// NoFill means that empty aggregate windows will be purged from the result.
	NoFill
	// NumberFill means that empty aggregate windows will be filled with a provided number.
	NumberFill
	// PreviousFill means that empty aggregate windows will be filled with whatever the previous aggregate window had.
	PreviousFill
	// LinearFill means that empty aggregate windows will be filled with whatever a linear value between non null windows.
	LinearFill
)

type GetRuntimeInfoStatement

type GetRuntimeInfoStatement struct{}

GetRuntimeInfoStatement represents a command for get runtimeinfo.

func (*GetRuntimeInfoStatement) RequiredPrivileges

func (s *GetRuntimeInfoStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a GetRuntimeInfoStatement.

func (*GetRuntimeInfoStatement) String

func (s *GetRuntimeInfoStatement) String() string

String returns a string representation of the get runtimeinfo command.

type GrantAdminStatement

type GrantAdminStatement struct {
	// Who to grant the privilege to.
	User string
}

GrantAdminStatement represents a command for granting admin privilege.

func (*GrantAdminStatement) RequiredPrivileges

func (s *GrantAdminStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a GrantAdminStatement.

func (*GrantAdminStatement) String

func (s *GrantAdminStatement) String() string

String returns a string representation of the grant admin statement.

type GrantStatement

type GrantStatement struct {
	// The privilege to be granted.
	Privilege Privilege

	// Database to grant the privilege to.
	On string

	// Who to grant the privilege to.
	User string
}

GrantStatement represents a command for granting a privilege.

func (*GrantStatement) DefaultDatabase

func (s *GrantStatement) DefaultDatabase() string

DefaultDatabase returns the default database from the statement.

func (*GrantStatement) RequiredPrivileges

func (s *GrantStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a GrantStatement.

func (*GrantStatement) String

func (s *GrantStatement) String() string

String returns a string representation of the grant statement.

type HasDefaultDatabase

type HasDefaultDatabase interface {
	Node

	DefaultDatabase() string
	// contains filtered or unexported methods
}

HasDefaultDatabase provides an interface to get the default database from a Statement.

type Hint

type Hint struct {
	Expr Expr
}

func (*Hint) String

func (d *Hint) String() string

String returns a string representation of the dimension.

type Hints

type Hints []*Hint

func (Hints) String

func (a Hints) String() string

type IntegerLiteral

type IntegerLiteral struct {
	Val int64
}

IntegerLiteral represents an integer literal.

func (*IntegerLiteral) String

func (l *IntegerLiteral) String() string

String returns a string representation of the literal.

type KillQueryStatement

type KillQueryStatement struct {
	// The query to kill.
	QueryID uint64

	// The host to delegate the kill to.
	Host string
}

KillQueryStatement represents a command for killing a query.

func (*KillQueryStatement) RequiredPrivileges

func (s *KillQueryStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a KillQueryStatement.

func (*KillQueryStatement) String

func (s *KillQueryStatement) String() string

String returns a string representation of the kill query statement.

type ListLiteral

type ListLiteral struct {
	Vals []string
}

ListLiteral represents a list of tag key literals.

func (*ListLiteral) String

func (s *ListLiteral) String() string

String returns a string representation of the literal.

type Literal

type Literal interface {
	Expr
	// contains filtered or unexported methods
}

Literal represents a static literal.

type MapValuer

type MapValuer map[string]interface{}

MapValuer is a valuer that substitutes values for the mapped interface.

func (MapValuer) SetValuer

func (m MapValuer) SetValuer(v Valuer, index int)

func (MapValuer) Value

func (m MapValuer) Value(key string) (interface{}, bool)

Value returns the value for a key in the MapValuer.

type Measurement

type Measurement struct {
	Database        string
	RetentionPolicy string
	Name            string
	Regex           *RegexLiteral
	IsTarget        bool

	// This field indicates that the measurement should read be read from the
	// specified system iterator.
	SystemIterator    string
	IsSystemStatement bool
}

Measurement represents a single measurement used as a datasource.

func (*Measurement) Clone

func (m *Measurement) Clone() *Measurement

Clone returns a deep clone of the Measurement.

func (*Measurement) String

func (m *Measurement) String() string

String returns a string representation of the measurement.

type Measurements

type Measurements []*Measurement

Measurements represents a list of measurements.

func (Measurements) String

func (a Measurements) String() string

String returns a string representation of the measurements.

type NilLiteral

type NilLiteral struct{}

NilLiteral represents a nil literal. This is not available to the query language itself. It's only used internally.

func (*NilLiteral) String

func (l *NilLiteral) String() string

String returns a string representation of the literal.

type Node

type Node interface {
	String() string
	// contains filtered or unexported methods
}

Node represents a node in the InfluxDB abstract syntax tree.

func Rewrite

func Rewrite(r Rewriter, node Node) Node

Rewrite recursively invokes the rewriter to replace each node. Nodes are traversed depth-first and rewritten from leaf to root.

func RewriteFunc

func RewriteFunc(node Node, fn func(Node) Node) Node

RewriteFunc rewrites a node hierarchy.

func RewriteOpsNest

func RewriteOpsNest(r RewriterOpsNest, node Node) Node

RewriteOpsNest recursively invokes the rewriter to replace each node. Nodes are traversed depth-first and rewritten from leaf to root.

func RewriteOpsNestFunc

func RewriteOpsNestFunc(node Node, fn func(Node) Node) Node

RewriteOpsNestFunc rewrites a node hierarchy.

func RewriteTopBottomStatement

func RewriteTopBottomStatement(node Node) Node

RewriteTopBottomStatement converts a query with a tag in the top or bottom to a subquery

type NowValuer

type NowValuer struct {
	Now      time.Time
	Location *time.Location
}

NowValuer returns only the value for "now()".

func (*NowValuer) Call

func (v *NowValuer) Call(name string, args []interface{}) (interface{}, bool)

Call evaluates the now() function to replace now() with the current time.

func (*NowValuer) SetValuer

func (v *NowValuer) SetValuer(vv Valuer, index int)

func (*NowValuer) Value

func (v *NowValuer) Value(key string) (interface{}, bool)

Value is a method that returns the value and existence flag for a given key.

func (*NowValuer) Zone

func (v *NowValuer) Zone() *time.Location

Zone is a method that returns the time.Location.

type NumberLiteral

type NumberLiteral struct {
	Val float64
}

NumberLiteral represents a numeric literal.

func (*NumberLiteral) String

func (l *NumberLiteral) String() string

String returns a string representation of the literal.

type ParenExpr

type ParenExpr struct {
	Expr Expr
}

ParenExpr represents a parenthesized expression.

func (*ParenExpr) String

func (e *ParenExpr) String() string

String returns a string representation of the parenthesized expression.

type ParseError

type ParseError struct {
	Message  string
	Found    string
	Expected []string
	Pos      Pos
}

ParseError represents an error that occurred during parsing.

func (*ParseError) Error

func (e *ParseError) Error() string

Error returns the string representation of the error.

type ParseTree

type ParseTree struct {
	Handlers map[Token]func(*Parser) (Statement, error)
	Tokens   map[Token]*ParseTree
	Keys     []string
}

func (*ParseTree) Clone

func (t *ParseTree) Clone() *ParseTree

func (*ParseTree) Group

func (t *ParseTree) Group(tokens ...Token) *ParseTree

Group groups together a set of related handlers with a common token prefix.

func (*ParseTree) Handle

func (t *ParseTree) Handle(tok Token, fn func(*Parser) (Statement, error))

Handle registers a handler to be invoked when seeing the given token.

func (*ParseTree) Parse

func (t *ParseTree) Parse(p *Parser) (Statement, error)

Parse parses a statement using the language defined in the parse tree.

func (*ParseTree) With

func (t *ParseTree) With(fn func(*ParseTree))

With passes the current parse tree to a function to allow nested functions.

type Parser

type Parser struct {
	// contains filtered or unexported fields
}

Parser represents an InfluxQL parser.

func NewParser

func NewParser(r io.Reader) *Parser

NewParser returns a new instance of Parser.

func (*Parser) GetScanner

func (p *Parser) GetScanner() *Scanner

func (*Parser) ParseDuration

func (p *Parser) ParseDuration() (time.Duration, error)

ParseDuration parses a string and returns a duration literal. This function assumes the DURATION token has already been consumed.

func (*Parser) ParseExpr

func (p *Parser) ParseExpr() (Expr, error)

ParseExpr parses an expression.

func (*Parser) ParseIdent

func (p *Parser) ParseIdent() (string, error)

ParseIdent parses an identifier.

func (*Parser) ParseIdentList

func (p *Parser) ParseIdentList() ([]string, error)

ParseIdentList parses a comma delimited list of identifiers.

func (*Parser) ParseInt

func (p *Parser) ParseInt(min, max int) (int, error)

ParseInt parses a string representing a base 10 integer and returns the number. It returns an error if the parsed number is outside the range [min, max].

func (*Parser) ParseOptionalTokenAndInt

func (p *Parser) ParseOptionalTokenAndInt(t Token) (int, error)

ParseOptionalTokenAndInt parses the specified token followed by an int, if it exists.

func (*Parser) ParseQuery

func (p *Parser) ParseQuery() (*Query, error)

ParseQuery parses an InfluxQL string and returns a Query AST object.

func (*Parser) ParseStatement

func (p *Parser) ParseStatement() (Statement, error)

ParseStatement parses an InfluxQL string and returns a Statement AST object.

func (*Parser) ParseUInt64

func (p *Parser) ParseUInt64() (uint64, error)

ParseUInt64 parses a string and returns a 64-bit unsigned integer literal.

func (*Parser) ParseVarRef

func (p *Parser) ParseVarRef() (*VarRef, error)

ParseVarRef parses a reference to a measurement or field.

func (*Parser) Release

func (p *Parser) Release()

func (*Parser) Scan

func (p *Parser) Scan() (tok Token, pos Pos, lit string)

scan returns the next token from the underlying scanner.

func (*Parser) ScanIgnoreWhitespace

func (p *Parser) ScanIgnoreWhitespace() (tok Token, pos Pos, lit string)

ScanIgnoreWhitespace scans the next non-whitespace and non-comment token.

func (*Parser) SetParams

func (p *Parser) SetParams(params map[string]interface{})

SetParams sets the parameters that will be used for any bound parameter substitutions.

func (*Parser) Unscan

func (p *Parser) Unscan()

Unscan pushes the previously read token back onto the buffer.

type Pos

type Pos struct {
	Line int
	Char int
}

Pos specifies the line and character position of a token. The Char and Line are both zero-based indexes.

type PrepareSnapshotStatement

type PrepareSnapshotStatement struct{}

PrepareSnapshotStatement represents a command for preparing preparing.

func (*PrepareSnapshotStatement) RequiredPrivileges

func (s *PrepareSnapshotStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a PrepareSnapshotStatement.

func (*PrepareSnapshotStatement) String

func (s *PrepareSnapshotStatement) String() string

String returns a string representation of the prepare preparing command.

type Privilege

type Privilege int

Privilege is a type of action a user can be granted the right to use.

const (
	// NoPrivileges means no privileges required / granted / revoked.
	NoPrivileges Privilege = iota
	// ReadPrivilege means read privilege required / granted / revoked.
	ReadPrivilege
	// WritePrivilege means write privilege required / granted / revoked.
	WritePrivilege
	// AllPrivileges means all privileges required / granted / revoked.
	AllPrivileges
)

func NewPrivilege

func NewPrivilege(p Privilege) *Privilege

NewPrivilege returns an initialized *Privilege.

func (Privilege) String

func (p Privilege) String() string

String returns a string representation of a Privilege.

type Query

type Query struct {
	Statements Statements
}

Query represents a collection of ordered statements.

func ParseQuery

func ParseQuery(s string) (*Query, error)

ParseQuery parses a query string and returns its AST representation.

func (*Query) String

func (q *Query) String() string

String returns a string representation of the query.

type RegexLiteral

type RegexLiteral struct {
	Val *regexp.Regexp
}

RegexLiteral represents a regular expression.

func CloneRegexLiteral

func CloneRegexLiteral(r *RegexLiteral) *RegexLiteral

CloneRegexLiteral returns a clone of the RegexLiteral.

func (*RegexLiteral) String

func (r *RegexLiteral) String() string

String returns a string representation of the literal.

type RevokeAdminStatement

type RevokeAdminStatement struct {
	// Who to revoke admin privilege from.
	User string
}

RevokeAdminStatement represents a command to revoke admin privilege from a user.

func (*RevokeAdminStatement) RequiredPrivileges

func (s *RevokeAdminStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a RevokeAdminStatement.

func (*RevokeAdminStatement) String

func (s *RevokeAdminStatement) String() string

String returns a string representation of the revoke admin statement.

type RevokeStatement

type RevokeStatement struct {
	// The privilege to be revoked.
	Privilege Privilege

	// Database to revoke the privilege from.
	On string

	// Who to revoke privilege from.
	User string
}

RevokeStatement represents a command to revoke a privilege from a user.

func (*RevokeStatement) DefaultDatabase

func (s *RevokeStatement) DefaultDatabase() string

DefaultDatabase returns the default database from the statement.

func (*RevokeStatement) RequiredPrivileges

func (s *RevokeStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a RevokeStatement.

func (*RevokeStatement) String

func (s *RevokeStatement) String() string

String returns a string representation of the revoke statement.

type Rewriter

type Rewriter interface {
	Rewrite(Node) Node
}

Rewriter can be called by Rewrite to replace nodes in the AST hierarchy. The Rewrite() function is called once per node.

type RewriterOpsNest

type RewriterOpsNest interface {
	RewriteOpsNest(Node) Node
}

type Scanner

type Scanner struct {
	// contains filtered or unexported fields
}

Scanner represents a lexical scanner for InfluxQL.

func NewScanner

func NewScanner(r io.Reader) *Scanner

NewScanner returns a new instance of Scanner.

func (*Scanner) Scan

func (s *Scanner) Scan() (tok Token, pos Pos, lit string)

Scan returns the next token and position from the underlying reader. Also returns the literal text read for strings, numbers, and duration tokens since these token types can have different literal representations.

func (*Scanner) ScanRegex

func (s *Scanner) ScanRegex() (tok Token, pos Pos, lit string)

ScanRegex consumes a token to find escapes

type Schema

type Schema struct {
	TagKeys  []string
	Files    int64
	FileSize int64
	MinTime  int64
	MaxTime  int64
}

func (*Schema) AddMinMaxTime

func (s *Schema) AddMinMaxTime(minT, maxT int64)

type SelectStatement

type SelectStatement struct {
	// Expressions returned from the selection.
	Fields Fields

	// Target (destination) for the result of a SELECT INTO query.
	Target *Target

	// Expressions used for grouping the selection.
	Dimensions Dimensions

	//Expressions used for optimize querys
	Hints Hints

	// Data sources (measurements) that fields are extracted from.
	Sources Sources

	// An expression evaluated on data point.
	Condition Expr

	// Fields to sort results by.
	SortFields SortFields

	// Maximum number of rows to be returned. Unlimited if zero.
	Limit int

	// Returns rows starting at an offset from the first row.
	Offset int

	// Maxiumum number of series to be returned. Unlimited if zero.
	SLimit int

	// Returns series starting at an offset from the first one.
	SOffset int

	// Whether it's a query for raw data values (i.e. not an aggregate).
	IsRawQuery bool

	// What fill option the select statement uses, if any.
	Fill FillOption

	// The value to fill empty aggregate buckets with, if any.
	FillValue interface{}

	// The timezone for the query, if any.
	Location *time.Location

	// Renames the implicit time field name.
	TimeAlias string

	// Removes the "time" column from the output.
	OmitTime bool

	// Removes measurement name from resulting query. Useful for meta queries.
	StripName bool

	// Overrides the output measurement name.
	EmitName string

	// Removes duplicate rows from raw queries.
	Dedupe bool

	Schema Schema

	// GroupByAllDims is true when group by single series
	GroupByAllDims bool
	// contains filtered or unexported fields
}

SelectStatement represents a command for extracting data from the database.

func (*SelectStatement) Clone

func (s *SelectStatement) Clone() *SelectStatement

Clone returns a deep copy of the statement.

func (*SelectStatement) ColumnNames

func (s *SelectStatement) ColumnNames() []string

ColumnNames will walk all fields and functions and return the appropriate field names for the select statement while maintaining order of the field names.

func (*SelectStatement) FieldExprByName

func (s *SelectStatement) FieldExprByName(name string) (int, Expr)

FieldExprByName returns the expression that matches the field name and the index where this was found. If the name matches one of the arguments to "top" or "bottom", the variable reference inside of the function is returned and the index is of the function call rather than the variable reference. If no expression is found, -1 is returned for the index and the expression will be nil.

func (*SelectStatement) GroupByInterval

func (s *SelectStatement) GroupByInterval() (time.Duration, error)

GroupByInterval extracts the time interval, if specified.

func (*SelectStatement) GroupByOffset

func (s *SelectStatement) GroupByOffset() (time.Duration, error)

GroupByOffset extracts the time interval offset, if specified.

func (*SelectStatement) HasDimensionWildcard

func (s *SelectStatement) HasDimensionWildcard() bool

HasDimensionWildcard returns whether or not the select statement has at least 1 wildcard in the dimensions aka `GROUP BY`.

func (*SelectStatement) HasFieldWildcard

func (s *SelectStatement) HasFieldWildcard() (hasWildcard bool)

HasFieldWildcard returns whether or not the select statement has at least 1 wildcard in the fields.

func (*SelectStatement) HasWildcard

func (s *SelectStatement) HasWildcard() bool

HasWildcard returns whether or not the select statement has at least 1 wildcard.

func (*SelectStatement) Reduce

func (s *SelectStatement) Reduce(valuer Valuer) *SelectStatement

Reduce calls the Reduce function on the different components of the SelectStatement to reduce the statement.

func (*SelectStatement) RequiredPrivileges

func (s *SelectStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute the SelectStatement. NOTE: Statement should be normalized first (database name(s) in Sources and Target should be populated). If the statement has not been normalized, an empty string will be returned for the database name and it is up to the caller to interpret that as the default database.

func (*SelectStatement) RewriteDistinct

func (s *SelectStatement) RewriteDistinct()

RewriteDistinct rewrites the expression to be a call for map/reduce to work correctly. This method assumes all validation has passed.

func (*SelectStatement) RewriteFields

func (s *SelectStatement) RewriteFields(m FieldMapper, batchEn bool) (*SelectStatement, error)

RewriteFields returns the re-written form of the select statement. Any wildcard query fields are replaced with the supplied fields, and any wildcard GROUP BY fields are replaced with the supplied dimensions. Any fields with no type specifier are rewritten with the appropriate type.

func (*SelectStatement) RewriteRegexConditions

func (s *SelectStatement) RewriteRegexConditions()

RewriteRegexConditions rewrites regex conditions to make better use of the database index.

Conditions that can currently be simplified are:

  • host =~ /^foo$/ becomes host = 'foo'
  • host !~ /^foo$/ becomes host != 'foo'

Note: if the regex contains groups, character classes, repetition or similar, it's likely it won't be rewritten. In order to support rewriting regexes with these characters would be a lot more work.

func (*SelectStatement) RewriteTimeFields

func (s *SelectStatement) RewriteTimeFields()

RewriteTimeFields removes any "time" field references.

func (*SelectStatement) RewriteTopBottom

func (s *SelectStatement) RewriteTopBottom()

RewriteTopBottom converts a query with a tag in the top or bottom to a subquery

func (*SelectStatement) SetTimeInterval

func (s *SelectStatement) SetTimeInterval(t time.Duration)

func (*SelectStatement) SetTimeRange

func (s *SelectStatement) SetTimeRange(start, end time.Time) error

SetTimeRange sets the start and end time of the select statement to [start, end). i.e. start inclusive, end exclusive. This is used commonly for continuous queries so the start and end are in buckets.

func (*SelectStatement) String

func (s *SelectStatement) String() string

String returns a string representation of the select statement.

func (*SelectStatement) TimeAscending

func (s *SelectStatement) TimeAscending() bool

TimeAscending returns true if the time field is sorted in chronological order.

func (*SelectStatement) TimeFieldName

func (s *SelectStatement) TimeFieldName() string

TimeFieldName returns the name of the time field.

type SetPasswordUserStatement

type SetPasswordUserStatement struct {
	// Plain-text password.
	Password string

	// Who to grant the privilege to.
	Name string
}

SetPasswordUserStatement represents a command for changing user password.

func (*SetPasswordUserStatement) RequiredPrivileges

func (s *SetPasswordUserStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a SetPasswordUserStatement.

func (*SetPasswordUserStatement) String

func (s *SetPasswordUserStatement) String() string

String returns a string representation of the set password statement.

type ShowContinuousQueriesStatement

type ShowContinuousQueriesStatement struct{}

ShowContinuousQueriesStatement represents a command for listing continuous queries.

func (*ShowContinuousQueriesStatement) RequiredPrivileges

func (s *ShowContinuousQueriesStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a ShowContinuousQueriesStatement.

func (*ShowContinuousQueriesStatement) String

String returns a string representation of the show continuous queries statement.

type ShowDatabasesStatement

type ShowDatabasesStatement struct{}

ShowDatabasesStatement represents a command for listing all databases in the cluster.

func (*ShowDatabasesStatement) RequiredPrivileges

func (s *ShowDatabasesStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a ShowDatabasesStatement.

func (*ShowDatabasesStatement) String

func (s *ShowDatabasesStatement) String() string

String returns a string representation of the show databases command.

type ShowDiagnosticsStatement

type ShowDiagnosticsStatement struct {
	// Module
	Module string
}

ShowDiagnosticsStatement represents a command for show node diagnostics.

func (*ShowDiagnosticsStatement) RequiredPrivileges

func (s *ShowDiagnosticsStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a ShowDiagnosticsStatement

func (*ShowDiagnosticsStatement) String

func (s *ShowDiagnosticsStatement) String() string

String returns a string representation of the ShowDiagnosticsStatement.

type ShowFieldKeyCardinalityStatement

type ShowFieldKeyCardinalityStatement struct {
	Database      string
	Exact         bool
	Sources       Sources
	Condition     Expr
	Dimensions    Dimensions
	Limit, Offset int
}

ShowFieldKeyCardinalityStatement represents a command for listing field key cardinality.

func (*ShowFieldKeyCardinalityStatement) DefaultDatabase

func (s *ShowFieldKeyCardinalityStatement) DefaultDatabase() string

DefaultDatabase returns the default database from the statement.

func (*ShowFieldKeyCardinalityStatement) RequiredPrivileges

func (s *ShowFieldKeyCardinalityStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a ShowFieldKeyCardinalityStatement.

func (*ShowFieldKeyCardinalityStatement) String

String returns a string representation of the statement.

type ShowFieldKeysStatement

type ShowFieldKeysStatement struct {
	// Database to query. If blank, use the default database.
	// The database can also be specified per source in the Sources.
	Database string

	// Data sources that fields are extracted from.
	Sources Sources

	// Fields to sort results by
	SortFields SortFields

	// Maximum number of rows to be returned.
	// Unlimited if zero.
	Limit int

	// Returns rows starting at an offset from the first row.
	Offset int
}

ShowFieldKeysStatement represents a command for listing field keys.

func (*ShowFieldKeysStatement) DefaultDatabase

func (s *ShowFieldKeysStatement) DefaultDatabase() string

DefaultDatabase returns the default database from the statement.

func (*ShowFieldKeysStatement) RequiredPrivileges

func (s *ShowFieldKeysStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege(s) required to execute a ShowFieldKeysStatement.

func (*ShowFieldKeysStatement) String

func (s *ShowFieldKeysStatement) String() string

String returns a string representation of the statement.

type ShowGrantsForUserStatement

type ShowGrantsForUserStatement struct {
	// Name of the user to display privileges.
	Name string
}

ShowGrantsForUserStatement represents a command for listing user privileges.

func (*ShowGrantsForUserStatement) RequiredPrivileges

func (s *ShowGrantsForUserStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a ShowGrantsForUserStatement

func (*ShowGrantsForUserStatement) String

func (s *ShowGrantsForUserStatement) String() string

String returns a string representation of the show grants for user.

type ShowMeasurementCardinalityStatement

type ShowMeasurementCardinalityStatement struct {
	Exact         bool // If false then cardinality estimation will be used.
	Database      string
	Sources       Sources
	Condition     Expr
	Dimensions    Dimensions
	Limit, Offset int
}

ShowMeasurementCardinalityStatement represents a command for listing measurement cardinality.

func (*ShowMeasurementCardinalityStatement) DefaultDatabase

func (s *ShowMeasurementCardinalityStatement) DefaultDatabase() string

DefaultDatabase returns the default database from the statement.

func (*ShowMeasurementCardinalityStatement) RequiredPrivileges

RequiredPrivileges returns the privilege required to execute a ShowMeasurementCardinalityStatement.

func (*ShowMeasurementCardinalityStatement) String

String returns a string representation of the statement.

type ShowMeasurementsStatement

type ShowMeasurementsStatement struct {
	// Database to query. If blank, use the default database.
	Database string

	// Measurement name or regex.
	Source Source

	// An expression evaluated on data point.
	Condition Expr

	// Fields to sort results by
	SortFields SortFields

	// Maximum number of rows to be returned.
	// Unlimited if zero.
	Limit int

	// Returns rows starting at an offset from the first row.
	Offset int
}

ShowMeasurementsStatement represents a command for listing measurements.

func (*ShowMeasurementsStatement) DefaultDatabase

func (s *ShowMeasurementsStatement) DefaultDatabase() string

DefaultDatabase returns the default database from the statement.

func (*ShowMeasurementsStatement) RequiredPrivileges

func (s *ShowMeasurementsStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege(s) required to execute a ShowMeasurementsStatement.

func (*ShowMeasurementsStatement) String

func (s *ShowMeasurementsStatement) String() string

String returns a string representation of the statement.

type ShowQueriesStatement

type ShowQueriesStatement struct{}

ShowQueriesStatement represents a command for listing all running queries.

func (*ShowQueriesStatement) RequiredPrivileges

func (s *ShowQueriesStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a ShowQueriesStatement.

func (*ShowQueriesStatement) String

func (s *ShowQueriesStatement) String() string

String returns a string representation of the show queries statement.

type ShowRetentionPoliciesStatement

type ShowRetentionPoliciesStatement struct {
	// Name of the database to list policies for.
	Database string
}

ShowRetentionPoliciesStatement represents a command for listing retention policies.

func (*ShowRetentionPoliciesStatement) DefaultDatabase

func (s *ShowRetentionPoliciesStatement) DefaultDatabase() string

DefaultDatabase returns the default database from the statement.

func (*ShowRetentionPoliciesStatement) RequiredPrivileges

func (s *ShowRetentionPoliciesStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege(s) required to execute a ShowRetentionPoliciesStatement

func (*ShowRetentionPoliciesStatement) String

String returns a string representation of a ShowRetentionPoliciesStatement.

type ShowSeriesCardinalityStatement

type ShowSeriesCardinalityStatement struct {
	// Database to query. If blank, use the default database.
	// The database can also be specified per source in the Sources.
	Database string

	// Specifies whether the user requires exact counting or not.
	Exact bool

	// Measurement(s) the series are listed for.
	Sources Sources

	// An expression evaluated on a series name or tag.
	Condition Expr

	// Expressions used for grouping the selection.
	Dimensions Dimensions

	Limit, Offset int
}

ShowSeriesCardinalityStatement represents a command for listing series cardinality.

func (*ShowSeriesCardinalityStatement) DefaultDatabase

func (s *ShowSeriesCardinalityStatement) DefaultDatabase() string

DefaultDatabase returns the default database from the statement.

func (*ShowSeriesCardinalityStatement) RequiredPrivileges

func (s *ShowSeriesCardinalityStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a ShowSeriesCardinalityStatement.

func (*ShowSeriesCardinalityStatement) String

String returns a string representation of the show continuous queries statement.

type ShowSeriesStatement

type ShowSeriesStatement struct {
	// Database to query. If blank, use the default database.
	// The database can also be specified per source in the Sources.
	Database string

	// Measurement(s) the series are listed for.
	Sources Sources

	// An expression evaluated on a series name or tag.
	Condition Expr

	// Fields to sort results by
	SortFields SortFields

	// Maximum number of rows to be returned.
	// Unlimited if zero.
	Limit int

	// Returns rows starting at an offset from the first row.
	Offset int
}

ShowSeriesStatement represents a command for listing series in the database.

func (*ShowSeriesStatement) DefaultDatabase

func (s *ShowSeriesStatement) DefaultDatabase() string

DefaultDatabase returns the default database from the statement.

func (*ShowSeriesStatement) RequiredPrivileges

func (s *ShowSeriesStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a ShowSeriesStatement.

func (*ShowSeriesStatement) String

func (s *ShowSeriesStatement) String() string

String returns a string representation of the list series statement.

type ShowShardGroupsStatement

type ShowShardGroupsStatement struct{}

ShowShardGroupsStatement represents a command for displaying shard groups in the cluster.

func (*ShowShardGroupsStatement) RequiredPrivileges

func (s *ShowShardGroupsStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privileges required to execute the statement.

func (*ShowShardGroupsStatement) String

func (s *ShowShardGroupsStatement) String() string

String returns a string representation of the SHOW SHARD GROUPS command.

type ShowShardsStatement

type ShowShardsStatement struct{}

ShowShardsStatement represents a command for displaying shards in the cluster.

func (*ShowShardsStatement) RequiredPrivileges

func (s *ShowShardsStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privileges required to execute the statement.

func (*ShowShardsStatement) String

func (s *ShowShardsStatement) String() string

String returns a string representation.

type ShowStatsStatement

type ShowStatsStatement struct {
	Module string
}

ShowStatsStatement displays statistics for a given module.

func (*ShowStatsStatement) RequiredPrivileges

func (s *ShowStatsStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege(s) required to execute a ShowStatsStatement

func (*ShowStatsStatement) String

func (s *ShowStatsStatement) String() string

String returns a string representation of a ShowStatsStatement.

type ShowSubscriptionsStatement

type ShowSubscriptionsStatement struct {
}

ShowSubscriptionsStatement represents a command to show a list of subscriptions.

func (*ShowSubscriptionsStatement) RequiredPrivileges

func (s *ShowSubscriptionsStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a ShowSubscriptionsStatement.

func (*ShowSubscriptionsStatement) String

func (s *ShowSubscriptionsStatement) String() string

String returns a string representation of the ShowSubscriptionsStatement.

type ShowTagKeyCardinalityStatement

type ShowTagKeyCardinalityStatement struct {
	Database      string
	Exact         bool
	Sources       Sources
	Condition     Expr
	Dimensions    Dimensions
	Limit, Offset int
}

ShowTagKeyCardinalityStatement represents a command for listing tag key cardinality.

func (*ShowTagKeyCardinalityStatement) DefaultDatabase

func (s *ShowTagKeyCardinalityStatement) DefaultDatabase() string

DefaultDatabase returns the default database from the statement.

func (*ShowTagKeyCardinalityStatement) RequiredPrivileges

func (s *ShowTagKeyCardinalityStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a ShowTagKeyCardinalityStatement.

func (*ShowTagKeyCardinalityStatement) String

String returns a string representation of the statement.

type ShowTagKeysStatement

type ShowTagKeysStatement struct {
	// Database to query. If blank, use the default database.
	// The database can also be specified per source in the Sources.
	Database string

	// Data sources that fields are extracted from.
	Sources Sources

	// An expression evaluated on data point.
	Condition Expr

	// Fields to sort results by.
	SortFields SortFields

	// Maximum number of tag keys per measurement. Unlimited if zero.
	Limit int

	// Returns tag keys starting at an offset from the first row.
	Offset int

	// Maxiumum number of series to be returned. Unlimited if zero.
	SLimit int

	// Returns series starting at an offset from the first one.
	SOffset int
}

ShowTagKeysStatement represents a command for listing tag keys.

func (*ShowTagKeysStatement) DefaultDatabase

func (s *ShowTagKeysStatement) DefaultDatabase() string

DefaultDatabase returns the default database from the statement.

func (*ShowTagKeysStatement) RequiredPrivileges

func (s *ShowTagKeysStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege(s) required to execute a ShowTagKeysStatement.

func (*ShowTagKeysStatement) String

func (s *ShowTagKeysStatement) String() string

String returns a string representation of the statement.

type ShowTagValuesCardinalityStatement

type ShowTagValuesCardinalityStatement struct {
	Database      string
	Exact         bool
	Sources       Sources
	Op            Token
	TagKeyExpr    Literal
	Condition     Expr
	Dimensions    Dimensions
	Limit, Offset int

	TagKeyCondition Expr
}

ShowTagValuesCardinalityStatement represents a command for listing tag value cardinality.

func (*ShowTagValuesCardinalityStatement) DefaultDatabase

func (s *ShowTagValuesCardinalityStatement) DefaultDatabase() string

DefaultDatabase returns the default database from the statement.

func (*ShowTagValuesCardinalityStatement) RequiredPrivileges

func (s *ShowTagValuesCardinalityStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege required to execute a ShowTagValuesCardinalityStatement.

func (*ShowTagValuesCardinalityStatement) String

String returns a string representation of the statement.

type ShowTagValuesStatement

type ShowTagValuesStatement struct {
	// Database to query. If blank, use the default database.
	// The database can also be specified per source in the Sources.
	Database string

	// Data source that fields are extracted from.
	Sources Sources

	// Operation to use when selecting tag key(s).
	Op Token

	// Literal to compare the tag key(s) with.
	TagKeyExpr Literal

	// An expression evaluated on tag key(s).
	TagKeyCondition Expr

	// An expression evaluated on data point.
	Condition Expr

	// Fields to sort results by.
	SortFields SortFields

	// Maximum number of rows to be returned.
	// Unlimited if zero.
	Limit int

	// Returns rows starting at an offset from the first row.
	Offset int
}

ShowTagValuesStatement represents a command for listing tag values.

func (*ShowTagValuesStatement) DefaultDatabase

func (s *ShowTagValuesStatement) DefaultDatabase() string

DefaultDatabase returns the default database from the statement.

func (*ShowTagValuesStatement) RequiredPrivileges

func (s *ShowTagValuesStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege(s) required to execute a ShowTagValuesStatement.

func (*ShowTagValuesStatement) String

func (s *ShowTagValuesStatement) String() string

String returns a string representation of the statement.

type ShowUsersStatement

type ShowUsersStatement struct{}

ShowUsersStatement represents a command for listing users.

func (*ShowUsersStatement) RequiredPrivileges

func (s *ShowUsersStatement) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges returns the privilege(s) required to execute a ShowUsersStatement

func (*ShowUsersStatement) String

func (s *ShowUsersStatement) String() string

String returns a string representation of the ShowUsersStatement.

type SortField

type SortField struct {
	// Name of the field.
	Name string

	// Sort order.
	Ascending bool
}

SortField represents a field to sort results by.

func (*SortField) String

func (field *SortField) String() string

String returns a string representation of a sort field.

type SortFields

type SortFields []*SortField

SortFields represents an ordered list of ORDER BY fields.

func (SortFields) String

func (a SortFields) String() string

String returns a string representation of sort fields.

type Source

type Source interface {
	Node
	// contains filtered or unexported methods
}

Source represents a source of data for a statement.

type Sources

type Sources []Source

Sources represents a list of sources.

func (Sources) MarshalBinary

func (a Sources) MarshalBinary() ([]byte, error)

MarshalBinary encodes a list of sources to a binary format.

func (Sources) Measurements

func (a Sources) Measurements() []*Measurement

Measurements returns all measurements including ones embedded in subqueries.

func (Sources) RequiredPrivileges

func (a Sources) RequiredPrivileges() (ExecutionPrivileges, error)

RequiredPrivileges recursively returns a list of execution privileges required.

func (Sources) String

func (a Sources) String() string

String returns a string representation of a Sources array.

func (*Sources) UnmarshalBinary

func (a *Sources) UnmarshalBinary(buf []byte) error

UnmarshalBinary decodes binary data into a list of sources.

type Statement

type Statement interface {
	Node

	RequiredPrivileges() (ExecutionPrivileges, error)
	// contains filtered or unexported methods
}

Statement represents a single command in InfluxQL.

func MustParseStatement

func MustParseStatement(s string) Statement

MustParseStatement parses a statement string and returns its AST. Panic on error.

func ParseStatement

func ParseStatement(s string) (Statement, error)

ParseStatement parses a statement string and returns its AST representation.

type Statements

type Statements []Statement

Statements represents a list of statements.

func (Statements) String

func (a Statements) String() string

String returns a string representation of the statements.

type StringLiteral

type StringLiteral struct {
	Val string
}

StringLiteral represents a string literal.

func (*StringLiteral) IsTimeLiteral

func (l *StringLiteral) IsTimeLiteral() bool

IsTimeLiteral returns if this string can be interpreted as a time literal.

func (*StringLiteral) String

func (l *StringLiteral) String() string

String returns a string representation of the literal.

func (*StringLiteral) ToTimeLiteral

func (l *StringLiteral) ToTimeLiteral(loc *time.Location) (*TimeLiteral, error)

ToTimeLiteral returns a time literal if this string can be converted to a time literal.

type SubQuery

type SubQuery struct {
	Statement *SelectStatement
}

SubQuery is a source with a SelectStatement as the backing store.

func (*SubQuery) String

func (s *SubQuery) String() string

String returns a string representation of the subquery.

type Target

type Target struct {
	// Measurement to write into.
	Measurement *Measurement
}

Target represents a target (destination) policy, measurement, and DB.

func (*Target) String

func (t *Target) String() string

String returns a string representation of the Target.

type TimeLiteral

type TimeLiteral struct {
	Val time.Time
}

TimeLiteral represents a point-in-time literal.

func (*TimeLiteral) String

func (l *TimeLiteral) String() string

String returns a string representation of the literal.

type TimeRange

type TimeRange struct {
	Min, Max time.Time
}

TimeRange represents a range of time from Min to Max. The times are inclusive.

func (TimeRange) Intersect

func (t TimeRange) Intersect(other TimeRange) TimeRange

Intersect joins this TimeRange with another TimeRange.

func (TimeRange) IsZero

func (t TimeRange) IsZero() bool

IsZero is true if the min and max of the time range are zero.

func (TimeRange) MaxTime

func (t TimeRange) MaxTime() time.Time

MaxTime returns the maximum time of the TimeRange. If the maximum time is zero, this returns the maximum possible time.

func (TimeRange) MaxTimeNano

func (t TimeRange) MaxTimeNano() int64

MaxTimeNano returns the maximum time in nanoseconds since the epoch. If the maximum time is zero, this returns the maximum possible time.

func (TimeRange) MinTime

func (t TimeRange) MinTime() time.Time

MinTime returns the minimum time of the TimeRange. If the minimum time is zero, this returns the minimum possible time.

func (TimeRange) MinTimeNano

func (t TimeRange) MinTimeNano() int64

MinTimeNano returns the minimum time in nanoseconds since the epoch. If the minimum time is zero, this returns the minimum possible time.

type Token

type Token int

Token is a lexical token of the InfluxQL language.

const (
	// ILLEGAL Token, EOF, WS are Special InfluxQL tokens.
	ILLEGAL Token = iota
	EOF
	WS
	COMMENT

	// IDENT and the following are InfluxQL literal tokens.
	//IDENT       // main
	BOUNDPARAM // $param
	//NUMBER      // 12345.67
	//INTEGER     // 12345
	//DURATIONVAL // 13h
	//STRING      // "abc"
	BADSTRING // "abc
	BADESCAPE // \q
	//TRUE      // true
	//FALSE     // false
	//REGEX    // Regular expressions
	BADREGEX // `.*

	//LPAREN // (
	//RPAREN // )
	//COMMA       // ,
	COLON // :

	// ALL and the following are InfluxQL Keywords
	//ALL
	//ALTER
	//ANALYZE
	ANY
	//AS
	//ASC
	BEGIN //CREATE CONTINUOUS QUERY ON "telegraf" BEGIN
	//BY
	//CARDINALITY
	//CREATE
	//CONTINUOUS // ContinuousQuery
	//DATABASE
	//DATABASES
	//DEFAULT
	//DELETE
	//DESC
	DESTINATIONS

	//DIAGNOSTICS  // SHOW DIAGNOSTICS
	DISTINCT //distinct()
	//DROP
	//DURATION
	//END
	EVERY
	//EXACT
	//EXPLAIN
	//FIELD
	//FOR  //SHOW GRANTS FOR "jdoe"
	//FROM
	//GRANT
	//GRANTS
	//GROUP
	//GROUPS
	//IN
	INF
	INSERT
	INTO
	//KEY
	//KEYS
	KILL
	//LIMIT
	//MEASUREMENT
	//MEASUREMENTS
	//NAME
	//OFFSET
	//ON
	//ORDER
	//PASSWORD
	//POLICY
	//POLICIES
	//PRIVILEGES
	//QUERIES
	//QUERY
	READ //privilege        = "ALL" [ "PRIVILEGES" ] | "READ" | "WRITE" .
	//REPLICATION
	RESAMPLE
	//RETENTION
	//REVOKE
	//SELECT
	//SERIES
	//SET
	//SHOW
	//SHARD
	//SHARDKEY
	//SHARDS
	//SLIMIT
	//SOFFSET
	//STATS
	//SUBSCRIPTION
	//SUBSCRIPTIONS
	//TYPE
	//TAG
	//TO
	//USER
	//USERS
	//VALUES
	//WHERE
	//WITH
	WRITE
	//PARTITION
	PREPARE
	SNAPSHOT
	GET
	RUNTIMEINFO
)

These are a comprehensive list of InfluxQL language tokens.

func Lookup

func Lookup(ident string) Token

Lookup returns the token associated with a given string.

func (Token) Precedence

func (tok Token) Precedence() int

Precedence returns the operator precedence of the binary operator token.

func (Token) String

func (tok Token) String() string

String returns the string representation of the token.

type TypeError

type TypeError struct {
	// Expr contains the expression that generated the type error.
	Expr Expr
	// Message contains the informational message about the type error.
	Message string
}

TypeError is an error when two types are incompatible.

func (*TypeError) Error

func (e *TypeError) Error() string

type TypeMapper

type TypeMapper interface {
	MapType(measurement *Measurement, field string) DataType
	MapTypeBatch(measurement *Measurement, field map[string]DataType, schema *Schema) error
}

TypeMapper maps a data type to the measurement and field.

func MultiTypeMapper

func MultiTypeMapper(mappers ...TypeMapper) TypeMapper

MultiTypeMapper combines multiple TypeMappers into a single one. The MultiTypeMapper will return the first type that is not Unknown. It will not iterate through all of them to find the highest priority one.

type TypeValuerEval

type TypeValuerEval struct {
	TypeMapper TypeMapper
	Sources    Sources
}

TypeValuerEval evaluates an expression to determine its output type.

func (*TypeValuerEval) EvalType

func (v *TypeValuerEval) EvalType(expr Expr, batchEn bool) (DataType, error)

EvalType returns the type for an expression. If the expression cannot be evaluated for some reason, like incompatible types, it is returned as a TypeError in the error. If the error is non-fatal so we can continue even though an error happened, true will be returned. This function assumes that the expression has already been reduced.

func (*TypeValuerEval) EvalTypeBatch

func (v *TypeValuerEval) EvalTypeBatch(exprs map[string]Expr, schema *Schema, batchEn bool) (err error)

type UnsignedLiteral

type UnsignedLiteral struct {
	Val uint64
}

UnsignedLiteral represents an unsigned literal. The parser will only use an unsigned literal if the parsed integer is greater than math.MaxInt64.

func (*UnsignedLiteral) String

func (l *UnsignedLiteral) String() string

String returns a string representation of the literal.

type Valuer

type Valuer interface {
	// Value returns the value and existence flag for a given key.
	Value(key string) (interface{}, bool)
	SetValuer(v Valuer, index int)
}

Valuer is the interface that wraps the Value() method.

func MultiValuer

func MultiValuer(valuers ...Valuer) Valuer

MultiValuer returns a Valuer that iterates over multiple Valuer instances to find a match.

func SliceValuer

func SliceValuer(valuers []Valuer) Valuer

type ValuerEval

type ValuerEval struct {
	Valuer Valuer

	// IntegerFloatDivision will set the eval system to treat
	// a division between two integers as a floating point division.
	IntegerFloatDivision bool
}

ValuerEval will evaluate an expression using the Valuer.

func (*ValuerEval) Eval

func (v *ValuerEval) Eval(expr Expr) interface{}

Eval evaluates an expression and returns a value.

func (*ValuerEval) EvalBool

func (v *ValuerEval) EvalBool(expr Expr) bool

EvalBool evaluates expr and returns true if result is a boolean true. Otherwise returns false.

type VarRef

type VarRef struct {
	Val  string
	Type DataType
}

VarRef represents a reference to a variable.

func ExprNames

func ExprNames(expr Expr) []VarRef

ExprNames returns a list of non-"time" field names from an expression.

func (*VarRef) String

func (r *VarRef) String() string

String returns a string representation of the variable reference.

type VarRefs

type VarRefs []VarRef

VarRefs represents a slice of VarRef types.

func (VarRefs) Len

func (a VarRefs) Len() int

Len implements sort.Interface.

func (VarRefs) Less

func (a VarRefs) Less(i, j int) bool

Less implements sort.Interface.

func (VarRefs) Strings

func (a VarRefs) Strings() []string

Strings returns a slice of the variable names.

func (VarRefs) Swap

func (a VarRefs) Swap(i, j int)

Swap implements sort.Interface.

type Visitor

type Visitor interface {
	Visit(Node) Visitor
}

Visitor can be called by Walk to traverse an AST hierarchy. The Visit() function is called once per node.

type Wildcard

type Wildcard struct {
	Type Token
}

Wildcard represents a wild card expression.

func (*Wildcard) String

func (e *Wildcard) String() string

String returns a string representation of the wildcard.

type ZoneValuer

type ZoneValuer interface {
	Valuer

	// Zone returns the time zone location. This function may return nil
	// if no time zone is known.
	Zone() *time.Location
}

ZoneValuer is the interface that specifies the current time zone.

Directories

Path Synopsis
Package influxql is a generated protocol buffer package.
Package influxql is a generated protocol buffer package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL