use of io.crate.common.collections.Lists2.mapTail in project crate by crate.
the class WindowFunction method toString.
@Override
public String toString(Style style) {
var builder = new StringBuilder(super.toString(style));
if (ignoreNulls != null) {
if (ignoreNulls) {
builder.append(" IGNORE NULLS");
} else {
builder.append(" RESPECT NULLS");
}
}
builder.append(" OVER (");
var partitions = windowDefinition.partitions();
if (!partitions.isEmpty()) {
builder.append("PARTITION BY ");
builder.append(Lists2.joinOn(", ", partitions, x -> x.toString(style)));
}
var orderBy = windowDefinition.orderBy();
if (orderBy != null) {
if (!partitions.isEmpty()) {
builder.append(" ");
}
builder.append("ORDER BY ");
OrderBy.explainRepresentation(builder, orderBy.orderBySymbols(), orderBy.reverseFlags(), orderBy.nullsFirst(), x -> x.toString(style));
}
WindowFrameDefinition frameDefinition = windowDefinition.windowFrameDefinition();
if (frameDefinition != WindowDefinition.RANGE_UNBOUNDED_PRECEDING_CURRENT_ROW) {
builder.append(" ");
builder.append(frameDefinition.mode().name());
builder.append(" BETWEEN ");
appendFrameBound(builder, style, frameDefinition.start());
builder.append(" AND ");
appendFrameBound(builder, style, frameDefinition.end());
}
builder.append(")");
return builder.toString();
}
use of io.crate.common.collections.Lists2.mapTail in project crate by crate.
the class CreateSnapshotPlan method createRequest.
@VisibleForTesting
public static CreateSnapshotRequest createRequest(AnalyzedCreateSnapshot createSnapshot, CoordinatorTxnCtx txnCtx, NodeContext nodeCtx, Row parameters, SubQueryResults subQueryResults, Schemas schemas) {
Function<? super Symbol, Object> eval = x -> SymbolEvaluator.evaluate(txnCtx, nodeCtx, x, parameters, subQueryResults);
Settings settings = GenericPropertiesConverter.genericPropertiesToSettings(createSnapshot.properties().map(eval), SnapshotSettings.SETTINGS);
boolean ignoreUnavailable = IGNORE_UNAVAILABLE.get(settings);
final HashSet<String> snapshotIndices;
final HashSet<String> templates = new HashSet<>();
if (createSnapshot.tables().isEmpty()) {
for (SchemaInfo schemaInfo : schemas) {
for (TableInfo tableInfo : schemaInfo.getTables()) {
// only check for user generated tables
if (tableInfo instanceof DocTableInfo) {
Operation.blockedRaiseException(tableInfo, Operation.READ);
}
}
}
snapshotIndices = new HashSet<>(AnalyzedCreateSnapshot.ALL_INDICES);
} else {
snapshotIndices = new HashSet<>(createSnapshot.tables().size());
for (Table<Symbol> table : createSnapshot.tables()) {
DocTableInfo docTableInfo;
try {
docTableInfo = (DocTableInfo) schemas.resolveTableInfo(table.getName(), Operation.CREATE_SNAPSHOT, txnCtx.sessionContext().sessionUser(), txnCtx.sessionContext().searchPath());
} catch (Exception e) {
if (ignoreUnavailable && e instanceof ResourceUnknownException) {
LOGGER.info("Ignore unknown relation '{}' for the '{}' snapshot'", table.getName(), createSnapshot.snapshot());
continue;
} else {
throw e;
}
}
if (docTableInfo.isPartitioned()) {
templates.add(PartitionName.templateName(docTableInfo.ident().schema(), docTableInfo.ident().name()));
}
if (table.partitionProperties().isEmpty()) {
snapshotIndices.addAll(Arrays.asList(docTableInfo.concreteIndices()));
} else {
var partitionName = toPartitionName(docTableInfo, Lists2.map(table.partitionProperties(), x -> x.map(eval)));
if (!docTableInfo.partitions().contains(partitionName)) {
if (!ignoreUnavailable) {
throw new PartitionUnknownException(partitionName);
} else {
LOGGER.info("ignoring unknown partition of table '{}' with ident '{}'", partitionName.relationName(), partitionName.ident());
}
} else {
snapshotIndices.add(partitionName.asIndexName());
}
}
}
}
return new CreateSnapshotRequest(createSnapshot.snapshot().getRepository(), createSnapshot.snapshot().getSnapshotId().getName()).includeGlobalState(createSnapshot.tables().isEmpty()).waitForCompletion(WAIT_FOR_COMPLETION.get(settings)).indices(snapshotIndices.toArray(new String[0])).indicesOptions(IndicesOptions.fromOptions(ignoreUnavailable, true, true, false, IndicesOptions.lenientExpandOpen())).templates(templates.stream().toList()).settings(settings);
}
use of io.crate.common.collections.Lists2.mapTail in project crate by crate.
the class PostgresWireProtocol method handleSingleQuery.
private CompletableFuture<?> handleSingleQuery(Statement statement, DelayableWriteChannel channel) {
CompletableFuture<?> result = new CompletableFuture<>();
String query;
try {
query = SqlFormatter.formatSql(statement);
} catch (Exception e) {
query = statement.toString();
}
AccessControl accessControl = getAccessControl.apply(session.sessionContext());
try {
session.analyze("", statement, Collections.emptyList(), query);
session.bind("", "", Collections.emptyList(), null);
DescribeResult describeResult = session.describe('P', "");
List<Symbol> fields = describeResult.getFields();
CompletableFuture<?> execute;
if (fields == null) {
RowCountReceiver rowCountReceiver = new RowCountReceiver(query, channel.bypassDelay(), accessControl);
execute = session.execute("", 0, rowCountReceiver);
} else {
Messages.sendRowDescription(channel, fields, null, describeResult.relation());
ResultSetReceiver resultSetReceiver = new ResultSetReceiver(query, channel.bypassDelay(), TransactionState.IDLE, accessControl, Lists2.map(fields, x -> PGTypes.get(x.valueType())), null);
execute = session.execute("", 0, resultSetReceiver);
}
if (execute != null) {
channel.delayWritesUntil(execute);
}
return session.sync();
} catch (Throwable t) {
Messages.sendErrorResponse(channel, accessControl, t);
result.completeExceptionally(t);
return result;
}
}
use of io.crate.common.collections.Lists2.mapTail in project crate by crate.
the class SQLIntegrationTestCase method assertFunctionIsCreatedOnAll.
public void assertFunctionIsCreatedOnAll(String schema, String name, List<DataType<?>> argTypes) throws Exception {
SearchPath searchPath = SearchPath.pathWithPGCatalogAndDoc();
assertBusy(() -> {
Iterable<Functions> functions = internalCluster().getInstances(Functions.class);
for (Functions function : functions) {
FunctionImplementation func = function.get(schema, name, Lists2.map(argTypes, t -> Literal.of(t, null)), searchPath);
assertThat(func, is(not(nullValue())));
assertThat(func.info().ident().argumentTypes(), is(equalTo(argTypes)));
}
}, 20L, TimeUnit.SECONDS);
}
use of io.crate.common.collections.Lists2.mapTail in project crate by crate.
the class TransportSQLActionTest method test_primary_key_lookups_returns_inserted_records.
@Test
public void test_primary_key_lookups_returns_inserted_records() throws Exception {
int numKeys = randomIntBetween(1, 3);
Random random = RandomizedContext.current().getRandom();
StringBuilder createTable = new StringBuilder("CREATE TABLE tbl (");
ArrayList<DataType<?>> types = new ArrayList<>();
List<DataType<?>> typeCandidates = DataTypes.PRIMITIVE_TYPES.stream().filter(x -> x.storageSupport() != null).collect(Collectors.toList());
for (int i = 0; i < numKeys; i++) {
var type = RandomPicks.randomFrom(random, typeCandidates);
types.add(type);
createTable.append("col");
createTable.append(i);
createTable.append(' ');
createTable.append(type.getName());
createTable.append(" PRIMARY KEY");
if (i + 1 < numKeys) {
createTable.append(", ");
}
}
createTable.append(")");
execute(createTable.toString());
String insert = "INSERT INTO tbl VALUES (" + String.join(", ", Lists2.map(types, ignored -> "?")) + ")";
Object[] args = new Object[types.size()];
for (int i = 0; i < types.size(); i++) {
var type = types.get(i);
args[i] = DataTypeTesting.getDataGenerator(type).get();
}
execute(insert, args);
StringBuilder selectInlineValues = new StringBuilder("SELECT 1 FROM tbl WHERE ");
StringBuilder selectParams = new StringBuilder("SELECT 1 FROM tbl WHERE ");
for (int i = 0; i < args.length; i++) {
var arg = args[i];
selectInlineValues.append("col");
selectParams.append("col");
selectInlineValues.append(i);
selectParams.append(i);
selectInlineValues.append(" = ");
if (arg instanceof String) {
selectInlineValues.append("'");
selectInlineValues.append(arg);
selectInlineValues.append("'");
} else {
selectInlineValues.append(arg);
}
selectParams.append(" = ?");
if (i + 1 < args.length) {
selectInlineValues.append(" AND ");
selectParams.append(" AND ");
}
}
execute(selectParams.toString(), args);
assertThat(selectParams.toString() + " with values " + Arrays.toString(args) + " must return a record", response.rowCount(), is(1L));
execute(selectInlineValues.toString());
assertThat(selectInlineValues.toString() + " must return a record", response.rowCount(), is(1L));
}
Aggregations