Search in sources :

Example 1 with TableElement

use of ru.curs.celesta.score.TableElement in project celesta by CourseOrchestra.

the class FirebirdAdaptor method processDefaults.

private void processDefaults(Connection conn, Column<?> c, DbColumnInfo dbColumnInfo) throws SQLException {
    String defaultValue = null;
    TableElement te = c.getParentTable();
    Grain g = te.getGrain();
    String sql = String.format("SELECT r.RDB$DEFAULT_SOURCE AS column_default_value%n" + "   FROM RDB$RELATION_FIELDS r%n" + "   WHERE r.RDB$RELATION_NAME='%s_%s' AND r.RDB$FIELD_NAME = '%s'", c.getParentTable().getGrain().getName(), c.getParentTable().getName(), c.getName());
    try (ResultSet rs = SqlUtils.executeQuery(conn, sql)) {
        rs.next();
        String defaultSource = rs.getString(1);
        if (defaultSource == null) {
            if (IntegerColumn.class.equals(dbColumnInfo.getType())) {
                String triggerName = SchemalessFunctions.generateSequenceTriggerName((IntegerColumn) c);
                sql = String.format("SELECT proc.RDB$DEPENDED_ON_NAME %n " + "FROM RDB$DEPENDENCIES tr%n " + "JOIN RDB$DEPENDENCIES proc ON tr.RDB$DEPENDED_ON_NAME = proc.RDB$DEPENDENT_NAME%n " + "WHERE tr.RDB$DEPENDENT_NAME = '%s' AND tr.RDB$DEPENDENT_TYPE = 2 " + "AND tr.RDB$DEPENDED_ON_TYPE = 5%n " + "AND proc.RDB$DEPENDENT_TYPE = 5 AND proc.RDB$DEPENDED_ON_TYPE = 14", triggerName);
                try (ResultSet sequenceRs = SqlUtils.executeQuery(conn, sql)) {
                    if (sequenceRs.next()) {
                        String sequenceName = sequenceRs.getString(1).trim();
                        defaultValue = "NEXTVAL(" + // TODO: score sequence name could be spoiled here because of name limitation
                        sequenceName.replace(g.getName() + "_", "") + ")";
                    }
                }
            }
        } else {
            defaultValue = defaultSource.replace("default", "").trim();
            if (BooleanColumn.class.equals(dbColumnInfo.getType())) {
                defaultValue = "0".equals(defaultValue) ? "'FALSE'" : "'TRUE'";
            } else if (DateTimeColumn.class.equals(dbColumnInfo.getType())) {
                if (FireBirdConstants.CURRENT_TIMESTAMP.equalsIgnoreCase(defaultValue)) {
                    defaultValue = "GETDATE()";
                } else {
                    Matcher m = DATE_PATTERN.matcher(defaultValue);
                    if (m.find()) {
                        defaultValue = String.format("'%s%s%s'", m.group(3), m.group(2), m.group(1));
                    }
                }
            } else if (BinaryColumn.class.equals(dbColumnInfo.getType())) {
                Matcher m = HEX_STRING.matcher(defaultValue);
                if (m.find()) {
                    defaultValue = "0x" + m.group(1);
                }
            }
        }
    }
    if (defaultValue != null) {
        dbColumnInfo.setDefaultValue(defaultValue);
    }
}
Also used : Matcher(java.util.regex.Matcher) Grain(ru.curs.celesta.score.Grain) ResultSet(java.sql.ResultSet) DateTimeColumn(ru.curs.celesta.score.DateTimeColumn) TableElement(ru.curs.celesta.score.TableElement)

Example 2 with TableElement

use of ru.curs.celesta.score.TableElement in project celesta by CourseOrchestra.

the class OpenSourceDbAdaptor method getOneFieldStatement.

@Override
public PreparedStatement getOneFieldStatement(Connection conn, Column<?> c, String where) {
    TableElement t = c.getParentTable();
    String sql = String.format(SELECT_S_FROM + tableString(t.getGrain().getName(), t.getName()) + " where %s limit 1;", c.getQuotedName(), where);
    return prepareStatement(conn, sql);
}
Also used : TableElement(ru.curs.celesta.score.TableElement)

Example 3 with TableElement

use of ru.curs.celesta.score.TableElement in project celesta by CourseOrchestra.

the class OraAdaptor method processDefaults.

private void processDefaults(Connection conn, Column<?> c, DbColumnInfo result) throws SQLException {
    ResultSet rs;
    TableElement te = c.getParentTable();
    Grain g = te.getGrain();
    PreparedStatement getDefault = conn.prepareStatement(String.format("select DATA_DEFAULT from DBA_TAB_COLUMNS where " + "owner = sys_context('userenv','session_user') " + "and TABLE_NAME = '%s_%s' and COLUMN_NAME = '%s'", g.getName(), te.getName(), c.getName()));
    try {
        rs = getDefault.executeQuery();
        if (!rs.next()) {
            return;
        }
        String body = rs.getString(1);
        if (body == null || "null".equalsIgnoreCase(body)) {
            if (c instanceof IntegerColumn) {
                IntegerColumn ic = (IntegerColumn) c;
                String sequenceTriggerName = generateSequenceTriggerName(ic);
                String sql = String.format("SELECT REFERENCED_NAME FROM USER_DEPENDENCIES " + " WHERE NAME = '%s' " + " AND TYPE = 'TRIGGER' " + " AND REFERENCED_TYPE = 'SEQUENCE'", sequenceTriggerName);
                try (Statement stmt = conn.createStatement();
                    ResultSet sequenceRs = stmt.executeQuery(sql)) {
                    if (sequenceRs.next()) {
                        String sequenceName = sequenceRs.getString(1);
                        body = "NEXTVAL(" + sequenceName.replace(g.getName() + "_", "") + ")";
                    } else {
                        return;
                    }
                }
            } else {
                return;
            }
        }
        if (BooleanColumn.class == result.getType()) {
            body = "0".equals(body.trim()) ? "'FALSE'" : "'TRUE'";
        } else if (DateTimeColumn.class == result.getType()) {
            if (body.toLowerCase().contains("sysdate")) {
                body = "GETDATE()";
            } else {
                Matcher m = DATE_PATTERN.matcher(body);
                if (m.find()) {
                    body = String.format("'%s%s%s'", m.group(1), m.group(2), m.group(3));
                }
            }
        } else if (BinaryColumn.class == result.getType()) {
            Matcher m = HEX_STRING.matcher(body);
            if (m.find()) {
                body = "0x" + m.group(1);
            }
        } else {
            body = body.trim();
        }
        result.setDefaultValue(body);
    } finally {
        getDefault.close();
    }
}
Also used : IntegerColumn(ru.curs.celesta.score.IntegerColumn) Matcher(java.util.regex.Matcher) Grain(ru.curs.celesta.score.Grain) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) DateTimeColumn(ru.curs.celesta.score.DateTimeColumn) ZonedDateTimeColumn(ru.curs.celesta.score.ZonedDateTimeColumn) TableElement(ru.curs.celesta.score.TableElement)

Example 4 with TableElement

use of ru.curs.celesta.score.TableElement in project celesta by CourseOrchestra.

the class CursorGenerator method generateCursor.

/**
 * Generate code for schema (grain) element.
 * @param ge Schema (grain) element
 * @param scorePath path to CelestaSQL file
 */
public void generateCursor(GrainElement ge, String scorePath) {
    final String sourcePackage = calcSourcePackage(ge, scorePath);
    if (sourcePackage.isEmpty()) {
        throw new CelestaException("Couldn't generate class file for %s.%s without package", ge.getGrain().getName(), ge.getName());
    }
    final String className = calcClassName(ge);
    final String columnsClassName = "Columns";
    boolean isVersionedGe = ge instanceof VersionedElement && ((VersionedElement) ge).isVersioned();
    ClassName classType = ClassName.bestGuess(className);
    TypeSpec.Builder cursorClass = buildClassDefinition(ge, classType);
    ClassName columnsClassType = classType.nestedClass(columnsClassName);
    cursorClass.addFields(buildMetaFields(ge));
    cursorClass.addMethods(buildConstructors(ge, columnsClassType));
    // FIELDS
    if (ge instanceof DataGrainElement) {
        DataGrainElement dge = (DataGrainElement) ge;
        FieldSpec columnsField = buildColumnsField(columnsClassType);
        cursorClass.addField(columnsField);
        cursorClass.addInitializerBlock(buildColumnsFiledInitializer(columnsField));
        List<FieldSpec> fieldSpecs = buildDataFields(dge);
        cursorClass.addFields(fieldSpecs);
        cursorClass.addMethods(generateGettersAndSetters(fieldSpecs, classType));
        cursorClass.addMethod(buildGetFieldValue(dge.getColumns()));
        cursorClass.addMethod(buildSetFieldValue(dge.getColumns()));
        StringBuilder parseResultOverridingMethodNameBuilder = new StringBuilder("_parseResult");
        Set<Column<?>> pk = Collections.emptySet();
        if (dge instanceof TableElement && !(dge instanceof ReadOnlyTable)) {
            TableElement te = (TableElement) dge;
            pk = new LinkedHashSet<>(te.getPrimaryKey().values());
            cursorClass.addMethod(buildCurrentKeyValues(pk));
            cursorClass.addMethod(buildTryGet(pk));
            cursorClass.addMethod(buildGet(pk));
            if (te instanceof Table) {
                parseResultOverridingMethodNameBuilder.append("Internal");
            }
        }
        final Map<String, ? extends ColumnMeta<?>> columns = dge.getColumns();
        MethodSpec buildParseResultMethod = buildParseResult(columns, parseResultOverridingMethodNameBuilder.toString(), isVersionedGe);
        cursorClass.addMethod(buildParseResultMethod);
        cursorClass.addMethod(buildClearBuffer(columns, pk));
        cursorClass.addMethod(buildCurrentValues(columns));
        cursorClass.addType(buildCursorColumnsAsInnerStaticClass(dge, columnsClassType));
        if (dge instanceof BasicTable) {
            BasicTable t = (BasicTable) dge;
            if (t instanceof Table) {
                cursorClass.addMethods(buildCalcBlobs(columns, className));
                cursorClass.addMethod(buildSetAutoIncrement(columns));
                cursorClass.addMethods(buildTriggerRegistration(classType));
            }
            cursorClass.addTypes(buildOptionFieldsAsInnerStaticClasses(t.getColumns().values()));
        }
        cursorClass.addMethods(buildCompileCopying(ge, classType, columns.keySet(), isVersionedGe));
        cursorClass.addMethod(buildIterator(classType));
    }
    cursorClass.addMethods(buildGrainNameAndObjectName(ge));
    JavaFile javaFile = JavaFile.builder(sourcePackage, cursorClass.build()).skipJavaLangImports(true).indent("    ").build();
    try {
        javaFile.writeTo(srcDir);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : ReadOnlyTable(ru.curs.celesta.score.ReadOnlyTable) BasicTable(ru.curs.celesta.score.BasicTable) ReadOnlyTable(ru.curs.celesta.score.ReadOnlyTable) Table(ru.curs.celesta.score.Table) MethodSpec(com.squareup.javapoet.MethodSpec) IOException(java.io.IOException) CelestaException(ru.curs.celesta.CelestaException) DataGrainElement(ru.curs.celesta.score.DataGrainElement) FieldSpec(com.squareup.javapoet.FieldSpec) TableElement(ru.curs.celesta.score.TableElement) BasicTable(ru.curs.celesta.score.BasicTable) VersionedElement(ru.curs.celesta.score.VersionedElement) StringColumn(ru.curs.celesta.score.StringColumn) Column(ru.curs.celesta.score.Column) IntegerColumn(ru.curs.celesta.score.IntegerColumn) ZonedDateTimeColumn(ru.curs.celesta.score.ZonedDateTimeColumn) BinaryColumn(ru.curs.celesta.score.BinaryColumn) ClassName(com.squareup.javapoet.ClassName) JavaFile(com.squareup.javapoet.JavaFile) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 5 with TableElement

use of ru.curs.celesta.score.TableElement in project celesta by CourseOrchestra.

the class FirebirdAdaptor method getOneFieldStatement.

@Override
public PreparedStatement getOneFieldStatement(Connection conn, Column<?> c, String where) {
    TableElement t = c.getParentTable();
    String sql = String.format("select first 1 %s from %s where %s;", c.getQuotedName(), tableString(t.getGrain().getName(), t.getName()), where);
    return prepareStatement(conn, sql);
}
Also used : TableElement(ru.curs.celesta.score.TableElement)

Aggregations

TableElement (ru.curs.celesta.score.TableElement)11 DateTimeColumn (ru.curs.celesta.score.DateTimeColumn)4 IntegerColumn (ru.curs.celesta.score.IntegerColumn)4 Matcher (java.util.regex.Matcher)3 TriggerQuery (ru.curs.celesta.event.TriggerQuery)3 Grain (ru.curs.celesta.score.Grain)3 IOException (java.io.IOException)2 ResultSet (java.sql.ResultSet)2 ArrayList (java.util.ArrayList)2 LinkedList (java.util.LinkedList)2 List (java.util.List)2 CelestaException (ru.curs.celesta.CelestaException)2 BasicTable (ru.curs.celesta.score.BasicTable)2 BinaryColumn (ru.curs.celesta.score.BinaryColumn)2 Column (ru.curs.celesta.score.Column)2 SequenceElement (ru.curs.celesta.score.SequenceElement)2 ZonedDateTimeColumn (ru.curs.celesta.score.ZonedDateTimeColumn)2 ClassName (com.squareup.javapoet.ClassName)1 FieldSpec (com.squareup.javapoet.FieldSpec)1 JavaFile (com.squareup.javapoet.JavaFile)1