Search in sources :

Example 41 with Record

use of org.jooq.Record in project jOOQ by jOOQ.

the class ParserImpl method parseCreateTable.

private static final DDLQuery parseCreateTable(ParserContext ctx) {
    boolean ifNotExists = parseKeywordIf(ctx, "IF NOT EXISTS");
    Table<?> tableName = parseTableName(ctx);
    if (parseKeywordIf(ctx, "AS")) {
        Select<?> select = parseSelect(ctx);
        CreateTableAsStep<Record> s1 = ifNotExists ? ctx.dsl.createTableIfNotExists(tableName) : ctx.dsl.createTable(tableName);
        CreateTableFinalStep s2 = s1.as(select);
        return s2;
    } else {
        List<Field<?>> fields = new ArrayList<Field<?>>();
        List<Constraint> constraints = new ArrayList<Constraint>();
        boolean primary = false;
        boolean noConstraint = true;
        parse(ctx, '(');
        do {
            String fieldName = parseIdentifier(ctx);
            DataType<?> type = parseDataType(ctx);
            boolean nullable = false;
            boolean defaultValue = false;
            boolean unique = false;
            for (; ; ) {
                if (!nullable) {
                    if (parseKeywordIf(ctx, "NULL")) {
                        type = type.nullable(true);
                        nullable = true;
                        continue;
                    } else if (parseKeywordIf(ctx, "NOT NULL")) {
                        type = type.nullable(false);
                        nullable = true;
                        continue;
                    }
                }
                if (!defaultValue) {
                    if (parseKeywordIf(ctx, "DEFAULT")) {
                        type = type.defaultValue((Field) parseField(ctx));
                        defaultValue = true;
                        continue;
                    }
                }
                if (!unique) {
                    if (parseKeywordIf(ctx, "PRIMARY KEY")) {
                        constraints.add(primaryKey(fieldName));
                        primary = true;
                        unique = true;
                        continue;
                    } else if (parseKeywordIf(ctx, "UNIQUE")) {
                        constraints.add(unique(fieldName));
                        unique = true;
                        continue;
                    }
                }
                if (parseKeywordIf(ctx, "CHECK")) {
                    parse(ctx, '(');
                    constraints.add(check(parseCondition(ctx)));
                    parse(ctx, ')');
                    continue;
                }
                break;
            }
            fields.add(field(name(fieldName), type));
        } while (parseIf(ctx, ',') && (noConstraint = !peekKeyword(ctx, "PRIMARY KEY") && !peekKeyword(ctx, "UNIQUE") && !peekKeyword(ctx, "FOREIGN KEY") && !peekKeyword(ctx, "CHECK") && !peekKeyword(ctx, "CONSTRAINT")));
        if (!noConstraint) {
            do {
                ConstraintTypeStep constraint = null;
                if (parseKeywordIf(ctx, "CONSTRAINT"))
                    constraint = constraint(parseIdentifier(ctx));
                if (parseKeywordIf(ctx, "PRIMARY KEY")) {
                    if (primary) {
                        throw ctx.exception();
                    } else {
                        primary = true;
                        parse(ctx, '(');
                        Field<?>[] fieldNames = parseFieldNames(ctx).toArray(EMPTY_FIELD);
                        parse(ctx, ')');
                        constraints.add(constraint == null ? primaryKey(fieldNames) : constraint.primaryKey(fieldNames));
                    }
                } else if (parseKeywordIf(ctx, "UNIQUE")) {
                    parse(ctx, '(');
                    Field<?>[] fieldNames = parseFieldNames(ctx).toArray(EMPTY_FIELD);
                    parse(ctx, ')');
                    constraints.add(constraint == null ? unique(fieldNames) : constraint.unique(fieldNames));
                } else if (parseKeywordIf(ctx, "FOREIGN KEY")) {
                    parse(ctx, '(');
                    Field<?>[] referencing = parseFieldNames(ctx).toArray(EMPTY_FIELD);
                    parse(ctx, ')');
                    parseKeyword(ctx, "REFERENCES");
                    Table<?> referencedTable = parseTableName(ctx);
                    parse(ctx, '(');
                    Field<?>[] referencedFields = parseFieldNames(ctx).toArray(EMPTY_FIELD);
                    parse(ctx, ')');
                    if (referencing.length != referencedFields.length)
                        throw ctx.exception();
                    constraints.add(constraint == null ? foreignKey(referencing).references(referencedTable, referencedFields) : constraint.foreignKey(referencing).references(referencedTable, referencedFields));
                } else if (parseKeywordIf(ctx, "CHECK")) {
                    parse(ctx, '(');
                    Condition condition = parseCondition(ctx);
                    parse(ctx, ')');
                    constraints.add(constraint == null ? check(condition) : constraint.check(condition));
                } else {
                    throw ctx.unexpectedToken();
                }
            } while (parseIf(ctx, ','));
        }
        parse(ctx, ')');
        CreateTableAsStep<Record> s1 = ifNotExists ? ctx.dsl.createTableIfNotExists(tableName) : ctx.dsl.createTable(tableName);
        CreateTableColumnStep s2 = s1.columns(fields);
        CreateTableConstraintStep s3 = constraints.isEmpty() ? s2 : s2.constraints(constraints);
        return s3;
    }
}
Also used : CreateTableFinalStep(org.jooq.CreateTableFinalStep) ConstraintTypeStep(org.jooq.ConstraintTypeStep) Condition(org.jooq.Condition) CreateTableConstraintStep(org.jooq.CreateTableConstraintStep) Constraint(org.jooq.Constraint) ArrayList(java.util.ArrayList) TableField(org.jooq.TableField) GroupField(org.jooq.GroupField) Field(org.jooq.Field) SortField(org.jooq.SortField) CreateTableColumnStep(org.jooq.CreateTableColumnStep) Record(org.jooq.Record)

Example 42 with Record

use of org.jooq.Record in project jOOQ by jOOQ.

the class ResultImpl method formatHTML.

@Override
public final void formatHTML(Writer writer) {
    try {
        writer.append("<table>");
        writer.append("<thead>");
        writer.append("<tr>");
        for (Field<?> field : fields.fields) {
            writer.append("<th>");
            writer.append(escapeXML(field.getName()));
            writer.append("</th>");
        }
        writer.append("</tr>");
        writer.append("</thead>");
        writer.append("<tbody>");
        for (Record record : this) {
            writer.append("<tr>");
            for (int index = 0; index < fields.fields.length; index++) {
                writer.append("<td>");
                writer.append(escapeXML(format0(record.getValue(index), false, true)));
                writer.append("</td>");
            }
            writer.append("</tr>");
        }
        writer.append("</tbody>");
        writer.append("</table>");
        writer.flush();
    } catch (java.io.IOException e) {
        throw new IOException("Exception while writing HTML", e);
    }
}
Also used : TableRecord(org.jooq.TableRecord) UpdatableRecord(org.jooq.UpdatableRecord) Record(org.jooq.Record) IOException(org.jooq.exception.IOException)

Example 43 with Record

use of org.jooq.Record in project jOOQ by jOOQ.

the class ResultImpl method formatJSON.

@Override
public final void formatJSON(Writer writer, JSONFormat format) {
    try {
        String separator;
        int recordLevel = format.header() ? 2 : 1;
        if (format.header()) {
            if (format.format())
                writer.append('{').append(format.newline()).append(format.indentString(1)).append("\"fields\": [");
            else
                writer.append("{\"fields\":[");
            separator = "";
            for (Field<?> field : fields.fields) {
                writer.append(separator);
                if (format.format())
                    writer.append(format.newline()).append(format.indentString(2));
                writer.append('{');
                if (format.format())
                    writer.append(format.newline()).append(format.indentString(3));
                if (field instanceof TableField) {
                    Table<?> table = ((TableField<?, ?>) field).getTable();
                    if (table != null) {
                        Schema schema = table.getSchema();
                        if (schema != null) {
                            writer.append("\"schema\":");
                            if (format.format())
                                writer.append(' ');
                            JSONValue.writeJSONString(schema.getName(), writer);
                            writer.append(',');
                            if (format.format())
                                writer.append(format.newline()).append(format.indentString(3));
                        }
                        writer.append("\"table\":");
                        if (format.format())
                            writer.append(' ');
                        JSONValue.writeJSONString(table.getName(), writer);
                        writer.append(',');
                        if (format.format())
                            writer.append(format.newline()).append(format.indentString(3));
                    }
                }
                writer.append("\"name\":");
                if (format.format())
                    writer.append(' ');
                JSONValue.writeJSONString(field.getName(), writer);
                writer.append(',');
                if (format.format())
                    writer.append(format.newline()).append(format.indentString(3));
                writer.append("\"type\":");
                if (format.format())
                    writer.append(' ');
                JSONValue.writeJSONString(field.getDataType().getTypeName().toUpperCase(), writer);
                if (format.format())
                    writer.append(format.newline()).append(format.indentString(2));
                writer.append('}');
                separator = ",";
            }
            if (format.format())
                writer.append(format.newline()).append(format.indentString(1)).append("],").append(format.newline()).append(format.indentString(1)).append("\"records\": ");
            else
                writer.append("],\"records\":");
        }
        writer.append('[');
        separator = "";
        switch(format.recordFormat()) {
            case ARRAY:
                for (Record record : this) {
                    writer.append(separator);
                    if (format.format())
                        writer.append(format.newline());
                    formatJSONArray0(record, fields, format, recordLevel, writer);
                    separator = ",";
                }
                break;
            case OBJECT:
                for (Record record : this) {
                    writer.append(separator);
                    if (format.format())
                        writer.append(format.newline());
                    formatJSONMap0(record, fields, format, recordLevel, writer);
                    separator = ",";
                }
                break;
            default:
                throw new IllegalArgumentException("Format not supported: " + format);
        }
        if (format.format()) {
            writer.append(format.newline());
            if (format.header())
                writer.append(format.indentString(1));
        }
        writer.append(']');
        if (format.header())
            writer.append(format.newline()).append('}');
        writer.flush();
    } catch (java.io.IOException e) {
        throw new IOException("Exception while writing JSON", e);
    }
}
Also used : Schema(org.jooq.Schema) TableRecord(org.jooq.TableRecord) UpdatableRecord(org.jooq.UpdatableRecord) Record(org.jooq.Record) IOException(org.jooq.exception.IOException) TableField(org.jooq.TableField)

Example 44 with Record

use of org.jooq.Record in project zipkin by openzipkin.

the class MySQLSpanStore method aggregateDependencies.

List<DependencyLink> aggregateDependencies(long endTs, @Nullable Long lookback, Connection conn) {
    endTs = endTs * 1000;
    // Lazy fetching the cursor prevents us from buffering the whole dataset in memory.
    Cursor<Record> cursor = context.get(conn).selectDistinct(schema.dependencyLinkFields).from(ZIPKIN_SPANS.leftJoin(ZIPKIN_ANNOTATIONS).on(ZIPKIN_SPANS.TRACE_ID.eq(ZIPKIN_ANNOTATIONS.TRACE_ID).and(ZIPKIN_SPANS.ID.eq(ZIPKIN_ANNOTATIONS.SPAN_ID))).and(ZIPKIN_ANNOTATIONS.A_KEY.in(CLIENT_SEND, CLIENT_ADDR, SERVER_RECV, SERVER_ADDR))).where(lookback == null ? ZIPKIN_SPANS.START_TS.lessOrEqual(endTs) : ZIPKIN_SPANS.START_TS.between(endTs - lookback * 1000, endTs)).groupBy(schema.dependencyLinkGroupByFields).fetchLazy();
    Iterator<Iterator<DependencyLinkSpan>> traces = new DependencyLinkSpanIterator.ByTraceId(cursor.iterator(), schema.hasTraceIdHigh);
    if (!traces.hasNext())
        return Collections.emptyList();
    DependencyLinker linker = new DependencyLinker();
    while (traces.hasNext()) {
        linker.putTrace(traces.next());
    }
    return linker.link();
}
Also used : GroupByTraceId(zipkin.internal.GroupByTraceId) DependencyLinker(zipkin.internal.DependencyLinker) Iterator(java.util.Iterator) Record(org.jooq.Record)

Example 45 with Record

use of org.jooq.Record in project zipkin by openzipkin.

the class MySQLSpanStore method toTraceIdQuery.

SelectOffsetStep<? extends Record> toTraceIdQuery(DSLContext context, QueryRequest request) {
    long endTs = (request.endTs > 0 && request.endTs != Long.MAX_VALUE) ? request.endTs * 1000 : System.currentTimeMillis() * 1000;
    TableOnConditionStep<?> table = ZIPKIN_SPANS.join(ZIPKIN_ANNOTATIONS).on(schema.joinCondition(ZIPKIN_ANNOTATIONS));
    int i = 0;
    for (String key : request.annotations) {
        ZipkinAnnotations aTable = ZIPKIN_ANNOTATIONS.as("a" + i++);
        table = maybeOnService(table.join(aTable).on(schema.joinCondition(aTable)).and(aTable.A_TYPE.eq(-1)).and(aTable.A_KEY.eq(key)), aTable, request.serviceName);
    }
    for (Map.Entry<String, String> kv : request.binaryAnnotations.entrySet()) {
        ZipkinAnnotations aTable = ZIPKIN_ANNOTATIONS.as("a" + i++);
        table = maybeOnService(table.join(aTable).on(schema.joinCondition(aTable)).and(aTable.A_TYPE.eq(STRING.value)).and(aTable.A_KEY.eq(kv.getKey())).and(aTable.A_VALUE.eq(kv.getValue().getBytes(UTF_8))), aTable, request.serviceName);
    }
    List<SelectField<?>> distinctFields = new ArrayList<>(schema.spanIdFields);
    distinctFields.add(ZIPKIN_SPANS.START_TS.max());
    SelectConditionStep<Record> dsl = context.selectDistinct(distinctFields).from(table).where(ZIPKIN_SPANS.START_TS.between(endTs - request.lookback * 1000, endTs));
    if (request.serviceName != null) {
        dsl.and(ZIPKIN_ANNOTATIONS.ENDPOINT_SERVICE_NAME.eq(request.serviceName));
    }
    if (request.spanName != null) {
        dsl.and(ZIPKIN_SPANS.NAME.eq(request.spanName));
    }
    if (request.minDuration != null && request.maxDuration != null) {
        dsl.and(ZIPKIN_SPANS.DURATION.between(request.minDuration, request.maxDuration));
    } else if (request.minDuration != null) {
        dsl.and(ZIPKIN_SPANS.DURATION.greaterOrEqual(request.minDuration));
    }
    return dsl.groupBy(schema.spanIdFields).orderBy(ZIPKIN_SPANS.START_TS.max().desc()).limit(request.limit);
}
Also used : ZipkinAnnotations(zipkin.storage.mysql.internal.generated.tables.ZipkinAnnotations) SelectField(org.jooq.SelectField) ArrayList(java.util.ArrayList) Record(org.jooq.Record) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Endpoint(zipkin.Endpoint)

Aggregations

Record (org.jooq.Record)93 ArrayList (java.util.ArrayList)40 SchemaDefinition (org.jooq.util.SchemaDefinition)36 TableDefinition (org.jooq.util.TableDefinition)32 ColumnDefinition (org.jooq.util.ColumnDefinition)23 DefaultDataTypeDefinition (org.jooq.util.DefaultDataTypeDefinition)22 DataTypeDefinition (org.jooq.util.DataTypeDefinition)19 DefaultColumnDefinition (org.jooq.util.DefaultColumnDefinition)11 TableField (org.jooq.TableField)9 UpdatableRecord (org.jooq.UpdatableRecord)9 TableRecord (org.jooq.TableRecord)7 Connection (java.sql.Connection)5 DSLContext (org.jooq.DSLContext)5 StringUtils.defaultString (org.jooq.tools.StringUtils.defaultString)5 DefaultParameterDefinition (org.jooq.util.DefaultParameterDefinition)5 DefaultSequenceDefinition (org.jooq.util.DefaultSequenceDefinition)5 ParameterDefinition (org.jooq.util.ParameterDefinition)5 SequenceDefinition (org.jooq.util.SequenceDefinition)5 Condition (org.jooq.Condition)4 Schema (org.jooq.Schema)4