proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
crate_crate
|
crate/server/src/main/java/io/crate/expression/operator/Operators.java
|
Operators
|
addFunctions
|
class Operators implements FunctionsProvider {
public static final Set<String> LOGICAL_OPERATORS = Set.of(
AndOperator.NAME, OrOperator.NAME, NotPredicate.NAME
);
public static final Set<String> COMPARISON_OPERATORS = Set.of(
EqOperator.NAME,
GtOperator.NAME, GteOperator.NAME,
LtOperator.NAME, LteOperator.NAME,
CIDROperator.CONTAINED_WITHIN
);
@Override
public void addFunctions(Settings settings,
SessionSettingRegistry sessionSettingRegistry,
Functions.Builder builder) {<FILL_FUNCTION_BODY>}
}
|
AndOperator.register(builder);
OrOperator.register(builder);
EqOperator.register(builder);
CIDROperator.register(builder);
LtOperator.register(builder);
LteOperator.register(builder);
GtOperator.register(builder);
GteOperator.register(builder);
RegexpMatchOperator.register(builder);
RegexpMatchCaseInsensitiveOperator.register(builder);
AnyOperator.register(builder);
AllOperator.register(builder);
LikeOperators.register(builder);
ExistsOperator.register(builder);
| 176
| 148
| 324
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/operator/OrOperator.java
|
OrOperator
|
normalizeSymbol
|
class OrOperator extends Operator<Boolean> {
public static final String NAME = "op_or";
public static final Signature SIGNATURE = Signature.scalar(
NAME,
DataTypes.BOOLEAN.getTypeSignature(),
DataTypes.BOOLEAN.getTypeSignature(),
DataTypes.BOOLEAN.getTypeSignature()
);
public static void register(Functions.Builder builder) {
builder.add(SIGNATURE, OrOperator::new);
}
public OrOperator(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
public Symbol normalizeSymbol(Function function, TransactionContext txnCtx, NodeContext nodeCtx) {<FILL_FUNCTION_BODY>}
@Override
public Boolean evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Boolean>... args) {
assert args != null : "args must not be null";
assert args.length == 2 : "number of args must be 2";
assert args[0] != null && args[1] != null : "1st and 2nd argument must not be null";
// implement three valued logic.
// don't touch anything unless you have a good reason for it! :)
// http://en.wikipedia.org/wiki/Three-valued_logic
Boolean left = args[0].value();
Boolean right = args[1].value();
if (left == null && right == null) {
return null;
}
if (left == null) {
return (right) ? true : null;
}
if (right == null) {
return (left) ? true : null;
}
return left || right;
}
@Override
public Query toQuery(Function function, Context context) {
BooleanQuery.Builder query = new BooleanQuery.Builder();
query.setMinimumNumberShouldMatch(1);
for (Symbol symbol : function.arguments()) {
query.add(symbol.accept(context.visitor(), context), BooleanClause.Occur.SHOULD);
}
return query.build();
}
}
|
assert function != null : "function must not be null";
assert function.arguments().size() == 2 : "number of args must be 2";
Symbol left = function.arguments().get(0);
Symbol right = function.arguments().get(1);
if (left.symbolType().isValueSymbol() && right.symbolType().isValueSymbol()) {
return Literal.of(evaluate(txnCtx, nodeCtx, (Input) left, (Input) right));
}
/*
* true or x -> true
* false or x -> x
* null or x -> null or true -> return function as is
*/
if (left instanceof Input) {
Object value = ((Input) left).value();
if (value == null) {
return function;
}
assert value instanceof Boolean : "value must be Boolean";
if ((Boolean) value) {
return Literal.of(true);
} else {
return right;
}
}
if (right instanceof Input) {
Object value = ((Input) right).value();
if (value == null) {
return function;
}
assert value instanceof Boolean : "value must be Boolean";
if ((Boolean) value) {
return Literal.of(true);
} else {
return left;
}
}
return function;
| 546
| 350
| 896
|
<methods>public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) <variables>public static final java.lang.String PREFIX,public static final io.crate.types.BooleanType RETURN_TYPE
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/operator/any/AnyNeqOperator.java
|
AnyNeqOperator
|
literalMatchesAnyArrayRef
|
class AnyNeqOperator extends AnyOperator {
public static String NAME = OPERATOR_PREFIX + ComparisonExpression.Type.NOT_EQUAL.getValue();
AnyNeqOperator(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
boolean matches(Object probe, Object candidate) {
return leftType.compare(probe, candidate) != 0;
}
@Override
protected Query refMatchesAnyArrayLiteral(Function any, Reference probe, Literal<?> candidates, Context context) {
// col != ANY ([1,2,3]) --> not(col=1 and col=2 and col=3)
String columnName = probe.storageIdent();
MappedFieldType fieldType = context.getFieldTypeOrNull(columnName);
if (fieldType == null) {
return newUnmappedFieldQuery(columnName);
}
BooleanQuery.Builder andBuilder = new BooleanQuery.Builder();
for (Object value : (Iterable<?>) candidates.value()) {
if (value == null) {
continue;
}
var fromPrimitive = EqOperator.fromPrimitive(
probe.valueType(),
columnName,
value,
probe.hasDocValues(),
probe.indexType());
if (fromPrimitive == null) {
return null;
}
andBuilder.add(fromPrimitive, BooleanClause.Occur.MUST);
}
Query exists = IsNullPredicate.refExistsQuery(probe, context, false);
return new BooleanQuery.Builder()
.add(Queries.not(andBuilder.build()), Occur.MUST)
.add(exists, Occur.FILTER)
.build();
}
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
protected Query literalMatchesAnyArrayRef(Function any, Literal<?> probe, Reference candidates, Context context) {<FILL_FUNCTION_BODY>}
}
|
// 1 != any ( col ) --> gt 1 or lt 1
String columnName = candidates.storageIdent();
MappedFieldType fieldType = context.getFieldTypeOrNull(columnName);
if (fieldType == null) {
return newUnmappedFieldQuery(columnName);
}
StorageSupport<?> storageSupport = probe.valueType().storageSupport();
if (storageSupport == null) {
return null;
}
EqQuery eqQuery = storageSupport.eqQuery();
if (eqQuery == null) {
return null;
}
Object value = probe.value();
BooleanQuery.Builder query = new BooleanQuery.Builder();
query.setMinimumNumberShouldMatch(1);
var gt = eqQuery.rangeQuery(
columnName,
value,
null,
false,
false,
candidates.hasDocValues(),
candidates.indexType() != IndexType.NONE);
var lt = eqQuery.rangeQuery(
columnName,
null,
value,
false,
false,
candidates.hasDocValues(),
candidates.indexType() != IndexType.NONE);
if (lt == null || gt == null) {
assert lt != null || gt == null : "If lt is null, gt must be null";
return null;
}
query.add(gt, BooleanClause.Occur.SHOULD);
query.add(lt, BooleanClause.Occur.SHOULD);
return query.build();
| 502
| 394
| 896
|
<methods>public final transient java.lang.Boolean evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Object>[]) ,public static void register(io.crate.metadata.Functions.Builder) ,public Query toQuery(io.crate.expression.symbol.Function, io.crate.lucene.LuceneQueryBuilder.Context) <variables>permits AnyEqOperator,permits AnyLikeOperator,permits AnyNeqOperator,permits AnyNotLikeOperator,permits AnyRangeOperator,public static final List<java.lang.String> OPERATOR_NAMES,public static final java.lang.String OPERATOR_PREFIX,public static final Set<java.lang.String> SUPPORTED_COMPARISONS,protected final non-sealed DataType<java.lang.Object> leftType
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/operator/any/AnyOperator.java
|
AnyOperator
|
evaluate
|
class AnyOperator extends Operator<Object>
permits AnyEqOperator, AnyNeqOperator, AnyRangeOperator, AnyLikeOperator, AnyNotLikeOperator {
public static final String OPERATOR_PREFIX = "any_";
public static final List<String> OPERATOR_NAMES = List.of(
AnyEqOperator.NAME,
AnyNeqOperator.NAME,
AnyRangeOperator.Comparison.GT.opName(),
AnyRangeOperator.Comparison.GTE.opName(),
AnyRangeOperator.Comparison.LT.opName(),
AnyRangeOperator.Comparison.LTE.opName(),
LikeOperators.ANY_LIKE,
LikeOperators.ANY_ILIKE,
LikeOperators.ANY_NOT_LIKE,
LikeOperators.ANY_NOT_ILIKE
);
public static final Set<String> SUPPORTED_COMPARISONS = Set.of(
ComparisonExpression.Type.EQUAL.getValue(),
ComparisonExpression.Type.NOT_EQUAL.getValue(),
ComparisonExpression.Type.LESS_THAN.getValue(),
ComparisonExpression.Type.LESS_THAN_OR_EQUAL.getValue(),
ComparisonExpression.Type.GREATER_THAN.getValue(),
ComparisonExpression.Type.GREATER_THAN_OR_EQUAL.getValue()
);
protected final DataType<Object> leftType;
public static void register(Functions.Builder builder) {
reg(builder, AnyEqOperator.NAME, (sig, boundSig) -> new AnyEqOperator(sig, boundSig));
reg(builder, AnyNeqOperator.NAME, (sig, boundSig) -> new AnyNeqOperator(sig, boundSig));
regRange(builder, AnyRangeOperator.Comparison.GT);
regRange(builder, AnyRangeOperator.Comparison.GTE);
regRange(builder, AnyRangeOperator.Comparison.LT);
regRange(builder, AnyRangeOperator.Comparison.LTE);
}
private static void regRange(Functions.Builder builder, Comparison comparison) {
reg(builder, comparison.opName(), (sig, boundSig) -> new AnyRangeOperator(sig, boundSig, comparison));
}
private static void reg(Functions.Builder builder, String name, FunctionFactory operatorFactory) {
builder.add(
Signature.scalar(
name,
TypeSignature.parse("E"),
TypeSignature.parse("array(E)"),
Operator.RETURN_TYPE.getTypeSignature()
).withTypeVariableConstraints(TypeVariableConstraint.typeVariable("E")),
operatorFactory
);
}
@SuppressWarnings("unchecked")
AnyOperator(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
this.leftType = (DataType<Object>) boundSignature.argTypes().get(0);
}
abstract boolean matches(Object probe, Object candidate);
protected abstract Query refMatchesAnyArrayLiteral(Function any, Reference probe, Literal<?> candidates, Context context);
protected abstract Query literalMatchesAnyArrayRef(Function any, Literal<?> probe, Reference candidates, Context context);
@Override
@SafeVarargs
public final Boolean evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Object> ... args) {<FILL_FUNCTION_BODY>}
@Override
public Query toQuery(Function function, Context context) {
List<Symbol> args = function.arguments();
Symbol probe = args.get(0);
Symbol candidates = args.get(1);
while (candidates instanceof Function fn && fn.signature().equals(ArrayUnnestFunction.SIGNATURE)) {
candidates = fn.arguments().get(0);
}
if (probe instanceof Literal<?> literal && candidates instanceof Reference ref) {
return literalMatchesAnyArrayRef(function, literal, ref, context);
} else if (probe instanceof Reference ref && candidates instanceof Literal<?> literal) {
return refMatchesAnyArrayLiteral(function, ref, literal, context);
} else {
return null;
}
}
}
|
assert args != null : "args must not be null";
assert args.length == 2 : "number of args must be 2";
assert args[0] != null : "1st argument must not be null";
Object item = args[0].value();
Object items = args[1].value();
if (items == null || item == null) {
return null;
}
boolean anyNulls = false;
for (Object rightValue : (Iterable<?>) items) {
if (rightValue == null) {
anyNulls = true;
continue;
}
if (matches(item, rightValue)) {
return true;
}
}
return anyNulls ? null : false;
| 1,032
| 187
| 1,219
|
<methods>public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) <variables>public static final java.lang.String PREFIX,public static final io.crate.types.BooleanType RETURN_TYPE
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/reference/StaticTableReferenceResolver.java
|
StaticTableReferenceResolver
|
getImplementationByRootTraversal
|
class StaticTableReferenceResolver<R> implements ReferenceResolver<NestableCollectExpression<R, ?>> {
private final Map<ColumnIdent, ? extends RowCollectExpressionFactory<R>> expressionFactories;
public StaticTableReferenceResolver(Map<ColumnIdent, ? extends RowCollectExpressionFactory<R>> expressionFactories) {
this.expressionFactories = expressionFactories;
}
@Override
public NestableCollectExpression<R, ?> getImplementation(Reference ref) {
return rowCollectExpressionFromFactoryMap(expressionFactories, ref);
}
private static <R> NestableCollectExpression<R, ?> rowCollectExpressionFromFactoryMap(
Map<ColumnIdent, ? extends RowCollectExpressionFactory<R>> factories,
Reference ref) {
ColumnIdent columnIdent = ref.column();
RowCollectExpressionFactory<R> factory = factories.get(columnIdent);
if (factory != null) {
return factory.create();
}
if (columnIdent.isRoot()) {
return null;
}
return getImplementationByRootTraversal(factories, columnIdent);
}
private static <R> NestableCollectExpression<R, ?> getImplementationByRootTraversal(
Map<ColumnIdent, ? extends RowCollectExpressionFactory<R>> innerFactories,
ColumnIdent columnIdent) {<FILL_FUNCTION_BODY>}
}
|
RowCollectExpressionFactory<R> factory = innerFactories.get(columnIdent.getRoot());
if (factory == null) {
return null;
}
NestableInput<?> refImpl = factory.create();
NestableInput<?> childByPath = NestableInput.getChildByPath(refImpl, columnIdent.path());
assert childByPath instanceof NestableCollectExpression
: "Child " + columnIdent.path() + " of " + refImpl + " must be a NestableCollectExpression";
return (NestableCollectExpression<R, ?>) childByPath;
| 347
| 152
| 499
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/reference/doc/lucene/ByteColumnReference.java
|
ByteColumnReference
|
value
|
class ByteColumnReference extends LuceneCollectorExpression<Byte> {
private final String columnName;
private SortedNumericDocValues values;
private int docId;
public ByteColumnReference(String columnName) {
this.columnName = columnName;
}
@Override
public Byte value() {<FILL_FUNCTION_BODY>}
@Override
public void setNextDocId(int docId) {
this.docId = docId;
}
@Override
public void setNextReader(ReaderContext context) throws IOException {
super.setNextReader(context);
values = DocValues.getSortedNumeric(context.reader(), columnName);
}
}
|
try {
if (values.advanceExact(docId)) {
switch (values.docValueCount()) {
case 1:
return (byte) values.nextValue();
default:
throw new ArrayViaDocValuesUnsupportedException(columnName);
}
} else {
return null;
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
| 179
| 111
| 290
|
<methods>public void setNextDocId(int) ,public void setNextReader(io.crate.execution.engine.fetch.ReaderContext) throws java.io.IOException,public void setScorer(Scorable) ,public void startCollect(io.crate.expression.reference.doc.lucene.CollectorContext) <variables>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/reference/doc/lucene/BytesRefColumnReference.java
|
BytesRefColumnReference
|
value
|
class BytesRefColumnReference extends LuceneCollectorExpression<String> {
private final String columnName;
private SortedBinaryDocValues values;
private int docId;
public BytesRefColumnReference(String columnName) {
this.columnName = columnName;
}
@Override
public String value() throws ArrayViaDocValuesUnsupportedException {<FILL_FUNCTION_BODY>}
@Override
public void setNextDocId(int docId) {
this.docId = docId;
}
@Override
public void setNextReader(ReaderContext context) throws IOException {
super.setNextReader(context);
values = FieldData.toString(DocValues.getSortedSet(context.reader(), columnName));
}
}
|
try {
if (values.advanceExact(docId)) {
if (values.docValueCount() == 1) {
return values.nextValue().utf8ToString();
} else {
throw new ArrayViaDocValuesUnsupportedException(columnName);
}
} else {
return null;
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
| 195
| 108
| 303
|
<methods>public void setNextDocId(int) ,public void setNextReader(io.crate.execution.engine.fetch.ReaderContext) throws java.io.IOException,public void setScorer(Scorable) ,public void startCollect(io.crate.expression.reference.doc.lucene.CollectorContext) <variables>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/reference/doc/lucene/IntegerColumnReference.java
|
IntegerColumnReference
|
value
|
class IntegerColumnReference extends LuceneCollectorExpression<Integer> {
private final String columnName;
private SortedNumericDocValues values;
private int docId;
public IntegerColumnReference(String columnName) {
this.columnName = columnName;
}
@Override
public Integer value() {<FILL_FUNCTION_BODY>}
@Override
public void setNextDocId(int docId) {
this.docId = docId;
}
@Override
public void setNextReader(ReaderContext context) throws IOException {
super.setNextReader(context);
values = DocValues.getSortedNumeric(context.reader(), columnName);
}
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (obj == this)
return true;
if (!(obj instanceof IntegerColumnReference))
return false;
return columnName.equals(((IntegerColumnReference) obj).columnName);
}
@Override
public int hashCode() {
return columnName.hashCode();
}
}
|
try {
if (values.advanceExact(docId)) {
switch (values.docValueCount()) {
case 1:
return (int) values.nextValue();
default:
throw new ArrayViaDocValuesUnsupportedException(columnName);
}
} else {
return null;
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
| 282
| 110
| 392
|
<methods>public void setNextDocId(int) ,public void setNextReader(io.crate.execution.engine.fetch.ReaderContext) throws java.io.IOException,public void setScorer(Scorable) ,public void startCollect(io.crate.expression.reference.doc.lucene.CollectorContext) <variables>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/reference/doc/lucene/LuceneReferenceResolver.java
|
LuceneReferenceResolver
|
getImplementation
|
class LuceneReferenceResolver implements ReferenceResolver<LuceneCollectorExpression<?>> {
private static final Set<Integer> NO_FIELD_TYPES_IDS = Set.of(ObjectType.ID, GeoShapeType.ID);
private final FieldTypeLookup fieldTypeLookup;
private final List<Reference> partitionColumns;
private final String indexName;
public LuceneReferenceResolver(final String indexName,
final FieldTypeLookup fieldTypeLookup,
final List<Reference> partitionColumns) {
this.indexName = indexName;
this.fieldTypeLookup = fieldTypeLookup;
this.partitionColumns = partitionColumns;
}
@Override
public LuceneCollectorExpression<?> getImplementation(final Reference ref) {<FILL_FUNCTION_BODY>}
private static LuceneCollectorExpression<?> maybeInjectPartitionValue(LuceneCollectorExpression<?> result,
String indexName,
List<Reference> partitionColumns,
ColumnIdent column) {
for (int i = 0; i < partitionColumns.size(); i++) {
final Reference partitionColumn = partitionColumns.get(i);
final var partitionColumnIdent = partitionColumn.column();
if (partitionColumnIdent.isChildOf(column)) {
return new PartitionValueInjectingExpression(
PartitionName.fromIndexOrTemplate(indexName),
i,
partitionColumnIdent.shiftRight(),
result
);
}
}
return result;
}
private static LuceneCollectorExpression<?> typeSpecializedExpression(final FieldTypeLookup fieldTypeLookup,
final Reference ref) {
final String fqn = ref.storageIdent();
final MappedFieldType fieldType = fieldTypeLookup.get(fqn);
if (fieldType == null) {
return NO_FIELD_TYPES_IDS.contains(unnest(ref.valueType()).id()) || isIgnoredDynamicReference(ref)
? DocCollectorExpression.create(toSourceLookup(ref))
: new LiteralValueExpression(null);
}
if (!fieldType.hasDocValues()) {
return DocCollectorExpression.create(toSourceLookup(ref));
}
switch (ref.valueType().id()) {
case BitStringType.ID:
return new BitStringColumnReference(fqn, ((BitStringType) ref.valueType()).length());
case ByteType.ID:
return new ByteColumnReference(fqn);
case ShortType.ID:
return new ShortColumnReference(fqn);
case IpType.ID:
return new IpColumnReference(fqn);
case StringType.ID:
case CharacterType.ID:
return new BytesRefColumnReference(fqn);
case DoubleType.ID:
return new DoubleColumnReference(fqn);
case BooleanType.ID:
return new BooleanColumnReference(fqn);
case FloatType.ID:
return new FloatColumnReference(fqn);
case LongType.ID:
case TimestampType.ID_WITH_TZ:
case TimestampType.ID_WITHOUT_TZ:
return new LongColumnReference(fqn);
case IntegerType.ID:
return new IntegerColumnReference(fqn);
case GeoPointType.ID:
return new GeoPointColumnReference(fqn);
case ArrayType.ID:
return DocCollectorExpression.create(toSourceLookup(ref));
case FloatVectorType.ID:
return new FloatVectorColumnReference(fqn);
default:
throw new UnhandledServerException("Unsupported type: " + ref.valueType().getName());
}
}
private static boolean isIgnoredDynamicReference(final Reference ref) {
return ref.symbolType() == SymbolType.DYNAMIC_REFERENCE && ref.columnPolicy() == ColumnPolicy.IGNORED;
}
static class LiteralValueExpression extends LuceneCollectorExpression<Object> {
private final Object value;
public LiteralValueExpression(Object value) {
this.value = value;
}
@Override
public Object value() {
return value;
}
}
static class PartitionValueInjectingExpression extends LuceneCollectorExpression<Object> {
private final LuceneCollectorExpression<?> inner;
private final ColumnIdent partitionPath;
private final int partitionPos;
private final PartitionName partitionName;
public PartitionValueInjectingExpression(PartitionName partitionName,
int partitionPos,
ColumnIdent partitionPath,
LuceneCollectorExpression<?> inner) {
this.inner = inner;
this.partitionName = partitionName;
this.partitionPos = partitionPos;
this.partitionPath = partitionPath;
}
@SuppressWarnings("unchecked")
@Override
public Object value() {
final var object = (Map<String, Object>) inner.value();
final var partitionValue = partitionName.values().get(partitionPos);
Maps.mergeInto(
object,
partitionPath.name(),
partitionPath.path(),
partitionValue
);
return object;
}
@Override
public void startCollect(final CollectorContext context) {
inner.startCollect(context);
}
@Override
public void setNextDocId(final int doc) {
inner.setNextDocId(doc);
}
@Override
public void setNextReader(ReaderContext context) throws IOException {
inner.setNextReader(context);
}
@Override
public void setScorer(final Scorable scorer) {
inner.setScorer(scorer);
}
}
}
|
final ColumnIdent column = ref.column();
switch (column.name()) {
case DocSysColumns.Names.RAW:
if (column.isRoot()) {
return new RawCollectorExpression();
}
throw new UnsupportedFeatureException("_raw expression does not support subscripts: " + column);
case DocSysColumns.Names.UID:
case DocSysColumns.Names.ID:
return new IdCollectorExpression();
case DocSysColumns.Names.FETCHID:
return new FetchIdCollectorExpression();
case DocSysColumns.Names.DOCID:
return new DocIdCollectorExpression();
case DocSysColumns.Names.SCORE:
return new ScoreCollectorExpression();
case DocSysColumns.Names.VERSION:
return new VersionCollectorExpression();
case DocSysColumns.Names.SEQ_NO:
return new SeqNoCollectorExpression();
case DocSysColumns.Names.PRIMARY_TERM:
return new PrimaryTermCollectorExpression();
case DocSysColumns.Names.DOC: {
var result = DocCollectorExpression.create(ref);
return maybeInjectPartitionValue(
result,
indexName,
partitionColumns,
column.isRoot() ? column : column.shiftRight() // Remove `_doc` prefix so that it can match the column against partitionColumns
);
}
default: {
int partitionPos = Reference.indexOf(partitionColumns, column);
if (partitionPos >= 0) {
return new LiteralValueExpression(
ref.valueType().implicitCast(PartitionName.fromIndexOrTemplate(indexName).values().get(partitionPos))
);
}
return maybeInjectPartitionValue(
typeSpecializedExpression(fieldTypeLookup, ref),
indexName,
partitionColumns,
column
);
}
}
| 1,440
| 477
| 1,917
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/reference/doc/lucene/PrimaryTermCollectorExpression.java
|
PrimaryTermCollectorExpression
|
setNextReader
|
class PrimaryTermCollectorExpression extends LuceneCollectorExpression<Long> {
private NumericDocValues primaryTerms = null;
private int doc;
@Override
public void setNextReader(ReaderContext context) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public void setNextDocId(int doc) {
this.doc = doc;
}
@Override
public Long value() {
try {
if (primaryTerms != null && primaryTerms.advanceExact(doc)) {
return primaryTerms.longValue();
}
return null;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
|
try {
primaryTerms = context.reader().getNumericDocValues(DocSysColumns.PRIMARY_TERM.name());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
| 184
| 59
| 243
|
<methods>public void setNextDocId(int) ,public void setNextReader(io.crate.execution.engine.fetch.ReaderContext) throws java.io.IOException,public void setScorer(Scorable) ,public void startCollect(io.crate.expression.reference.doc.lucene.CollectorContext) <variables>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/reference/doc/lucene/RawCollectorExpression.java
|
RawCollectorExpression
|
value
|
class RawCollectorExpression extends LuceneCollectorExpression<String> {
private SourceLookup sourceLookup;
private ReaderContext context;
@Override
public void startCollect(CollectorContext context) {
this.sourceLookup = context.sourceLookup();
}
@Override
public void setNextDocId(int doc) {
sourceLookup.setSegmentAndDocument(context, doc);
}
@Override
public void setNextReader(ReaderContext context) throws IOException {
this.context = context;
}
@Override
public String value() {<FILL_FUNCTION_BODY>}
}
|
try {
return CompressorFactory.uncompressIfNeeded(sourceLookup.rawSource()).utf8ToString();
} catch (IOException e) {
throw new RuntimeException("Failed to uncompress source", e);
}
| 162
| 61
| 223
|
<methods>public void setNextDocId(int) ,public void setNextReader(io.crate.execution.engine.fetch.ReaderContext) throws java.io.IOException,public void setScorer(Scorable) ,public void startCollect(io.crate.expression.reference.doc.lucene.CollectorContext) <variables>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/reference/doc/lucene/VersionCollectorExpression.java
|
VersionCollectorExpression
|
value
|
class VersionCollectorExpression extends LuceneCollectorExpression<Long> {
private NumericDocValues versions = null;
private int docId;
@Override
public void setNextReader(ReaderContext context) throws IOException {
try {
versions = context.reader().getNumericDocValues(DocSysColumns.VERSION.name());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void setNextDocId(int doc) {
this.docId = doc;
}
@Override
public Long value() {<FILL_FUNCTION_BODY>}
}
|
try {
if (versions != null && versions.advanceExact(docId)) {
return versions.longValue();
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return null;
| 163
| 66
| 229
|
<methods>public void setNextDocId(int) ,public void setNextReader(io.crate.execution.engine.fetch.ReaderContext) throws java.io.IOException,public void setScorer(Scorable) ,public void startCollect(io.crate.expression.reference.doc.lucene.CollectorContext) <variables>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/reference/sys/check/cluster/LuceneVersionChecks.java
|
LuceneVersionChecks
|
isUpgradeRequired
|
class LuceneVersionChecks {
static boolean isUpgradeRequired(@Nullable String versionStr) {<FILL_FUNCTION_BODY>}
}
|
if (versionStr == null || versionStr.isEmpty()) {
return false;
}
try {
return !Version.parse(versionStr).onOrAfter(Version.LATEST);
} catch (ParseException e) {
throw new IllegalArgumentException("'" + versionStr + "' is not a valid Lucene version");
}
| 38
| 85
| 123
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/reference/sys/check/cluster/NumberOfPartitionsSysCheck.java
|
NumberOfPartitionsSysCheck
|
isValid
|
class NumberOfPartitionsSysCheck extends AbstractSysCheck {
private static final int ID = 2;
private static final String DESCRIPTION =
"The total number of partitions of one or more partitioned tables should" +
" not be greater than 1000. A large amount of shards can significantly reduce performance.";
private static final int PARTITIONS_THRESHOLD = 1000;
private final Schemas schemas;
@Inject
public NumberOfPartitionsSysCheck(Schemas schemas) {
super(ID, DESCRIPTION, Severity.MEDIUM);
this.schemas = schemas;
}
@Override
public boolean isValid() {<FILL_FUNCTION_BODY>}
boolean validateDocTablesPartitioning(SchemaInfo schemaInfo) {
for (TableInfo tableInfo : schemaInfo.getTables()) {
DocTableInfo docTableInfo = (DocTableInfo) tableInfo;
if (docTableInfo.isPartitioned() && docTableInfo.partitions().size() > PARTITIONS_THRESHOLD) {
return false;
}
}
return true;
}
}
|
for (SchemaInfo schemaInfo : schemas) {
if (schemaInfo instanceof DocSchemaInfo && !validateDocTablesPartitioning(schemaInfo)) {
return false;
}
}
return true;
| 296
| 55
| 351
|
<methods>public void <init>(int, java.lang.String, io.crate.expression.reference.sys.check.SysCheck.Severity) ,public CompletableFuture<?> computeResult() ,public java.lang.String description() ,public static java.lang.String getLinkedDescription(int, java.lang.String, java.lang.String) ,public int id() ,public abstract boolean isValid() ,public io.crate.expression.reference.sys.check.SysCheck.Severity severity() <variables>public static final java.lang.String CLUSTER_CHECK_LINK_PATTERN,private final non-sealed java.lang.String description,private final non-sealed int id,private final non-sealed io.crate.expression.reference.sys.check.SysCheck.Severity severity
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/reference/sys/check/node/MaxShardsPerNodeSysCheck.java
|
MaxShardsPerNodeSysCheck
|
isValid
|
class MaxShardsPerNodeSysCheck extends AbstractSysNodeCheck {
static final int ID = 8;
private static final String DESCRIPTION = ("The amount of shards on the node reached 90 % of the limit of the cluster setting `cluster.max_shards_per_node`. " +
"Creating new tables or partitions which would push the number of shards beyond 100 % of the limit will be rejected.");
private static final double PERCENTAGE_MAX_SHARDS_PER_NODE_THRESHOLD = 0.90d;
private final ClusterService clusterService;
@Inject
public MaxShardsPerNodeSysCheck(ClusterService clusterService) {
super(ID, DESCRIPTION, Severity.MEDIUM);
this.clusterService = clusterService;
}
@Override
public boolean isValid() {<FILL_FUNCTION_BODY>}
private static Iterable<ShardRouting> shardsForOpenIndices(ClusterState clusterState) {
var concreteIndices = Arrays.stream(clusterState.metadata().getConcreteAllOpenIndices())
.filter(index -> !IndexParts.isDangling(index))
.toArray(String[]::new);
return clusterState.routingTable().allShards(concreteIndices);
}
}
|
var maxShardLimitPerNode = clusterService.getClusterSettings().get(SETTING_CLUSTER_MAX_SHARDS_PER_NODE).doubleValue();
var cs = clusterService.state();
var localNodeId = cs.nodes().getLocalNodeId();
var numberOfShardsOnLocalNode = 0d;
for (var shardRouting : shardsForOpenIndices(cs)) {
if (localNodeId.equals(shardRouting.currentNodeId())) {
numberOfShardsOnLocalNode++;
}
}
return numberOfShardsOnLocalNode / maxShardLimitPerNode < PERCENTAGE_MAX_SHARDS_PER_NODE_THRESHOLD;
| 337
| 180
| 517
|
<methods>public boolean acknowledged() ,public void acknowledged(boolean) ,public java.lang.String nodeId() ,public java.lang.String rowId() ,public void setNodeId(java.lang.String) <variables>private static final java.lang.String LINK_PATTERN,private static final Function<List<java.lang.String>,java.lang.String> PK_FUNC,private boolean acknowledged,private java.lang.String nodeId,private java.lang.String rowId
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/reference/sys/check/node/RecoveryAfterNodesSysCheck.java
|
RecoveryAfterNodesSysCheck
|
isValid
|
class RecoveryAfterNodesSysCheck extends AbstractSysNodeCheck {
private final ClusterService clusterService;
private final Settings settings;
static final int ID = 2;
private static final String DESCRIPTION = "The cluster setting 'gateway.recover_after_data_nodes' " +
"(or the deprecated `gateway.recovery_after_nodes` setting) " +
"is not configured or it is set to a value that seems low in " +
"relation to the the maximum/expected number of (data) nodes " +
"in the cluster.";
@Inject
public RecoveryAfterNodesSysCheck(ClusterService clusterService, Settings settings) {
super(ID, DESCRIPTION, Severity.MEDIUM);
this.clusterService = clusterService;
this.settings = settings;
}
@Override
public boolean isValid() {<FILL_FUNCTION_BODY>}
private static boolean validate(int afterNodes, int expectedNodes, int actualNodes) {
return actualNodes == 1
|| (expectedNodes / 2) < afterNodes && afterNodes <= expectedNodes;
}
}
|
int actualNodes = clusterService.state().nodes().getDataNodes().size();
int afterNodes = GatewayService.RECOVER_AFTER_DATA_NODES_SETTING.get(settings);
int expectedNodes = GatewayService.EXPECTED_DATA_NODES_SETTING.get(settings);
if (afterNodes == -1 || expectedNodes == -1) {
// fallback to deprecated settings for BWC
actualNodes = clusterService.state().nodes().getSize();
afterNodes = GatewayService.RECOVER_AFTER_NODES_SETTING.get(settings);
expectedNodes = GatewayService.EXPECTED_NODES_SETTING.get(settings);
}
return validate(afterNodes, expectedNodes, actualNodes);
| 290
| 193
| 483
|
<methods>public boolean acknowledged() ,public void acknowledged(boolean) ,public java.lang.String nodeId() ,public java.lang.String rowId() ,public void setNodeId(java.lang.String) <variables>private static final java.lang.String LINK_PATTERN,private static final Function<List<java.lang.String>,java.lang.String> PK_FUNC,private boolean acknowledged,private java.lang.String nodeId,private java.lang.String rowId
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/reference/sys/check/node/RecoveryExpectedNodesSysCheck.java
|
RecoveryExpectedNodesSysCheck
|
isValid
|
class RecoveryExpectedNodesSysCheck extends AbstractSysNodeCheck {
private final ClusterService clusterService;
private final Settings settings;
static final int ID = 1;
private static final String DESCRIPTION = "It has been detected that the 'gateway.expected_data_nodes' setting " +
"(or the deprecated 'gateway.recovery_after_nodes' setting) is not " +
"configured or it does not match the actual number of (data) nodes in the cluster.";
@Inject
public RecoveryExpectedNodesSysCheck(ClusterService clusterService, Settings settings) {
super(ID, DESCRIPTION, Severity.MEDIUM);
this.clusterService = clusterService;
this.settings = settings;
}
@Override
public boolean isValid() {<FILL_FUNCTION_BODY>}
private static boolean validate(int actualNodes, int expectedNodes) {
return actualNodes == 1 || actualNodes == expectedNodes;
}
}
|
int actualNodes = clusterService.state().nodes().getDataNodes().size();
int expectedNodes = GatewayService.EXPECTED_DATA_NODES_SETTING.get(settings);
if (expectedNodes == -1) {
// fallback to deprecated setting for BWC
actualNodes = clusterService.state().nodes().getSize();
expectedNodes = GatewayService.EXPECTED_NODES_SETTING.get(settings);
}
return validate(actualNodes, expectedNodes);
| 251
| 126
| 377
|
<methods>public boolean acknowledged() ,public void acknowledged(boolean) ,public java.lang.String nodeId() ,public java.lang.String rowId() ,public void setNodeId(java.lang.String) <variables>private static final java.lang.String LINK_PATTERN,private static final Function<List<java.lang.String>,java.lang.String> PK_FUNC,private boolean acknowledged,private java.lang.String nodeId,private java.lang.String rowId
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/reference/sys/check/node/SysNodeChecksModule.java
|
SysNodeChecksModule
|
configure
|
class SysNodeChecksModule extends AbstractModule {
@Override
protected void configure() {<FILL_FUNCTION_BODY>}
}
|
bind(SysNodeChecks.class).asEagerSingleton();
MapBinder<Integer, SysNodeCheck> b = MapBinder.newMapBinder(binder(), Integer.class, SysNodeCheck.class);
// Node checks ordered by ID. New ID must be max ID + 1 and must not be reused.
b.addBinding(RecoveryExpectedNodesSysCheck.ID).to(RecoveryExpectedNodesSysCheck.class);
b.addBinding(RecoveryAfterNodesSysCheck.ID).to(RecoveryAfterNodesSysCheck.class);
b.addBinding(RecoveryAfterTimeSysCheck.ID).to(RecoveryAfterTimeSysCheck.class);
b.addBinding(HighDiskWatermarkNodesSysCheck.ID).to(HighDiskWatermarkNodesSysCheck.class);
b.addBinding(LowDiskWatermarkNodesSysCheck.ID).to(LowDiskWatermarkNodesSysCheck.class);
b.addBinding(FloodStageDiskWatermarkNodesSysCheck.ID).to(FloodStageDiskWatermarkNodesSysCheck.class);
b.addBinding(MaxShardsPerNodeSysCheck.ID).to(MaxShardsPerNodeSysCheck.class);
| 38
| 308
| 346
|
<methods>public non-sealed void <init>() ,public final synchronized void configure(org.elasticsearch.common.inject.Binder) <variables>org.elasticsearch.common.inject.Binder binder
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/reference/sys/operation/OperationContext.java
|
OperationContext
|
equals
|
class OperationContext {
public final int id;
public final UUID jobId;
public final String name;
public final long started;
private final LongSupplier bytesUsed;
public OperationContext(int id, UUID jobId, String name, long started, LongSupplier bytesUsed) {
this.id = id;
this.jobId = jobId;
this.name = name;
this.started = started;
this.bytesUsed = bytesUsed;
}
public int id() {
return id;
}
public UUID jobId() {
return jobId;
}
public String name() {
return name;
}
public long started() {
return started;
}
public long usedBytes() {
return bytesUsed.getAsLong();
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(id, jobId);
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OperationContext that = (OperationContext) o;
if (id != that.id) return false;
return jobId.equals(that.jobId);
| 267
| 74
| 341
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/reference/sys/shard/SysAllocations.java
|
SysAllocations
|
iterator
|
class SysAllocations implements Iterable<SysAllocation> {
private final ClusterService clusterService;
private final ClusterInfoService clusterInfoService;
private final AllocationDeciders allocationDeciders;
private final AllocationService allocationService;
private final SnapshotsInfoService snapshotInfoService;
@Inject
public SysAllocations(ClusterService clusterService,
ClusterInfoService clusterInfoService,
SnapshotsInfoService snapshotInfoService,
AllocationDeciders allocationDeciders,
AllocationService allocationService) {
this.clusterService = clusterService;
this.clusterInfoService = clusterInfoService;
this.snapshotInfoService = snapshotInfoService;
this.allocationDeciders = allocationDeciders;
this.allocationService = allocationService;
}
@Override
public Iterator<SysAllocation> iterator() {<FILL_FUNCTION_BODY>}
private SysAllocation createSysAllocations(RoutingAllocation allocation, ShardRouting shardRouting) {
allocation.setDebugMode(RoutingAllocation.DebugMode.EXCLUDE_YES_DECISIONS);
Supplier<ShardAllocationDecision> shardDecision = () -> {
if (shardRouting.initializing() || shardRouting.relocating()) {
return ShardAllocationDecision.NOT_TAKEN;
} else {
return allocationService.explainShardAllocation(shardRouting, allocation);
}
};
return new SysAllocation(
shardRouting.shardId(),
shardRouting.state(),
shardDecision,
shardRouting.currentNodeId(),
shardRouting.primary()
);
}
}
|
final ClusterState state = clusterService.state();
final RoutingNodes routingNodes = state.getRoutingNodes();
final ClusterInfo clusterInfo = clusterInfoService.getClusterInfo();
final RoutingAllocation allocation = new RoutingAllocation(
allocationDeciders,
routingNodes,
state,
clusterInfo,
snapshotInfoService.snapshotShardSizes(),
System.nanoTime()
);
return allocation.routingTable().allShards()
.stream()
.filter(shardRouting -> !IndexParts.isDangling(shardRouting.getIndexName()))
.map(shardRouting -> createSysAllocations(allocation, shardRouting))
.iterator();
| 439
| 186
| 625
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/reference/sys/snapshot/SysSnapshots.java
|
SysSnapshots
|
currentSnapshots
|
class SysSnapshots {
private static final Logger LOGGER = LogManager.getLogger(SysSnapshots.class);
private final Supplier<Collection<Repository>> getRepositories;
@Inject
public SysSnapshots(RepositoriesService repositoriesService) {
this(repositoriesService::getRepositoriesList);
}
@VisibleForTesting
SysSnapshots(Supplier<Collection<Repository>> getRepositories) {
this.getRepositories = getRepositories;
}
public CompletableFuture<Iterable<SysSnapshot>> currentSnapshots() {<FILL_FUNCTION_BODY>}
private static SysSnapshot toSysSnapshot(Repository repository,
SnapshotId snapshotId,
SnapshotInfo snapshotInfo,
List<String> partedTables) {
Version version = snapshotInfo.version();
return new SysSnapshot(
snapshotId.getName(),
repository.getMetadata().name(),
snapshotInfo.indices(),
partedTables,
snapshotInfo.startTime(),
snapshotInfo.endTime(),
version == null ? null : version.toString(),
snapshotInfo.state().name(),
Lists.map(snapshotInfo.shardFailures(), SnapshotShardFailure::toString)
);
}
private static CompletableFuture<SysSnapshot> createSysSnapshot(Repository repository, SnapshotId snapshotId) {
return repository.getSnapshotGlobalMetadata(snapshotId).thenCombine(
repository.getSnapshotInfo(snapshotId),
(metadata, snapshotInfo) -> {
List<String> partedTables = new ArrayList<>();
for (var template : metadata.templates().values()) {
partedTables.add(RelationName.fqnFromIndexName(template.value.name()));
}
return SysSnapshots.toSysSnapshot(repository, snapshotId, snapshotInfo, partedTables);
}).exceptionally(t -> {
var err = SQLExceptions.unwrap(t);
if (err instanceof SnapshotException) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Couldn't retrieve snapshotId={} error={}", snapshotId, err);
}
return new SysSnapshot(
snapshotId.getName(),
repository.getMetadata().name(),
Collections.emptyList(),
Collections.emptyList(),
null,
null,
null,
SnapshotState.FAILED.name(),
List.of()
);
}
throw Exceptions.toRuntimeException(err);
});
}
}
|
ArrayList<CompletableFuture<List<SysSnapshot>>> sysSnapshots = new ArrayList<>();
for (Repository repository : getRepositories.get()) {
var futureSnapshots = repository.getRepositoryData()
.thenCompose(repositoryData -> {
Collection<SnapshotId> snapshotIds = repositoryData.getSnapshotIds();
ArrayList<CompletableFuture<SysSnapshot>> snapshots = new ArrayList<>(snapshotIds.size());
for (SnapshotId snapshotId : snapshotIds) {
snapshots.add(createSysSnapshot(repository, snapshotId));
}
return CompletableFutures.allSuccessfulAsList(snapshots);
});
sysSnapshots.add(futureSnapshots);
}
return CompletableFutures.allSuccessfulAsList(sysSnapshots).thenApply(data -> {
ArrayList<SysSnapshot> result = new ArrayList<>();
for (Collection<SysSnapshot> datum : data) {
result.addAll(datum);
}
return result;
});
| 657
| 252
| 909
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/AgeFunction.java
|
AgeFunction
|
getPeriod
|
class AgeFunction extends Scalar<Period, Object> {
private static final FunctionName NAME = new FunctionName(PgCatalogSchemaInfo.NAME, "age");
public static void register(Functions.Builder builder) {
builder.add(
scalar(
NAME,
DataTypes.TIMESTAMP.getTypeSignature(),
DataTypes.INTERVAL.getTypeSignature()
).withFeatures(EnumSet.of(Feature.NULLABLE)),
AgeFunction::new
);
builder.add(
scalar(
NAME,
DataTypes.TIMESTAMP.getTypeSignature(),
DataTypes.TIMESTAMP.getTypeSignature(),
DataTypes.INTERVAL.getTypeSignature()
).withFeatures(EnumSet.of(Feature.NULLABLE)),
AgeFunction::new
);
}
public AgeFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
public Period evaluate(TransactionContext txnCtx, NodeContext nodeContext, Input<Object>... args) {
/*
We cannot create Period from millis difference
since sometimes we need to treat different millis range as same interval.
Postgres treats age between first days of the sequential months as
'1 month' despite on possibly different 28, 30, 31 days/millis range.
*/
assert args.length > 0 && args.length < 3 : "Invalid number of arguments";
var arg1 = args[0].value();
if (arg1 == null) {
return null;
}
if (args.length == 1) {
long curDateMillis = txnCtx.currentInstant().toEpochMilli();
curDateMillis = curDateMillis - curDateMillis % 86400000; // current_date at midnight, similar to CurrentDateFunction implementation.
return getPeriod(curDateMillis, (long) arg1);
} else {
var arg2 = args[1].value();
if (arg2 == null) {
return null;
}
return getPeriod((long) arg1, (long) arg2);
}
}
/**
* returns Period in yearMonthDayTime which corresponds to Postgres default Interval output format.
* See https://www.postgresql.org/docs/14/datatype-datetime.html#DATATYPE-INTERVAL-OUTPUT
*/
public static Period getPeriod(long timestamp1, long timestamp2) {<FILL_FUNCTION_BODY>}
}
|
/*
PeriodType is important as it affects the internal representation of the Period object.
PeriodType.yearMonthDayTime() is needed to return 8 days but not 1 week 1 day.
Streamer of the IntervalType will simply put 0 in 'out.writeVInt(p.getWeeks())' as getWeeks() returns zero for unused fields.
*/
if (timestamp1 < timestamp2) {
/*
In Postgres second argument is subtracted from the first.
Interval's first argument must be smaller than second and thus we swap params and negate.
We need to pass UTC timezone to be sure that Interval doesn't end up using system default time zone.
Currently, timestamps are in UTC (see https://github.com/crate/crate/issues/10037 and
https://github.com/crate/crate/issues/12064) but if https://github.com/crate/crate/issues/7196 ever gets
implemented, we need to pass here not UTC but time zone set by SET TIMEZONE.
*/
return new Interval(timestamp1, timestamp2, DateTimeZone.UTC).toPeriod(PeriodType.yearMonthDayTime()).negated();
} else {
return new Interval(timestamp2, timestamp1, DateTimeZone.UTC).toPeriod(PeriodType.yearMonthDayTime());
}
| 632
| 342
| 974
|
<methods>public BoundSignature boundSignature() ,public Scalar<Period,java.lang.Object> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract Period evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Object>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/ArrayAppendFunction.java
|
ArrayAppendFunction
|
evaluate
|
class ArrayAppendFunction extends Scalar<List<Object>, Object> {
public static final String NAME = "array_append";
public static void register(Functions.Builder builder) {
builder.add(
Signature.scalar(
NAME,
TypeSignature.parse("array(E)"),
TypeSignature.parse("E"),
TypeSignature.parse("array(E)")
).withTypeVariableConstraints(typeVariable("E"))
.withFeature(Feature.NON_NULLABLE),
ArrayAppendFunction::new
);
}
private final DataType<?> innerType;
ArrayAppendFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
this.innerType = ((ArrayType<?>) boundSignature.returnType()).innerType();
}
@Override
public final List<Object> evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input[] args) {<FILL_FUNCTION_BODY>}
}
|
ArrayList<Object> resultList = new ArrayList<>();
@SuppressWarnings("unchecked")
List<Object> values = (List<Object>) args[0].value();
Object valueToAdd = args[1].value();
if (values != null) {
for (Object value : values) {
resultList.add(innerType.sanitizeValue(value));
}
}
resultList.add(innerType.sanitizeValue(valueToAdd));
return resultList;
| 250
| 131
| 381
|
<methods>public BoundSignature boundSignature() ,public Scalar<List<java.lang.Object>,java.lang.Object> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract List<java.lang.Object> evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Object>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/ConcatFunction.java
|
GenericConcatFunction
|
evaluate
|
class GenericConcatFunction extends ConcatFunction {
public GenericConcatFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
public String evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<String>[] args) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sb = new StringBuilder();
for (int i = 0; i < args.length; i++) {
String value = args[i].value();
if (value != null) {
sb.append(value);
}
}
return sb.toString();
| 91
| 74
| 165
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.String,java.lang.String> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.String evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.String>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/DateBinFunction.java
|
DateBinFunction
|
evaluate
|
class DateBinFunction extends Scalar<Long, Object> {
public static final String NAME = "date_bin";
public static void register(Functions.Builder module) {
module.add(
Signature.scalar(
NAME,
DataTypes.INTERVAL.getTypeSignature(),
DataTypes.TIMESTAMPZ.getTypeSignature(), // source
DataTypes.TIMESTAMPZ.getTypeSignature(), // origin
DataTypes.TIMESTAMPZ.getTypeSignature()
).withFeatures(EnumSet.of(Feature.DETERMINISTIC, Feature.COMPARISON_REPLACEMENT, Feature.NULLABLE)),
DateBinFunction::new);
module.add(
Signature.scalar(
NAME,
DataTypes.INTERVAL.getTypeSignature(),
DataTypes.TIMESTAMP.getTypeSignature(), // source
DataTypes.TIMESTAMP.getTypeSignature(), // origin
DataTypes.TIMESTAMP.getTypeSignature()
).withFeatures(EnumSet.of(Feature.DETERMINISTIC, Feature.COMPARISON_REPLACEMENT, Feature.NULLABLE)),
DateBinFunction::new);
}
private DateBinFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
public Scalar<Long, Object> compile(List<Symbol> arguments, String currentUser, Roles roles) {
assert arguments.size() == 3 : "Invalid number of arguments";
if (arguments.get(0) instanceof Input<?> input) {
var value = input.value();
if (value != null) {
Period p = (Period) value;
checkMonthsAndYears(p);
long intervalInMs = p.toStandardDuration().getMillis();
if (intervalInMs == 0) {
throw new IllegalArgumentException("Interval cannot be zero");
}
return new CompiledDateBin(signature, boundSignature, intervalInMs);
}
}
return this;
}
@Override
@SafeVarargs
public final Long evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Object> ... args) {<FILL_FUNCTION_BODY>}
/**
* Similar to the check called in {@link Period#toStandardDuration()} anyway,
* but do it beforehand to provide a better error message.
*/
private static void checkMonthsAndYears(Period p) {
if (p.getMonths() != 0 || p.getYears() != 0) {
throw new IllegalArgumentException("Cannot use intervals containing months or years");
}
}
private static long getBinnedTimestamp(long interval, long timestamp, long origin) {
if (interval == 0) {
throw new IllegalArgumentException("Interval cannot be zero");
}
/*
in Java % operator returns negative result only if dividend is negative.
https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.17.3
We need to shift timestamp by the timeline to the "earlier" direction, to the left.
If diff is negative, remainder will be also negative (see link above), we subtract negative
to move to right side of the bin and then subtract abs(interval) to move to beginning of the bin.
*/
long diff = timestamp - origin;
if (diff >= 0) {
// diff % interval >= 0 regardless of the interval sign.
return timestamp - diff % interval;
} else {
// diff % interval < 0 regardless of the interval sign.
if (interval > 0) {
return timestamp - diff % interval - interval;
} else {
return timestamp - diff % interval + interval;
}
}
}
private static class CompiledDateBin extends Scalar<Long, Object> {
private final long intervalInMs;
private CompiledDateBin(Signature signature, BoundSignature boundSignature, long intervalInMs) {
super(signature, boundSignature);
this.intervalInMs = intervalInMs;
}
@Override
@SafeVarargs
public final Long evaluate(TransactionContext txnCtx, NodeContext nodeContext, Input<Object>... args) {
// Validation for arguments amount is done in compile.
var timestamp = args[1].value();
var origin = args[2].value();
if (timestamp == null || origin == null) {
return null;
}
return getBinnedTimestamp(intervalInMs, (long) timestamp, (long) origin);
}
}
}
|
assert args.length == 3 : "Invalid number of arguments";
var interval = args[0].value();
var timestamp = args[1].value();
var origin = args[2].value();
if (interval == null || timestamp == null || origin == null) {
return null;
}
Period p = (Period) interval;
checkMonthsAndYears(p);
return getBinnedTimestamp(p.toStandardDuration().getMillis(), (long) timestamp, (long) origin);
| 1,153
| 128
| 1,281
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.Long,java.lang.Object> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.Long evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Object>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/DateFormatFunction.java
|
DateFormatFunction
|
evaluate
|
class DateFormatFunction extends Scalar<String, Object> {
public static final String NAME = "date_format";
public static final String DEFAULT_FORMAT = "%Y-%m-%dT%H:%i:%s.%fZ";
public static void register(Functions.Builder module) {
List<DataType<?>> supportedTimestampTypes = List.of(
DataTypes.TIMESTAMPZ, DataTypes.TIMESTAMP, DataTypes.LONG);
for (DataType<?> dataType : supportedTimestampTypes) {
// without format
module.add(
Signature.scalar(
NAME,
dataType.getTypeSignature(),
DataTypes.STRING.getTypeSignature()
), DateFormatFunction::new
);
// with format
module.add(
Signature.scalar(
NAME,
DataTypes.STRING.getTypeSignature(),
dataType.getTypeSignature(),
DataTypes.STRING.getTypeSignature()
), DateFormatFunction::new
);
// time zone aware variant
module.add(
Signature.scalar(
NAME,
DataTypes.STRING.getTypeSignature(),
DataTypes.STRING.getTypeSignature(),
dataType.getTypeSignature(),
DataTypes.STRING.getTypeSignature()
), DateFormatFunction::new
);
}
}
public DateFormatFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
public String evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Object>... args) {<FILL_FUNCTION_BODY>}
}
|
String format;
Input<?> timezoneLiteral = null;
if (args.length == 1) {
format = DEFAULT_FORMAT;
} else {
format = (String) args[0].value();
if (format == null) {
return null;
}
if (args.length == 3) {
timezoneLiteral = args[1];
}
}
Object tsValue = args[args.length - 1].value();
if (tsValue == null) {
return null;
}
Long timestamp = DataTypes.TIMESTAMPZ.sanitizeValue(tsValue);
DateTimeZone timezone = DateTimeZone.UTC;
if (timezoneLiteral != null) {
Object timezoneValue = timezoneLiteral.value();
if (timezoneValue == null) {
return null;
}
timezone = TimeZoneParser.parseTimeZone((String) timezoneValue);
}
DateTime dateTime = new DateTime(timestamp, timezone);
return TimestampFormatter.format(format, dateTime);
| 413
| 266
| 679
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.String,java.lang.Object> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.String evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Object>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/HasDatabasePrivilegeFunction.java
|
HasDatabasePrivilegeFunction
|
parsePermissions
|
class HasDatabasePrivilegeFunction extends HasPrivilegeFunction {
public static final FunctionName NAME = new FunctionName(PgCatalogSchemaInfo.NAME, "has_database_privilege");
private static final FourFunction<Roles, Role, Object, Collection<Permission>, Boolean> CHECK_BY_DB_NAME =
(roles, user, db, permissions) -> {
if (Constants.DB_NAME.equals(db) == false) {
throw new IllegalArgumentException(String.format(Locale.ENGLISH,
"database \"%s\" does not exist",
db));
}
return checkPrivileges(user, permissions);
};
private static final FourFunction<Roles, Role, Object, Collection<Permission>, Boolean> CHECK_BY_DB_OID =
(roles, user, db, privileges) -> {
if (Constants.DB_OID != (Integer) db) {
throw new IllegalArgumentException(String.format(Locale.ENGLISH,
"database with OID \"%s\" does not exist",
db));
}
return checkPrivileges(user, privileges);
};
private static boolean checkPrivileges(Role user, Collection<Permission> permissions) {
if (permissions.contains(Permission.DQL)) { // CONNECT
return true;
}
boolean result = true;
if (permissions.contains(Permission.DML)) { // TEMP privilege
result = false;
}
if (permissions.contains(Permission.DDL)) { // CREATE privilege
result = hasCreatePrivilege(user);
}
return result;
}
private static boolean hasCreatePrivilege(Role user) {
if (user.isSuperUser()) {
return true;
}
for (Privilege p : user.privileges()) {
if (p.subject().permission() == Permission.DDL &&
(p.subject().securable() == Securable.SCHEMA || p.subject().securable() == Securable.CLUSTER)) {
return true;
}
}
return false;
}
/**
* @param permissionNames is a comma separated list.
* Valid permissionNames are 'CONNECT', 'CREATE' and 'TEMP' or `TEMPORARY` which map to DQL, DDL and DML respectively.
* Extra whitespaces between privilege names and repetition of the valid argument are allowed.
*
* @see HasPrivilegeFunction#parsePermissions(String)
*/
@Nullable
protected Collection<Permission> parsePermissions(String permissionNames) {<FILL_FUNCTION_BODY>}
public static void register(Functions.Builder module) {
// Signature without user, takes user from session.
module.add(
Signature.scalar(
NAME,
DataTypes.STRING.getTypeSignature(), // Database
DataTypes.STRING.getTypeSignature(), // Privilege
DataTypes.BOOLEAN.getTypeSignature()
).withFeatures(DETERMINISTIC_ONLY),
(signature, boundSignature) -> new HasDatabasePrivilegeFunction(signature, boundSignature, USER_BY_NAME, CHECK_BY_DB_NAME)
);
// Signature without user, takes user from session.
module.add(
Signature.scalar(
NAME,
DataTypes.INTEGER.getTypeSignature(), // Database
DataTypes.STRING.getTypeSignature(), // Privilege
DataTypes.BOOLEAN.getTypeSignature()
).withFeatures(DETERMINISTIC_ONLY),
(signature, boundSignature) -> new HasDatabasePrivilegeFunction(signature, boundSignature,
USER_BY_NAME, CHECK_BY_DB_OID)
);
module.add(
Signature.scalar(
NAME,
DataTypes.STRING.getTypeSignature(), // User
DataTypes.STRING.getTypeSignature(), // Database
DataTypes.STRING.getTypeSignature(), // Privilege
DataTypes.BOOLEAN.getTypeSignature()
).withFeatures(DETERMINISTIC_ONLY),
(signature, boundSignature) -> new HasDatabasePrivilegeFunction(signature, boundSignature,
USER_BY_NAME, CHECK_BY_DB_NAME)
);
module.add(
Signature.scalar(
NAME,
DataTypes.STRING.getTypeSignature(), // User
DataTypes.INTEGER.getTypeSignature(), // Database
DataTypes.STRING.getTypeSignature(), // Privilege
DataTypes.BOOLEAN.getTypeSignature()
).withFeatures(DETERMINISTIC_ONLY),
(signature, boundSignature) -> new HasDatabasePrivilegeFunction(signature, boundSignature,
USER_BY_NAME, CHECK_BY_DB_OID)
);
module.add(
Signature.scalar(
NAME,
DataTypes.INTEGER.getTypeSignature(), // User
DataTypes.STRING.getTypeSignature(), // Database
DataTypes.STRING.getTypeSignature(), // Privilege
DataTypes.BOOLEAN.getTypeSignature()
).withFeatures(DETERMINISTIC_ONLY),
(signature, boundSignature) -> new HasDatabasePrivilegeFunction(signature, boundSignature,
USER_BY_OID, CHECK_BY_DB_NAME)
);
module.add(
Signature.scalar(
NAME,
DataTypes.INTEGER.getTypeSignature(), // User
DataTypes.INTEGER.getTypeSignature(), // Database
DataTypes.STRING.getTypeSignature(), // Privilege
DataTypes.BOOLEAN.getTypeSignature()
).withFeatures(DETERMINISTIC_ONLY),
(signature, boundSignature) -> new HasDatabasePrivilegeFunction(signature, boundSignature,
USER_BY_OID, CHECK_BY_DB_OID)
);
}
protected HasDatabasePrivilegeFunction(Signature signature,
BoundSignature boundSignature,
BiFunction<Roles, Object, Role> getUser,
FourFunction<Roles, Role, Object, Collection<Permission>, Boolean> checkPrivilege) {
super(signature, boundSignature, getUser, checkPrivilege);
}
}
|
Collection<Permission> toCheck = new HashSet<>();
String[] permissions = permissionNames.toLowerCase(Locale.ENGLISH).split(",");
for (String p : permissions) {
p = p.trim();
switch (p) {
case "connect" -> toCheck.add(Permission.DQL);
case "create" -> toCheck.add(Permission.DDL);
case "temp" -> toCheck.add(Permission.DML);
case "temporary" -> toCheck.add(Permission.DML);
default ->
// Same error as PG
throw new IllegalArgumentException(String.format(Locale.ENGLISH,
"Unrecognized permission: %s",
p));
}
}
return toCheck;
| 1,617
| 199
| 1,816
|
<methods>public Scalar<java.lang.Boolean,java.lang.Object> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public final java.lang.Boolean evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Object>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) <variables>protected static final BiFunction<io.crate.role.Roles,java.lang.Object,io.crate.role.Role> USER_BY_NAME,protected static final BiFunction<io.crate.role.Roles,java.lang.Object,io.crate.role.Role> USER_BY_OID,private final non-sealed FourFunction<io.crate.role.Roles,io.crate.role.Role,java.lang.Object,Collection<io.crate.role.Permission>,java.lang.Boolean> checkPrivilege,private final non-sealed BiFunction<io.crate.role.Roles,java.lang.Object,io.crate.role.Role> getUser
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/KnnMatch.java
|
KnnMatch
|
evaluate
|
class KnnMatch extends Scalar<Boolean, Object> {
public static void register(Functions.Builder module) {
module.add(
Signature.scalar(
"knn_match",
TypeSignature.parse(FloatVectorType.NAME),
TypeSignature.parse(FloatVectorType.NAME),
DataTypes.INTEGER.getTypeSignature(),
DataTypes.BOOLEAN.getTypeSignature()
),
KnnMatch::new
);
}
public KnnMatch(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
@SafeVarargs
public final Boolean evaluate(TransactionContext txnCtx,
NodeContext nodeContext,
Input<Object>... args) {<FILL_FUNCTION_BODY>}
@Override
@Nullable
public Query toQuery(Function function, Context context) {
List<Symbol> args = function.arguments();
if (args.get(0) instanceof Reference ref
&& args.get(1) instanceof Literal<?> targetLiteral
&& args.get(2) instanceof Literal<?> kLiteral) {
Object target = targetLiteral.value();
Object k = kLiteral.value();
if (target instanceof float[] && k instanceof Integer) {
return new KnnFloatVectorQuery(ref.storageIdent(), (float[]) target, (int) k);
}
return null;
}
return null;
}
}
|
throw new UnsupportedOperationException("knn_match can only be used in WHERE clause for tables as it needs an index to operate on");
| 371
| 34
| 405
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.Boolean,java.lang.Object> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.Boolean evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Object>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/SubscriptFunctions.java
|
SubscriptFunctions
|
tryCreateSubscript
|
class SubscriptFunctions {
public static Function makeObjectSubscript(Symbol base, List<String> path) {
assert base.valueType().id() == ObjectType.ID
: "makeObjectSubscript only works on base symbols of type `object`, got `" + base.valueType().getName() + '`';
List<Symbol> arguments = Lists.mapTail(base, path, Literal::of);
DataType<?> returnType = ((ObjectType) base.valueType()).resolveInnerType(path);
return new Function(
SubscriptObjectFunction.SIGNATURE,
arguments,
returnType
);
}
public static Function makeObjectSubscript(Symbol base, ColumnIdent column) {
return makeObjectSubscript(base, column.path());
}
@Nullable
public static Function tryCreateSubscript(Symbol baseSymbol, List<String> path) {<FILL_FUNCTION_BODY>}
}
|
assert !path.isEmpty() : "Path must not be empty to create subscript function";
var baseType = baseSymbol.valueType();
switch (baseType.id()) {
case ObjectType.ID: {
List<Symbol> arguments = Lists.mapTail(baseSymbol, path, Literal::of);
DataType<?> returnType = ((ObjectType) baseType).resolveInnerType(path);
return new Function(
SubscriptObjectFunction.SIGNATURE,
arguments,
returnType
);
}
case RowType.ID: {
String child = path.get(0);
RowType rowType = (RowType) baseType;
int idx = rowType.fieldNames().indexOf(child);
if (idx < 0) {
return null;
}
Function recordSubscript = new Function(
SubscriptRecordFunction.SIGNATURE,
List.of(baseSymbol, Literal.of(child)),
rowType.getFieldType(idx)
);
if (path.size() > 1) {
return tryCreateSubscript(recordSubscript, path.subList(1, path.size()));
}
return recordSubscript;
}
default:
return null;
}
| 233
| 314
| 547
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/SubscriptObjectFunction.java
|
SubscriptObjectFunction
|
evaluate
|
class SubscriptObjectFunction extends Scalar<Object, Map<String, Object>> {
public static final String NAME = "subscript_obj";
public static final Signature SIGNATURE = Signature
.scalar(
NAME,
DataTypes.UNTYPED_OBJECT.getTypeSignature(),
DataTypes.STRING.getTypeSignature(),
DataTypes.UNDEFINED.getTypeSignature())
.withVariableArity();
public static void register(Functions.Builder module) {
module.add(
SIGNATURE,
SubscriptObjectFunction::new
);
}
private SubscriptObjectFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
public Symbol normalizeSymbol(Function func, TransactionContext txnCtx, NodeContext nodeCtx) {
Symbol result = evaluateIfLiterals(this, txnCtx, nodeCtx, func);
if (result instanceof Literal) {
return result;
}
return tryToInferReturnTypeFromObjectTypeAndArguments(func);
}
static Symbol tryToInferReturnTypeFromObjectTypeAndArguments(Function func) {
if (!func.valueType().equals(DataTypes.UNDEFINED)) {
return func;
}
var arguments = func.arguments();
ObjectType objectType = (ObjectType) arguments.get(0).valueType();
List<String> path = maybeCreatePath(arguments);
if (path == null) {
return func;
} else {
DataType<?> returnType = objectType.resolveInnerType(path);
return returnType.equals(DataTypes.UNDEFINED)
? func
: new Function(
func.signature(),
func.arguments(),
returnType
);
}
}
@Nullable
private static List<String> maybeCreatePath(List<Symbol> arguments) {
List<String> path = null;
for (int i = 1; i < arguments.size(); i++) {
Symbol arg = arguments.get(i);
if (arg instanceof Literal) {
if (path == null) {
path = new ArrayList<>();
}
path.add(DataTypes.STRING.sanitizeValue(((Literal<?>) arg).value()));
} else {
return null;
}
}
return path;
}
@Override
@SafeVarargs
public final Object evaluate(TransactionContext txnCtx, NodeContext ndeCtx, Input<Map<String, Object>>... args) {<FILL_FUNCTION_BODY>}
}
|
assert args.length >= 2 : NAME + " takes 2 or more arguments, got " + args.length;
Object mapValue = args[0].value();
for (var i = 1; i < args.length; i++) {
if (mapValue == null) {
return null;
}
mapValue = SubscriptFunction.lookupByName(
boundSignature.argTypes(),
mapValue,
args[i].value(),
txnCtx.sessionSettings().errorOnUnknownObjectKey()
);
}
return mapValue;
| 656
| 141
| 797
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.Object,Map<java.lang.String,java.lang.Object>> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.Object evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<Map<java.lang.String,java.lang.Object>>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/SubstrFunction.java
|
SubstrFunction
|
register
|
class SubstrFunction extends Scalar<String, Object> {
public static final String NAME = "substr";
public static final String ALIAS = "substring";
public static void register(Functions.Builder builder) {<FILL_FUNCTION_BODY>}
private SubstrFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
public String evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input[] args) {
assert args.length == 2 || args.length == 3 : "number of arguments must be 2 or 3";
String val = (String) args[0].value();
if (val == null) {
return null;
}
Number beginIdx = (Number) args[1].value();
if (beginIdx == null) {
return null;
}
if (args.length == 3) {
Number len = (Number) args[2].value();
if (len == null) {
return null;
}
return evaluate(val, (beginIdx).intValue(), len.intValue());
}
return evaluate(val, (beginIdx).intValue());
}
private static String evaluate(@NotNull String inputStr, int beginIdx) {
final int startPos = Math.max(0, beginIdx - 1);
if (startPos > inputStr.length() - 1) {
return "";
}
int endPos = inputStr.length();
return substring(inputStr, startPos, endPos);
}
@VisibleForTesting
static String evaluate(@NotNull String inputStr, int beginIdx, int len) {
final int startPos = Math.max(0, beginIdx - 1);
if (startPos > inputStr.length() - 1) {
return "";
}
int endPos = inputStr.length();
if (startPos + len < endPos) {
endPos = startPos + len;
}
return substring(inputStr, startPos, endPos);
}
@VisibleForTesting
static String substring(String value, int begin, int end) {
return value.substring(begin, end);
}
private static class SubstrExtractFunction extends Scalar<String, String> {
SubstrExtractFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
@SafeVarargs
public final String evaluate(TransactionContext txnCtx, NodeContext nodeContext, Input<String>... args) {
String string = args[0].value();
if (string == null) {
return null;
}
String pattern = args[1].value();
if (pattern == null) {
return null;
}
Pattern re = Pattern.compile(pattern);
Matcher matcher = re.matcher(string);
int groupCount = matcher.groupCount();
if (matcher.find()) {
String group = matcher.group(groupCount > 0 ? 1 : 0);
return group;
} else {
return null;
}
}
@Override
public Scalar<String, String> compile(List<Symbol> arguments, String currentUser, Roles roles) {
Symbol patternSymbol = arguments.get(1);
if (patternSymbol instanceof Input<?> input) {
String pattern = (String) input.value();
if (pattern == null) {
return this;
}
return new CompiledSubstr(signature, boundSignature, pattern);
}
return this;
}
}
private static class CompiledSubstr extends Scalar<String, String> {
private final Matcher matcher;
public CompiledSubstr(Signature signature, BoundSignature boundSignature, String pattern) {
super(signature, boundSignature);
this.matcher = Pattern.compile(pattern).matcher("");
}
@Override
@SafeVarargs
public final String evaluate(TransactionContext txnCtx, NodeContext nodeContext, Input<String>... args) {
String string = args[0].value();
if (string == null) {
return null;
}
matcher.reset(string);
int groupCount = matcher.groupCount();
if (matcher.find()) {
String group = matcher.group(groupCount > 0 ? 1 : 0);
return group;
} else {
return null;
}
}
}
}
|
TypeSignature stringType = DataTypes.STRING.getTypeSignature();
TypeSignature intType = DataTypes.INTEGER.getTypeSignature();
for (var name : List.of(NAME, ALIAS)) {
builder.add(
Signature.scalar(name, stringType, intType, stringType),
SubstrFunction::new
);
builder.add(
Signature.scalar(name, stringType, intType, intType, stringType),
SubstrFunction::new
);
builder.add(
Signature.scalar(name, stringType, stringType, stringType),
SubstrExtractFunction::new
);
}
| 1,143
| 168
| 1,311
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.String,java.lang.Object> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.String evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Object>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/TimeZoneParser.java
|
TimeZoneParser
|
parseTimeZone
|
class TimeZoneParser {
public static final DateTimeZone DEFAULT_TZ = DateTimeZone.UTC;
public static final Literal<String> DEFAULT_TZ_LITERAL = Literal.of("UTC");
private static final ConcurrentMap<String, DateTimeZone> TIME_ZONE_MAP = new ConcurrentHashMap<>();
private TimeZoneParser() {
}
public static DateTimeZone parseTimeZone(String timezone) throws IllegalArgumentException {<FILL_FUNCTION_BODY>}
}
|
if (timezone == null) {
throw new IllegalArgumentException("invalid time zone value NULL");
}
if (timezone.equals(DEFAULT_TZ_LITERAL.value())) {
return DEFAULT_TZ;
}
DateTimeZone tz = TIME_ZONE_MAP.get(timezone);
if (tz == null) {
try {
int index = timezone.indexOf(':');
if (index != -1) {
int beginIndex = timezone.charAt(0) == '+' ? 1 : 0;
// format like -02:30
tz = DateTimeZone.forOffsetHoursMinutes(
Integer.parseInt(timezone.substring(beginIndex, index)),
Integer.parseInt(timezone.substring(index + 1))
);
} else {
// id, listed here: http://joda-time.sourceforge.net/timezones.html
// or here: http://www.joda.org/joda-time/timezones.html
tz = DateTimeZone.forID(timezone);
}
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(String.format(Locale.ENGLISH,
"invalid time zone value '%s'", timezone));
}
TIME_ZONE_MAP.putIfAbsent(timezone, tz);
}
return tz;
| 127
| 356
| 483
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/UnaryScalar.java
|
UnaryScalar
|
evaluate
|
class UnaryScalar<R, T> extends Scalar<R, T> {
private final Function<T, R> func;
private final DataType<T> type;
public UnaryScalar(Signature signature,
BoundSignature boundSignature,
DataType<T> type,
Function<T, R> func) {
super(signature, boundSignature);
assert signature.hasFeature(Feature.NULLABLE) : "A UnaryScalar is NULLABLE by definition";
assert boundSignature.argTypes().get(0).id() == type.id() :
"The bound argument type of the signature must match the type argument";
this.type = type;
this.func = func;
}
@SafeVarargs
@Override
public final R evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<T>... args) {<FILL_FUNCTION_BODY>}
}
|
assert args.length == 1 : "UnaryScalar expects exactly 1 argument, got: " + args.length;
T value = type.sanitizeValue(args[0].value());
if (value == null) {
return null;
}
return func.apply(value);
| 228
| 76
| 304
|
<methods>public BoundSignature boundSignature() ,public Scalar<R,T> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract R evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<T>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/VectorSimilarityFunction.java
|
VectorSimilarityFunction
|
evaluate
|
class VectorSimilarityFunction extends Scalar<Float, float[]> {
public static void register(Functions.Builder module) {
module.add(
Signature.scalar(
"vector_similarity",
FloatVectorType.INSTANCE_ONE.getTypeSignature(),
FloatVectorType.INSTANCE_ONE.getTypeSignature(),
DataTypes.FLOAT.getTypeSignature()
).withFeature(Scalar.Feature.NULLABLE),
VectorSimilarityFunction::new
);
}
private VectorSimilarityFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
public Float evaluate(TransactionContext txnCtx, NodeContext nodeContext, Input<float[]>... args) {<FILL_FUNCTION_BODY>}
}
|
assert args.length == 2 : "Invalid number of arguments";
var v1 = args[0].value();
var v2 = args[1].value();
if (v1 == null || v2 == null) {
return null;
}
if (v1.length != v2.length) {
throw new IllegalArgumentException("Vectors must have same length");
}
return FloatVectorType.SIMILARITY_FUNC.compare(v1, v2);
| 204
| 128
| 332
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.Float,float[]> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.Float evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<float[]>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/arithmetic/ExpFunction.java
|
ExpFunction
|
register
|
class ExpFunction {
public static final String NAME = "exp";
public static void register(Functions.Builder module) {<FILL_FUNCTION_BODY>}
}
|
var type = DataTypes.DOUBLE;
var signature = type.getTypeSignature();
module.add(
scalar(NAME, signature, signature)
.withFeature(Scalar.Feature.NULLABLE),
(declaredSignature, boundSignature) ->
new UnaryScalar<>(
declaredSignature,
boundSignature,
type,
x -> type.sanitizeValue(Math.exp(((Number) x).doubleValue()))
)
);
| 46
| 122
| 168
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/arithmetic/LogFunction.java
|
LogFunction
|
validateResult
|
class LogFunction extends Scalar<Number, Number> {
public static final String NAME = "log";
public static void register(Functions.Builder module) {
LogBaseFunction.registerLogBaseFunctions(module);
Log10Function.registerLog10Functions(module);
LnFunction.registerLnFunctions(module);
}
LogFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
/**
* @param result the value to validate
* @param caller used in the error message for clarification purposes.
* @return the validated result
*/
Double validateResult(Double result, String caller) {<FILL_FUNCTION_BODY>}
static class LogBaseFunction extends LogFunction {
static void registerLogBaseFunctions(Functions.Builder builder) {
// log(valueType, baseType) : double
builder.add(
scalar(
NAME,
DataTypes.DOUBLE.getTypeSignature(),
DataTypes.DOUBLE.getTypeSignature(),
TypeSignature.parse("double precision"))
.withFeature(Feature.NULLABLE),
LogBaseFunction::new
);
}
LogBaseFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
public Number evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Number>... args) {
assert args.length == 2 : "number of args must be 2";
Number value1 = args[0].value();
Number value2 = args[1].value();
if (value1 == null || value2 == null) {
return null;
}
double value = value1.doubleValue();
double base = value2.doubleValue();
double baseResult = Math.log(base);
if (baseResult == 0) {
throw new IllegalArgumentException("log(x, b): given 'base' would result in a division by zero.");
}
return validateResult(Math.log(value) / baseResult, "log(x, b)");
}
}
static class Log10Function extends LogFunction {
static void registerLog10Functions(Functions.Builder builder) {
// log(double) : double
builder.add(
scalar(
NAME,
DataTypes.DOUBLE.getTypeSignature(),
DataTypes.DOUBLE.getTypeSignature())
.withFeature(Feature.NULLABLE),
Log10Function::new
);
}
Log10Function(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
public Number evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Number>... args) {
assert args.length == 1 : "number of args must be 1";
Number value = args[0].value();
if (value == null) {
return null;
}
return evaluate(value.doubleValue());
}
protected Double evaluate(double value) {
return validateResult(Math.log10(value), "log(x)");
}
}
public static class LnFunction extends Log10Function {
static void registerLnFunctions(Functions.Builder builder) {
// ln(double) : double
builder.add(
scalar(
LnFunction.NAME,
DataTypes.DOUBLE.getTypeSignature(),
DataTypes.DOUBLE.getTypeSignature())
.withFeature(Feature.NULLABLE),
LnFunction::new
);
}
public static final String NAME = "ln";
LnFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
protected Double evaluate(double value) {
return validateResult(Math.log(value), "ln(x)");
}
}
}
|
if (result == null) {
return null;
}
if (Double.isNaN(result) || Double.isInfinite(result)) {
throw new IllegalArgumentException(caller + ": given arguments would result in: '" + result + "'");
}
return result;
| 989
| 74
| 1,063
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.Number,java.lang.Number> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.Number evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Number>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/arithmetic/RandomFunction.java
|
RandomFunction
|
normalizeSymbol
|
class RandomFunction extends Scalar<Double, Void> {
public static final String NAME = "random";
public static void register(Functions.Builder module) {
module.add(
scalar(
NAME,
DataTypes.DOUBLE.getTypeSignature()
).withFeatures(EnumSet.of(Feature.NON_NULLABLE)),
RandomFunction::new
);
}
private final Random random = new Random();
public RandomFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
public Symbol normalizeSymbol(Function symbol, TransactionContext txnCtx, NodeContext nodeCtx) {<FILL_FUNCTION_BODY>}
@Override
@SafeVarargs
public final Double evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Void> ... args) {
assert args.length == 0 : "number of args must be 0";
return this.random.nextDouble();
}
}
|
/* There is no evaluation here, so the function is executed
per row. Else every row would contain the same random value*/
assert symbol.arguments().size() == 0 : "function's number of arguments must be 0";
return symbol;
| 256
| 62
| 318
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.Double,java.lang.Void> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.Double evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Void>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/arithmetic/SquareRootFunction.java
|
SquareRootFunction
|
register
|
class SquareRootFunction {
public static final String NAME = "sqrt";
public static void register(Functions.Builder module) {<FILL_FUNCTION_BODY>}
private static double sqrt(double value) {
if (value < 0) {
throw new IllegalArgumentException("cannot take square root of a negative number");
}
return Math.sqrt(value);
}
}
|
for (var type : DataTypes.NUMERIC_PRIMITIVE_TYPES) {
var typeSignature = type.getTypeSignature();
module.add(
scalar(NAME, typeSignature, DataTypes.DOUBLE.getTypeSignature())
.withFeature(Scalar.Feature.NULLABLE),
(signature, boundSignature) ->
new DoubleScalar(signature, boundSignature, SquareRootFunction::sqrt)
);
}
| 100
| 112
| 212
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/arithmetic/SubtractTimestampScalar.java
|
SubtractTimestampScalar
|
register
|
class SubtractTimestampScalar extends Scalar<Period, Object> {
public static void register(Functions.Builder module) {<FILL_FUNCTION_BODY>}
public SubtractTimestampScalar(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
public Period evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Object>[] args) {
Long start = (Long) args[1].value();
Long end = (Long) args[0].value();
if (end == null || start == null) {
return null;
}
return new Period(end - start).normalizedStandard(PeriodType.yearMonthDayTime());
}
}
|
for (var timestampType : List.of(DataTypes.TIMESTAMP, DataTypes.TIMESTAMPZ)) {
module.add(
Signature.scalar(
ArithmeticFunctions.Names.SUBTRACT,
timestampType.getTypeSignature(),
timestampType.getTypeSignature(),
DataTypes.INTERVAL.getTypeSignature()
),
SubtractTimestampScalar::new
);
}
| 185
| 107
| 292
|
<methods>public BoundSignature boundSignature() ,public Scalar<Period,java.lang.Object> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract Period evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Object>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/array/ArrayArgumentValidators.java
|
ArrayArgumentValidators
|
ensureSingleArgumentArrayInnerTypeIsNotUndefined
|
class ArrayArgumentValidators {
public static void ensureInnerTypeIsNotUndefined(List<DataType<?>> dataTypes, String functionName) {
DataType<?> innerType = ((ArrayType<?>) dataTypes.get(0)).innerType();
if (innerType.equals(DataTypes.UNDEFINED)) {
throw new IllegalArgumentException(String.format(
Locale.ENGLISH,
"The inner type of the array argument `%s` function cannot be undefined",
functionName));
}
}
public static void ensureBothInnerTypesAreNotUndefined(List<DataType<?>> dataTypes, String functionName) {
DataType<?> innerType0 = ((ArrayType<?>) dataTypes.get(0)).innerType();
DataType<?> innerType1 = ((ArrayType<?>) dataTypes.get(1)).innerType();
if (innerType0.equals(DataTypes.UNDEFINED) || innerType1.equals(DataTypes.UNDEFINED)) {
throw new IllegalArgumentException(
"One of the arguments of the `" + functionName +
"` function can be of undefined inner type, but not both");
}
}
public static void ensureSingleArgumentArrayInnerTypeIsNotUndefined(List<DataType<?>> dataTypes) {<FILL_FUNCTION_BODY>}
}
|
DataType<?> innerType = ((ArrayType<?>) dataTypes.get(0)).innerType();
if (innerType.equals(DataTypes.UNDEFINED)) {
throw new IllegalArgumentException(
"When used with only one argument, the inner type of the array argument cannot be undefined");
}
| 341
| 79
| 420
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/bitwise/BitwiseFunctions.java
|
BitwiseFunctions
|
register
|
class BitwiseFunctions {
private static final TriConsumer<String, BitString, BitString> LENGTH_VALIDATOR = (op, bs1, bs2) -> {
if (bs1.length() != bs2.length()) {
throw new IllegalArgumentException(String.format(Locale.ENGLISH, "Cannot %s bit strings of different sizes", op));
}
};
private static <T> void register(Functions.Builder module,
String name,
DataType<T> type,
BinaryOperator<T> operator) {<FILL_FUNCTION_BODY>}
public static void register(Functions.Builder module) {
register(module, "AND", LONG, (a, b) -> a & b);
register(module, "AND", INTEGER, (a, b) -> a & b);
register(module, "AND", SHORT, (a, b) -> (short) (a & b)); // Bitwise operations on short and byte types are auto-casted to int, need to cast back.
register(module, "AND", BYTE, (a, b) -> (byte) (a & b));
register(module, "AND", BitStringType.INSTANCE_ONE, (a, b) -> {
LENGTH_VALIDATOR.accept("AND", a, b);
a.bitSet().and(b.bitSet());
return a;
});
register(module, "OR", LONG, (a, b) -> a | b);
register(module, "OR", INTEGER, (a, b) -> a | b);
register(module, "OR", SHORT, (a, b) -> (short) (a | b));
register(module, "OR", BYTE, (a, b) -> (byte) (a | b));
register(module, "OR", BitStringType.INSTANCE_ONE, (a, b) -> {
LENGTH_VALIDATOR.accept("OR", a, b);
a.bitSet().or(b.bitSet());
return a;
});
register(module, "XOR", LONG, (a, b) -> a ^ b);
register(module, "XOR", INTEGER, (a, b) -> a ^ b);
register(module, "XOR", SHORT, (a, b) -> (short) (a ^ b));
register(module, "XOR", BYTE, (a, b) -> (byte) (a ^ b));
register(module, "XOR", BitStringType.INSTANCE_ONE, (a, b) -> {
LENGTH_VALIDATOR.accept("XOR", a, b);
a.bitSet().xor(b.bitSet());
return a;
});
}
}
|
TypeSignature typeSignature = type.getTypeSignature();
Signature scalar = Signature.scalar(
name.toLowerCase(Locale.ENGLISH),
typeSignature,
typeSignature,
typeSignature
)
.withFeatures(Scalar.DETERMINISTIC_ONLY)
.withFeature(Scalar.Feature.NULLABLE);
module.add(scalar, (signature, boundSignature) -> new BinaryScalar<>(operator, signature, boundSignature, type));
| 706
| 126
| 832
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/conditional/CaseFunction.java
|
CaseFunction
|
evaluate
|
class CaseFunction extends Scalar<Object, Object> {
public static final String NAME = "case";
public static void register(Functions.Builder module) {
TypeSignature t = TypeSignature.parse("T");
TypeSignature bool = TypeSignature.parse("boolean");
module.add(
Signature.builder()
.name(new FunctionName(null, NAME))
.kind(FunctionType.SCALAR)
.typeVariableConstraints(typeVariable("T"))
.argumentTypes(bool, t)
.returnType(t)
.variableArityGroup(List.of(bool, t))
.build(),
CaseFunction::new
);
}
private CaseFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
public Object evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Object>[] args) {<FILL_FUNCTION_BODY>}
}
|
// args structure is [true, default T, condition1 Boolean, value T, condition2 Boolean, value T ...]
// Therefore skip first pair which represents the default value
for (int i = 2; i < args.length; i = i + 2) {
var condition = (Boolean) args[i].value();
if (condition != null && condition) {
return args[i + 1].value();
}
}
// Fallback to default value which is the first pair
return args[1].value();
| 244
| 129
| 373
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.Object,java.lang.Object> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.Object evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Object>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/geo/IntersectsFunction.java
|
IntersectsFunction
|
normalizeSymbol
|
class IntersectsFunction extends Scalar<Boolean, Object> {
public static final String NAME = "intersects";
public static void register(Functions.Builder module) {
module.add(
scalar(
NAME,
DataTypes.GEO_SHAPE.getTypeSignature(),
DataTypes.GEO_SHAPE.getTypeSignature(),
DataTypes.BOOLEAN.getTypeSignature()
).withFeature(Feature.NULLABLE),
IntersectsFunction::new
);
}
public IntersectsFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
public Boolean evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Object>... args) {
assert args.length == 2 : "Invalid number of Arguments";
Object left = args[0].value();
if (left == null) {
return null;
}
Object right = args[1].value();
if (right == null) {
return null;
}
Shape leftShape = GeoJSONUtils.map2Shape(DataTypes.GEO_SHAPE.sanitizeValue(left));
Shape rightShape = GeoJSONUtils.map2Shape(DataTypes.GEO_SHAPE.sanitizeValue(right));
return leftShape.relate(rightShape).intersects();
}
@Override
public Symbol normalizeSymbol(Function symbol, TransactionContext txnCtx, NodeContext nodeCtx) {<FILL_FUNCTION_BODY>}
}
|
Symbol left = symbol.arguments().get(0);
Symbol right = symbol.arguments().get(1);
int numLiterals = 0;
if (left.symbolType().isValueSymbol()) {
numLiterals++;
}
if (right.symbolType().isValueSymbol()) {
numLiterals++;
}
if (numLiterals == 2) {
return Literal.of(evaluate(txnCtx, nodeCtx, (Input) left, (Input) right));
}
return symbol;
| 394
| 139
| 533
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.Boolean,java.lang.Object> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.Boolean evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Object>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/geo/WithinFunction.java
|
WithinFunction
|
toQuery
|
class WithinFunction extends Scalar<Boolean, Object> {
public static final String NAME = "within";
public static void register(Functions.Builder module) {
module.add(
Signature.scalar(
NAME,
DataTypes.GEO_SHAPE.getTypeSignature(),
DataTypes.GEO_SHAPE.getTypeSignature(),
DataTypes.BOOLEAN.getTypeSignature()
),
WithinFunction::new
);
// Needed to avoid casts on references of `geo_point` and thus to avoid generic function filter on lucene.
// Coercion must be forbidden, as string representation could be a `geo_shape` and thus must match
// the other signature
for (var type : List.of(DataTypes.GEO_SHAPE, DataTypes.STRING, DataTypes.UNTYPED_OBJECT, DataTypes.UNDEFINED)) {
module.add(
Signature.scalar(
NAME,
DataTypes.GEO_POINT.getTypeSignature(),
type.getTypeSignature(),
DataTypes.BOOLEAN.getTypeSignature()
).withForbiddenCoercion(),
WithinFunction::new
);
}
}
private WithinFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
@SuppressWarnings("rawtypes")
public Boolean evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input[] args) {
assert args.length == 2 : "number of args must be 2";
return evaluate(args[0], args[1]);
}
public Boolean evaluate(Input<?> leftInput, Input<?> rightInput) {
Object left = leftInput.value();
if (left == null) {
return null;
}
Object right = rightInput.value();
if (right == null) {
return null;
}
return parseLeftShape(left).relate(parseRightShape(right)) == SpatialRelation.WITHIN;
}
@SuppressWarnings("unchecked")
private static Shape parseLeftShape(Object left) {
Shape shape;
if (left instanceof Point point) {
shape = SpatialContext.GEO.getShapeFactory().pointXY(point.getX(), point.getY());
} else if (left instanceof Double[] values) {
shape = SpatialContext.GEO.getShapeFactory().pointXY(values[0], values[1]);
} else if (left instanceof String str) {
shape = GeoJSONUtils.wkt2Shape(str);
} else {
shape = GeoJSONUtils.map2Shape((Map<String, Object>) left);
}
return shape;
}
@SuppressWarnings("unchecked")
private Shape parseRightShape(Object right) {
return (right instanceof String str) ?
GeoJSONUtils.wkt2Shape(str) :
GeoJSONUtils.map2Shape((Map<String, Object>) right);
}
@Override
public Symbol normalizeSymbol(Function symbol, TransactionContext txnCtx, NodeContext nodeCtx) {
Symbol left = symbol.arguments().get(0);
Symbol right = symbol.arguments().get(1);
short numLiterals = 0;
if (left.symbolType().isValueSymbol()) {
numLiterals++;
}
if (right.symbolType().isValueSymbol()) {
numLiterals++;
}
if (numLiterals == 2) {
return Literal.of(evaluate((Input<?>) left, (Input<?>) right));
}
return symbol;
}
@Override
public Query toQuery(Function parent, Function inner, Context context) {<FILL_FUNCTION_BODY>}
@Override
public Query toQuery(Reference ref, Literal<?> literal) {
if (ref.valueType().equals(DataTypes.GEO_SHAPE)) {
// Can only optimize on point columns, not on shapes
return null;
}
Map<String, Object> geoJSON = DataTypes.GEO_SHAPE.implicitCast(literal.value());
Geometry geometry;
Shape shape = GeoJSONUtils.map2Shape(geoJSON);
if (shape instanceof ShapeCollection<?> collection) {
int i = 0;
org.locationtech.jts.geom.Polygon[] polygons = new org.locationtech.jts.geom.Polygon[collection.size()];
for (Shape s : collection.getShapes()) {
Geometry subGeometry = JtsSpatialContext.GEO.getShapeFactory().getGeometryFrom(s);
if (subGeometry instanceof org.locationtech.jts.geom.Polygon polygon) {
polygons[i++] = polygon;
} else {
throw new InvalidShapeException("Shape collection must contain only Polygon shapes.");
}
}
GeometryFactory geometryFactory = JtsSpatialContext.GEO.getShapeFactory().getGeometryFactory();
geometry = geometryFactory.createMultiPolygon(polygons);
} else {
geometry = JtsSpatialContext.GEO.getShapeFactory().getGeometryFrom(shape);
}
return getPolygonQuery(ref.storageIdent(), geometry);
}
private static Query getPolygonQuery(String column, Geometry geometry) {
Coordinate[] coordinates = geometry.getCoordinates();
// close the polygon shape if startpoint != endpoint
if (!CoordinateArrays.isRing(coordinates)) {
coordinates = Arrays.copyOf(coordinates, coordinates.length + 1);
coordinates[coordinates.length - 1] = coordinates[0];
}
final double[] lats = new double[coordinates.length];
final double[] lons = new double[coordinates.length];
for (int i = 0; i < coordinates.length; i++) {
lats[i] = coordinates[i].y;
lons[i] = coordinates[i].x;
}
return LatLonPoint.newPolygonQuery(column, new Polygon(lats, lons));
}
}
|
// within(p, pointOrShape) = [ true | false ]
if (parent.name().equals(EqOperator.NAME)
&& parent.arguments().get(1) instanceof Literal<?> eqLiteral
&& inner.arguments().get(0) instanceof Reference ref
&& inner.arguments().get(1) instanceof Literal<?> pointOrShape) {
Query query = toQuery(ref, pointOrShape);
if (query == null) {
return null;
}
Boolean isWithin = (Boolean) eqLiteral.value();
if (isWithin == null) {
// Need to fallback to generic function filter because `null = null` is `null`
// and depending on parent queries that could turn into a match.
return null;
}
return isWithin ? query : Queries.not(query);
}
return null;
| 1,548
| 216
| 1,764
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.Boolean,java.lang.Object> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.Boolean evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Object>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/object/ObjectKeysFunction.java
|
ObjectKeysFunction
|
register
|
class ObjectKeysFunction {
public static void register(Functions.Builder module) {<FILL_FUNCTION_BODY>}
}
|
module.add(
Signature.scalar(
"object_keys",
DataTypes.UNTYPED_OBJECT.getTypeSignature(),
DataTypes.STRING_ARRAY.getTypeSignature()
).withFeature(Scalar.Feature.NULLABLE),
(signature, boundSignature) ->
new UnaryScalar<>(
signature,
boundSignature,
DataTypes.UNTYPED_OBJECT,
obj -> new ArrayList<>(obj.keySet())
)
);
| 35
| 130
| 165
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/object/ObjectMergeFunction.java
|
ObjectMergeFunction
|
evaluate
|
class ObjectMergeFunction extends Scalar<Map<String, Object>, Map<String, Object>> {
public ObjectMergeFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@SafeVarargs
@Override
public final Map<String, Object> evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Map<String, Object>>... args) {<FILL_FUNCTION_BODY>}
}
|
var objectOne = args[0].value();
var objectTwo = args[1].value();
if (objectOne == null) {
return objectTwo;
}
if (objectTwo == null) {
return objectOne;
}
Map<String,Object> resultObject = new HashMap<>();
resultObject.putAll(objectOne);
resultObject.putAll(objectTwo);
return resultObject;
| 117
| 109
| 226
|
<methods>public BoundSignature boundSignature() ,public Scalar<Map<java.lang.String,java.lang.Object>,Map<java.lang.String,java.lang.Object>> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract Map<java.lang.String,java.lang.Object> evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<Map<java.lang.String,java.lang.Object>>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/postgres/CurrentSettingFunction.java
|
CurrentSettingFunction
|
evaluate
|
class CurrentSettingFunction extends Scalar<String, Object> {
private static final String NAME = "current_setting";
private static final FunctionName FQN = new FunctionName(PgCatalogSchemaInfo.NAME, NAME);
public static void register(Functions.Builder builder, SessionSettingRegistry sessionSettingRegistry) {
builder.add(
scalar(
FQN,
DataTypes.STRING.getTypeSignature(),
DataTypes.STRING.getTypeSignature()
).withFeature(Feature.NULLABLE),
(signature, boundSignature) ->
new CurrentSettingFunction(
signature,
boundSignature,
sessionSettingRegistry
)
);
builder.add(
scalar(
FQN,
DataTypes.STRING.getTypeSignature(),
DataTypes.BOOLEAN.getTypeSignature(),
DataTypes.STRING.getTypeSignature()
).withFeature(Feature.NULLABLE),
(signature, boundSignature) ->
new CurrentSettingFunction(
signature,
boundSignature,
sessionSettingRegistry
)
);
}
private final SessionSettingRegistry sessionSettingRegistry;
CurrentSettingFunction(Signature signature, BoundSignature boundSignature, SessionSettingRegistry sessionSettingRegistry) {
super(signature, boundSignature);
this.sessionSettingRegistry = sessionSettingRegistry;
}
@Override
public String evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Object>... args) {<FILL_FUNCTION_BODY>}
}
|
assert args.length == 1 || args.length == 2 : "number of args must be 1 or 2";
final String settingName = (String) args[0].value();
if (settingName == null) {
return null;
}
final Boolean missingOk = (args.length == 2)
? (Boolean) args[1].value()
: Boolean.FALSE;
if (missingOk == null) {
return null;
}
final SessionSetting<?> sessionSetting = sessionSettingRegistry.settings().get(settingName);
if (sessionSetting == null) {
if (missingOk) {
return null;
} else {
throw new IllegalArgumentException("Unrecognised Setting: " + settingName);
}
}
return sessionSetting.getValue(txnCtx.sessionSettings());
| 373
| 209
| 582
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.String,java.lang.Object> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.String evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Object>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/postgres/PgBackendPidFunction.java
|
PgBackendPidFunction
|
normalizeSymbol
|
class PgBackendPidFunction extends Scalar<Integer, Void> {
public static final String NAME = "pg_backend_pid";
private static final FunctionName FQN = new FunctionName(PgCatalogSchemaInfo.NAME, NAME);
public static void register(Functions.Builder module) {
module.add(
scalar(
FQN,
DataTypes.INTEGER.getTypeSignature()
).withFeatures(EnumSet.of(Feature.NON_NULLABLE)),
PgBackendPidFunction::new
);
}
public PgBackendPidFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
public Symbol normalizeSymbol(Function symbol, TransactionContext txnCtx, NodeContext nodeCtx) {<FILL_FUNCTION_BODY>}
@Override
public Integer evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input[] args) {
assert args.length == 0 : "number of args must be 0";
return -1;
}
}
|
assert symbol.arguments().size() == 0 : "function's number of arguments must be 0";
return Literal.of(-1);
| 277
| 37
| 314
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.Integer,java.lang.Void> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.Integer evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Void>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/postgres/PgEncodingToCharFunction.java
|
PgEncodingToCharFunction
|
evaluate
|
class PgEncodingToCharFunction extends Scalar<String, Integer> {
private static final FunctionName FQN = new FunctionName(PgCatalogSchemaInfo.NAME, "pg_encoding_to_char");
public static void register(Functions.Builder module) {
module.add(
scalar(
FQN,
DataTypes.INTEGER.getTypeSignature(),
DataTypes.STRING.getTypeSignature()
).withFeature(Feature.NON_NULLABLE),
PgEncodingToCharFunction:: new
);
}
public PgEncodingToCharFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@SafeVarargs
@Override
public final String evaluate(TransactionContext txnCtx, NodeContext nodeContext, Input<Integer>... args) {<FILL_FUNCTION_BODY>}
private enum PgEncodingIdentifiers {
// See https://github.com/postgres/postgres/blob/master/src/include/mb/pg_wchar.h
SQL_ASCII,
EUC_JP,
EUC_CN,
EUC_KR,
EUC_TW,
EUC_JIS_2004,
UTF8,
MULE_INTERNAL,
LATIN1,
LATIN2,
LATIN3,
LATIN4,
LATIN5,
LATIN6,
LATIN7,
LATIN8,
LATIN9,
LATIN10,
WIN1256,
WIN1258,
WIN866,
WIN874,
KOI8R,
WIN1251,
WIN1252,
ISO_8859_5,
ISO_8859_6,
ISO_8859_7,
ISO_8859_8,
WIN1250,
WIN1253,
WIN1254,
WIN1255,
WIN1257,
KOI8U,
SJIS,
BIG5,
GBK,
UHC,
GB18030,
JOHAB,
SHIFT_JIS_2004;
}
}
|
var value = args[0].value();
if (value == null || value < 0 || value >= PgEncodingIdentifiers.values().length) {
return null;
}
return PgEncodingIdentifiers.values()[value].name();
| 613
| 63
| 676
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.String,java.lang.Integer> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.String evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Integer>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/string/ParseURIFunction.java
|
ParseURIFunction
|
parseURI
|
class ParseURIFunction extends Scalar<Object, String> {
private static final String NAME = "parse_uri";
public static void register(Functions.Builder module) {
module.add(
Signature.scalar(
NAME,
DataTypes.STRING.getTypeSignature(),
DataTypes.UNTYPED_OBJECT.getTypeSignature()
).withFeature(Scalar.Feature.NULLABLE),
ParseURIFunction::new
);
}
public ParseURIFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
@SafeVarargs
public final Object evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<String>... args) {
String uri = args[0].value();
if (uri == null) {
return null;
}
return parseURI(uri);
}
private final Object parseURI(String uriText) {<FILL_FUNCTION_BODY>}
}
|
final Map<String, Object> uriMap = new HashMap<>();
URI uri = null;
try {
uri = new URI(uriText);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(String.format(Locale.ENGLISH,
"unable to parse uri %s",
uriText));
}
uriMap.put("scheme", uri.getScheme());
uriMap.put("userinfo", uri.getUserInfo());
uriMap.put("hostname", uri.getHost());
uriMap.put("port", uri.getPort() == -1 ? null : uri.getPort());
uriMap.put("path", uri.getPath());
uriMap.put("query", uri.getQuery());
uriMap.put("fragment", uri.getFragment());
return uriMap;
| 258
| 215
| 473
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.Object,java.lang.String> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.Object evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.String>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/string/QuoteIdentFunction.java
|
QuoteIdentFunction
|
charIsOutsideSafeRange
|
class QuoteIdentFunction {
private static final FunctionName FQNAME = new FunctionName(PgCatalogSchemaInfo.NAME, "quote_ident");
public static void register(Functions.Builder module) {
module.add(
Signature.scalar(
FQNAME,
DataTypes.STRING.getTypeSignature(),
DataTypes.STRING.getTypeSignature()
).withFeature(Scalar.Feature.NULLABLE),
(signature, boundSignature) ->
new UnaryScalar<>(
signature,
boundSignature,
DataTypes.STRING,
QuoteIdentFunction::maybeQuoteExpression
)
);
}
/**
* Similar to {@link Identifiers#quoteIfNeeded}.
* The main difference is that for subscript expressions, this method will quote the base(root) columns only
* when it's needed.
*/
@VisibleForTesting
static String maybeQuoteExpression(String expression) {
int length = expression.length();
if (length == 0) {
return "\"\"";
}
if (isKeyWord(expression)) {
return '"' + expression + '"';
}
StringBuilder sb = new StringBuilder();
boolean addQuotes = false;
int subscriptStartPos = -1;
for (int i = 0; i < length; i++) {
char c = expression.charAt(i);
if (c == '"') {
sb.append('"');
}
sb.append(c);
if (subscriptStartPos == -1) {
if (c == '[' && i + 1 < length && expression.charAt(i + 1) == '\'') {
subscriptStartPos = i;
} else {
addQuotes = addQuotes || charIsOutsideSafeRange(i, c);
}
}
}
if (addQuotes) {
sb.insert(0, '"');
if (subscriptStartPos == -1) {
sb.append('"');
} else {
sb.insert(subscriptStartPos + 1, '"');
}
}
return sb.toString();
}
private static boolean charIsOutsideSafeRange(int i, char c) {<FILL_FUNCTION_BODY>}
}
|
if (i == 0) {
return c != '_' && (c < 'a' || c > 'z');
}
return c != '_' && (c < 'a' || c > 'z') && (c < '0' || c > '9');
| 573
| 70
| 643
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/string/ReverseFunction.java
|
ReverseFunction
|
register
|
class ReverseFunction {
private static final String NAME = "reverse";
public static void register(Functions.Builder module) {<FILL_FUNCTION_BODY>}
}
|
module.add(
Signature.scalar(
NAME,
DataTypes.STRING.getTypeSignature(),
DataTypes.STRING.getTypeSignature()
).withFeature(Scalar.Feature.NULLABLE),
(signature, boundSignature) -> {
return new UnaryScalar<>(
signature,
boundSignature,
DataTypes.STRING,
s -> new StringBuilder(s).reverse().toString()
);
}
);
| 49
| 119
| 168
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/string/StringCaseFunction.java
|
StringCaseFunction
|
register
|
class StringCaseFunction {
public static void register(Functions.Builder module) {<FILL_FUNCTION_BODY>}
}
|
module.add(
Signature.scalar(
"upper",
DataTypes.STRING.getTypeSignature(),
DataTypes.STRING.getTypeSignature()
).withFeature(Scalar.Feature.NULLABLE),
(signature, boundSignature) ->
new UnaryScalar<>(
signature,
boundSignature,
DataTypes.STRING,
val -> val.toUpperCase(Locale.ENGLISH)
)
);
module.add(
Signature.scalar(
"lower",
DataTypes.STRING.getTypeSignature(),
DataTypes.STRING.getTypeSignature()
).withFeature(Scalar.Feature.NULLABLE),
(signature, boundSignature) ->
new UnaryScalar<>(
signature,
boundSignature,
DataTypes.STRING,
val -> val.toLowerCase(Locale.ENGLISH)
)
);
| 35
| 233
| 268
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/string/StringLeftRightFunction.java
|
StringLeftRightFunction
|
right
|
class StringLeftRightFunction extends Scalar<String, Object> {
public static void register(Functions.Builder module) {
module.add(
Signature.scalar(
"left",
DataTypes.STRING.getTypeSignature(),
DataTypes.INTEGER.getTypeSignature(),
DataTypes.STRING.getTypeSignature()
),
(signature, boundSignature) ->
new StringLeftRightFunction(signature, boundSignature, StringLeftRightFunction::left)
);
module.add(
Signature.scalar(
"right",
DataTypes.STRING.getTypeSignature(),
DataTypes.INTEGER.getTypeSignature(),
DataTypes.STRING.getTypeSignature()
),
(signature, boundSignature) ->
new StringLeftRightFunction(signature, boundSignature, StringLeftRightFunction::right)
);
}
private final BiFunction<String, Integer, String> func;
private StringLeftRightFunction(Signature signature,
BoundSignature boundSignature,
BiFunction<String, Integer, String> func) {
super(signature, boundSignature);
this.func = func;
}
@Override
public String evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input[] args) {
assert args.length == 2 : String.format(Locale.ENGLISH,
"number of arguments must be 2, got %d instead",
args.length);
String str = (String) args[0].value();
Number len = (Number) args[1].value();
if (str == null || len == null) {
return null;
}
return len.intValue() == 0 || str.isEmpty() ? "" : func.apply(str, len.intValue());
}
private static String left(String str, int len) {
if (len > 0) {
return str.substring(0, Math.min(len, str.length()));
}
final int finalLen = str.length() + len;
return finalLen > 0 ? str.substring(0, finalLen) : "";
}
private static String right(String str, int len) {<FILL_FUNCTION_BODY>}
}
|
if (len < 0) {
return str.substring(Math.min(-len, str.length()));
}
final int finalLen = str.length() - len;
return finalLen <= 0 ? str : str.substring(finalLen);
| 548
| 65
| 613
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.String,java.lang.Object> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.String evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Object>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/string/StringRepeatFunction.java
|
StringRepeatFunction
|
evaluate
|
class StringRepeatFunction extends Scalar<String, Object> {
public static void register(Functions.Builder module) {
module.add(
Signature.scalar(
"repeat",
DataTypes.STRING.getTypeSignature(),
DataTypes.INTEGER.getTypeSignature(),
DataTypes.STRING.getTypeSignature()
),
StringRepeatFunction::new
);
}
public StringRepeatFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
public String evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Object>[] args) {<FILL_FUNCTION_BODY>}
}
|
assert args.length == 2 : "repeat takes exactly two arguments";
var text = (String) args[0].value();
var repetitions = (Integer) args[1].value();
if (text == null || repetitions == null) {
return null;
}
if (repetitions <= 0) {
return "";
} else {
return text.repeat(repetitions);
}
| 178
| 105
| 283
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.String,java.lang.Object> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.String evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Object>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/systeminformation/ColDescriptionFunction.java
|
ColDescriptionFunction
|
evaluate
|
class ColDescriptionFunction extends Scalar<String, Object> {
private static final String NAME = "col_description";
private static final FunctionName FQN = new FunctionName(PgCatalogSchemaInfo.NAME, NAME);
public static void register(Functions.Builder module) {
module.add(
Signature.scalar(
FQN,
DataTypes.INTEGER.getTypeSignature(),
DataTypes.INTEGER.getTypeSignature(),
DataTypes.STRING.getTypeSignature()
),
ColDescriptionFunction::new
);
}
public ColDescriptionFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@SafeVarargs
@Override
public final String evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Object>... args) {<FILL_FUNCTION_BODY>}
}
|
// CrateDB doesn't support comments for table columns, so always return null
return null;
| 225
| 27
| 252
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.String,java.lang.Object> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.String evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Object>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/systeminformation/FormatTypeFunction.java
|
FormatTypeFunction
|
evaluate
|
class FormatTypeFunction extends Scalar<String, Object> {
private static final String NAME = "format_type";
private static final FunctionName FQN = new FunctionName(PgCatalogSchemaInfo.NAME, NAME);
public static void register(Functions.Builder module) {
module.add(
Signature.scalar(
FQN,
DataTypes.INTEGER.getTypeSignature(),
DataTypes.INTEGER.getTypeSignature(),
DataTypes.STRING.getTypeSignature()
).withFeature(Feature.NULLABLE),
FormatTypeFunction::new
);
}
public FormatTypeFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
@SafeVarargs
public final String evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Object>... args) {<FILL_FUNCTION_BODY>}
}
|
var typeOid = (Integer) args[0].value();
if (typeOid == null) {
return null;
}
var type = PGTypes.fromOID(typeOid);
if (type == null) {
return "???";
} else {
int dimensions = 0;
while (type instanceof ArrayType) {
type = ((ArrayType<?>) type).innerType();
dimensions++;
}
if (dimensions == 0) {
return type.getName();
}
var sb = new StringBuilder();
sb.append(type.getName());
for (int i = 0; i < dimensions; i++) {
sb.append("[]");
}
return sb.toString();
}
| 233
| 194
| 427
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.String,java.lang.Object> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.String evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Object>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/systeminformation/PgFunctionIsVisibleFunction.java
|
PgFunctionIsVisibleFunction
|
evaluate
|
class PgFunctionIsVisibleFunction extends Scalar<Boolean, Integer> {
public static final String NAME = "pg_function_is_visible";
public static void register(Functions.Builder module) {
module.add(
Signature.scalar(
NAME,
DataTypes.INTEGER.getTypeSignature(),
DataTypes.BOOLEAN.getTypeSignature()
).withFeature(Feature.NULLABLE),
PgFunctionIsVisibleFunction::new);
}
public PgFunctionIsVisibleFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
public Boolean evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Integer>... args) {<FILL_FUNCTION_BODY>}
}
|
assert args.length == 1 : NAME + " expects exactly 1 argument, got " + args.length;
Integer oid = args[0].value();
if (oid == null) {
return null;
}
return nodeCtx.functions().findFunctionSignatureByOid(oid) != null;
| 200
| 79
| 279
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.Boolean,java.lang.Integer> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.Boolean evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Integer>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/systeminformation/PgGetFunctionResultFunction.java
|
PgGetFunctionResultFunction
|
evaluate
|
class PgGetFunctionResultFunction extends Scalar<String, Integer> {
public static final String NAME = "pg_get_function_result";
public static void register(Functions.Builder module) {
module.add(
Signature.scalar(
NAME,
DataTypes.INTEGER.getTypeSignature(),
DataTypes.STRING.getTypeSignature()
).withFeature(Feature.NULLABLE),
PgGetFunctionResultFunction::new);
}
public PgGetFunctionResultFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
public String evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Integer>... args) {<FILL_FUNCTION_BODY>}
}
|
assert args.length == 1 : NAME + " expects exactly 1 argument, got " + args.length;
Integer oid = args[0].value();
if (oid == null) {
return null;
}
Signature sig = nodeCtx.functions().findFunctionSignatureByOid(oid);
return sig != null ? sig.getReturnType().toString() : null;
| 196
| 97
| 293
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.String,java.lang.Integer> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.String evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Integer>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/systeminformation/VersionFunction.java
|
VersionFunction
|
formatVersion
|
class VersionFunction extends Scalar<String, Void> {
public static final String NAME = "version";
private static final FunctionName FQN = new FunctionName(PgCatalogSchemaInfo.NAME, NAME);
public static void register(Functions.Builder module) {
module.add(
Signature.scalar(
FQN,
DataTypes.STRING.getTypeSignature()
).withFeatures(EnumSet.of(Feature.NON_NULLABLE)),
VersionFunction::new
);
}
private static String formatVersion() {<FILL_FUNCTION_BODY>}
private static final String VERSION = formatVersion();
public VersionFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
@Override
@SafeVarargs
public final String evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Void>... args) {
return VERSION;
}
}
|
String version = Version.displayVersion(Version.CURRENT, Version.CURRENT.isSnapshot());
String built = String.format(
Locale.ENGLISH,
"built %s/%s",
Build.CURRENT.hashShort(),
Build.CURRENT.timestamp());
String vmVersion = String.format(
Locale.ENGLISH,
"%s %s",
System.getProperty("java.vm.name"),
System.getProperty("java.vm.version"));
String osVersion = String.format(
Locale.ENGLISH,
"%s %s %s",
System.getProperty("os.name"),
System.getProperty("os.version"),
System.getProperty("os.arch"));
return String.format(
Locale.ENGLISH,
"CrateDB %s (%s, %s, %s)",
version,
built,
osVersion,
vmVersion);
| 248
| 239
| 487
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.String,java.lang.Void> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.String evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Void>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/scalar/timestamp/TimezoneFunction.java
|
TimezoneFunction
|
register
|
class TimezoneFunction extends Scalar<Long, Object> {
public static final String NAME = "timezone";
private static final ZoneId UTC = ZoneId.of("UTC");
private final DataType returnType;
public static void register(Functions.Builder module) {<FILL_FUNCTION_BODY>}
private TimezoneFunction(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
this.returnType = boundSignature.returnType();
}
@Override
public Long evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Object>... args) {
assert args.length == 2 : String.format(Locale.ENGLISH,
"number of arguments must be 2, got %d instead",
args.length);
String zoneStr = (String) args[0].value();
if (zoneStr == null) {
return null;
}
ZoneId zoneId;
try {
zoneId = ZoneId.of(zoneStr);
} catch (DateTimeException e) {
throw new IllegalArgumentException(String.format(Locale.ENGLISH,
" time zone \"%s\" not recognized",
zoneStr));
}
Number utcTimestamp = (Number) args[1].value();
if (utcTimestamp == null) {
return null;
}
Instant instant = Instant.ofEpochMilli(utcTimestamp.longValue());
boolean paramHadTimezone = returnType == DataTypes.TIMESTAMP;
ZoneId srcZoneId = paramHadTimezone ? zoneId : UTC;
ZoneId dstZoneId = paramHadTimezone ? UTC : zoneId;
ZonedDateTime zonedDateTime = instant.atZone(srcZoneId).withZoneSameLocal(dstZoneId);
return zonedDateTime.toInstant().toEpochMilli();
}
}
|
module.add(
Signature.scalar(
NAME,
DataTypes.STRING.getTypeSignature(),
DataTypes.TIMESTAMPZ.getTypeSignature(),
DataTypes.TIMESTAMP.getTypeSignature()
),
TimezoneFunction::new
);
module.add(
Signature.scalar(
NAME,
DataTypes.STRING.getTypeSignature(),
DataTypes.TIMESTAMP.getTypeSignature(),
DataTypes.TIMESTAMPZ.getTypeSignature()
),
TimezoneFunction::new
);
module.add(
Signature.scalar(
NAME,
DataTypes.STRING.getTypeSignature(),
DataTypes.LONG.getTypeSignature(),
DataTypes.TIMESTAMPZ.getTypeSignature()
),
TimezoneFunction::new
);
| 467
| 209
| 676
|
<methods>public BoundSignature boundSignature() ,public Scalar<java.lang.Long,java.lang.Object> compile(List<io.crate.expression.symbol.Symbol>, java.lang.String, io.crate.role.Roles) ,public transient abstract java.lang.Long evaluate(io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext, Input<java.lang.Object>[]) ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public io.crate.metadata.functions.Signature signature() <variables>public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT,public static final Set<io.crate.metadata.Scalar.Feature> DETERMINISTIC_ONLY,public static final Set<io.crate.metadata.Scalar.Feature> NO_FEATURES,protected final non-sealed BoundSignature boundSignature,protected final non-sealed io.crate.metadata.functions.Signature signature
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/symbol/Aggregation.java
|
Aggregation
|
equals
|
class Aggregation implements Symbol {
private static final long SHALLOW_SIZE = RamUsageEstimator.shallowSizeOfInstance(Aggregation.class);
private final Signature signature;
private final DataType<?> boundSignatureReturnType;
private final List<Symbol> inputs;
private final DataType<?> valueType;
private final Symbol filter;
public Aggregation(Signature signature, DataType<?> valueType, List<Symbol> inputs) {
this(signature,
valueType,
valueType,
inputs,
Literal.BOOLEAN_TRUE
);
}
public Aggregation(Signature signature,
DataType<?> boundSignatureReturnType,
DataType<?> valueType,
List<Symbol> inputs,
Symbol filter) {
requireNonNull(inputs, "inputs must not be null");
requireNonNull(filter, "filter must not be null");
this.valueType = valueType;
this.signature = signature;
this.boundSignatureReturnType = boundSignatureReturnType;
this.inputs = inputs;
this.filter = filter;
}
public Aggregation(StreamInput in) throws IOException {
Signature generatedSignature = null;
if (in.getVersion().before(Version.V_5_0_0)) {
generatedSignature = Signature.readFromFunctionInfo(in);
}
valueType = DataTypes.fromStream(in);
if (in.getVersion().onOrAfter(Version.V_4_1_0)) {
filter = Symbols.fromStream(in);
} else {
filter = Literal.BOOLEAN_TRUE;
}
inputs = Symbols.listFromStream(in);
if (in.getVersion().onOrAfter(Version.V_4_2_0)) {
if (in.getVersion().before(Version.V_5_0_0)) {
in.readBoolean();
}
signature = new Signature(in);
boundSignatureReturnType = DataTypes.fromStream(in);
} else {
assert generatedSignature != null : "expecting a non-null generated signature";
signature = generatedSignature;
boundSignatureReturnType = valueType;
}
}
@Override
public SymbolType symbolType() {
return SymbolType.AGGREGATION;
}
@Override
public <C, R> R accept(SymbolVisitor<C, R> visitor, C context) {
return visitor.visitAggregation(this, context);
}
@Override
public DataType<?> valueType() {
return valueType;
}
public DataType<?> boundSignatureReturnType() {
return boundSignatureReturnType;
}
@Nullable
public Signature signature() {
return signature;
}
public List<Symbol> inputs() {
return inputs;
}
public Symbol filter() {
return filter;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
if (out.getVersion().before(Version.V_5_0_0)) {
signature.writeAsFunctionInfo(out, Symbols.typeView(inputs));
}
DataTypes.toStream(valueType, out);
if (out.getVersion().onOrAfter(Version.V_4_1_0)) {
Symbols.toStream(filter, out);
}
Symbols.toStream(inputs, out);
if (out.getVersion().onOrAfter(Version.V_4_2_0)) {
if (out.getVersion().before(Version.V_5_0_0)) {
out.writeBoolean(true);
}
signature.writeTo(out);
DataTypes.toStream(boundSignatureReturnType, out);
}
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(signature, inputs, valueType, filter);
}
@Override
public String toString() {
return toString(Style.UNQUALIFIED);
}
@Override
public String toString(Style style) {
StringBuilder sb = new StringBuilder(signature.getName().name())
.append("(");
for (int i = 0; i < inputs.size(); i++) {
sb.append(inputs.get(i).toString(style));
if (i + 1 < inputs.size()) {
sb.append(", ");
}
}
sb.append(")");
return sb.toString();
}
@Override
public long ramBytesUsed() {
return SHALLOW_SIZE
+ signature.ramBytesUsed()
+ boundSignatureReturnType.ramBytesUsed()
+ inputs.stream().mapToLong(Symbol::ramBytesUsed).sum()
+ valueType.ramBytesUsed()
+ filter.ramBytesUsed();
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Aggregation that = (Aggregation) o;
return Objects.equals(signature, that.signature) &&
Objects.equals(inputs, that.inputs) &&
Objects.equals(valueType, that.valueType) &&
Objects.equals(filter, that.filter);
| 1,257
| 120
| 1,377
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/symbol/DefaultTraversalSymbolVisitor.java
|
DefaultTraversalSymbolVisitor
|
visitWindowFunction
|
class DefaultTraversalSymbolVisitor<C, R> extends SymbolVisitor<C, R> {
/*
* These methods don't call into super to enable subclasses to use overwrite `visitSymbol` to visit all leaves.
* If we called super.visitXY here,
* it would cause visitSymbol to be called for Function, FetchReference and MatchPredicate as well.
*/
@Override
public R visitFunction(Function symbol, C context) {
for (Symbol arg : symbol.arguments()) {
arg.accept(this, context);
}
var filter = symbol.filter();
if (filter != null) {
filter.accept(this, context);
}
return null;
}
@Override
public R visitWindowFunction(WindowFunction symbol, C context) {<FILL_FUNCTION_BODY>}
@Override
public R visitFetchReference(FetchReference fetchReference, C context) {
fetchReference.fetchId().accept(this, context);
fetchReference.ref().accept(this, context);
return null;
}
@Override
public R visitMatchPredicate(MatchPredicate matchPredicate, C context) {
for (Symbol field : matchPredicate.identBoostMap().keySet()) {
field.accept(this, context);
}
matchPredicate.queryTerm().accept(this, context);
matchPredicate.options().accept(this, context);
return null;
}
@Override
public R visitAlias(AliasSymbol aliasSymbol, C context) {
aliasSymbol.symbol().accept(this, context);
return null;
}
}
|
for (Symbol arg : symbol.arguments()) {
arg.accept(this, context);
}
Symbol filter = symbol.filter();
if (filter != null) {
filter.accept(this, context);
}
WindowDefinition windowDefinition = symbol.windowDefinition();
OrderBy orderBy = windowDefinition.orderBy();
if (orderBy != null) {
for (Symbol orderBySymbol : orderBy.orderBySymbols()) {
orderBySymbol.accept(this, context);
}
}
for (Symbol partition : windowDefinition.partitions()) {
partition.accept(this, context);
}
Symbol frameStartValueSymbol = windowDefinition.windowFrameDefinition().start().value();
if (frameStartValueSymbol != null) {
frameStartValueSymbol.accept(this, context);
}
FrameBoundDefinition end = windowDefinition.windowFrameDefinition().end();
if (end != null) {
Symbol frameEndValueSymbol = end.value();
if (frameEndValueSymbol != null) {
frameEndValueSymbol.accept(this, context);
}
}
return null;
| 414
| 285
| 699
|
<methods>public non-sealed void <init>() ,public R visitAggregation(io.crate.expression.symbol.Aggregation, C) ,public R visitAlias(io.crate.expression.symbol.AliasSymbol, C) ,public R visitDynamicReference(io.crate.expression.symbol.DynamicReference, C) ,public R visitFetchMarker(io.crate.expression.symbol.FetchMarker, C) ,public R visitFetchReference(io.crate.expression.symbol.FetchReference, C) ,public R visitFetchStub(io.crate.expression.symbol.FetchStub, C) ,public R visitField(io.crate.expression.symbol.ScopedSymbol, C) ,public R visitFunction(io.crate.expression.symbol.Function, C) ,public R visitInputColumn(io.crate.expression.symbol.InputColumn, C) ,public R visitLiteral(Literal<?>, C) ,public R visitMatchPredicate(io.crate.expression.symbol.MatchPredicate, C) ,public R visitOuterColumn(io.crate.expression.symbol.OuterColumn, C) ,public R visitParameterSymbol(io.crate.expression.symbol.ParameterSymbol, C) ,public R visitReference(io.crate.metadata.Reference, C) ,public R visitSelectSymbol(io.crate.expression.symbol.SelectSymbol, C) ,public R visitVoidReference(io.crate.expression.symbol.VoidReference, C) ,public R visitWindowFunction(io.crate.expression.symbol.WindowFunction, C) <variables>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/symbol/FetchStub.java
|
FetchStub
|
writeTo
|
class FetchStub implements Symbol {
private final FetchMarker fetchMarker;
private final Reference ref;
/**
* @param fetchMarker the _fetchId marker that must be used to fetch the value for the reference
*/
public FetchStub(FetchMarker fetchMarker, Reference ref) {
this.fetchMarker = fetchMarker;
this.ref = ref;
}
public FetchMarker fetchMarker() {
return fetchMarker;
}
public Reference ref() {
return ref;
}
@Override
public SymbolType symbolType() {
return SymbolType.FETCH_STUB;
}
@Override
public <C, R> R accept(SymbolVisitor<C, R> visitor, C context) {
return visitor.visitFetchStub(this, context);
}
@Override
public DataType<?> valueType() {
return ref.valueType();
}
@Override
public String toString() {
return toString(Style.UNQUALIFIED);
}
@Override
public String toString(Style style) {
return ref.toString(style);
}
@Override
public void writeTo(StreamOutput out) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public long ramBytesUsed() {
return ref.ramBytesUsed() + fetchMarker.ramBytesUsed();
}
}
|
throw new UnsupportedEncodingException(
"Cannot stream FetchStub. This is a planning symbol and not suitable for the execution layer");
| 363
| 35
| 398
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/symbol/InputColumn.java
|
InputColumn
|
mapToInputColumns
|
class InputColumn implements Symbol, Comparable<InputColumn> {
private final DataType<?> dataType;
private final int index;
/**
* Map each data type to an {@link InputColumn} with an index corresponding to the data type's position in the list.
*/
public static List<Symbol> mapToInputColumns(List<DataType<?>> dataTypes) {
List<Symbol> inputColumns = new ArrayList<>(dataTypes.size());
for (int i = 0; i < dataTypes.size(); i++) {
inputColumns.add(new InputColumn(i, dataTypes.get(i)));
}
return inputColumns;
}
/**
* Map each symbol to an {@link InputColumn} with an index corresponding to the symbol's position in the collection.
*/
public static List<Symbol> mapToInputColumns(Collection<? extends Symbol> symbols) {<FILL_FUNCTION_BODY>}
public InputColumn(int index, @Nullable DataType<?> dataType) {
assert index >= 0 : "index must be >= 0";
this.index = index;
this.dataType = Objects.requireNonNullElse(dataType, DataTypes.UNDEFINED);
}
public InputColumn(StreamInput in) throws IOException {
index = in.readVInt();
dataType = DataTypes.fromStream(in);
}
public InputColumn(int index) {
this(index, null);
}
public int index() {
return index;
}
@Override
public SymbolType symbolType() {
return SymbolType.INPUT_COLUMN;
}
@Override
public DataType<?> valueType() {
return dataType;
}
@Override
public String toString() {
return "INPUT(" + index + ")";
}
@Override
public String toString(Style style) {
return "INPUT(" + index + ")";
}
@Override
public <C, R> R accept(SymbolVisitor<C, R> visitor, C context) {
return visitor.visitInputColumn(this, context);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVInt(index);
DataTypes.toStream(dataType, out);
}
@Override
public int compareTo(InputColumn o) {
return Integer.compare(index, o.index);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
InputColumn that = (InputColumn) o;
return index == that.index;
}
@Override
public int hashCode() {
return index;
}
@Override
public long ramBytesUsed() {
return IntegerType.INTEGER_SIZE + dataType.ramBytesUsed();
}
}
|
List<Symbol> inputColumns = new ArrayList<>(symbols.size());
int idx = 0;
for (Symbol symbol : symbols) {
inputColumns.add(new InputColumn(idx, symbol.valueType()));
idx++;
}
return inputColumns;
| 756
| 70
| 826
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/symbol/LiteralValueFormatter.java
|
LiteralValueFormatter
|
formatArray
|
class LiteralValueFormatter {
private static final LiteralValueFormatter INSTANCE = new LiteralValueFormatter();
public static void format(Object value, StringBuilder builder) {
INSTANCE.formatValue(value, builder);
}
private LiteralValueFormatter() {
}
@SuppressWarnings("unchecked")
public void formatValue(Object value, StringBuilder builder) {
if (value == null) {
builder.append("NULL");
} else if (value instanceof Map) {
formatMap((Map<String, Object>) value, builder);
} else if (value instanceof Collection) {
formatIterable((Iterable<?>) value, builder);
} else if (value.getClass().isArray()) {
formatArray(value, builder);
} else if (value instanceof String || value instanceof Point) {
builder.append(Literals.quoteStringLiteral(value.toString()));
} else if (value instanceof Period) {
builder.append(Literals.quoteStringLiteral(value.toString()));
builder.append("::interval");
} else if (value instanceof Long
&& ((Long) value <= Integer.MAX_VALUE
|| (Long) value >= Integer.MIN_VALUE)) {
builder.append(value.toString());
builder.append("::bigint");
} else {
builder.append(value);
}
}
private void formatIterable(Iterable<?> iterable, StringBuilder builder) {
builder.append('[');
var it = iterable.iterator();
while (it.hasNext()) {
var elem = it.next();
formatValue(elem, builder);
if (it.hasNext()) {
builder.append(", ");
}
}
builder.append(']');
}
private void formatMap(Map<String, Object> map, StringBuilder builder) {
builder.append("{");
var it = map
.entrySet()
.stream()
.iterator();
while (it.hasNext()) {
var entry = it.next();
formatIdentifier(entry.getKey(), builder);
builder.append("=");
formatValue(entry.getValue(), builder);
if (it.hasNext()) {
builder.append(", ");
}
}
builder.append("}");
}
private void formatIdentifier(String identifier, StringBuilder builder) {
builder.append('"').append(identifier).append('"');
}
private void formatArray(Object array, StringBuilder builder) {<FILL_FUNCTION_BODY>}
}
|
builder.append('[');
for (int i = 0, length = Array.getLength(array); i < length; i++) {
formatValue(Array.get(array, i), builder);
if (i + 1 < length) {
builder.append(", ");
}
}
builder.append(']');
| 648
| 85
| 733
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/symbol/MatchPredicate.java
|
MatchPredicate
|
ramBytesUsed
|
class MatchPredicate implements Symbol {
private final Map<Symbol, Symbol> identBoostMap;
private final Symbol queryTerm;
private final String matchType;
private final Symbol options;
public MatchPredicate(Map<Symbol, Symbol> identBoostMap,
Symbol queryTerm,
String matchType,
Symbol options) {
assert options.valueType().id() == ObjectType.ID : "options symbol must be of type object";
this.identBoostMap = identBoostMap;
this.queryTerm = queryTerm;
this.matchType = matchType;
this.options = options;
}
public Map<Symbol, Symbol> identBoostMap() {
return identBoostMap;
}
public Symbol queryTerm() {
return queryTerm;
}
public String matchType() {
return matchType;
}
public Symbol options() {
return options;
}
@Override
public SymbolType symbolType() {
return SymbolType.MATCH_PREDICATE;
}
@Override
public <C, R> R accept(SymbolVisitor<C, R> visitor, C context) {
return visitor.visitMatchPredicate(this, context);
}
@Override
public BooleanType valueType() {
return DataTypes.BOOLEAN;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
throw new UnsupportedOperationException("Cannot stream MatchPredicate");
}
@Override
public String toString() {
return toString(Style.UNQUALIFIED);
}
@Override
public long ramBytesUsed() {<FILL_FUNCTION_BODY>}
@Override
public String toString(Style style) {
StringBuilder sb = new StringBuilder("MATCH((");
Iterator<Map.Entry<Symbol, Symbol>> it = identBoostMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Symbol, Symbol> entry = it.next();
sb.append(entry.getKey().toString(style));
sb.append(" ");
sb.append(entry.getValue().toString(style));
if (it.hasNext()) {
sb.append(", ");
}
}
sb.append("), ");
sb.append(queryTerm.toString(style));
sb.append(") USING ");
sb.append(matchType);
sb.append(" WITH (");
sb.append(options.toString(style));
sb.append(")");
return sb.toString();
}
}
|
long bytes = 0L;
for (var entry : identBoostMap.entrySet()) {
bytes += entry.getKey().ramBytesUsed();
bytes += entry.getValue().ramBytesUsed();
}
return bytes
+ queryTerm.ramBytesUsed()
+ RamUsageEstimator.sizeOf(matchType)
+ options.ramBytesUsed();
| 656
| 93
| 749
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/symbol/RefReplacer.java
|
RefReplacer
|
visitReference
|
class RefReplacer extends FunctionCopyVisitor<Function<? super Reference, ? extends Symbol>> {
private static final RefReplacer REPLACER = new RefReplacer();
private RefReplacer() {
super();
}
/**
* Applies {@code mapper} on all {@link Reference} instances within {@code tree}
*/
public static Symbol replaceRefs(Symbol tree, Function<? super Reference, ? extends Symbol> mapper) {
return tree.accept(REPLACER, mapper);
}
@Override
public Symbol visitReference(Reference ref, Function<? super Reference, ? extends Symbol> mapper) {<FILL_FUNCTION_BODY>}
}
|
return requireNonNull(mapper.apply(ref), "mapper function used in RefReplacer must not return null values");
| 177
| 33
| 210
|
<methods>public non-sealed void <init>() ,public io.crate.expression.symbol.Symbol visitAlias(io.crate.expression.symbol.AliasSymbol, Function<? super io.crate.metadata.Reference,? extends io.crate.expression.symbol.Symbol>) ,public io.crate.expression.symbol.Symbol visitDynamicReference(io.crate.expression.symbol.DynamicReference, Function<? super io.crate.metadata.Reference,? extends io.crate.expression.symbol.Symbol>) ,public io.crate.expression.symbol.Symbol visitFetchMarker(io.crate.expression.symbol.FetchMarker, Function<? super io.crate.metadata.Reference,? extends io.crate.expression.symbol.Symbol>) ,public io.crate.expression.symbol.Symbol visitFetchStub(io.crate.expression.symbol.FetchStub, Function<? super io.crate.metadata.Reference,? extends io.crate.expression.symbol.Symbol>) ,public io.crate.expression.symbol.Symbol visitFunction(io.crate.expression.symbol.Function, Function<? super io.crate.metadata.Reference,? extends io.crate.expression.symbol.Symbol>) ,public io.crate.expression.symbol.Symbol visitMatchPredicate(io.crate.expression.symbol.MatchPredicate, Function<? super io.crate.metadata.Reference,? extends io.crate.expression.symbol.Symbol>) ,public io.crate.expression.symbol.Symbol visitWindowFunction(io.crate.expression.symbol.WindowFunction, Function<? super io.crate.metadata.Reference,? extends io.crate.expression.symbol.Symbol>) <variables>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/symbol/format/MatchPrinter.java
|
MatchPrinter
|
printProperties
|
class MatchPrinter {
private MatchPrinter() {}
public static void printMatchPredicate(Function matchPredicate, Style style, StringBuilder sb) {
List<Symbol> arguments = matchPredicate.arguments();
sb.append("MATCH((");
printColumns(arguments.get(0), sb);
sb.append("), ");
// second argument (keyword)
sb.append(arguments.get(1).toString(style));
sb.append(") USING ");
// third argument (method)
// need to print as identifier without quotes
sb.append((String) ((Literal<?>) arguments.get(2)).value());
printProperties(arguments.get(3), sb);
}
@SuppressWarnings("unchecked")
private static void printColumns(Symbol cols, StringBuilder sb) {
// first argument (cols)
var columnBootMap = (Map<String, Object>) ((Literal<?>) cols).value();
Iterator<Map.Entry<String, Object>> entryIterator = columnBootMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<String, Object> entry = entryIterator.next();
sb.append(entry.getKey());
Object boost = entry.getValue();
if (boost != null) {
sb
.append(" ")
.append(boost);
}
if (entryIterator.hasNext()) {
sb.append(", ");
}
}
}
private static void printProperties(Symbol propSymbol, StringBuilder sb) {<FILL_FUNCTION_BODY>}
}
|
// fourth argument (properties)
var properties = (Map<?, ?>) ((Literal<?>) propSymbol).value();
if (properties.isEmpty()) {
return;
}
sb.append(" WITH (");
var it = properties.entrySet().iterator();
while (it.hasNext()) {
var entry = it.next();
sb.append(entry.getKey()).append(" = ");
Object value = entry.getValue();
if (value != null) {
sb.append("'");
sb.append(value);
sb.append("'");
}
if (it.hasNext()) {
sb.append(", ");
}
}
sb.append(")");
| 402
| 183
| 585
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/tablefunctions/GenerateSubscripts.java
|
GenerateSubscripts
|
getNumRows
|
class GenerateSubscripts<T> extends TableFunctionImplementation<T> {
public static final FunctionName NAME = new FunctionName(PgCatalogSchemaInfo.NAME, "generate_subscripts");
private static final RowType RETURN_TYPE = new RowType(List.of(INTEGER), List.of(NAME.name()));
public static void register(Functions.Builder builder) {
builder.add(
Signature.table(
NAME,
TypeSignature.parse("array(E)"),
DataTypes.INTEGER.getTypeSignature(),
DataTypes.INTEGER.getTypeSignature()
).withTypeVariableConstraints(typeVariable("E"))
.withFeature(Feature.NON_NULLABLE),
GenerateSubscripts::new
);
builder.add(
Signature.table(
NAME,
TypeSignature.parse("array(E)"),
DataTypes.INTEGER.getTypeSignature(),
DataTypes.BOOLEAN.getTypeSignature(),
DataTypes.INTEGER.getTypeSignature()
).withTypeVariableConstraints(typeVariable("E"))
.withFeature(Feature.NON_NULLABLE),
GenerateSubscripts::new
);
}
private GenerateSubscripts(Signature signature, BoundSignature boundSignature) {
super(signature, boundSignature);
}
private static int getNumRows(List<?> array, int depthLevel) {<FILL_FUNCTION_BODY>}
@SafeVarargs
@Override
public final Iterable<Row> evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<T>... args) {
assert args.length == 2 || args.length == 3 :
"Signature must ensure that there are either two or three arguments";
List<?> array = (List<?>) args[0].value();
Integer dim = (Integer) args[1].value();
if (array == null || array.isEmpty() || dim == null) {
return List.of();
}
int numRows = getNumRows(array, dim);
if (numRows == 0) {
return List.of();
}
Boolean rev = null;
if (args.length == 3) {
rev = (Boolean) args[2].value();
}
boolean reversed = rev != null && rev.booleanValue();
int startInclusive = reversed ? numRows : 1;
int stopInclusive = reversed ? 1 : numRows;
int step = reversed ? -1 : 1;
return new RangeIterable<>(
startInclusive,
stopInclusive,
value -> value + step,
Integer::compareTo,
i -> i
);
}
@Override
public RowType returnType() {
return RETURN_TYPE;
}
@Override
public boolean hasLazyResultSet() {
return true;
}
}
|
if (depthLevel <= 0) {
throw new IllegalArgumentException("target level must be greater than zero");
}
List<?> targetArray = array;
for (int level = 2; level <= depthLevel; level++) {
if (targetArray == null || targetArray.isEmpty()) {
return 0;
}
int size = -1;
List<?> firstNonNullElement = null;
for (int i = 0; i < targetArray.size(); i++) {
Object oi = targetArray.get(i);
if (oi == null) {
// null is a valid value within an array
continue;
}
if (!(oi instanceof List)) {
return 0;
}
List<?> element = (List<?>) oi;
if (size == -1) {
size = element.size();
} else {
if (size != element.size()) {
throw new IllegalArgumentException(String.format(
Locale.ENGLISH,
"nested arrays must have the same dimension within a level, offending level %d, position %d",
level, i + 1));
}
}
if (firstNonNullElement == null) {
firstNonNullElement = element;
}
}
targetArray = firstNonNullElement;
}
return targetArray != null ? targetArray.size() : 0;
| 732
| 353
| 1,085
|
<methods>public abstract boolean hasLazyResultSet() ,public io.crate.expression.symbol.Symbol normalizeSymbol(io.crate.expression.symbol.Function, io.crate.metadata.TransactionContext, io.crate.metadata.NodeContext) ,public abstract io.crate.types.RowType returnType() <variables>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/tablefunctions/TableFunctionFactory.java
|
TableFunctionFactory
|
from
|
class TableFunctionFactory {
public static TableFunctionImplementation<?> from(FunctionImplementation functionImplementation) {<FILL_FUNCTION_BODY>}
/**
* Evaluates the {@link Scalar} function and emits scalar result as a 1x1 table
*/
private static class ScalarTableFunctionImplementation<T> extends TableFunctionImplementation<T> {
private final Scalar<?, T> functionImplementation;
private final RowType returnType;
private ScalarTableFunctionImplementation(Scalar<?, T> functionImplementation) {
super(
Signature.table(
functionImplementation.signature().getName(),
Lists.concat(
functionImplementation.signature().getArgumentTypes(),
functionImplementation.signature().getReturnType()
).toArray(new TypeSignature[0])
),
new BoundSignature(
functionImplementation.boundSignature().argTypes(),
functionImplementation.boundSignature().returnType()
)
);
this.functionImplementation = functionImplementation;
var boundReturnType = functionImplementation.boundSignature().returnType();
returnType = new RowType(
List.of(boundReturnType),
List.of(functionImplementation.signature().getName().name())
);
}
@Override
public Iterable<Row> evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<T>[] args) {
return List.of(new Row1(functionImplementation.evaluate(txnCtx, nodeCtx, args)));
}
@Override
public RowType returnType() {
return returnType;
}
@Override
public boolean hasLazyResultSet() {
return true;
}
}
}
|
TableFunctionImplementation<?> tableFunction;
switch (functionImplementation.signature().getKind()) {
case TABLE:
tableFunction = (TableFunctionImplementation<?>) functionImplementation;
break;
case SCALAR:
tableFunction = new ScalarTableFunctionImplementation<>((Scalar<?, ?>) functionImplementation);
break;
case WINDOW:
case AGGREGATE:
throw new UnsupportedOperationException(
String.format(
Locale.ENGLISH,
"Window or Aggregate function: '%s' is not allowed in function in FROM clause",
functionImplementation.signature().getName().displayName()));
default:
throw new UnsupportedOperationException(
String.format(
Locale.ENGLISH,
"Unknown type function: '%s' is not allowed in function in FROM clause",
functionImplementation.signature().getName().displayName()));
}
return tableFunction;
| 435
| 235
| 670
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/expression/udf/UserDefinedFunctionsMetadata.java
|
UserDefinedFunctionsMetadata
|
equals
|
class UserDefinedFunctionsMetadata extends AbstractNamedDiffable<Metadata.Custom> implements Metadata.Custom {
public static final String TYPE = "user_defined_functions";
private final List<UserDefinedFunctionMetadata> functionsMetadata;
private UserDefinedFunctionsMetadata(List<UserDefinedFunctionMetadata> functions) {
this.functionsMetadata = functions;
}
public static UserDefinedFunctionsMetadata newInstance(UserDefinedFunctionsMetadata instance) {
return new UserDefinedFunctionsMetadata(new ArrayList<>(instance.functionsMetadata));
}
@VisibleForTesting
public static UserDefinedFunctionsMetadata of(UserDefinedFunctionMetadata... functions) {
return new UserDefinedFunctionsMetadata(Arrays.asList(functions));
}
public void add(UserDefinedFunctionMetadata function) {
functionsMetadata.add(function);
}
public void replace(UserDefinedFunctionMetadata function) {
for (int i = 0; i < functionsMetadata.size(); i++) {
if (functionsMetadata.get(i).sameSignature(function.schema(), function.name(), function.argumentTypes())) {
functionsMetadata.set(i, function);
}
}
}
public boolean contains(String schema, String name, List<DataType<?>> types) {
for (UserDefinedFunctionMetadata function : functionsMetadata) {
if (function.sameSignature(schema, name, types)) {
return true;
}
}
return false;
}
public void remove(String schema, String name, List<DataType<?>> types) {
for (ListIterator<UserDefinedFunctionMetadata> iter = functionsMetadata.listIterator(); iter.hasNext(); ) {
if (iter.next().sameSignature(schema, name, types)) {
iter.remove();
}
}
}
public List<UserDefinedFunctionMetadata> functionsMetadata() {
return functionsMetadata;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVInt(functionsMetadata.size());
for (UserDefinedFunctionMetadata function : functionsMetadata) {
function.writeTo(out);
}
}
public UserDefinedFunctionsMetadata(StreamInput in) throws IOException {
int size = in.readVInt();
List<UserDefinedFunctionMetadata> functions = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
functions.add(new UserDefinedFunctionMetadata(in));
}
this.functionsMetadata = functions;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startArray("functions");
for (UserDefinedFunctionMetadata function : functionsMetadata) {
function.toXContent(builder, params);
}
builder.endArray();
return builder;
}
public static UserDefinedFunctionsMetadata fromXContent(XContentParser parser) throws IOException {
List<UserDefinedFunctionMetadata> functions = new ArrayList<>();
while (parser.nextToken() != XContentParser.Token.END_OBJECT) {
if (parser.currentToken() == XContentParser.Token.FIELD_NAME && Objects.equals(parser.currentName(), "functions")) {
if (parser.nextToken() == XContentParser.Token.START_ARRAY) {
while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
functions.add(UserDefinedFunctionMetadata.fromXContent(parser));
}
}
}
}
return new UserDefinedFunctionsMetadata(functions);
}
@Override
public EnumSet<Metadata.XContentContext> context() {
return EnumSet.of(Metadata.XContentContext.GATEWAY, Metadata.XContentContext.SNAPSHOT);
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(functionsMetadata);
}
@Override
public String getWriteableName() {
return TYPE;
}
@Override
public Version getMinimalSupportedVersion() {
return Version.V_3_0_1;
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserDefinedFunctionsMetadata that = (UserDefinedFunctionsMetadata) o;
return functionsMetadata.equals(that.functionsMetadata);
| 1,071
| 69
| 1,140
|
<methods>public non-sealed void <init>() ,public Diff<org.elasticsearch.cluster.metadata.Metadata.Custom> diff(org.elasticsearch.cluster.metadata.Metadata.Custom) ,public org.elasticsearch.cluster.metadata.Metadata.Custom get() ,public static NamedDiff<T> readDiffFrom(Class<? extends T>, java.lang.String, org.elasticsearch.common.io.stream.StreamInput) throws java.io.IOException<variables>
|
crate_crate
|
crate/server/src/main/java/io/crate/fdw/AddServerTask.java
|
AddServerTask
|
execute
|
class AddServerTask extends AckedClusterStateUpdateTask<AcknowledgedResponse> {
private final ForeignDataWrappers foreignDataWrappers;
private final CreateServerRequest request;
public AddServerTask(ForeignDataWrappers foreignDataWrappers, CreateServerRequest request) {
super(Priority.NORMAL, request);
this.foreignDataWrappers = foreignDataWrappers;
this.request = request;
}
@Override
protected AcknowledgedResponse newResponse(boolean acknowledged) {
return new AcknowledgedResponse(acknowledged);
}
@Override
public ClusterState execute(ClusterState currentState) throws Exception {<FILL_FUNCTION_BODY>}
}
|
if (!foreignDataWrappers.contains(request.fdw())) {
throw new IllegalArgumentException(
"foreign-data wrapper " + request.fdw() + " does not exist");
}
ServersMetadata serversMetadata = currentState.metadata().custom(
ServersMetadata.TYPE,
ServersMetadata.EMPTY
);
String serverName = request.name();
if (serversMetadata.contains(serverName)) {
if (request.ifNotExists()) {
return currentState;
}
throw new ServerAlreadyExistsException(serverName);
}
var newServersMetadata = serversMetadata.add(
serverName,
request.fdw(),
request.owner(),
request.options()
);
return ClusterState.builder(currentState)
.metadata(
Metadata.builder(currentState.metadata())
.putCustom(ServersMetadata.TYPE, newServersMetadata)
)
.build();
| 184
| 242
| 426
|
<methods>public io.crate.common.unit.TimeValue ackTimeout() ,public CompletableFuture<org.elasticsearch.action.support.master.AcknowledgedResponse> completionFuture() ,public boolean mustAck(org.elasticsearch.cluster.node.DiscoveryNode) ,public void onAckTimeout() ,public void onAllNodesAcked(java.lang.Exception) ,public void onFailure(java.lang.String, java.lang.Exception) ,public io.crate.common.unit.TimeValue timeout() <variables>private final non-sealed CompletableFuture<org.elasticsearch.action.support.master.AcknowledgedResponse> future,private final non-sealed org.elasticsearch.cluster.ack.AckedRequest request
|
crate_crate
|
crate/server/src/main/java/io/crate/fdw/AddUserMappingTask.java
|
AddUserMappingTask
|
execute
|
class AddUserMappingTask extends AckedClusterStateUpdateTask<AcknowledgedResponse> {
private final CreateUserMappingRequest request;
AddUserMappingTask(CreateUserMappingRequest request) {
super(Priority.NORMAL, request);
this.request = request;
}
@Override
protected AcknowledgedResponse newResponse(boolean acknowledged) {
return new AcknowledgedResponse(acknowledged);
}
@Override
public ClusterState execute(ClusterState currentState) throws Exception {<FILL_FUNCTION_BODY>}
}
|
ServersMetadata serversMetadata = currentState.metadata().custom(ServersMetadata.TYPE);
if (serversMetadata == null) {
throw new ResourceNotFoundException(String.format(
Locale.ENGLISH,
"Server `%s` not found",
request.server()
));
}
var updatedServersMetadata = serversMetadata.addUser(
request.server(),
request.ifNotExists(),
request.userName(),
request.options()
);
if (updatedServersMetadata == serversMetadata) {
return currentState;
}
return ClusterState.builder(currentState)
.metadata(
Metadata.builder(currentState.metadata())
.putCustom(ServersMetadata.TYPE, updatedServersMetadata)
)
.build();
| 143
| 199
| 342
|
<methods>public io.crate.common.unit.TimeValue ackTimeout() ,public CompletableFuture<org.elasticsearch.action.support.master.AcknowledgedResponse> completionFuture() ,public boolean mustAck(org.elasticsearch.cluster.node.DiscoveryNode) ,public void onAckTimeout() ,public void onAllNodesAcked(java.lang.Exception) ,public void onFailure(java.lang.String, java.lang.Exception) ,public io.crate.common.unit.TimeValue timeout() <variables>private final non-sealed CompletableFuture<org.elasticsearch.action.support.master.AcknowledgedResponse> future,private final non-sealed org.elasticsearch.cluster.ack.AckedRequest request
|
crate_crate
|
crate/server/src/main/java/io/crate/fdw/ForeignDataWrappers.java
|
ForeignDataWrappers
|
getIterator
|
class ForeignDataWrappers implements CollectSource {
public static Setting<Boolean> ALLOW_LOCAL = Setting.boolSetting(
"fdw.allow_local",
false,
Property.NodeScope,
Property.Exposed
);
private final ClusterService clusterService;
private final InputFactory inputFactory;
private final Map<String, ForeignDataWrapper> wrappers;
private final Roles roles;
@Inject
public ForeignDataWrappers(Settings settings,
ClusterService clusterService,
NodeContext nodeContext) {
this.clusterService = clusterService;
this.inputFactory = new InputFactory(nodeContext);
this.wrappers = Map.of(
"jdbc", new JdbcForeignDataWrapper(settings, inputFactory)
);
this.roles = nodeContext.roles();
}
public boolean contains(String fdw) {
return wrappers.containsKey(fdw);
}
public ForeignDataWrapper get(String fdw) {
var foreignDataWrapper = wrappers.get(fdw);
if (foreignDataWrapper == null) {
throw new IllegalArgumentException(
"foreign-data wrapper " + fdw + " does not exist");
}
return foreignDataWrapper;
}
@Override
public CompletableFuture<BatchIterator<Row>> getIterator(TransactionContext txnCtx,
CollectPhase collectPhase,
CollectTask collectTask,
boolean supportMoveToStart) {<FILL_FUNCTION_BODY>}
}
|
if (!(collectPhase instanceof ForeignCollectPhase phase)) {
throw new IllegalArgumentException(
"ForeignDataWrappers requires ForeignCollectPhase, not: " + collectPhase);
}
Metadata metadata = clusterService.state().metadata();
ForeignTablesMetadata foreignTables = metadata.custom(ForeignTablesMetadata.TYPE);
if (foreignTables == null) {
throw new RelationUnknown(phase.relationName());
}
ForeignTable foreignTable = foreignTables.get(phase.relationName());
if (foreignTable == null) {
throw new RelationUnknown(phase.relationName());
}
ServersMetadata servers = metadata.custom(ServersMetadata.TYPE);
if (servers == null) {
throw new ResourceNotFoundException(
String.format(Locale.ENGLISH, "Server `%s` not found", foreignTable.server()));
}
Server server = servers.get(foreignTable.server());
ForeignDataWrapper fdw = wrappers.get(server.fdw());
if (fdw == null) {
throw new ResourceNotFoundException(String.format(
Locale.ENGLISH,
"Foreign data wrapper '%s' used by server '%s' no longer exists",
server.fdw(),
foreignTable.server()
));
}
return fdw.getIterator(
requireNonNull(roles.findUser(txnCtx.sessionSettings().userName()), "current user must exit"),
server,
foreignTable,
txnCtx,
collectPhase.toCollect(),
phase.query()
);
| 393
| 404
| 797
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/fdw/ForeignTableRelation.java
|
ForeignTableRelation
|
getField
|
class ForeignTableRelation extends AbstractTableRelation<ForeignTable> {
public ForeignTableRelation(ForeignTable table) {
super(table, List.copyOf(table.columns()), List.of());
}
@Override
public <C, R> R accept(AnalyzedRelationVisitor<C, R> visitor, C context) {
return visitor.visitForeignTable(this, context);
}
@Override
@Nullable
public Symbol getField(ColumnIdent column,
Operation operation,
boolean errorOnUnknownObjectKey)
throws AmbiguousColumnException, ColumnUnknownException, UnsupportedOperationException {<FILL_FUNCTION_BODY>}
}
|
if (operation != Operation.READ) {
throw new UnsupportedOperationException("Cannot write or delete on foreign tables");
}
Reference reference = tableInfo.getReadReference(column);
if (reference == null) {
throw new ColumnUnknownException(column, tableInfo.name());
}
return reference;
| 171
| 82
| 253
|
<methods>public void <init>(ForeignTable, List<io.crate.expression.symbol.Symbol>, List<io.crate.expression.symbol.Symbol>) ,public boolean equals(java.lang.Object) ,public io.crate.metadata.Reference getField(io.crate.metadata.ColumnIdent) ,public int hashCode() ,public List<io.crate.expression.symbol.Symbol> hiddenOutputs() ,public List<io.crate.expression.symbol.Symbol> outputs() ,public io.crate.metadata.RelationName relationName() ,public io.crate.metadata.Reference resolveField(io.crate.expression.symbol.ScopedSymbol) ,public ForeignTable tableInfo() ,public java.lang.String toString() <variables>private final non-sealed List<io.crate.expression.symbol.Symbol> hiddenOutputs,private final non-sealed List<io.crate.expression.symbol.Symbol> outputs,protected final non-sealed ForeignTable tableInfo
|
crate_crate
|
crate/server/src/main/java/io/crate/fdw/TransportDropUserMapping.java
|
Action
|
masterOperation
|
class Action extends ActionType<AcknowledgedResponse> {
public static final String NAME = "internal:crate:sql/fdw/user/drop";
private Action() {
super(NAME);
}
}
@Inject
public TransportDropUserMapping(TransportService transportService,
ClusterService clusterService,
ThreadPool threadPool) {
super(
ACTION.name(),
transportService,
clusterService,
threadPool,
DropUserMappingRequest::new
);
}
@Override
protected String executor() {
return ThreadPool.Names.SAME;
}
@Override
protected AcknowledgedResponse read(StreamInput in) throws IOException {
return new AcknowledgedResponse(in);
}
@Override
protected void masterOperation(DropUserMappingRequest request,
ClusterState state,
ActionListener<AcknowledgedResponse> listener) throws Exception {<FILL_FUNCTION_BODY>
|
if (state.nodes().getMinNodeVersion().before(Version.V_5_7_0)) {
throw new IllegalStateException(
"Cannot execute DROP USER MAPPING while there are <5.7.0 nodes in the cluster");
}
DropUserMappingTask updateTask = new DropUserMappingTask(request);
updateTask.completionFuture().whenComplete(listener);
clusterService.submitStateUpdateTask("drop_user_mapping", updateTask);
| 247
| 117
| 364
|
<methods><variables>protected final non-sealed org.elasticsearch.cluster.service.ClusterService clusterService,private final non-sealed java.lang.String executor,protected final non-sealed org.elasticsearch.threadpool.ThreadPool threadPool,protected final non-sealed org.elasticsearch.transport.TransportService transportService
|
crate_crate
|
crate/server/src/main/java/io/crate/interval/NumericalIntervalParser.java
|
NumericalIntervalParser
|
roundToPrecision
|
class NumericalIntervalParser {
private NumericalIntervalParser() {
}
static Period apply(String value,
@Nullable IntervalParser.Precision start,
@Nullable IntervalParser.Precision end) {
try {
return roundToPrecision(parseInteger(value), parseMilliSeconds(value), start, end);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid interval format: " + value);
}
}
private static Period roundToPrecision(int value,
int millis,
@Nullable IntervalParser.Precision start,
@Nullable IntervalParser.Precision end) {<FILL_FUNCTION_BODY>}
private static int parseInteger(String value) {
BigInteger result = new BigDecimal(value).toBigInteger();
if (result.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0 ||
result.compareTo(BigInteger.valueOf(Integer.MIN_VALUE)) < 0) {
throw new ArithmeticException("Interval field value out of range " + value);
}
return result.intValue();
}
private static Period buildSecondsWithMillisPeriod(int seconds, int millis) {
Period period = Period.seconds(seconds);
if (millis != 0) {
period = period.withMillis(millis);
}
return period;
}
}
|
if (start == null && end == null) {
return buildSecondsWithMillisPeriod(value, millis);
}
if (start == IntervalParser.Precision.YEAR) {
if (end == null) {
return Period.years(value);
}
if (end == IntervalParser.Precision.MONTH) {
return Period.months(value);
}
}
if (start == IntervalParser.Precision.MONTH && end == null) {
return Period.months(value);
}
if (start == IntervalParser.Precision.DAY) {
if (end == null) {
return Period.days(value);
}
if (end == IntervalParser.Precision.HOUR) {
return Period.hours(value);
}
if (end == IntervalParser.Precision.MINUTE) {
return Period.minutes(value);
}
if (end == IntervalParser.Precision.SECOND) {
return buildSecondsWithMillisPeriod(value, millis);
}
}
if (start == IntervalParser.Precision.HOUR) {
if (end == null) {
return Period.hours(value);
}
if (end == IntervalParser.Precision.MINUTE) {
return Period.minutes(value);
}
if (end == IntervalParser.Precision.SECOND) {
return buildSecondsWithMillisPeriod(value, millis);
}
}
if (start == IntervalParser.Precision.MINUTE) {
if (end == null) {
return Period.minutes(value);
}
if (end == IntervalParser.Precision.SECOND) {
return Period.seconds(value);
}
}
if (start == IntervalParser.Precision.SECOND && end == null) {
return buildSecondsWithMillisPeriod(value, millis);
}
throw new IllegalArgumentException("Invalid start and end combination");
| 357
| 512
| 869
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/interval/PGIntervalParser.java
|
PGIntervalParser
|
apply
|
class PGIntervalParser {
private PGIntervalParser() {}
static Period apply(String value,
@Nullable IntervalParser.Precision start,
@Nullable IntervalParser.Precision end) {
return roundToPrecision(apply(value), start, end);
}
static Period apply(String value) {<FILL_FUNCTION_BODY>}
private static int firstCharacterInStr(String token) {
for (int i = 0; i < token.length(); i++) {
if (Character.isLetter(token.charAt(i))) {
return i;
}
}
return -1;
}
private static int parseInteger(String value) {
return new BigDecimal(value).intValue();
}
}
|
String strInterval = value.trim().toLowerCase(Locale.ENGLISH);
final boolean ISOFormat = !strInterval.startsWith("@");
final boolean hasAgo = strInterval.endsWith("ago");
strInterval = strInterval
.replace("+", "")
.replace("@", "")
.replace("ago", "")
.trim();
// Just a simple '0'
if (!ISOFormat && value.length() == 3 && value.charAt(2) == '0') {
return new Period();
}
int years = 0;
int months = 0;
int days = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
int milliSeconds = 0;
boolean weeksParsed = false;
boolean daysParsed = false;
try {
String unitToken = null;
String valueToken;
boolean timeParsed = false;
final StringTokenizer st = new StringTokenizer(strInterval);
while (st.hasMoreTokens()) {
String token = st.nextToken();
int firstCharIdx = firstCharacterInStr(token);
if (firstCharIdx > 0) { // value next to unit, e.g.: '1year'
valueToken = token.substring(0, firstCharIdx);
unitToken = token.substring(firstCharIdx);
} else { // value and unit separated with whitespace, e.g.: '1 year'
valueToken = token;
if (st.hasMoreTokens()) {
unitToken = st.nextToken();
}
}
int endHours = token.indexOf(':');
if (endHours > 0) {
if (timeParsed) {
throw new IllegalArgumentException("Invalid interval format: " + value);
}
// This handles hours, minutes, seconds and microseconds for
// ISO intervals
int offset = (token.charAt(0) == '-') ? 1 : 0;
hours = nullSafeIntGet(token.substring(offset, endHours));
minutes = nullSafeIntGet(token.substring(endHours + 1, endHours + 3));
int endMinutes = token.indexOf(':', endHours + 1);
seconds = parseInteger(token.substring(endMinutes + 1));
milliSeconds = parseMilliSeconds(token.substring(endMinutes + 1));
if (offset == 1) {
hours = -hours;
minutes = -minutes;
seconds = -seconds;
milliSeconds = -milliSeconds;
}
timeParsed = true;
} else {
if (unitToken == null) {
throw new IllegalArgumentException("Invalid interval format: " + value);
}
}
// This handles years, months, days for both, ISO and
// Non-ISO intervals. Hours, minutes, seconds and microseconds
// are handled for Non-ISO intervals here.
if (unitToken != null) {
switch (unitToken) {
case "year", "years", "y" -> {
if (years > 0) {
throw new IllegalArgumentException("Invalid interval format: " + value);
}
years = nullSafeIntGet(valueToken);
}
case "month", "months", "mon", "mons" -> {
if (months > 0) {
throw new IllegalArgumentException("Invalid interval format: " + value);
}
months = nullSafeIntGet(valueToken);
}
case "day", "days", "d" -> {
if (daysParsed) {
throw new IllegalArgumentException("Invalid interval format: " + value);
}
days += nullSafeIntGet(valueToken);
daysParsed = true;
}
case "week", "weeks", "w" -> {
if (weeksParsed) {
throw new IllegalArgumentException("Invalid interval format: " + value);
}
days += nullSafeIntGet(valueToken) * 7;
weeksParsed = true;
}
case "hour", "hours", "h" -> {
if (hours > 0) {
throw new IllegalArgumentException("Invalid interval format: " + value);
}
hours = nullSafeIntGet(valueToken);
timeParsed = true;
}
case "min", "mins", "minute", "minutes", "m" -> {
if (minutes > 0) {
throw new IllegalArgumentException("Invalid interval format: " + value);
}
minutes = nullSafeIntGet(valueToken);
timeParsed = true;
}
case "sec", "secs", "second", "seconds", "s" -> {
if (seconds > 0 || milliSeconds > 0) {
throw new IllegalArgumentException("Invalid interval format: " + value);
}
seconds = parseInteger(valueToken);
milliSeconds = parseMilliSeconds(valueToken);
timeParsed = true;
}
default -> throw new IllegalArgumentException("Invalid interval format: " + value);
}
}
unitToken = null;
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid interval format: " + value);
}
Period period = new Period(years, months, 0, days, hours, minutes, seconds, milliSeconds);
if (!ISOFormat && hasAgo) {
// Inverse the leading sign
period = period.negated();
}
return period;
| 197
| 1,398
| 1,595
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/interval/SQLStandardIntervalParser.java
|
SQLStandardIntervalParser
|
apply
|
class SQLStandardIntervalParser {
private enum ParserState {
NOTHING_PARSED,
HMS_PARSED,
SECOND_PARSED,
DAYS_PARSED,
YEAR_MONTH_PARSED
}
static Period apply(String value,
@Nullable IntervalParser.Precision start,
@Nullable IntervalParser.Precision end) {
return roundToPrecision(apply(value), start, end);
}
static Period apply(String value) {<FILL_FUNCTION_BODY>}
private static final Pattern YEAR_MONTH_PATTERN = Pattern.compile("-?\\d{1,9}-\\d{1,9}");
}
|
String[] values = value.split(" ");
if (values.length > 3 || values.length == 0) {
throw new IllegalArgumentException("Invalid interval format: " + value);
}
ParserState state = ParserState.NOTHING_PARSED;
boolean negative = false;
int years = 0;
int months = 0;
int days = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
try {
String part;
// Parse from backwards
for (int i = values.length - 1; i >= 0; i--) {
part = values[i];
if (part.isBlank()) {
continue;
}
if (part.startsWith("-")) {
negative = true;
part = part.substring(1);
}
if (part.startsWith("+")) {
part = part.substring(1);
}
if (part.contains(":")) {
// H:M:S: Using a single value defines seconds only
// Using two values defines hours and minutes.
String[] hms = part.split(":");
if (hms.length == 3) {
hours = nullSafeIntGet(hms[0]);
minutes = nullSafeIntGet(hms[1]);
seconds = nullSafeIntGet(hms[2]);
} else if (hms.length == 2) {
hours = nullSafeIntGet(hms[0]);
minutes = nullSafeIntGet(hms[1]);
} else if (hms.length == 1) {
seconds = nullSafeIntGet(hms[0]);
} else {
throw new IllegalArgumentException("Invalid interval format: " + value);
}
if (negative) {
hours = -hours;
minutes = -minutes;
seconds = -seconds;
negative = false;
}
state = ParserState.HMS_PARSED;
} else if (part.contains("-")) {
//YEAR-MONTH
String[] ym = part.split("-");
if (ym.length == 2) {
years = nullSafeIntGet(ym[0]);
months = nullSafeIntGet(ym[1]);
} else {
throw new IllegalArgumentException("Invalid interval format: " + value);
}
if (negative) {
years = -years;
months = -months;
negative = false;
}
state = ParserState.YEAR_MONTH_PARSED;
} else if (state == ParserState.NOTHING_PARSED) {
// Trying to parse days or second by looking ahead
// and trying to guess what the next value is
int number = nullSafeIntGet(part);
if (i - 1 >= 0) {
String next = values[i - 1];
if (YEAR_MONTH_PATTERN.matcher(next).matches()) {
days = number;
if (negative) {
days = -days;
negative = false;
}
state = ParserState.DAYS_PARSED;
} else {
//Invalid day/second only combination
throw new IllegalArgumentException("Invalid interval format: " + value);
}
} else {
seconds = number;
if (negative) {
seconds = -seconds;
negative = false;
}
state = ParserState.SECOND_PARSED;
}
} else if (state == ParserState.HMS_PARSED) {
days = nullSafeIntGet(part);
if (negative) {
days = -days;
negative = false;
}
state = ParserState.DAYS_PARSED;
} else if (state == ParserState.SECOND_PARSED) {
//Invalid day second combination
throw new IllegalArgumentException("Invalid interval format: " + value);
}
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid interval format: " + value);
}
if (ParserState.NOTHING_PARSED == state) {
throw new IllegalArgumentException("Invalid interval format: " + value);
}
return new Period(years, months, 0, days, hours, minutes, seconds, 0);
| 185
| 1,074
| 1,259
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/lucene/GenericFunctionQuery.java
|
GenericFunctionQuery
|
explain
|
class GenericFunctionQuery extends Query {
private final Function function;
private final LuceneCollectorExpression[] expressions;
private final Input<Boolean> condition;
GenericFunctionQuery(Function function,
Collection<? extends LuceneCollectorExpression<?>> expressions,
Input<Boolean> condition) {
this.function = function;
// inner loop iterates over expressions - call toArray to avoid iterator allocations
this.expressions = expressions.toArray(new LuceneCollectorExpression[0]);
this.condition = condition;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GenericFunctionQuery that = (GenericFunctionQuery) o;
return function.equals(that.function);
}
@Override
public int hashCode() {
return function.hashCode();
}
@Override
public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
return new Weight(this) {
@Override
public boolean isCacheable(LeafReaderContext ctx) {
if (SymbolVisitors.any(s -> s instanceof Function fn && !fn.signature().isDeterministic(), function)) {
return false;
}
var fields = new ArrayList<String>();
RefVisitor.visitRefs(function, ref -> fields.add(ref.storageIdent()));
return DocValues.isCacheable(ctx, fields.toArray(new String[0]));
}
@Override
public Explanation explain(LeafReaderContext context, int doc) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
return new ConstantScoreScorer(this, 0f, scoreMode, getTwoPhaseIterator(context));
}
};
}
@Override
public void visit(QueryVisitor visitor) {
}
private FilteredTwoPhaseIterator getTwoPhaseIterator(final LeafReaderContext context) throws IOException {
for (LuceneCollectorExpression<?> expression : expressions) {
expression.setNextReader(new ReaderContext(context));
}
return new FilteredTwoPhaseIterator(context.reader(), condition, expressions);
}
@Override
public String toString(String field) {
return function.toString();
}
private static class FilteredTwoPhaseIterator extends TwoPhaseIterator {
private final Input<Boolean> condition;
private final LuceneCollectorExpression[] expressions;
private final Bits liveDocs;
FilteredTwoPhaseIterator(LeafReader reader,
Input<Boolean> condition,
LuceneCollectorExpression[] expressions) {
super(DocIdSetIterator.all(reader.maxDoc()));
this.liveDocs = reader.getLiveDocs() == null
? new Bits.MatchAllBits(reader.maxDoc())
: reader.getLiveDocs();
this.condition = condition;
this.expressions = expressions;
}
@Override
public boolean matches() throws IOException {
int doc = approximation.docID();
if (!liveDocs.get(doc)) {
return false;
}
for (LuceneCollectorExpression<?> expression : expressions) {
expression.setNextDocId(doc);
}
return InputCondition.matches(condition);
}
@Override
public float matchCost() {
// Arbitrary number, we don't have a way to get the cost of the condition
return 10;
}
}
}
|
final Scorer s = scorer(context);
final boolean match;
final TwoPhaseIterator twoPhase = s.twoPhaseIterator();
if (twoPhase == null) {
match = s.iterator().advance(doc) == doc;
} else {
match = twoPhase.approximation().advance(doc) == doc && twoPhase.matches();
}
if (match) {
assert s.score() == 0f : "score must be 0";
return Explanation.match(0f, "Match on id " + doc);
} else {
return Explanation.match(0f, "No match on id " + doc);
}
| 924
| 175
| 1,099
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/lucene/LuceneQueryBuilder.java
|
Visitor
|
visitFunction
|
class Visitor extends SymbolVisitor<Context, Query> {
@Override
public Query visitFunction(Function function, Context context) {<FILL_FUNCTION_BODY>}
private Query queryFromInnerFunction(Function parent, Context context) {
for (Symbol arg : parent.arguments()) {
if (arg instanceof Function inner) {
FunctionImplementation implementation = context.nodeContext.functions().getQualified(inner);
Query query = implementation instanceof FunctionToQuery funcToQuery
? funcToQuery.toQuery(parent, inner, context)
: null;
if (query != null) {
return query;
}
}
}
return null;
}
private static boolean fieldIgnored(Function function, Context context) {
if (function.arguments().size() != 2) {
return false;
}
Symbol left = function.arguments().get(0);
Symbol right = function.arguments().get(1);
if (left.symbolType() == SymbolType.REFERENCE && right.symbolType().isValueSymbol()) {
String columnName = ((Reference) left).column().name();
if (Context.FILTERED_FIELDS.contains(columnName)) {
context.filteredFieldValues.put(columnName, ((Input<?>) right).value());
return true;
}
String unsupportedMessage = Context.UNSUPPORTED_FIELDS.get(columnName);
if (unsupportedMessage != null) {
throw new UnsupportedFeatureException(unsupportedMessage);
}
}
return false;
}
private static Function rewriteAndValidateFields(Function function, Context context) {
List<Symbol> arguments = function.arguments();
if (arguments.size() == 2) {
Symbol left = arguments.get(0);
Symbol right = arguments.get(1);
if (left.symbolType() == SymbolType.REFERENCE && right.symbolType().isValueSymbol()) {
Reference ref = (Reference) left;
if (ref.column().equals(DocSysColumns.UID)) {
return new Function(
function.signature(),
List.of(DocSysColumns.forTable(ref.ident().tableIdent(), DocSysColumns.ID), right),
function.valueType()
);
} else {
String unsupportedMessage = context.unsupportedMessage(ref.column().name());
if (unsupportedMessage != null) {
throw new UnsupportedFeatureException(unsupportedMessage);
}
}
}
}
return function;
}
@Override
public Query visitReference(Reference ref, Context context) {
DataType<?> type = ref.valueType();
// called for queries like: where boolColumn
if (type == DataTypes.BOOLEAN) {
EqQuery<? super Boolean> eqQuery = DataTypes.BOOLEAN.storageSupportSafe().eqQuery();
if (eqQuery != null) {
return eqQuery.termQuery(
ref.storageIdent(), Boolean.TRUE, ref.hasDocValues(), ref.indexType() != IndexType.NONE);
}
}
return super.visitReference(ref, context);
}
@Override
public Query visitLiteral(Literal<?> literal, Context context) {
Object value = literal.value();
if (value == null) {
return new MatchNoDocsQuery("WHERE null -> no match");
}
try {
return (boolean) value
? new MatchAllDocsQuery()
: new MatchNoDocsQuery("WHERE false -> no match");
} catch (ClassCastException e) {
// Throw a nice error if the top-level literal doesn't have a boolean type
// (This is currently caught earlier, so this code is just a safe-guard)
return visitSymbol(literal, context);
}
}
@Override
protected Query visitSymbol(Symbol symbol, Context context) {
throw new UnsupportedOperationException(
Symbols.format("Can't build query from symbol %s", symbol));
}
}
|
assert function != null : "function must not be null";
if (fieldIgnored(function, context)) {
return new MatchAllDocsQuery();
}
function = rewriteAndValidateFields(function, context);
FunctionImplementation implementation = context.nodeContext.functions().getQualified(function);
if (implementation instanceof FunctionToQuery funcToQuery) {
Query query;
try {
query = funcToQuery.toQuery(function, context);
if (query == null) {
query = queryFromInnerFunction(function, context);
}
} catch (UnsupportedOperationException e) {
return genericFunctionFilter(function, context);
}
if (query != null) {
return query;
}
}
return genericFunctionFilter(function, context);
| 1,014
| 202
| 1,216
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/memory/MemoryManagerFactory.java
|
MemoryManagerFactory
|
getMemoryManager
|
class MemoryManagerFactory implements Function<RamAccounting, MemoryManager> {
enum MemoryType {
ON_HEAP("on-heap"),
OFF_HEAP("off-heap");
private final String value;
MemoryType(String value) {
this.value = value;
}
public String value() {
return value;
}
public static MemoryType of(String value) {
if (value.equals(ON_HEAP.value)) {
return ON_HEAP;
} else if (value.equals(OFF_HEAP.value)) {
return OFF_HEAP;
}
throw new IllegalArgumentException("Invalid memory type `" + value + "`. Expected one of: " + TYPES);
}
}
private static final Set<String> TYPES = Set.of(MemoryType.OFF_HEAP.value(), MemoryType.ON_HEAP.value());
// Explicit generic is required for eclipse JDT, otherwise it won't compile
public static final Setting<String> MEMORY_ALLOCATION_TYPE = new Setting<String>(
"memory.allocation.type",
MemoryType.ON_HEAP.value(),
input -> {
if (TYPES.contains(input)) {
return input;
}
throw new IllegalArgumentException(
"Invalid argument `" + input + "` for `memory.allocation.type`, valid values are: " + TYPES);
},
DataTypes.STRING,
Property.NodeScope,
Property.Dynamic,
Property.Exposed
);
private volatile MemoryType currentMemoryType = MemoryType.ON_HEAP;
@Inject
public MemoryManagerFactory(ClusterSettings clusterSettings) {
clusterSettings.addSettingsUpdateConsumer(MEMORY_ALLOCATION_TYPE, newValue -> {
currentMemoryType = MemoryType.of(newValue);
});
}
/**
* @return a MemoryManager instance that doesn't support concurrent access.
* Any component acquiring a MemoryManager must make sure to close it after use.
*/
public MemoryManager getMemoryManager(RamAccounting ramAccounting) {<FILL_FUNCTION_BODY>}
@Override
public MemoryManager apply(RamAccounting ramAccounting) {
return getMemoryManager(ramAccounting);
}
}
|
switch (currentMemoryType) {
case ON_HEAP:
return new OnHeapMemoryManager(ramAccounting::addBytes);
case OFF_HEAP:
return new OffHeapMemoryManager();
default:
throw new AssertionError("MemoryType is supposed to have only 2 cases");
}
| 596
| 81
| 677
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/memory/OnHeapMemoryManager.java
|
OnHeapMemoryManager
|
allocate
|
class OnHeapMemoryManager implements MemoryManager {
private final IntConsumer accountBytes;
/**
* @param accountBytes A consumer that will be called on each ByteBuf allocation with the number of allocated bytes.
*/
public OnHeapMemoryManager(IntConsumer accountBytes) {
this.accountBytes = accountBytes;
}
@Override
public ByteBuf allocate(int capacity) {<FILL_FUNCTION_BODY>}
@Override
public void close() {
}
}
|
accountBytes.accept(capacity);
// We don't track the ByteBuf instance to release it later because it is not necessary for on-heap buffers.
return Unpooled.buffer(capacity);
| 127
| 54
| 181
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/metadata/DanglingArtifactsService.java
|
DanglingArtifactsService
|
clusterChanged
|
class DanglingArtifactsService extends AbstractLifecycleComponent implements ClusterStateListener {
private static final Logger LOGGER = LogManager.getLogger(DanglingArtifactsService.class);
private final ClusterService clusterService;
private final List<Pattern> danglingPatterns;
@Inject
public DanglingArtifactsService(ClusterService clusterService) {
this.clusterService = clusterService;
this.danglingPatterns = IndexParts.DANGLING_INDICES_PREFIX_PATTERNS
.stream()
.map(Pattern::compile)
.collect(Collectors.toList());
}
@Override
protected void doStart() {
clusterService.addListener(this);
}
@Override
protected void doStop() {
clusterService.removeListener(this);
}
@Override
protected void doClose() {
}
@Override
public void clusterChanged(ClusterChangedEvent event) {<FILL_FUNCTION_BODY>}
}
|
if (LOGGER.isInfoEnabled() && event.isNewCluster()) {
for (ObjectCursor<String> key : event.state().metadata().indices().keys()) {
for (Pattern pattern : danglingPatterns) {
if (pattern.matcher(key.value).matches()) {
LOGGER.info("Dangling artifacts exist in the cluster. Use 'alter cluster gc dangling artifacts;' to remove them");
doStop();
return;
}
}
}
}
| 265
| 131
| 396
|
<methods>public void addLifecycleListener(org.elasticsearch.common.component.LifecycleListener) ,public void close() ,public org.elasticsearch.common.component.Lifecycle.State lifecycleState() ,public void removeLifecycleListener(org.elasticsearch.common.component.LifecycleListener) ,public void start() ,public void stop() <variables>protected final org.elasticsearch.common.component.Lifecycle lifecycle,private final List<org.elasticsearch.common.component.LifecycleListener> listeners
|
crate_crate
|
crate/server/src/main/java/io/crate/metadata/GeoReference.java
|
GeoReference
|
toMapping
|
class GeoReference extends SimpleReference {
private final String geoTree;
@Nullable
private final String precision;
@Nullable
private final Integer treeLevels;
@Nullable
private final Double distanceErrorPct;
public GeoReference(ReferenceIdent ident,
DataType<?> type,
ColumnPolicy columnPolicy,
IndexType indexType,
boolean nullable,
int position,
long oid,
boolean isDropped,
Symbol defaultExpression,
String geoTree,
String precision,
Integer treeLevels,
Double distanceErrorPct) {
super(ident,
RowGranularity.DOC, // Only primitive types columns can be used in PARTITIONED BY clause
type,
columnPolicy,
indexType,
nullable,
false, //Geo shapes don't have doc values
position,
oid,
isDropped,
defaultExpression
);
this.geoTree = Objects.requireNonNullElse(geoTree, TREE_GEOHASH);
if (TREE_BKD.equals(this.geoTree) && (precision != null || treeLevels != null || distanceErrorPct != null)) {
throw new IllegalArgumentException(
"The parameters precision, tree_levels, and distance_error_pct are not applicable to BKD tree indexes."
);
}
this.precision = precision;
this.treeLevels = treeLevels;
this.distanceErrorPct = distanceErrorPct;
}
@Override
public SymbolType symbolType() {
return SymbolType.GEO_REFERENCE;
}
public String geoTree() {
return geoTree;
}
@Nullable
public String precision() {
return precision;
}
@Nullable
public Integer treeLevels() {
return treeLevels;
}
@Nullable
public Double distanceErrorPct() {
return distanceErrorPct;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
GeoReference that = (GeoReference) o;
return java.util.Objects.equals(geoTree, that.geoTree) &&
java.util.Objects.equals(precision, that.precision) &&
java.util.Objects.equals(treeLevels, that.treeLevels) &&
java.util.Objects.equals(distanceErrorPct, that.distanceErrorPct);
}
@Override
public int hashCode() {
return java.util.Objects.hash(super.hashCode(), geoTree, precision, treeLevels, distanceErrorPct);
}
public GeoReference(StreamInput in) throws IOException {
super(in);
geoTree = in.readString();
precision = in.readOptionalString();
treeLevels = in.readBoolean() ? null : in.readVInt();
distanceErrorPct = in.readBoolean() ? null : in.readDouble();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(geoTree);
out.writeOptionalString(precision);
out.writeBoolean(treeLevels == null);
if (treeLevels != null) {
out.writeVInt(treeLevels);
}
out.writeBoolean(distanceErrorPct == null);
if (distanceErrorPct != null) {
out.writeDouble(distanceErrorPct);
}
}
@Override
public Reference withReferenceIdent(ReferenceIdent newIdent) {
return new GeoReference(
newIdent,
type,
columnPolicy,
indexType,
nullable,
position,
oid,
isDropped,
defaultExpression,
geoTree,
precision,
treeLevels,
distanceErrorPct
);
}
@Override
public Reference withOidAndPosition(LongSupplier acquireOid, IntSupplier acquirePosition) {
long newOid = oid == COLUMN_OID_UNASSIGNED ? acquireOid.getAsLong() : oid;
int newPosition = position < 0 ? acquirePosition.getAsInt() : position;
if (newOid == oid && newPosition == position) {
return this;
}
return new GeoReference(
ident,
type,
columnPolicy,
indexType,
nullable,
newPosition,
newOid,
isDropped,
defaultExpression,
geoTree,
precision,
treeLevels,
distanceErrorPct
);
}
@Override
public GeoReference withValueType(DataType<?> newType) {
return new GeoReference(
ident,
newType,
columnPolicy,
indexType,
nullable,
position,
oid,
isDropped,
defaultExpression,
geoTree,
precision,
treeLevels,
distanceErrorPct
);
}
@Override
public Map<String, Object> toMapping(int position) {<FILL_FUNCTION_BODY>}
}
|
Map<String, Object> mapping = super.toMapping(position);
Maps.putNonNull(mapping, "tree", geoTree);
Maps.putNonNull(mapping, "precision", precision);
Maps.putNonNull(mapping, "tree_levels", treeLevels);
if (distanceErrorPct != null) {
mapping.put("distance_error_pct", distanceErrorPct.floatValue());
}
return mapping;
| 1,370
| 118
| 1,488
|
<methods>public void <init>(org.elasticsearch.common.io.stream.StreamInput) throws java.io.IOException,public void <init>(io.crate.metadata.ReferenceIdent, io.crate.metadata.RowGranularity, DataType<?>, int, io.crate.expression.symbol.Symbol) ,public void <init>(io.crate.metadata.ReferenceIdent, io.crate.metadata.RowGranularity, DataType<?>, io.crate.sql.tree.ColumnPolicy, io.crate.metadata.IndexType, boolean, boolean, int, long, boolean, io.crate.expression.symbol.Symbol) ,public R accept(SymbolVisitor<C,R>, C) ,public io.crate.metadata.ColumnIdent column() ,public io.crate.sql.tree.ColumnPolicy columnPolicy() ,public io.crate.expression.symbol.Symbol defaultExpression() ,public boolean equals(java.lang.Object) ,public io.crate.metadata.RowGranularity granularity() ,public boolean hasDocValues() ,public int hashCode() ,public io.crate.metadata.ReferenceIdent ident() ,public io.crate.metadata.IndexType indexType() ,public boolean isDropped() ,public boolean isGenerated() ,public boolean isNullable() ,public long oid() ,public int position() ,public long ramBytesUsed() ,public io.crate.expression.symbol.SymbolType symbolType() ,public Map<java.lang.String,java.lang.Object> toMapping(int) ,public java.lang.String toString() ,public java.lang.String toString(io.crate.expression.symbol.format.Style) ,public DataType<?> valueType() ,public io.crate.metadata.Reference withDropped(boolean) ,public io.crate.metadata.Reference withOidAndPosition(java.util.function.LongSupplier, java.util.function.IntSupplier) ,public io.crate.metadata.Reference withReferenceIdent(io.crate.metadata.ReferenceIdent) ,public io.crate.metadata.Reference withValueType(DataType<?>) ,public void writeTo(org.elasticsearch.common.io.stream.StreamOutput) throws java.io.IOException<variables>private static final long SHALLOW_SIZE,protected final non-sealed io.crate.sql.tree.ColumnPolicy columnPolicy,protected final non-sealed io.crate.expression.symbol.Symbol defaultExpression,protected final non-sealed io.crate.metadata.RowGranularity granularity,protected final non-sealed boolean hasDocValues,protected final non-sealed io.crate.metadata.ReferenceIdent ident,protected final non-sealed io.crate.metadata.IndexType indexType,protected boolean isDropped,protected final non-sealed boolean nullable,protected final non-sealed long oid,protected final non-sealed int position,protected DataType<?> type
|
crate_crate
|
crate/server/src/main/java/io/crate/metadata/IndexParts.java
|
IndexParts
|
assertEmpty
|
class IndexParts {
private static final String PARTITIONED_KEY_WORD = "partitioned";
@VisibleForTesting
static final String PARTITIONED_TABLE_PART = "." + PARTITIONED_KEY_WORD + ".";
public static final List<String> DANGLING_INDICES_PREFIX_PATTERNS = List.of(
AlterTableOperation.RESIZE_PREFIX + "*"
);
private final String schema;
private final String table;
private final String partitionIdent;
public IndexParts(String indexName) {
if (BlobIndex.isBlobIndex(indexName)) {
schema = BlobSchemaInfo.NAME;
table = BlobIndex.stripPrefix(indexName);
partitionIdent = null;
} else {
// Index names are only allowed to contain '.' as separators
String[] parts = indexName.split("\\.", 6);
switch (parts.length) {
case 1:
// "table_name"
schema = Schemas.DOC_SCHEMA_NAME;
table = indexName;
partitionIdent = null;
break;
case 2:
// "schema"."table_name"
schema = parts[0];
table = parts[1];
partitionIdent = null;
break;
case 4:
// ""."partitioned"."table_name". ["ident"]
assertEmpty(parts[0]);
schema = Schemas.DOC_SCHEMA_NAME;
assertPartitionPrefix(parts[1]);
table = parts[2];
partitionIdent = parts[3];
break;
case 5:
// "schema".""."partitioned"."table_name". ["ident"]
schema = parts[0];
assertEmpty(parts[1]);
assertPartitionPrefix(parts[2]);
table = parts[3];
partitionIdent = parts[4];
break;
default:
throw new IllegalArgumentException("Invalid index name: " + indexName);
}
}
}
public String getSchema() {
return schema;
}
public String getTable() {
return table;
}
public String getPartitionIdent() {
return isPartitioned() ? partitionIdent : "";
}
public boolean isPartitioned() {
return partitionIdent != null;
}
public RelationName toRelationName() {
return new RelationName(schema, table);
}
public String toFullyQualifiedName() {
return schema + "." + table;
}
public boolean matchesSchema(String schema) {
return this.schema.equals(schema);
}
/////////////////////////
// Static utility methods
/////////////////////////
public static String toIndexName(RelationName relationName, String partitionIdent) {
return toIndexName(relationName.schema(), relationName.name(), partitionIdent);
}
public static String toIndexName(PartitionName partitionName) {
RelationName relationName = partitionName.relationName();
return toIndexName(relationName.schema(), relationName.name(), partitionName.ident());
}
/**
* Encodes the given parts to a CrateDB index name.
*/
public static String toIndexName(String schema, String table, @Nullable String partitionIdent) {
StringBuilder stringBuilder = new StringBuilder();
final boolean isPartitioned = partitionIdent != null;
if (!schema.equals(Schemas.DOC_SCHEMA_NAME)) {
stringBuilder.append(schema).append(".");
}
if (isPartitioned) {
stringBuilder.append(PARTITIONED_TABLE_PART);
}
stringBuilder.append(table);
if (isPartitioned) {
stringBuilder.append(".").append(partitionIdent);
}
return stringBuilder.toString();
}
/**
* Checks whether the index/template name belongs to a partitioned table.
*
* A partition index name looks like on of these:
*
* .partitioned.table.ident
* schema..partitioned.table.ident
* schema..partitioned.table.
*
* @param templateOrIndex The index name to check
* @return True if the index/template name denotes a partitioned table
*/
public static boolean isPartitioned(String templateOrIndex) {
int idx1 = templateOrIndex.indexOf('.');
if (idx1 == -1) {
return false;
}
int idx2 = templateOrIndex.indexOf(PARTITIONED_TABLE_PART, idx1);
if (idx2 == -1) {
return false;
}
int diff = idx2 - idx1;
return ((diff == 0 && idx1 == 0) || diff == 1) && idx2 + PARTITIONED_TABLE_PART.length() < templateOrIndex.length();
}
public static boolean isDangling(String indexName) {
return indexName.startsWith(".") &&
!indexName.startsWith(PARTITIONED_TABLE_PART) &&
!BlobIndex.isBlobIndex(indexName);
}
private static void assertPartitionPrefix(String prefix) {
if (!PARTITIONED_KEY_WORD.equals(prefix)) {
throw new IllegalArgumentException("Invalid partition prefix: " + prefix);
}
}
private static void assertEmpty(String prefix) {<FILL_FUNCTION_BODY>}
}
|
if (!"".equals(prefix)) {
throw new IllegalArgumentException("Invalid index name: " + prefix);
}
| 1,365
| 32
| 1,397
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/metadata/MapBackedRefResolver.java
|
MapBackedRefResolver
|
lookupMapWithChildTraversal
|
class MapBackedRefResolver implements ReferenceResolver<NestableInput<?>> {
private Map<ColumnIdent, NestableInput> implByColumn;
public MapBackedRefResolver(Map<ColumnIdent, NestableInput> implByColumn) {
this.implByColumn = implByColumn;
}
@Override
public NestableInput getImplementation(Reference ref) {
return lookupMapWithChildTraversal(implByColumn, ref.column());
}
static NestableInput lookupMapWithChildTraversal(Map<ColumnIdent, NestableInput> implByColumn, ColumnIdent column) {<FILL_FUNCTION_BODY>}
}
|
if (column.isRoot()) {
return implByColumn.get(column);
}
NestableInput<?> rootImpl = implByColumn.get(column.getRoot());
if (rootImpl == null) {
return implByColumn.get(column);
}
return NestableInput.getChildByPath(rootImpl, column.path());
| 168
| 94
| 262
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/metadata/PartitionReferenceResolver.java
|
PartitionReferenceResolver
|
getImplementation
|
class PartitionReferenceResolver implements ReferenceResolver<PartitionExpression> {
private final Map<ReferenceIdent, PartitionExpression> expressionMap;
private final List<PartitionExpression> partitionExpressions;
public PartitionReferenceResolver(List<PartitionExpression> partitionExpressions) {
this.partitionExpressions = partitionExpressions;
this.expressionMap = new HashMap<>(partitionExpressions.size(), 1.0f);
for (PartitionExpression partitionExpression : partitionExpressions) {
expressionMap.put(partitionExpression.reference().ident(), partitionExpression);
}
}
@Override
public PartitionExpression getImplementation(Reference ref) {<FILL_FUNCTION_BODY>}
public List<PartitionExpression> expressions() {
return partitionExpressions;
}
}
|
PartitionExpression expression = expressionMap.get(ref.ident());
assert expression != null : "granularity < PARTITION should have been resolved already";
return expression;
| 198
| 46
| 244
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/metadata/Routing.java
|
Routing
|
writeTo
|
class Routing implements Writeable {
private final Map<String, Map<String, IntIndexedContainer>> locations;
public Routing(Map<String, Map<String, IntIndexedContainer>> locations) {
assert locations != null : "locations must not be null";
assert assertLocationsAllTreeMap(locations) : "locations must be a TreeMap only and must contain only TreeMap's";
this.locations = locations;
}
/**
* @return a map with the locations in the following format: <p>
* Map<nodeName (string), <br>
* Map<indexName (string), List<ShardId (int)>>> <br>
* </p>
*/
public Map<String, Map<String, IntIndexedContainer>> locations() {
return locations;
}
public boolean hasLocations() {
return locations.size() > 0;
}
public Set<String> nodes() {
return locations.keySet();
}
/**
* get the number of shards in this routing for a node with given nodeId
*
* @return int >= 0
*/
public int numShards(String nodeId) {
Map<String, IntIndexedContainer> indicesAndShards = locations.get(nodeId);
if (indicesAndShards == null) {
return 0;
}
int numShards = 0;
for (IntIndexedContainer shardIds : indicesAndShards.values()) {
numShards += shardIds.size();
}
return numShards;
}
/**
* returns true if the routing contains shards for any table of the given node
*/
public boolean containsShards(String nodeId) {
Map<String, IntIndexedContainer> indicesAndShards = locations.get(nodeId);
if (indicesAndShards == null) {
return false;
}
for (IntIndexedContainer shardIds : indicesAndShards.values()) {
if (!shardIds.isEmpty()) {
return true;
}
}
return false;
}
public boolean containsShards() {
for (Map<String, IntIndexedContainer> indices : locations.values()) {
for (IntIndexedContainer shards : indices.values()) {
if (!shards.isEmpty()) {
return true;
}
}
}
return false;
}
@Override
public String toString() {
return "Routing{" +
"locations=" + locations +
'}';
}
public Routing(StreamInput in) throws IOException {
int numLocations = in.readVInt();
if (numLocations == 0) {
locations = Map.of();
} else {
locations = new TreeMap<>();
for (int i = 0; i < numLocations; i++) {
String nodeId = in.readString();
int numInner = in.readVInt();
Map<String, IntIndexedContainer> shardsByIndex = new TreeMap<>();
locations.put(nodeId, shardsByIndex);
for (int j = 0; j < numInner; j++) {
String indexName = in.readString();
int numShards = in.readVInt();
IntArrayList shardIds = new IntArrayList(numShards);
for (int k = 0; k < numShards; k++) {
shardIds.add(in.readVInt());
}
shardsByIndex.put(indexName, shardIds);
}
}
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {<FILL_FUNCTION_BODY>}
private boolean assertLocationsAllTreeMap(Map<String, Map<String, IntIndexedContainer>> locations) {
if (locations.isEmpty()) {
return true;
}
if (!(locations instanceof TreeMap) && locations.size() > 1) {
return false;
}
for (Map<String, IntIndexedContainer> shardsByIndex : locations.values()) {
if (shardsByIndex.size() > 1 && !(shardsByIndex instanceof TreeMap)) {
return false;
}
}
return true;
}
/**
* Return a routing for the given table on the given node id.
*/
public static Routing forTableOnSingleNode(RelationName relationName, String nodeId) {
Map<String, Map<String, IntIndexedContainer>> locations = new TreeMap<>();
Map<String, IntIndexedContainer> tableLocation = new TreeMap<>();
tableLocation.put(relationName.fqn(), IntArrayList.from(IntArrayList.EMPTY_ARRAY));
locations.put(nodeId, tableLocation);
return new Routing(locations);
}
public static Routing forTableOnAllNodes(RelationName relationName, DiscoveryNodes nodes) {
TreeMap<String, Map<String, IntIndexedContainer>> indicesByNode = new TreeMap<>();
Map<String, IntIndexedContainer> shardsByIndex = Collections.singletonMap(
relationName.indexNameOrAlias(),
IntArrayList.from(IntArrayList.EMPTY_ARRAY)
);
for (DiscoveryNode node : nodes) {
indicesByNode.put(node.getId(), shardsByIndex);
}
return new Routing(indicesByNode);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Routing other = (Routing) o;
return locations.equals(other.locations);
}
@Override
public int hashCode() {
return locations.hashCode();
}
}
|
out.writeVInt(locations.size());
for (Map.Entry<String, Map<String, IntIndexedContainer>> entry : locations.entrySet()) {
out.writeString(entry.getKey());
Map<String, IntIndexedContainer> shardsByIndex = entry.getValue();
if (shardsByIndex == null) {
out.writeVInt(0);
} else {
out.writeVInt(shardsByIndex.size());
for (Map.Entry<String, IntIndexedContainer> innerEntry : shardsByIndex.entrySet()) {
out.writeString(innerEntry.getKey());
IntIndexedContainer shardIds = innerEntry.getValue();
if (shardIds == null || shardIds.size() == 0) {
out.writeVInt(0);
} else {
out.writeVInt(shardIds.size());
for (IntCursor shardId: shardIds) {
out.writeVInt(shardId.value);
}
}
}
}
}
| 1,496
| 266
| 1,762
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/metadata/Scalar.java
|
Scalar
|
normalizeSymbol
|
class Scalar<ReturnType, InputType> implements FunctionImplementation, FunctionToQuery {
public static final Set<Feature> NO_FEATURES = Set.of();
public static final Set<Feature> DETERMINISTIC_ONLY = EnumSet.of(Feature.DETERMINISTIC);
public static final Set<Feature> DETERMINISTIC_AND_COMPARISON_REPLACEMENT = EnumSet.of(
Feature.DETERMINISTIC, Feature.COMPARISON_REPLACEMENT);
protected final Signature signature;
protected final BoundSignature boundSignature;
protected Scalar(Signature signature, BoundSignature boundSignature) {
this.signature = signature;
this.boundSignature = boundSignature;
}
@Override
public Signature signature() {
return signature;
}
@Override
public BoundSignature boundSignature() {
return boundSignature;
}
/**
* Evaluate the function using the provided arguments
*/
public abstract ReturnType evaluate(TransactionContext txnCtx, NodeContext nodeContext, Input<InputType>... args);
/**
* Called to return a "optimized" version of a scalar implementation.
*
* The returned instance will only be used in the context of a single query
* (or rather, a subset of a single query if executed distributed).
*
* @param arguments arguments in symbol form. If any symbols are literals, any arguments passed to
* {@link #evaluate(TransactionContext, NodeContext, Input[])} will have the same
* value as those literals. (Within the scope of a single operation)
*/
public Scalar<ReturnType, InputType> compile(List<Symbol> arguments, String currentUser, Roles roles) {
return this;
}
@Override
public Symbol normalizeSymbol(Function symbol, TransactionContext txnCtx, NodeContext nodeCtx) {<FILL_FUNCTION_BODY>}
protected static boolean anyNonLiterals(Collection<? extends Symbol> arguments) {
for (Symbol symbol : arguments) {
if (!symbol.symbolType().isValueSymbol()) {
return true;
}
}
return false;
}
/**
* This method will evaluate the function using the given scalar if all arguments are literals.
* Otherwise it will return the function as is or NULL in case it contains a null literal
*/
protected static <ReturnType, InputType> Symbol evaluateIfLiterals(Scalar<ReturnType, InputType> scalar,
TransactionContext txnCtx,
NodeContext nodeCtx,
Function function) {
List<Symbol> arguments = function.arguments();
for (Symbol argument : arguments) {
if (!(argument instanceof Input)) {
return function;
}
}
Input[] inputs = new Input[arguments.size()];
int idx = 0;
for (Symbol arg : arguments) {
inputs[idx] = (Input<?>) arg;
idx++;
}
//noinspection unchecked
return Literal.ofUnchecked(function.valueType(), scalar.evaluate(txnCtx, nodeCtx, inputs));
}
public enum Feature {
DETERMINISTIC,
/**
* If this feature is set, for this function it is possible to replace the containing
* comparison while preserving the truth value for all used operators
* with or without an operator mapping.
* <p>
* It describes the following:
* <p>
* say we have a comparison-query like this:
* <p>
* col > 10.5
* <p>
* then a function f, for which comparisons are replaceable, can be applied so
* that:
* <p>
* f(col) > f(10.5)
* <p>
* for all col for which col > 10.5 is true. Maybe > needs to be mapped to another
* operator, but this may not depend on the actual values used here.
* <p>
* Fun facts:
* <p>
* * This property holds for the = comparison operator for all functions f.
* * This property is transitive so if f and g are replaceable,
* then f(g(x)) also is
* * it is possible to replace:
* <p>
* col > 10.5
* <p>
* with:
* <p>
* f(col) > f(10.5)
* <p>
* for every operator (possibly mapped) and the query is still equivalent.
* <p>
* Example 1:
* <p>
* if f is defined as f(v) = v + 1
* then col + 1 > 11.5 must be true for all col > 10.5.
* This is indeed true.
* <p>
* So f is replaceable for >.
* <p>
* Fun fact: for f all comparison operators =, >, <, >=,<= are replaceable
* <p>
* Example 2 (a rounding function):
* <p>
* if f is defined as f(v) = ceil(v)
* then ceil(col) > 11 for all col > 10.5.
* But there is 10.8 for which f is 11 and
* 11 > 11 is false.
* <p>
* Here a simple mapping of the operator will do the trick:
* <p>
* > -> >=
* < -> <=
* <p>
* So for f comparisons are replaceable using the mapping above.
* <p>
* Example 3:
* <p>
* if f is defined as f(v) = v % 5
* then col % 5 > 0.5 for all col > 10.5
* but there is 20 for which
* f is 0 and
* 0 > 0.5 is false.
* <p>
* So for f comparisons cannot be replaced.
*/
COMPARISON_REPLACEMENT,
LAZY_ATTRIBUTES,
/**
* If this feature is set, the function will return for null argument(s) as result null.
*/
NULLABLE,
/**
* If this feature is set, the function will never return null.
*/
NON_NULLABLE
}
}
|
try {
return evaluateIfLiterals(this, txnCtx, nodeCtx, symbol);
} catch (Throwable t) {
return symbol;
}
| 1,623
| 46
| 1,669
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/metadata/blob/BlobSchemaInfo.java
|
BlobSchemaInfo
|
getTableInfo
|
class BlobSchemaInfo implements SchemaInfo {
public static final String NAME = "blob";
private final ClusterService clusterService;
private final BlobTableInfoFactory blobTableInfoFactory;
private final ConcurrentHashMap<String, BlobTableInfo> tableByName = new ConcurrentHashMap<>();
@Inject
public BlobSchemaInfo(ClusterService clusterService,
BlobTableInfoFactory blobTableInfoFactory) {
this.clusterService = clusterService;
this.blobTableInfoFactory = blobTableInfoFactory;
}
@Override
public TableInfo getTableInfo(String name) {<FILL_FUNCTION_BODY>}
@Override
public String name() {
return NAME;
}
@Override
public void invalidateTableCache(String tableName) {
tableByName.remove(tableName);
}
@Override
public void update(ClusterChangedEvent event) {
if (event.metadataChanged()) {
tableByName.clear();
}
}
@Override
public Iterable<TableInfo> getTables() {
return Stream.of(clusterService.state().metadata().getConcreteAllOpenIndices())
.filter(BlobIndex::isBlobIndex)
.map(BlobIndex::stripPrefix)
.map(this::getTableInfo)
::iterator;
}
@Override
public Iterable<ViewInfo> getViews() {
return Collections.emptyList();
}
@Override
public void close() throws Exception {
}
}
|
try {
return tableByName.computeIfAbsent(
name,
n -> blobTableInfoFactory.create(new RelationName(NAME, n), clusterService.state())
);
} catch (Exception e) {
if (e instanceof ResourceUnknownException) {
return null;
}
throw e;
}
| 397
| 89
| 486
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/metadata/blob/BlobTableInfoFactory.java
|
BlobTableInfoFactory
|
create
|
class BlobTableInfoFactory {
private final Path[] dataFiles;
private final Path globalBlobPath;
@Inject
public BlobTableInfoFactory(Settings settings, Environment environment) {
this.dataFiles = environment.dataFiles();
this.globalBlobPath = BlobIndicesService.getGlobalBlobPath(settings);
}
private IndexMetadata resolveIndexMetadata(String tableName, Metadata metadata) {
String indexName = BlobIndex.fullIndexName(tableName);
Index index;
try {
index = IndexNameExpressionResolver.concreteIndices(metadata, IndicesOptions.strictExpandOpen(), indexName)[0];
} catch (IndexNotFoundException ex) {
throw new RelationUnknown(indexName, ex);
}
return metadata.index(index);
}
public BlobTableInfo create(RelationName ident, ClusterState clusterState) {<FILL_FUNCTION_BODY>}
private String blobsPath(Settings indexMetadataSettings) {
String blobsPath;
String blobsPathStr = BlobIndicesService.SETTING_INDEX_BLOBS_PATH.get(indexMetadataSettings);
if (Strings.hasLength(blobsPathStr)) {
blobsPath = blobsPathStr;
} else {
Path path = globalBlobPath;
if (path != null) {
blobsPath = path.toString();
} else {
// TODO: should we set this to null because there is no special blobPath?
blobsPath = dataFiles[0].toString();
}
}
return blobsPath;
}
}
|
IndexMetadata indexMetadata = resolveIndexMetadata(ident.name(), clusterState.metadata());
Settings settings = indexMetadata.getSettings();
return new BlobTableInfo(
ident,
indexMetadata.getIndex().getName(),
indexMetadata.getNumberOfShards(),
NumberOfReplicas.fromSettings(settings),
settings,
blobsPath(settings),
IndexMetadata.SETTING_INDEX_VERSION_CREATED.get(settings),
settings.getAsVersion(IndexMetadata.SETTING_VERSION_UPGRADED, null),
indexMetadata.getState() == IndexMetadata.State.CLOSE);
| 408
| 155
| 563
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/metadata/information/ForeignServerTableInfo.java
|
ForeignServerTableInfo
|
create
|
class ForeignServerTableInfo {
public static final String NAME = "foreign_servers";
public static final RelationName IDENT = new RelationName(InformationSchemaInfo.NAME, NAME);
public static SystemTable<Server> create() {<FILL_FUNCTION_BODY>}
}
|
return SystemTable.<Server>builder(IDENT)
.add("foreign_server_catalog", DataTypes.STRING, ignored -> Constants.DB_NAME)
.add("foreign_server_name", DataTypes.STRING, Server::name)
.add("foreign_data_wrapper_catalog", DataTypes.STRING, ignored -> Constants.DB_NAME)
.add("foreign_data_wrapper_name", DataTypes.STRING, Server::fdw)
.add("foreign_server_type", DataTypes.STRING, ignored -> null)
.add("foreign_server_version", DataTypes.STRING, ignored -> null)
.add("authorization_identifier", DataTypes.STRING, Server::owner)
.build();
| 73
| 187
| 260
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/metadata/information/InformationPartitionsTableInfo.java
|
InformationPartitionsTableInfo
|
create
|
class InformationPartitionsTableInfo {
public static final String NAME = "table_partitions";
public static final RelationName IDENT = new RelationName(InformationSchemaInfo.NAME, NAME);
public static SystemTable<PartitionInfo> create() {<FILL_FUNCTION_BODY>}
private static Function<PartitionInfo, Long> fromByteSize(Setting<ByteSizeValue> byteSizeSetting) {
return rel -> byteSizeSetting.get(rel.tableParameters()).getBytes();
}
@SuppressWarnings("unchecked")
private static <T> Function<PartitionInfo, Map<String, Object>> fromSetting(Setting.AffixSetting<T> setting) {
return rel -> {
return (Map<String, Object>) setting.getAsMap(rel.tableParameters());
};
}
private static <T> Function<PartitionInfo, T> fromSetting(Setting<T> setting) {
return rel -> setting.get(rel.tableParameters());
}
private static <T, U> Function<PartitionInfo, U> fromSetting(Setting<T> setting, Function<T, U> andThen) {
return rel -> andThen.apply(setting.get(rel.tableParameters()));
}
private static Function<PartitionInfo, Long> fromTimeValue(Setting<TimeValue> timeValueSetting) {
return rel -> timeValueSetting.get(rel.tableParameters()).millis();
}
}
|
return SystemTable.<PartitionInfo>builder(IDENT)
.add("table_schema", STRING, r -> r.name().relationName().schema())
.add("table_name", STRING, r -> r.name().relationName().name())
.add("partition_ident", STRING, r -> r.name().ident())
.addDynamicObject("values", STRING, PartitionInfo::values)
.add("number_of_shards", INTEGER, PartitionInfo::numberOfShards)
.add("number_of_replicas", STRING, PartitionInfo::numberOfReplicas)
.add("routing_hash_function", STRING, r -> IndexMappings.DEFAULT_ROUTING_HASH_FUNCTION_PRETTY_NAME)
.add("closed", BOOLEAN, PartitionInfo::isClosed)
.startObject("version")
.add(Version.Property.CREATED.toString(), STRING, r -> r.versionCreated().externalNumber())
.add(Version.Property.UPGRADED.toString(), STRING, r -> r.versionUpgraded().externalNumber())
.endObject()
.startObject("settings")
.startObject("blocks")
.add("read_only", BOOLEAN, fromSetting(IndexMetadata.INDEX_READ_ONLY_SETTING))
.add("read", BOOLEAN, fromSetting(IndexMetadata.INDEX_BLOCKS_READ_SETTING))
.add("write", BOOLEAN, fromSetting(IndexMetadata.INDEX_BLOCKS_WRITE_SETTING))
.add("metadata", BOOLEAN, fromSetting(IndexMetadata.INDEX_BLOCKS_METADATA_SETTING))
.add("read_only_allow_delete", BOOLEAN, fromSetting(IndexMetadata.INDEX_BLOCKS_READ_ONLY_ALLOW_DELETE_SETTING))
.endObject()
.add("codec", STRING, fromSetting(INDEX_CODEC_SETTING))
.startObject("store")
.add("type", STRING, fromSetting(IndexModule.INDEX_STORE_TYPE_SETTING))
.endObject()
.startObject("translog")
.add("flush_threshold_size", LONG, fromByteSize(IndexSettings.INDEX_TRANSLOG_FLUSH_THRESHOLD_SIZE_SETTING))
.add("sync_interval", LONG, fromTimeValue(IndexSettings.INDEX_TRANSLOG_SYNC_INTERVAL_SETTING))
.add("durability", STRING, fromSetting(IndexSettings.INDEX_TRANSLOG_DURABILITY_SETTING, Translog.Durability::name))
.endObject()
.startObject("routing")
.startObject("allocation")
.add("enable", STRING, fromSetting(EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE_SETTING, EnableAllocationDecider.Allocation::toString))
.add("total_shards_per_node", INTEGER, fromSetting(ShardsLimitAllocationDecider.INDEX_TOTAL_SHARDS_PER_NODE_SETTING))
.addDynamicObject("require", STRING, fromSetting(IndexMetadata.INDEX_ROUTING_REQUIRE_GROUP_SETTING))
.addDynamicObject("include", STRING, fromSetting(IndexMetadata.INDEX_ROUTING_INCLUDE_GROUP_SETTING))
.addDynamicObject("exclude", STRING, fromSetting(IndexMetadata.INDEX_ROUTING_EXCLUDE_GROUP_SETTING))
.endObject()
.endObject()
.startObject("warmer")
.add("enabled", BOOLEAN, fromSetting(IndexSettings.INDEX_WARMER_ENABLED_SETTING))
.endObject()
.startObject("unassigned")
.startObject("node_left")
.add("delayed_timeout", LONG, fromTimeValue(UnassignedInfo.INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING))
.endObject()
.endObject()
.startObject("mapping")
.startObject("total_fields")
.add("limit", INTEGER, fromSetting(MapperService.INDEX_MAPPING_TOTAL_FIELDS_LIMIT_SETTING, INTEGER::sanitizeValue))
.endObject()
.endObject()
.startObject("merge")
.startObject("scheduler")
.add("max_thread_count", INTEGER, fromSetting(MAX_THREAD_COUNT_SETTING))
.add("max_merge_count", INTEGER, fromSetting(MAX_MERGE_COUNT_SETTING))
.endObject()
.endObject()
.startObject("write")
.add("wait_for_active_shards", STRING, fromSetting(IndexMetadata.SETTING_WAIT_FOR_ACTIVE_SHARDS, ActiveShardCount::toString))
.endObject()
.endObject()
.setPrimaryKeys(
new ColumnIdent("table_schema"),
new ColumnIdent("table_name"),
new ColumnIdent("partition_ident")
)
.build();
| 358
| 1,314
| 1,672
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/metadata/information/InformationRoutinesTableInfo.java
|
InformationRoutinesTableInfo
|
create
|
class InformationRoutinesTableInfo {
public static final String NAME = "routines";
public static final RelationName IDENT = new RelationName(InformationSchemaInfo.NAME, NAME);
public static SystemTable<RoutineInfo> create() {<FILL_FUNCTION_BODY>}
}
|
return SystemTable.<RoutineInfo>builder(IDENT)
.add("routine_name", STRING, RoutineInfo::name)
.add("routine_type", STRING, RoutineInfo::type)
.add("routine_schema", STRING, RoutineInfo::schema)
.add("specific_name", STRING, RoutineInfo::specificName)
.add("routine_body", STRING, RoutineInfo::body)
.add("routine_definition", STRING, RoutineInfo::definition)
.add("data_type", STRING, RoutineInfo::dataType)
.add("is_deterministic", BOOLEAN, RoutineInfo::isDeterministic)
.build();
| 76
| 191
| 267
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/metadata/pgcatalog/PgAttrDefTable.java
|
PgAttrDefTable
|
create
|
class PgAttrDefTable {
public static final RelationName IDENT = new RelationName(PgCatalogSchemaInfo.NAME, "pg_attrdef");
private PgAttrDefTable() {}
public static SystemTable<Void> create() {<FILL_FUNCTION_BODY>}
}
|
return SystemTable.<Void>builder(IDENT)
.add("oid", INTEGER, x -> 0)
.add("adrelid", REGCLASS, x -> null)
.add("adnum", INTEGER, x -> 0)
.add("adbin", STRING, x -> null)
.add("adsrc", STRING, x -> null)
.build();
| 79
| 105
| 184
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/metadata/pgcatalog/PgConstraintTable.java
|
PgConstraintTable
|
create
|
class PgConstraintTable {
public static final RelationName IDENT = new RelationName(PgCatalogSchemaInfo.NAME, "pg_constraint");
private static final String NO_ACTION = "a";
private static final String MATCH_SIMPLE = "s";
private PgConstraintTable() {}
public static SystemTable<ConstraintInfo> create() {<FILL_FUNCTION_BODY>}
}
|
return SystemTable.<ConstraintInfo>builder(IDENT)
.add("oid", INTEGER, c -> constraintOid(c.relationName().fqn(), c.constraintName(), c.constraintType().toString()))
.add("conname", STRING, ConstraintInfo::constraintName)
.add("connamespace", INTEGER, c -> schemaOid(c.relationName().schema()))
.add("contype", STRING, c -> c.constraintType().postgresChar())
.add("condeferrable", BOOLEAN, c -> false)
.add("condeferred", BOOLEAN, c -> false)
.add("convalidated", BOOLEAN, c -> true)
.add("conrelid", INTEGER, c -> relationOid(c.relationInfo()))
.add("contypid", INTEGER, c -> 0)
.add("conindid", INTEGER, c -> 0)
.add("conparentid", INTEGER, c -> 0)
.add("confrelid", INTEGER, c -> 0)
.add("confupdtype", STRING, c -> NO_ACTION)
.add("confdeltype", STRING, c -> NO_ACTION)
.add("confmatchtype", STRING, c -> MATCH_SIMPLE)
.add("conislocal", BOOLEAN, c -> true)
.add("coninhcount", INTEGER, c -> 0)
.add("connoinherit", BOOLEAN, c -> true)
.add("conkey", SHORT_ARRAY, c -> c.conkey())
.add("confkey", SHORT_ARRAY, c -> null)
.add("conpfeqop", INTEGER_ARRAY, c -> null)
.add("conppeqop", INTEGER_ARRAY, c -> null)
.add("conffeqop", INTEGER_ARRAY, c -> null)
.add("conexclop", INTEGER_ARRAY, c -> null)
.add("conbin", STRING, c -> null)
.build();
| 107
| 549
| 656
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/metadata/pgcatalog/PgCursors.java
|
PgCursors
|
create
|
class PgCursors {
public static final String NAME = "pg_cursors";
public static final RelationName IDENT = new RelationName(PgCatalogSchemaInfo.NAME, NAME);
private PgCursors() {}
public static SystemTable<Cursor> create() {<FILL_FUNCTION_BODY>}
}
|
return SystemTable.<Cursor>builder(IDENT)
.add("name", DataTypes.STRING, Cursor::name)
.add("statement", DataTypes.STRING, Cursor::declareStatement)
.add("is_holdable", DataTypes.BOOLEAN, Cursor::isHold)
.add("is_binary", DataTypes.BOOLEAN, Cursor::isBinary)
.add("is_scrollable", DataTypes.BOOLEAN, Cursor::isScrollable)
.add("creation_time", DataTypes.TIMESTAMPZ, Cursor::creationTime)
.build();
| 88
| 154
| 242
|
<no_super_class>
|
crate_crate
|
crate/server/src/main/java/io/crate/metadata/pgcatalog/PgDatabaseTable.java
|
PgDatabaseTable
|
create
|
class PgDatabaseTable {
public static final RelationName NAME = new RelationName(PgCatalogSchemaInfo.NAME, "pg_database");
private PgDatabaseTable() {}
public static SystemTable<Void> create() {<FILL_FUNCTION_BODY>}
}
|
return SystemTable.<Void>builder(NAME)
.add("oid", INTEGER, c -> Constants.DB_OID)
.add("datname", STRING, c -> Constants.DB_NAME)
.add("datdba", INTEGER, c -> 1)
.add("encoding", INTEGER, c -> 6)
.add("datcollate", STRING, c -> "en_US.UTF-8")
.add("datctype", STRING, c -> "en_US.UTF-8")
.add("datistemplate", BOOLEAN,c -> false)
.add("datallowconn", BOOLEAN, c -> true)
.add("datconnlimit", INTEGER,c -> -1) // no limit
// We don't have any good values for these
.add("datlastsysoid", INTEGER, c -> null)
.add("datfrozenxid", INTEGER, c -> null)
.add("datminmxid", INTEGER, c -> null)
.add("dattablespace", INTEGER, c -> null)
// should be `aclitem[]` but we lack `aclitem`, so going with same choice that Cockroach made:
// https://github.com/cockroachdb/cockroach/blob/45deb66abbca3aae56bd27910a36d90a6a8bcafe/pkg/sql/vtable/pg_catalog.go#L277
.add("datacl", STRING_ARRAY, c -> null)
.build();
| 75
| 423
| 498
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.