Commit Graph

193 Commits

Author SHA1 Message Date
Lee Hinman 97eef004de SQL: Remove instanceof checks for field retrieval (elastic/x-pack-elasticsearch#3402)
* SQL: Remove instanceof checks for field retrieval

This removes the `instanceof` checks iterating through the columns determining
what fields need to be retrieved from the ES document. It adds an interface
`FieldExtraction` that collects the fields needed in a builder. The builder can
then build the fields necessary from a `SearchSourceBuilder`.

* Remove default implementation in favor of pushing down exception throwing

Original commit: elastic/x-pack-elasticsearch@11d3d69eb1
2017-12-21 17:11:31 -07:00
Nik Everett 1cf9d6e3f3 SQL: Document a few functions (elastic/x-pack-elasticsearch#3390)
* Starts to build the list of supported functions, adding links to
wikipedia when there is any doubt what the functions mean.
* Extracts an example of using the function from the test suite.
* Explicitly calls out how we round (half up) because there are
lots of ways to round.

Original commit: elastic/x-pack-elasticsearch@5fb64ba869
2017-12-20 17:42:29 -05:00
Lee Hinman c26f039207 SQL: Add all QUERY() query options (elastic/x-pack-elasticsearch#3389)
This adds support for (almost) all of the options that the `query_string` query
supports.

Additionally, it reverts back to the default operator of `OR` rather than `AND`
for the `QUERY()` query.

Relates to elastic/x-pack-elasticsearch#3361

Original commit: elastic/x-pack-elasticsearch@da8b29b53c
2017-12-20 15:05:40 -07:00
Lee Hinman 5b47c67dec SQL: Add all MATCH() query options (elastic/x-pack-elasticsearch#3387)
* SQL: Add all MATCH() query options

This adds support for (almost) all of the options that the `match` query
supports.

Additionally, it reverts back to the default operator of `OR` rather than `AND`
for the `MATCH()` query.

Relates to elastic/x-pack-elasticsearch#3361

* Add getters required for Node usage

Original commit: elastic/x-pack-elasticsearch@144e2bec02
2017-12-20 12:35:32 -07:00
Nik Everett 42d1c62d03 SQL: Nicer failure message one EXISTS (elastic/x-pack-elasticsearch#3384)
We don't support the SQL `EXISTS` keyword. It looks like:
```
SELECT * FROM test WHERE EXISTS (SELECT * FROM foo WHERE test.id =
foo.id)
```

It is basically a `JOIN` that doesn't return columns. Since we don't
support `JOIN`, we don't support `EXISTS`.

This PR improves the error message from "unresolved blah blah blah" to
"EXISTS is not yet supported".

relates elastic/x-pack-elasticsearch#3176

Original commit: elastic/x-pack-elasticsearch@548d57c8c1
2017-12-20 12:04:46 -05:00
Lee Hinman 38cee807b9 SQL: Parse all multi_match options from request (elastic/x-pack-elasticsearch#3361)
* Parse all multi_match options from request

Rather than hardcoding predicates that require more methods for each newly added
options, this encapsulates the state into a collection of appliers that can
accumulate what's needed in the QueryBuilder itself.

For example, the following:

```json
GET /_xpack/sql/translate
{
  "query": "SELECT foo,baz from i WHERE MATCH('baz', 'should clause', 'operator=AND;type=cross_fields')"
}
```

Then generates the following:

```json
{
  "size" : 1000,
  "query" : {
    "multi_match" : {
      "query" : "should clause",
      "fields" : [
        "baz^1.0"
      ],
      "type" : "cross_fields",
      "operator" : "AND",
      "slop" : 0,
      "prefix_length" : 0,
      "max_expansions" : 50,
      "zero_terms_query" : "NONE",
      "auto_generate_synonyms_phrase_query" : true,
      "fuzzy_transpositions" : true,
      "boost" : 1.0
    }
  },
  "_source" : {
    "includes" : [
      "baz"
    ],
    "excludes" : [ ]
  },
  "docvalue_fields" : [
    "foo"
  ]
}
```

And when an invalid field value is used:

```json
GET /_xpack/sql
{
  "query": "SELECT foo,baz from i WHERE MATCH('baz', 'should clause', 'operator=AND;minimum_should_match=potato')"
}
```

We get what ES would usually send back:

```json
{
  "error" : {
    "root_cause" : [
      {
        "type" : "query_shard_exception",
        "reason" : "failed to create query: {\n  \"multi_match\" : {\n    \"query\" : \"should clause\",\n    \"fields\" : [\n      \"baz^1.0\"\n    ],\n    \"type\" : \"best_fields\",\n    \"operator\" : \"AND\",\n    \"slop\" : 0,\n    \"prefix_length\" : 0,\n    \"max_expansions\" : 50,\n    \"minimum_should_match\" : \"potato\",\n    \"zero_terms_query\" : \"NONE\",\n    \"auto_generate_synonyms_phrase_query\" : true,\n    \"fuzzy_transpositions\" : true,\n    \"boost\" : 1.0\n  }\n}",
        "index_uuid" : "ef3MWf8FTUe2Qjz2FLbhoQ",
        "index" : "i"
      }
    ],
    "type" : "search_phase_execution_exception",
    "reason" : "all shards failed",
    "phase" : "query",
    "grouped" : true,
    "failed_shards" : [
      {
        "shard" : 0,
        "index" : "i",
        "node" : "VfG9zfk9TDWdWvEZu0a4Rw",
        "reason" : {
          "type" : "query_shard_exception",
          "reason" : "failed to create query: {\n  \"multi_match\" : {\n    \"query\" : \"should clause\",\n    \"fields\" : [\n      \"baz^1.0\"\n    ],\n    \"type\" : \"best_fields\",\n    \"operator\" : \"AND\",\n    \"slop\" : 0,\n    \"prefix_length\" : 0,\n    \"max_expansions\" : 50,\n    \"minimum_should_match\" : \"potato\",\n    \"zero_terms_query\" : \"NONE\",\n    \"auto_generate_synonyms_phrase_query\" : true,\n    \"fuzzy_transpositions\" : true,\n    \"boost\" : 1.0\n  }\n}",
          "index_uuid" : "ef3MWf8FTUe2Qjz2FLbhoQ",
          "index" : "i",
          "caused_by" : {
            "type" : "number_format_exception",
            "reason" : "For input string: \"potato\""
          }
        }
      }
    ]
  },
  "status" : 400
}
```

It even includes the validation that ES already does for things like `type`:

```json
GET /_xpack/sql
{
  "query": "SELECT foo,baz from i WHERE MATCH('baz', 'should clause', 'operator=AND;type=eggplant')"
}
```

```json
{
  "error" : {
    "root_cause" : [
      {
        "type" : "parse_exception",
        "reason" : "failed to parse [multi_match] query type [eggplant]. unknown type."
      }
    ],
    "type" : "parse_exception",
    "reason" : "failed to parse [multi_match] query type [eggplant]. unknown type."
  },
  "status" : 400
}
```

Resolves elastic/x-pack-elasticsearch#3257


Original commit: elastic/x-pack-elasticsearch@59f518af4a
2017-12-20 09:48:05 -07:00
Nik Everett 9765058e5c SQL: Remove whenClause from grammar (elastic/x-pack-elasticsearch#3378)
It wasn't used. Also remove tokens that we aren't using.

Related to elastic/x-pack-elasticsearch#3176

Original commit: elastic/x-pack-elasticsearch@3358b1e241
2017-12-20 11:06:54 -05:00
Nik Everett 2c5cfcfae4 SQL: Proper errors on set qualifiers (elastic/x-pack-elasticsearch#3377)
`SELECT DISTINCT foo FROM bar` is not yet implemented and was returning
an "unplanned item" error which isn't useful to users so I replaced it
with `SELECT DISTINCT is not yet supported`.

`SELECT foo, COUNT(*) FROM bar GROUP BY ALL foo` is not supported.
Specifically the `ALL` part. It is fairly esoteric so see [1] for what
it does. Regardless of what it does it is not widely supported and even
Microsoft's SQL Server has deprecated it so we should never support it.
Probably.

[1]: https://technet.microsoft.com/en-us/library/ms175028(v=sql.90).aspx

Related to elastic/x-pack-elasticsearch#3176

Original commit: elastic/x-pack-elasticsearch@56e5ca3009
2017-12-20 09:25:00 -05:00
Nik Everett 2cb58f3dc4 SQL: Remove ThreadLocal (elastic/x-pack-elasticsearch#3370)
`ThreadLocal` variables have a tendency to complicate control flow,
especially if these variables are "context" variables. This PR drops the
`ThreadLocal` that SQL was using for its request context in favor of
delaying construction of the components that need the context until what
they need is ready.

This further simplifies things by passing to components what they need
rather than a larger context object. This is important because not all
of the context is ready at all parts of the request. In particular we
haven't resolved the index until long after the parsing stage, but the
parser wants to know the time zone.

This way of doing things does create a few more objects on each request
but those objects are fairly light and should die as soon as the SQL has
been translated to an Elasticsearch query.

relates elastic/x-pack-elasticsearch#3178

Original commit: elastic/x-pack-elasticsearch@8331f24399
2017-12-19 12:20:23 -05:00
Nik Everett 4820bc757e SQL: Implement sorting and retrieving score (elastic/x-pack-elasticsearch#3340)
Accessing `_score` from SQL looks like:
```
--------------------------------------------------
POST /_sql
{
    "query": "SELECT SCORE(), * FROM library WHERE match(name, 'dune') ORDER BY SCORE() DESC"
}
--------------------------------------------------
```

This replaces elastic/x-pack-elasticsearch#3187

relates elastic/x-pack-elasticsearch#2887

Original commit: elastic/x-pack-elasticsearch@fe96348c22
2017-12-18 20:57:50 -05:00
Nik Everett dc69f92b49 SQL: Respond with nice error if there is a JOIN (elastic/x-pack-elasticsearch#3343)
`JOIN`s aren't supported right yet so we should send back a nice 400
level error to the user telling them that.

Also pulls out some common code in `RestSqlTestCase` that I've been
staring at for a while.

Relates to elastic/x-pack-elasticsearch#3176

Original commit: elastic/x-pack-elasticsearch@1c1bd1c355
2017-12-18 16:42:03 -05:00
Nik Everett 13428f4217 SQL: Do not compile against matrix aggs module
Since matrix aggs module isn't on the classpath at runtime, we shouldn't
compile with it on the classpath. Doing so makes it possible for us to
die with dignity when we can't load the class. Which happens right now.

Original commit: elastic/x-pack-elasticsearch@6d2ca5e367
2017-12-18 15:08:18 -05:00
Nik Everett 021e8dd111 SQL: Don't put aggs only queries into scroll context
SQL was adding scroll timeouts to aggregation only queries. At best this
is just confusing because we never scroll these queries. It *might*
leave behind a scroll context that we don't want. It is failing some new
validation that says that we have to have a `size` for every scroll
query.

Anyway, the simplest thing to do is to not put a scroll on aggregation
only queries.

Original commit: elastic/x-pack-elasticsearch@f6819a32b8
2017-12-18 13:57:58 -05:00
Lee Hinman a8e9272994 SQL: Add remaining matrix aggregations (elastic/x-pack-elasticsearch#3330)
* Add remaining matrix aggregations

This adds the remaining [matrix aggregations](https://www.elastic.co/guide/en/elasticsearch/reference/6.1/search-aggregations-matrix-stats-aggregation.html).

These aggregations aren't currently implemented due to the inter-plugin
communication not being set up, so they return "innerkey/matrix stats not
handled (yet)".

For matrix aggs that share a name with an existing aggregation (like 'count'),
they have be prefixed with "matrix_", so, "matrix_count", "matrix_mean", and
"matrix_variance".

Relates to elastic/x-pack-elasticsearch#2885

* Return HTTP 400 for innerkey/matrix stats aggs

* Add integration test for unimplemented matrix aggs

Original commit: elastic/x-pack-elasticsearch@34459c59aa
2017-12-15 14:33:58 -07:00
Nik Everett 28f1107dad SQL: Fix test for UnresolvedRelation
`UnresolvedRelation`'s equality test would sometimes not properly mutate
the object under test. This is because `ESTestCase#randomValueOtherThan`
will only run its provider one time if passed `null` for the "other
than" value.

Original commit: elastic/x-pack-elasticsearch@7b13e8dc98
2017-12-14 10:45:59 -05:00
Costin Leau 624a1530c0 SQL: Fix checkstyle / add missing hashCode (elastic/x-pack-elasticsearch#3323)
* Fix checkstyle / add missing hashCode
* Improve formatting

Original commit: elastic/x-pack-elasticsearch@a3ad2793bb
2017-12-14 17:17:26 +02:00
Nik Everett f5af60c7cf SQL: Fix error message on bad index (elastic/x-pack-elasticsearch#3312)
Fixes the error message that SQL produces when it sees unsupported
indexes. It was always returning all broken indexes as "unknown" even
though we have much better error messages. It was just throwing them
away.

I caught this originally when backporting to 6.x where we had a test
that we produced a useful error message when the user attempted to run
SQL on an index with more than one type. We couldn't run that in the
feature/sql branch because it is inside the full cluster restart tests
and the "old" version of Elasticsearch used in those tests in
feature/sql is 6.x which doesn't allow indexes with multiple types. When
I backported to 6.x the test failed because it hadn't been run before.

In addition to fixing that test and the problem, this adds another test
that will reveal the problem when run in the feature/sql and master
branch.

Original commit: elastic/x-pack-elasticsearch@c7b787baee
2017-12-14 09:56:36 -05:00
Costin Leau cdfe0f1f5a Revert "Revert "Merge branch 'feature/sql'""
This reverts commit elastic/x-pack-elasticsearch@cc79e19911.

We'll merge this when we're good and ready.

Original commit: elastic/x-pack-elasticsearch@b3ef4f2836
2017-12-13 10:19:31 -05:00
Costin Leau 2e60e831c0 Revert "Merge branch 'feature/sql'"
This reverts commit elastic/x-pack-elasticsearch@2b3f7697a5, reversing
changes made to elastic/x-pack-elasticsearch@b79f16673c.

We're backing out all of SQL.

Original commit: elastic/x-pack-elasticsearch@cc79e19911
2017-12-13 09:33:13 -05:00
Igor Motov 4bebc307c3 SQL: Add ability to close cursors (elastic/x-pack-elasticsearch#3249)
This commits adds a new end point for closing in-flight cursors, it also ensures that all cursors are properly closed by adding after test checks that ensures that we don't leave any search context open.

relates elastic/x-pack-elasticsearch#2878

Original commit: elastic/x-pack-elasticsearch@1052ea28dc
2017-12-11 11:36:02 -05:00
Igor Motov b72a9b5674 SQL: switch from _sql/ endpoint to _xpack/sql endpoint (elastic/x-pack-elasticsearch#3270)
As a part of xpack, SQL should use _xpack/sql endpoint instead of _sql endpoint.

relates elastic/x-pack-elasticsearch#3114

Original commit: elastic/x-pack-elasticsearch@f561b57f16
2017-12-08 12:17:26 -05:00
Costin Leau 432f10e736 SQL: Introduce LiteralAttribute for values that are not extracted from ES (elastic/x-pack-elasticsearch#3209)
This is mainly a promotion of Literal to Attribute to better handle folding expressions from extracted queries

Original commit: elastic/x-pack-elasticsearch@c3bb48bb61
2017-12-06 19:35:34 +02:00
Costin Leau aa9199f5d1 SQL: Push limit down to GroupByColumn aggs (elastic/x-pack-elasticsearch#3200)
Limit operators if available are pushed into `GROUP BY`

Original commit: elastic/x-pack-elasticsearch@e5f82df810
2017-12-06 19:29:48 +02:00
javanna 9664363575 remove Catalog abstraction and rename its package from catalog to index
Given that the Catalog was only ever used to hold a single index, the corresponding abstraction can be removed in favour of the abstraction that it holds, namely `GetIndexResult`.

Original commit: elastic/x-pack-elasticsearch@6932db642c
2017-12-06 13:58:17 +01:00
javanna 90aee54251 Trim down the Catalog implementations to a single one
Catalog is now a final class rather than an interface with different implementations.

relates elastic/x-pack-elasticsearch#3179

Original commit: elastic/x-pack-elasticsearch@4cc927e113
2017-12-06 13:58:17 +01:00
javanna 08950ff491 Remove security filter, replaced by get index api call which returns filtered mappings
Given that we get now filtered mappings directly from the get index API (in case security is configured with FLS), we don't need the security filter nor the filtered catalog. That means we can remove the delayed action support also from AuthorizationService and rather make SQLAction a composite action like others. It will be authorized as an action, but its indices won't be checked while that will happen with its inner actions (get index and search) which need to be properly authorized.

Also, SQLGetIndicesAction is not needed anymore, as its purpose was to retrieve the indices access resolver put in the context by the security plugin for delayed actions, which are not supported anymore.

This commit kind of reverts elastic/x-pack-elasticsearch#2162, as it is now possible to integrate with security out-of-the-box

relates elastic/x-pack-elasticsearch#2934

Original commit: elastic/x-pack-elasticsearch@64d5044426
2017-12-06 13:58:17 +01:00
Igor Motov 3b2667048a SQL: Cleanup of Cursor wrappers
The follow up for elastic/x-pack-elasticsearch#3197, addresses nik9000's review comments.

Original commit: elastic/x-pack-elasticsearch@2307029bd8
2017-12-05 20:54:12 -05:00
Costin Leau 88b8794801 SQL: Forbid multi field groups (elastic/x-pack-elasticsearch#3199)
* SQL: GROUP BY with multiple fields are forbidden

The check is performed in the folder Verifier as the optimizer can eliminate some fields (like those with constants)

Original commit: elastic/x-pack-elasticsearch@8d49f4ab02
2017-12-05 18:41:19 +02:00
Costin Leau 4e49769efb SQL: Extend HAVING support (elastic/x-pack-elasticsearch#3155)
SQL: Extend HAVING support

Enhance Analyzer to support HAVING scalar functions over aggregates
Enhance Analyzer to push down undeclared aggs into the Aggregate
Fix bug in Analyzer$MissingRef that caused invalid groupings to still be resolved when pushed into an Aggregate
Preserve location information across the plan
Add AttributeMap as a backing for AttributeSet
Add Optimizer rule for combining projects
Add tz to DT functions toString
Change formatTemplate to not use String.format and thus to avoid
interfering with special % chars
Extend dataset with random salary and languages
Add unit tests for AttributeMap
Fix MathFunction scripting
Improve MissingRefs to enrich UnresolvedAttribute with metadata
During the Analysis unpushed attributes are automatically enriched to
provide more accurate error information
Enhance Verifier to deal with invalid (but resolved) ORDER/HAVING
Add OrderBy arithmetic tests
Improve Verifier to prevent GROUP BY on aggregations
Add tests on grouping by scalar functions

Original commit: elastic/x-pack-elasticsearch@5030d7a755
2017-12-05 18:14:15 +02:00
Igor Motov 1971adda68 SQL: Improve SqlResponseTests
This commit fixes a bug in the testVersionHandling test and adds more randomization to serialized cursors.

Original commit: elastic/x-pack-elasticsearch@fab8d50518
2017-12-02 18:40:52 -05:00
Igor Motov 773cdf0f9f SQL: Switch to the standard way of cursor serialization (elastic/x-pack-elasticsearch#3197)
While working on cursor cleanup, I realized that we still have two ways to serialize the cursor and the second way doesn't contain the cursor version (only client version, that can be potentially different from the cursor version). This commit switches to the unified way of serializing the cursor.

This is a follow up for elastic/x-pack-elasticsearch#3064.

Original commit: elastic/x-pack-elasticsearch@ef1a6427dd
2017-12-02 16:03:22 -05:00
Costin Leau 7cab29760d SQL: Introduce PreAnalyze phase to resolve catalogs async (elastic/x-pack-elasticsearch#2962)
SQL: Introduce PreAnalyze phase to resolve catalogs async

The new preanalyze phase collects all unresolved relations and tries
to resolve them as indices through typical async calls _before_ starting the analysis process.
The result is loaded into a catalog which is then passed to the analyzer.
While at it, the analyzer was made singleton and state across the engine
is done through SqlSession#currentContext().


Commit missing fix
Fix typo
Fix license
Fix line length
remove redundant static modifier
Remove redundant generics type
Rename catalogResolver instance member to indexResolver
Fix translate action to return a response through the listener, it hangs otherwise
IndexResolver improvements

Make sure that get index requests calls are locally executed by providing local flag.
Don't replace index/alias name with concrete index name in asCatalog response conversion. We need to preserve the original alias name for security, so it is reused in the subsequent search.
Update roles and actions names for security tests
Get index is now executed instead of sql get indices, and sql get indices has been removed.
Also made cluster privileges more restrictive to make sure that cluster state calls are no longer executed.
Fix most of the security IT tests
indices options are now unified, always lenient. The only situation where we get authorization exception back is when the user is not authorized for the sql action (besides for which indices).
Improve SessionContext handling
Fix context being invalid in non-executable phases
Make Explain & Debug command fully async
Resolve checkstyle error about redundant modifiers
Temporarily restore SqlGetIndicesAction

SqlGetIndicesAction action is still needed in RestSqlJdbcAction (metaTable and metaColumn methods), where we can't at the moment call IndexResolver directly, as security (FLS) needs index resolver to be called as part of the execution of an indices action. Once mappings are returned filtered, delayed action and the security filter will go away, as well as SqlGetIndicesAction.
SqlGetIndicesAction doesn't need to be a delayed action, my bad

[TEST] remove unused expectSqlWithAsyncLookup and rename expectSqlWithSyncLookup to expectSqlCompositeAction
Polish and feedback
Add unit test for PreAnalyzer

Original commit: elastic/x-pack-elasticsearch@57846ed613
2017-11-30 18:18:08 +02:00
Costin Leau c08eb56238 SQL: Improve grammar to better handle quotes (elastic/x-pack-elasticsearch#3051)
SQL: Improve grammar to better handle quotes

Fix typo in handling (back)quoted identifiers
Clarify use of unquote (dedicated for literals) and text (generic)
Address feedback
clarify that ` are picked up but not supported/recommended
Fix merge and adjust json errors to work on windows

Original commit: elastic/x-pack-elasticsearch@67e0f3f38e
2017-11-29 15:42:04 +02:00
Igor Motov 5c88fa0b3b SQL: Add support for plain text output to /_sql endpoint (elastic/x-pack-elasticsearch#3124)
The /_sql endpoint now returns the results in the text format by default. Structured formats are also supported using the format parameter or accept header similar to _cat endpoints.

Original commit: elastic/x-pack-elasticsearch@4353793b83
2017-11-27 18:10:13 -05:00
Nik Everett f97f56ba54 SQL: Throw exceptions on errors (elastic/x-pack-elasticsearch#3066)
Instead of returning "error response" objects and then translating them
into SQL exceptions this just throws the SQL exceptions directly. This
means the CLI catches exceptions and prints out the messages which isn't
ideal if this were hot code but it isn't and this is a much simpler way
of doing things.

Original commit: elastic/x-pack-elasticsearch@08431d3941
2017-11-22 11:22:31 -05:00
Igor Motov a4915a5714 SQL: remove all remaining NOCOMMITs
relates elastic/x-pack-elasticsearch#2873

Original commit: elastic/x-pack-elasticsearch@68b206efd2
2017-11-21 14:37:59 -05:00
Igor Motov 2fe4da80ad SQL: add filter support in REST action (elastic/x-pack-elasticsearch#3045)
Adds the option to specify an elasticsearch filter in addition to the SQL query by introducing a filter parameter in the REST query which would create a boolean filter if the SQL query generates an elasticsearch query or a constant score query if SQL if the SQL query doesn't generates an elasticsearch query. Usage:

{
   "query": "SELECT * FROM index",
   "filter" : {  "term" : { "tag" : "tech" } }
}

relates elastic/x-pack-elasticsearch#2895

Original commit: elastic/x-pack-elasticsearch@9a73813c7f
2017-11-21 11:40:38 -05:00
Igor Motov 3e14c30aa1 SQL: Add version to cursor serialization (elastic/x-pack-elasticsearch#3064)
This commits also simplifies the serialization mechanism by remove 2 ways to serialize the cursor. Adding the version there was complicating things too much otherwise.

Original commit: elastic/x-pack-elasticsearch@4f2c541e0a
2017-11-21 11:24:27 -05:00
Nik Everett fce5b494be SQL: Stop serializing errors for CLI and JDBC (elastic/x-pack-elasticsearch#3034)
Now that we can parse Elasticsearch's standard error messages in the CLI
and JDBC client we can just let those standard error messages bubble out
of Elasticsearch rather than catch and encode them.

In a followup we can remove the encoding entirely.

Original commit: elastic/x-pack-elasticsearch@bad043b6f7
2017-11-17 12:16:37 -05:00
Nik Everett 89e80e0cba Teach SQL to parse Elasticsearch's standard error responses (elastic/x-pack-elasticsearch#2764)
This teaches SQL to parse Elasticsearch's standard error responses
but doesn't change SQL to general Elasticsearch's standard error responses
in all cases. That can come in a followup. We do this parsing with
jackson-core, the same dependency Elasticsearch uses for parsing
json. We shade jackson-core in the JDBC driver so that users don't have to worry about
dependency clashes. We do not do so in the CLI because it is a standalone
application.

We get a few "bonus" changes along the way:
1. We save a copy operation. Before this change responses were spooled
into memory and then parsed. After this change they are parsed directly
from the response stream.
2. We had a few classes entirely to support the spooling operation that we
no longer need: `BytesArray`, `FastByteArrayInputStream`, and
`BasicByteArrayOutputStream`.
3. SQL's `Version` was incorrectly parsing the version from the jar manifest.
We didn't notice because the test was rigged to return `UNKNOWN` because
we *were* running the test from the compiled classes directory instead of the
jar. As part of shading jackson we moved running the tests to running against
the shaded jar. Now we can actually assert that we parse the version correctly.
It turns out we weren't. So I fixed it.

Original commit: elastic/x-pack-elasticsearch@2e8f397bf4
2017-11-14 21:31:35 -05:00
Costin Leau c8eb883c47 Fix incorrect assertions and javadoc
Original commit: elastic/x-pack-elasticsearch@0e6ebc0a69
2017-11-14 09:46:26 +02:00
Costin Leau 9a0b43cd17 Fix several NOCOMMITS (elastic/x-pack-elasticsearch#2968)
* Fix several NOCOMMITS

- renamed Assert to Check to make the intent clear
- clarify esMajor/Minor inside connection (thse are actually our own
methods, not part of JDBC API)
- wire pageTimeout into Cursor#nextPage


Original commit: elastic/x-pack-elasticsearch@7626c0a44a
2017-11-14 01:08:10 +02:00
Igor Motov ea0e58f971 SQL: introduce setting to disable SQL (elastic/x-pack-elasticsearch#2966)
Adds xpack.sql.enabled setting to provide ability to disable SQL on elasticsearch nodes.

relates elastic/x-pack-elasticsearch#2872

Original commit: elastic/x-pack-elasticsearch@d13b72e9ea
2017-11-13 15:10:47 -05:00
Costin Leau 8f55a4192c Improve grammar so keywords have priority over identifiers
Original commit: elastic/x-pack-elasticsearch@8222e30060
2017-11-09 21:40:09 +02:00
Costin Leau c48d2b14dc Define structure for docs and improve grammar
The keywords inside SqlBase are now sorted alphabetically - much easier
to read and update the docs

Original commit: elastic/x-pack-elasticsearch@5aa89c5950
2017-11-09 17:49:10 +02:00
Nik Everett 6ce140cf0f SQL: Make schema optional in RowSet (elastic/x-pack-elasticsearch#2834)
This prevents us from having to hack a fake schema together on the
second (and third and fourth, etc) page of results.

Original commit: elastic/x-pack-elasticsearch@7ba3119daa
2017-11-04 22:52:13 +00:00
Nik Everett 44dc98385a SQL: Reuse a registry meant to be shared (elastic/x-pack-elasticsearch#2838)
The CLI and JDBC were meant to share the same named xcontent registry
but the cli action didn't reuse it by mistake.

Original commit: elastic/x-pack-elasticsearch@6c9af5a22a
2017-11-04 13:10:35 +00:00
Nik Everett 68779a81e4 SQL: Remove now unused class (elastic/x-pack-elasticsearch#2839)
The `AbstractSqlServer` class was used when SQL's CLI and JDBC were
transport actions. They are REST layer concepts now and it is unused so
it should go.

Original commit: elastic/x-pack-elasticsearch@25ec699564
2017-11-04 00:01:15 +00:00
Nik Everett 41284cae93 SQL: Fix the name of the indices lookup action (elastic/x-pack-elasticsearch#2840)
Fix the name of the action the SQL uses to lookup index information from
the cluster state. The old name was silly.

Original commit: elastic/x-pack-elasticsearch@805fb29662
2017-11-03 23:37:22 +00:00
Nik Everett 25a0ec42f6 SQL: Reorganize the translate action (elastic/x-pack-elasticsearch#2841)
Organizes the SQL translate action to match the way that x-pack has been
organizing new actions for a while. All of the pieces are put into the
same class file.

Original commit: elastic/x-pack-elasticsearch@def911c0ab
2017-11-03 23:25:52 +00:00
Nik Everett d933b1b48b Initial docs for SQL (elastic/x-pack-elasticsearch#2810)
Adds docs for the REST API, translate API, the CLI, and JDBC.

Next we need to add more example queries and documentation for our
extensions.

Original commit: elastic/x-pack-elasticsearch@ed6d1360d2
2017-10-30 17:23:27 +00:00
Costin Leau 66719f7a92 Improve DateTime script template
When dealing with TZ, the script is reused across extractors by
externalizing the tz & chronofield

Original commit: elastic/x-pack-elasticsearch@9e63ea8cd8
2017-10-28 13:35:16 +03:00
Costin Leau 660cb3b814 Upgrade ANTLR to 4.5.3
Relates to elastic/x-pack-elasticsearch#26834

Original commit: elastic/x-pack-elasticsearch@57ba8f1d5f
2017-10-27 23:29:00 +03:00
Costin Leau af591b9edd SQL: Remove usage of Settings inside SqlSettings (elastic/x-pack-elasticsearch#2757)
* Remove usage of Settings inside SqlSettings

Also hook client timeouts to the backend
Set UTC as default timezone when using CSV
As the JVM timezone changes, make sure to pin it to UTC since this is what the results are computed against

Original commit: elastic/x-pack-elasticsearch@3e7aad8c1f
2017-10-27 18:55:59 +03:00
Costin Leau 6b1d0d1c8e SQL: Remove time threshold for rule executor (elastic/x-pack-elasticsearch#2750)
Refactor RuleExecutor to eliminate time-based thresholds

Original commit: elastic/x-pack-elasticsearch@ba131f8058
2017-10-27 18:43:13 +03:00
Igor Motov 387944d176 SQL: Move special joda time handling into DocValueExtractor (elastic/x-pack-elasticsearch#2758)
Moves joda time handling into DocValueExtractor, that's the only place where it occurs at the moment.

Original commit: elastic/x-pack-elasticsearch@205e82990a
2017-10-22 15:54:00 +02:00
Costin Leau 353c0c500b Fix and enable datetime tests (elastic/x-pack-elasticsearch#2680)
Firstly, data in H2 is now stored in TIMESTAMP WITH TIME ZONE since H2
does not allow a global TZ to be set and picks the JVM TZ when a record
is read.
JdbcAssert is now aware of this allows TIMESTAMP with TZ == TIMESTAMP

Discovered a serious bug in DateTimeFunction - unfortunately date
histogram is not useful except for year since most extract functions
avoid ordering which a histogram preserves.
Thus most DTF are now terms aggs with scripting.

Improved a bug that caused duplicate functions to not be detected because
of aliasing.

Moved some datetime tests to CSV but the aggs tests now are in sync with
H2

Fixed bug that caused arithmetic on aggs to not be properly resolved by
splitting the processor definition tree to aggName (unresolved) and
aggPath (resolved)

Original commit: elastic/x-pack-elasticsearch@e75ada68f1
2017-10-13 13:52:48 +03:00
Costin Leau 2bbb86eff7 Eliminate NOCOMMITS per discussion
Original commit: elastic/x-pack-elasticsearch@bd091a6608
2017-10-13 00:33:16 +03:00
Nik Everett 852af7de57 Fix error handling in SQL's CLI (elastic/x-pack-elasticsearch#2730)
We weren't returning errors correctly from the server
or catching them correctly in the CLI. This fixes that
and adds simple integration tests.

Original commit: elastic/x-pack-elasticsearch@259da0da6f
2017-10-12 16:32:15 +00:00
Costin Leau fa4504ed28 Fix some NOCOMMITs
Original commit: elastic/x-pack-elasticsearch@1a6ac1e6c6
2017-10-12 14:24:56 +03:00
Costin Leau e3d072aeea Make JDBC driver throw only SQLException (elastic/x-pack-elasticsearch#2708)
A JDBC driver should throw only checked SQLExceptions.
Introduce JdbcSQLException and fix some no-commits along the way.

Original commit: elastic/x-pack-elasticsearch@299fcf9ace
2017-10-12 12:27:19 +03:00
Igor Motov 7f0c44f138 SQL: Fix string to boolean conversion (elastic/x-pack-elasticsearch#2728)
This commit also adds tests for conversion to boolean

Original commit: elastic/x-pack-elasticsearch@d7740929a2
2017-10-11 19:56:36 -04:00
Igor Motov 06b4c043b9 SQL: Add toXcontent test for SqlResponse (elastic/x-pack-elasticsearch#2726)
Original commit: elastic/x-pack-elasticsearch@aa7b8f1a91
2017-10-11 19:55:59 -04:00
Costin Leau 2026198dd4 Add size for column tests (elastic/x-pack-elasticsearch#2685)
Add displaySize to columnInfo

Original commit: elastic/x-pack-elasticsearch@ed1d265e98
2017-10-12 00:03:41 +03:00
Costin Leau c9a41e111e Improve Sql exception reporting (elastic/x-pack-elasticsearch#2679)
Better handling of SQL exceptions (result of incorrect queries) vs
unexpected ones (engine failure, ES...)

Original commit: elastic/x-pack-elasticsearch@2698402cdb
2017-10-11 23:23:52 +03:00
Costin Leau 1cd6fb23ec Make SearchCursor limit aware
Original commit: elastic/x-pack-elasticsearch@c4839bc293
2017-10-10 19:22:42 +03:00
Igor Motov ed712d0e3f SQL: clean unused Exceptions and replace Util functions with core versions (elastic/x-pack-elasticsearch#2654)
This commit removes ThrowableConsumer, WrappingException, ActionUtils and ObjectUtils by replacing them with core equivalents when needed.

Original commit: elastic/x-pack-elasticsearch@5a68418a3d
2017-10-09 18:00:29 -04:00
Igor Motov fa410095ce SQL: remove synchronous execute method from Command (elastic/x-pack-elasticsearch#2653)
We switched most of the commands to asynchronous mode, this commit removes the synchronous version of exec to prevent accidental use of it in the future.

Original commit: elastic/x-pack-elasticsearch@03d0a6350d
2017-10-09 16:01:56 -04:00
Nik Everett 8675f6998b Use LF line endings in SQL generated files (elastic/x-pack-elasticsearch#26822) (elastic/x-pack-elasticsearch#2706)
Right now if you run `gradle regen` on Windows you'll get `CRLF` line
endings on all the ANTLR generated files because we run
```
ant.fixcrlf(srcdir: outputPath) {
    patternset(includes: 'SqlBase*.java')
}
```

The docs for fixcrlf say that the default line endings that it
corrects to is based on the OS:
https://ant.apache.org/manual/Tasks/fixcrlf.html

This change locks it to `LF`.

Original commit: elastic/x-pack-elasticsearch@4396729e04
2017-10-07 07:54:21 -04:00
Costin Leau e1a7c59d15 Rework StringUtilsTest from plain JUnit to ESTestCase
Original commit: elastic/x-pack-elasticsearch@cd16043f23
2017-09-30 01:17:33 +03:00
Costin Leau e0d02033de More JDBC improvements
properly return the precision for VARCHAR
ignore type when specified in index pattern

Original commit: elastic/x-pack-elasticsearch@71a5ac1812
2017-09-30 00:40:57 +03:00
Costin Leau cc66bbaa00 All jdbc client escaping is done on the server
Original commit: elastic/x-pack-elasticsearch@2b8b7c8c2e
2017-09-29 20:09:58 +03:00
Nik Everett c8e69b160e SQL: Fix build
Fix a few forgetten things from the validation change.

Original commit: elastic/x-pack-elasticsearch@807098dc6a
2017-09-28 16:57:58 -04:00
Costin Leau d634314dd1 Add comments to SqlSession
Original commit: elastic/x-pack-elasticsearch@82291d41c8
2017-09-28 22:29:23 +03:00
Costin Leau aca8a5b6c0 Analysis validation (elastic/x-pack-elasticsearch#2651)
Rework unresolved items messages
Update URLs in embedded HttpServers
Add antlr-runtime for embedded classpath

Original commit: elastic/x-pack-elasticsearch@36f0331d90
2017-09-28 22:27:20 +03:00
Igor Motov 33717f477f SQL: Make ShowColumns async (elastic/x-pack-elasticsearch#2638)
Original commit: elastic/x-pack-elasticsearch@54214b1109
2017-09-28 14:22:22 -04:00
Nik Everett 6be886edd8 Drop SQL's Session features (elastic/x-pack-elasticsearch#2639)
They don't work now and don't seem important enough to fix for
the first release. Maybe not ever.

Original commit: elastic/x-pack-elasticsearch@61e2b77e08
2017-09-28 13:41:58 -04:00
Costin Leau c33dfe7dbe Hook _translate rest endpoint
Add rest testcase plus fix some NOCOMMITs

Original commit: elastic/x-pack-elasticsearch@150576869c
2017-09-27 18:50:35 +03:00
Nik Everett 4da12381bf Remove RowSetCursor (elastic/x-pack-elasticsearch#2624)
`RowSetCursor` was just like `RowSet` only it had methods that allowed
you to scroll to the next page. We now use `RowSet#nextPageCursor` to
get the next page in a way that doesn't require us to store state on
the server. So we can remove `RowSetCursor` entirely now.

Original commit: elastic/x-pack-elasticsearch@6a4a1efb20
2017-09-25 17:35:03 -04:00
Nik Everett c7c79bc1c0 Add scrolling support to jdbc (elastic/x-pack-elasticsearch#2524)
* Switch `ResultSet#getFetchSize` from returning the *requested*
fetch size to returning the size of the current page of results.
For scrolling searches without parent/child this'll match the
requested fetch size but for other things it won't. The nice thing
about this is that it lets us tell users a thing to look at if
they are wondering why they are using a bunch of memory.
* Remove all the entire JDBC action and implement it on the REST
layer instead.
* Create some code that can be shared between the cli and jdbc
actions to properly handle errors and request deserialization so
there isn't as much copy and paste between the two. This helps
because it calls out explicitly the places where they are different.
  * I have not moved the CLI REST handle to shared code because
I think it'd be clearer to make that change in a followup PR.
* There is now no more need for constructs that allow iterating
all of the results in the same request. I have not removed these
because I feel that that cleanup is big enough to deserve its own
PR.

Original commit: elastic/x-pack-elasticsearch@3b12afd11c
2017-09-25 14:41:46 -04:00
Nik Everett 63a5ad0b1d Add versioned DataInput and DataOutput to SQL (elastic/x-pack-elasticsearch#2600)
These wrap `DataInput` and `DataOutput` to add the protocol
version being serialized. This is similar to the mechanism
used by core and it has made adding and removing fields from
the serialization protocol fairly simple.

Original commit: elastic/x-pack-elasticsearch@90b3f1199a
2017-09-25 11:01:57 -04:00
Nik Everett 71a33323ff SQL: Soften some more NOCOMMITs
Original commit: elastic/x-pack-elasticsearch@910e2485df
2017-09-21 11:33:30 -04:00
Costin Leau 6cc3c067b7 Introduce _sql/translate endpoint
Builds on RestSqlAction and in fact, extends SqlAction to keep up
with future request settings.

Original commit: elastic/x-pack-elasticsearch@7bbef4bdff
2017-09-20 21:48:53 +03:00
Nik Everett 1405773acb Fix serialization for HitExtractorProcessor
Also get more information when SQL fails in IT.

Original commit: elastic/x-pack-elasticsearch@09f6625274
2017-09-20 14:15:35 -04:00
Costin Leau 87293272d8 Arithmetic
* big refactor of Processor by introducing ProcessorDefinition an
immutable tree structure used for resolving multiple inputs across
folding (in particular for aggregations) which at runtime gets
translated into 'compiled' or small Processors

Add expression arithmetic, expression folding and type coercion

Folding
* for literals, scalars and inside the optimizer

Type validation happens per type hierarchy (numeric vs decimal) not type
Ceil/Floor/Round functions return long/int instead of double
ScalarFunction preserves ProcessorDefinition instead of functionId

Original commit: elastic/x-pack-elasticsearch@a703f8b455
2017-09-20 19:32:37 +03:00
Nik Everett b8f5720283 Switch SqlGetIndicesAction after merge
Merging picked up a change that starts to migrate away from Streamable
and we have to handle it.

Original commit: elastic/x-pack-elasticsearch@fa3489e128
2017-09-20 12:29:42 -04:00
Nik Everett 6ea902f913 SQL: NOCOMMIT cleanup
Removes a few NOCOMMITs that are tracked other places and updates
a few with plans on how to work on them.

Original commit: elastic/x-pack-elasticsearch@8d1cfdf4ee
2017-09-20 11:19:05 -04:00
Nik Everett bc03aa6c03 Line up sql serialization methods with core's (elastic/x-pack-elasticsearch#2538)
This renames that `write` and `read` methods in SQL to `writeTo` and
`readFrom` to line up with the names used in core. I don't have a
strong opinion whether or not any name is better than any other but
I figure there isn't a good reason for SQL to be different from the
rest of Elasticsearch.

Original commit: elastic/x-pack-elasticsearch@e5de9a4b81
2017-09-18 16:06:14 -04:00
Nik Everett 204e340397 Drop parameterized type from SQL's exception messages (elastic/x-pack-elasticsearch#2540)
The type parameter wasn't buying us anything.

Original commit: elastic/x-pack-elasticsearch@5005b26c09
2017-09-18 16:06:05 -04:00
Nik Everett 5d3f5cc4f8 Support scrolling in SQL's CLI (elastic/x-pack-elasticsearch#2494)
* Move CLI to TransportSqlAction
    * Moves REST endpoint from `/_cli` to `/_sql/cli`
    * Removes the special purpose CLI transport action instead
    implements the CLI entirely on the REST layer, delegating
    all SQL stuff to the same action that backs the `/_sql` REST
    API.
    * Reworks "embedded testing mode" to use a `FilterClient` to
    bounce capture the sql transport action and execute in embedded.
    * Switches CLI formatting from consuming the entire response
    to consuming just the first page of the response and returning
    a `cursor` that can be used to read the next page. That read is
    not yet implemented.
    * Switch CLI formatting from the consuming the `RowSetCursor` to
    consuming the `SqlResponse` object.
    * Adds tests for CLI formatting.
* Support next page in the cli
    * Rename cli's CommandRequest/CommandResponse to
    QueryInitRequest/QueryInitResponse to line up with jdbc
    * Implement QueryPageRequest/QueryPageResponse in cli
    * Use `byte[]` to represent the cursor in the cli. Those bytes
    mean something, but only to the server. The only reasonint that
    the client does about them is "if length == 0 then there isn't a
    next page."
    * Pull common code from jdbc's QueryInitRequest, QueryPageRequest,
    QueryInitResponse, and QueryPageResponse into the shared-proto
    project
        * By implication this switches jdbc's QueryPageRequest to using
     the same cursor implementation as the cli

Original commit: elastic/x-pack-elasticsearch@193586f1ee
2017-09-14 10:26:42 -04:00
Nik Everett 8b6a0daa05 Add tests for SqlGetIndicesAction.Request serialization (elastic/x-pack-elasticsearch#2452)
This request is already serializeable so we may as well add
tests for that so we don't break it.

Original commit: elastic/x-pack-elasticsearch@16cca77ccf
2017-09-11 14:37:57 -04:00
Nik Everett 94de0d8041 Replace exception catching with fancy returns (elastic/x-pack-elasticsearch#2454)
Instead of throwing and catching an exception for invalid
indices this returns *why* they are invalid in a convenient
object form that can be thrown as an exception when the index
is required or the entire index can be ignored when listing
indices.

Original commit: elastic/x-pack-elasticsearch@f45cbce647
2017-09-11 14:27:50 -04:00
Igor Motov 6ef174aa19 SQL: restore support for timezones in the DateTimeProcessor (elastic/x-pack-elasticsearch#2450)
The timezone handling seems to be lost in a merge conflict in elastic/x-pack-elasticsearch@20f41e2

Original commit: elastic/x-pack-elasticsearch@92c0ca3572
2017-09-10 17:44:45 -07:00
Nik Everett 3f8bf7ccc8 Integrate sql's metadata with security (elastic/x-pack-elasticsearch#2446)
This integrates SQL's metadata calls with security by creating
`SqlIndicesAction` and routing all of SQL's metadata calls through
it. Since it *does* know up from which indices it is working against
it can be an `IndicesRequest.Replaceable` and integrate with the
existing security infrastructure for filtering indices.

This request is implemented fairly similarly to the `GetIndexAction`
with the option to read from the master or from a local copy of
cluster state. Currently SQL forces it to run on the local copy
because the request doesn't properly support serialization. I'd
like to implement that in a followup.

Original commit: elastic/x-pack-elasticsearch@15f9512820
2017-09-08 10:59:47 -04:00
Igor Motov be32241263 SQL: Trivial gradle files cleanups (elastic/x-pack-elasticsearch#2447)
Resolved a few NOCOMMITS in Gradle files plus some minor cleanups

Original commit: elastic/x-pack-elasticsearch@b422d693b0
2017-09-08 09:43:18 -04:00
Nik Everett c540e1d583 Drop AbstractLifecycleComponent from PlanExecutor (elastic/x-pack-elasticsearch#2375)
In core we prefer not to extend `AbstractLifecycleComponent` because
the reasons for the tradeoffs that it makes are lost to the sands of
time.

Original commit: elastic/x-pack-elasticsearch@ec1a32bbb3
2017-08-30 17:09:29 -04:00
Nik Everett fd13c54cdc Remove some collection utils (elastic/x-pack-elasticsearch#2384)
Core doesn't go in for fancy collection utils in general and just
manipulates the required collections in line. In an effort to keep
SQL "more like the rest of Elasticsearch" I'm starting to remove
SQL's `CollectionUtils`.

Original commit: elastic/x-pack-elasticsearch@878ee181cb
2017-08-30 16:33:56 -04:00
Nik Everett 833ff18181 Fix broke test for ComposeProcessor
It had a bad branch in its mutate function.

Original commit: elastic/x-pack-elasticsearch@d35ec8549c
2017-08-30 16:20:27 -04:00
Nik Everett 972c56dafe Begin migrating SQL's next page (elastic/x-pack-elasticsearch#2271)
Scrolling was only implemented for the `SqlAction` (not jdbc or cli)
and it was implemented by keeping request state on the server. On
principle we try to avoid adding extra state to elasticsearch where
possible because it creates extra points of failure and tends to
have lots of hidden complexity.

This replaces the state on the server with serializing state to the
client. This looks to the user like a "next_page" key with fairly
opaque content. It actually consists of an identifier for the *kind*
of scroll, the scroll id, and a base64 string containing the field
extractors.

Right now this only implements scrolling for `SqlAction`. The plan
is to reuse the same implementation for jdbc and cli in a followup.

This also doesn't implement all of the required serialization.
Specifically it doesn't implement serialization of
`ProcessingHitExtractor` because I haven't implemented serialization
for *any* `ColumnProcessors`.

Original commit: elastic/x-pack-elasticsearch@a8567bc5ec
2017-08-28 08:46:49 -04:00
Costin Leau a040f3bb14 More integration tests (BETWEEN) plus minor polishing
Original commit: elastic/x-pack-elasticsearch@1546713d5c
2017-08-26 23:14:20 +03:00