Search in sources :

Example 1 with DbColumn

use of ch.ehi.sqlgen.repository.DbColumn in project ili2db by claeis.

the class GeneratorMsSql method visitTableBeginConstraint.

@Override
public void visitTableBeginConstraint(DbTable dbTab) throws IOException {
    super.visitTableBeginConstraint(dbTab);
    String sqlTabName = dbTab.getName().getQName();
    for (Iterator dbColi = dbTab.iteratorColumn(); dbColi.hasNext(); ) {
        DbColumn dbCol = (DbColumn) dbColi.next();
        if (dbCol.getReferencedTable() != null) {
            String createstmt = null;
            String action = "";
            if (dbCol.getOnUpdateAction() != null) {
                action = action + " ON UPDATE " + dbCol.getOnUpdateAction();
            }
            if (dbCol.getOnDeleteAction() != null) {
                action = action + " ON DELETE " + dbCol.getOnDeleteAction();
            }
            String constraintName = createConstraintName(dbTab, "fkey", dbCol.getName());
            // +action+" DEFERRABLE INITIALLY DEFERRED";
            createstmt = "ALTER TABLE " + sqlTabName + " ADD CONSTRAINT " + constraintName + " FOREIGN KEY ( " + dbCol.getName() + " ) REFERENCES " + dbCol.getReferencedTable().getQName();
            String dropstmt = null;
            dropstmt = "ALTER TABLE " + sqlTabName + " DROP CONSTRAINT " + constraintName;
            addConstraint(dbTab, constraintName, createstmt, dropstmt);
        }
        if (dbCol instanceof DbColNumber && (((DbColNumber) dbCol).getMinValue() != null || ((DbColNumber) dbCol).getMaxValue() != null)) {
            DbColNumber dbColNum = (DbColNumber) dbCol;
            String createstmt = null;
            String action = "";
            if (dbColNum.getMinValue() != null || dbColNum.getMaxValue() != null) {
                if (dbColNum.getMaxValue() == null) {
                    action = ">=" + dbColNum.getMinValue();
                } else if (dbColNum.getMinValue() == null) {
                    action = "<=" + dbColNum.getMaxValue();
                } else {
                    action = "BETWEEN " + dbColNum.getMinValue() + " AND " + dbColNum.getMaxValue();
                }
            }
            String constraintName = createConstraintName(dbTab, "check", dbCol.getName());
            createstmt = "ALTER TABLE " + sqlTabName + " ADD CONSTRAINT " + constraintName + " CHECK( " + dbCol.getName() + " " + action + ")";
            String dropstmt = null;
            dropstmt = "ALTER TABLE " + sqlTabName + " DROP CONSTRAINT " + constraintName;
            addConstraint(dbTab, constraintName, createstmt, dropstmt);
        } else if (dbCol instanceof DbColDecimal && (((DbColDecimal) dbCol).getMinValue() != null || ((DbColDecimal) dbCol).getMaxValue() != null)) {
            DbColDecimal dbColNum = (DbColDecimal) dbCol;
            String createstmt = null;
            String action = "";
            if (dbColNum.getMinValue() != null || dbColNum.getMaxValue() != null) {
                if (dbColNum.getMaxValue() == null) {
                    action = ">=" + dbColNum.getMinValue();
                } else if (dbColNum.getMinValue() == null) {
                    action = "<=" + dbColNum.getMaxValue();
                } else {
                    action = "BETWEEN " + dbColNum.getMinValue() + " AND " + dbColNum.getMaxValue();
                }
            }
            String constraintName = createConstraintName(dbTab, "check", dbCol.getName());
            createstmt = "ALTER TABLE " + sqlTabName + " ADD CONSTRAINT " + constraintName + " CHECK( " + dbCol.getName() + " " + action + ")";
            String dropstmt = null;
            dropstmt = "ALTER TABLE " + sqlTabName + " DROP CONSTRAINT " + constraintName;
            addConstraint(dbTab, constraintName, createstmt, dropstmt);
        }
    }
}
Also used : DbColumn(ch.ehi.sqlgen.repository.DbColumn) Iterator(java.util.Iterator) DbColDecimal(ch.ehi.sqlgen.repository.DbColDecimal) DbColNumber(ch.ehi.sqlgen.repository.DbColNumber)

Example 2 with DbColumn

use of ch.ehi.sqlgen.repository.DbColumn in project ili2db by claeis.

the class GeneratorMsSql method visitIndex.

@Override
public void visitIndex(DbIndex idx) throws IOException {
    if (idx.isUnique()) {
        java.io.StringWriter out = new java.io.StringWriter();
        DbTable tab = idx.getTable();
        String tableName = tab.getName().getQName();
        String constraintName = idx.getName();
        if (constraintName == null) {
            String[] colNames = new String[idx.sizeAttr()];
            int i = 0;
            for (Iterator attri = idx.iteratorAttr(); attri.hasNext(); ) {
                DbColumn attr = (DbColumn) attri.next();
                colNames[i++] = attr.getName();
            }
            constraintName = createConstraintName(tab, "key", colNames);
        }
        out.write(getIndent() + "CREATE UNIQUE INDEX " + constraintName + " ON " + tableName + " (");
        String sep = "";
        String condition = " ";
        String sepCondition = " ";
        for (Iterator attri = idx.iteratorAttr(); attri.hasNext(); ) {
            DbColumn attr = (DbColumn) attri.next();
            out.write(sep + attr.getName());
            condition += sepCondition + attr.getName() + " is not null";
            sep = ",";
            sepCondition = " AND ";
        }
        out.write(") WHERE" + condition + newline());
        String stmt = out.toString();
        addCreateLine(new Stmt(stmt));
        out = null;
        if (createdTables.contains(tab.getName())) {
            Statement dbstmt = null;
            try {
                try {
                    dbstmt = conn.createStatement();
                    EhiLogger.traceBackendCmd(stmt);
                    dbstmt.executeUpdate(stmt);
                } finally {
                    dbstmt.close();
                }
            } catch (SQLException ex) {
                IOException iox = new IOException("failed to add UNIQUE to table " + tab.getName());
                iox.initCause(ex);
                throw iox;
            }
        }
    }
}
Also used : DbColumn(ch.ehi.sqlgen.repository.DbColumn) SQLException(java.sql.SQLException) Statement(java.sql.Statement) IOException(java.io.IOException) Iterator(java.util.Iterator) DbTable(ch.ehi.sqlgen.repository.DbTable)

Example 3 with DbColumn

use of ch.ehi.sqlgen.repository.DbColumn in project ili2db by claeis.

the class FromIliRecordConverter method generateAttr.

public void generateAttr(DbTable dbTable, Viewable aclass, AttributeDef attr) throws Ili2dbException {
    Holder<DbColumn> dbCol = new Holder<DbColumn>();
    dbCol.value = null;
    Holder<Unit> unitDef = new Holder<Unit>();
    unitDef.value = null;
    Holder<Boolean> mText = new Holder<Boolean>();
    mText.value = false;
    ArrayList<DbColumn> dbColExts = new ArrayList<DbColumn>();
    Type type = attr.getDomainResolvingAll();
    if (createSimpleDbCol(dbTable, aclass, attr, type, dbCol, unitDef, mText, dbColExts)) {
    } else if (type instanceof SurfaceOrAreaType) {
        if (createItfLineTables) {
            dbCol.value = null;
        } else {
            DbColGeometry ret = new DbColGeometry();
            boolean curvePolygon = false;
            if (!strokeArcs) {
                curvePolygon = true;
            }
            ret.setType(curvePolygon ? DbColGeometry.CURVEPOLYGON : DbColGeometry.POLYGON);
            // get crs from ili
            setCrs(ret, attr);
            CoordType coord = (CoordType) ((SurfaceOrAreaType) type).getControlPointDomain().getType();
            ret.setDimension(coord.getDimensions().length);
            setBB(ret, coord, attr.getContainer().getScopedName(null) + "." + attr.getName());
            dbCol.value = ret;
        }
        if (createItfAreaRef) {
            if (type instanceof AreaType) {
                DbColGeometry ret = new DbColGeometry();
                String sqlName = getSqlAttrName(attr, dbTable.getName().getName(), null) + DbNames.ITF_MAINTABLE_GEOTABLEREF_COL_SUFFIX;
                ret.setName(sqlName);
                ret.setType(DbColGeometry.POINT);
                setNullable(aclass, attr, ret);
                // get crs from ili
                setCrs(ret, attr);
                // always 2 (even if defined as 3d in ili)
                ret.setDimension(2);
                CoordType coord = (CoordType) ((SurfaceOrAreaType) type).getControlPointDomain().getType();
                setBB(ret, coord, attr.getContainer().getScopedName(null) + "." + attr.getName());
                dbColExts.add(ret);
            }
        }
    } else if (type instanceof PolylineType) {
        String attrName = attr.getContainer().getScopedName(null) + "." + attr.getName();
        DbColGeometry ret = generatePolylineType((PolylineType) type, attrName);
        setCrs(ret, attr);
        dbCol.value = ret;
    } else if (type instanceof CoordType) {
        DbColGeometry ret = new DbColGeometry();
        ret.setType(DbColGeometry.POINT);
        // get crs from ili
        setCrs(ret, attr);
        CoordType coord = (CoordType) type;
        ret.setDimension(coord.getDimensions().length);
        setBB(ret, coord, attr.getContainer().getScopedName(null) + "." + attr.getName());
        dbCol.value = ret;
    } else if (type instanceof CompositionType) {
        // skip it
        if (!createGenericStructRef) {
            if (isChbaseCatalogueRef(td, attr) && (coalesceCatalogueRef || TrafoConfigNames.CATALOGUE_REF_TRAFO_COALESCE.equals(trafoConfig.getAttrConfig(attr, TrafoConfigNames.CATALOGUE_REF_TRAFO)))) {
                DbColId ret = new DbColId();
                ret.setNotNull(false);
                ret.setPrimaryKey(false);
                if (createFk) {
                    ret.setReferencedTable(getSqlType(((ReferenceType) ((AttributeDef) ((CompositionType) type).getComponentType().getAttributes().next()).getDomain()).getReferred()));
                }
                if (createFkIdx) {
                    ret.setIndex(true);
                }
                trafoConfig.setAttrConfig(attr, TrafoConfigNames.CATALOGUE_REF_TRAFO, TrafoConfigNames.CATALOGUE_REF_TRAFO_COALESCE);
                dbCol.value = ret;
            } else if (Ili2cUtility.isMultiSurfaceAttr(td, attr) && (coalesceMultiSurface || TrafoConfigNames.MULTISURFACE_TRAFO_COALESCE.equals(trafoConfig.getAttrConfig(attr, TrafoConfigNames.MULTISURFACE_TRAFO)))) {
                multiSurfaceAttrs.addMultiSurfaceAttr(attr);
                MultiSurfaceMapping attrMapping = multiSurfaceAttrs.getMapping(attr);
                DbColGeometry ret = new DbColGeometry();
                boolean curvePolygon = false;
                if (!strokeArcs) {
                    curvePolygon = true;
                }
                ret.setType(curvePolygon ? DbColGeometry.MULTISURFACE : DbColGeometry.MULTIPOLYGON);
                // get crs from ili
                AttributeDef surfaceAttr = (AttributeDef) ((CompositionType) ((AttributeDef) ((CompositionType) type).getComponentType().getElement(AttributeDef.class, attrMapping.getBagOfSurfacesAttrName())).getDomain()).getComponentType().getElement(AttributeDef.class, attrMapping.getSurfaceAttrName());
                setCrs(ret, surfaceAttr);
                SurfaceType surface = ((SurfaceType) surfaceAttr.getDomainResolvingAliases());
                CoordType coord = (CoordType) surface.getControlPointDomain().getType();
                ret.setDimension(coord.getDimensions().length);
                setBB(ret, coord, attr.getContainer().getScopedName(null) + "." + attr.getName());
                dbCol.value = ret;
                trafoConfig.setAttrConfig(attr, TrafoConfigNames.MULTISURFACE_TRAFO, TrafoConfigNames.MULTISURFACE_TRAFO_COALESCE);
            } else if (Ili2cUtility.isMultiLineAttr(td, attr) && (coalesceMultiLine || TrafoConfigNames.MULTILINE_TRAFO_COALESCE.equals(trafoConfig.getAttrConfig(attr, TrafoConfigNames.MULTILINE_TRAFO)))) {
                multiLineAttrs.addMultiLineAttr(attr);
                MultiLineMapping attrMapping = multiLineAttrs.getMapping(attr);
                DbColGeometry ret = new DbColGeometry();
                boolean curvePolyline = false;
                if (!strokeArcs) {
                    curvePolyline = true;
                }
                ret.setType(curvePolyline ? DbColGeometry.MULTICURVE : DbColGeometry.MULTILINESTRING);
                // get crs from ili
                AttributeDef polylineAttr = (AttributeDef) ((CompositionType) ((AttributeDef) ((CompositionType) type).getComponentType().getElement(AttributeDef.class, attrMapping.getBagOfLinesAttrName())).getDomain()).getComponentType().getElement(AttributeDef.class, attrMapping.getLineAttrName());
                setCrs(ret, polylineAttr);
                PolylineType polylineType = ((PolylineType) polylineAttr.getDomainResolvingAliases());
                CoordType coord = (CoordType) polylineType.getControlPointDomain().getType();
                ret.setDimension(coord.getDimensions().length);
                setBB(ret, coord, attr.getContainer().getScopedName(null) + "." + attr.getName());
                dbCol.value = ret;
                trafoConfig.setAttrConfig(attr, TrafoConfigNames.MULTILINE_TRAFO, TrafoConfigNames.MULTILINE_TRAFO_COALESCE);
            } else if (Ili2cUtility.isMultiPointAttr(td, attr) && (coalesceMultiPoint || TrafoConfigNames.MULTIPOINT_TRAFO_COALESCE.equals(trafoConfig.getAttrConfig(attr, TrafoConfigNames.MULTIPOINT_TRAFO)))) {
                multiPointAttrs.addMultiPointAttr(attr);
                MultiPointMapping attrMapping = multiPointAttrs.getMapping(attr);
                DbColGeometry ret = new DbColGeometry();
                ret.setType(DbColGeometry.MULTIPOINT);
                // get crs from ili
                AttributeDef coordAttr = (AttributeDef) ((CompositionType) ((AttributeDef) ((CompositionType) type).getComponentType().getElement(AttributeDef.class, attrMapping.getBagOfPointsAttrName())).getDomain()).getComponentType().getElement(AttributeDef.class, attrMapping.getPointAttrName());
                setCrs(ret, coordAttr);
                CoordType coord = (CoordType) (coordAttr.getDomainResolvingAliases());
                ret.setDimension(coord.getDimensions().length);
                setBB(ret, coord, attr.getContainer().getScopedName(null) + "." + attr.getName());
                dbCol.value = ret;
                trafoConfig.setAttrConfig(attr, TrafoConfigNames.MULTIPOINT_TRAFO, TrafoConfigNames.MULTIPOINT_TRAFO_COALESCE);
            } else if (Ili2cUtility.isArrayAttr(td, attr) && (coalesceArray || TrafoConfigNames.ARRAY_TRAFO_COALESCE.equals(trafoConfig.getAttrConfig(attr, TrafoConfigNames.ARRAY_TRAFO)))) {
                arrayAttrs.addArrayAttr(attr);
                ArrayMapping attrMapping = arrayAttrs.getMapping(attr);
                AttributeDef localAttr = attrMapping.getValueAttr();
                Type localType = localAttr.getDomainResolvingAll();
                if (!createSimpleDbCol(dbTable, aclass, localAttr, localType, dbCol, unitDef, mText, dbColExts)) {
                    throw new IllegalStateException("unexpected attr type " + localAttr.getScopedName());
                }
                dbCol.value.setArraySize(DbColumn.UNLIMITED_ARRAY);
                trafoConfig.setAttrConfig(attr, TrafoConfigNames.ARRAY_TRAFO, TrafoConfigNames.ARRAY_TRAFO_COALESCE);
            } else if (isChbaseMultilingual(td, attr) && (expandMultilingual || TrafoConfigNames.MULTILINGUAL_TRAFO_EXPAND.equals(trafoConfig.getAttrConfig(attr, TrafoConfigNames.MULTILINGUAL_TRAFO)))) {
                for (String sfx : DbNames.MULTILINGUAL_TXT_COL_SUFFIXS) {
                    DbColVarchar ret = new DbColVarchar();
                    ret.setName(getSqlAttrName(attr, dbTable.getName().getName(), null) + sfx);
                    ret.setSize(DbColVarchar.UNLIMITED);
                    ret.setNotNull(false);
                    ret.setPrimaryKey(false);
                    dbColExts.add(ret);
                }
                trafoConfig.setAttrConfig(attr, TrafoConfigNames.MULTILINGUAL_TRAFO, TrafoConfigNames.MULTILINGUAL_TRAFO_EXPAND);
            } else {
                // add reference col from struct ele to parent obj to struct table
                addParentRef(aclass, attr);
                dbCol.value = null;
            }
        } else {
            dbCol.value = null;
        }
    } else if (type instanceof ReferenceType) {
        ArrayList<ViewableWrapper> targetTables = getTargetTables(((ReferenceType) type).getReferred());
        for (ViewableWrapper targetTable : targetTables) {
            DbColId ret = new DbColId();
            ret.setName(ili2sqlName.mapIliAttributeDef(attr, dbTable.getName().getName(), targetTable.getSqlTablename(), targetTables.size() > 1));
            ret.setNotNull(false);
            ret.setPrimaryKey(false);
            if (createFk) {
                ret.setReferencedTable(targetTable.getSqlTable());
            }
            if (createFkIdx) {
                ret.setIndex(true);
            }
            dbColExts.add(ret);
        }
    } else {
        DbColVarchar ret = new DbColVarchar();
        ret.setSize(255);
        dbCol.value = ret;
    }
    if (type instanceof EnumerationType) {
        if (createEnumTxtCol) {
            DbColVarchar ret = new DbColVarchar();
            ret.setSize(255);
            ret.setName(getSqlAttrName(attr, dbTable.getName().getName(), null) + DbNames.ENUM_TXT_COL_SUFFIX);
            setNullable(aclass, attr, ret);
            dbColExts.add(ret);
        }
    }
    if (dbCol.value != null) {
        String sqlColName = getSqlAttrName(attr, dbTable.getName().getName(), null);
        setAttrDbColProps(aclass, attr, dbCol.value, sqlColName);
        String subType = null;
        Viewable attrClass = (Viewable) attr.getContainer();
        if (attrClass != aclass && attrClass.isExtending(aclass)) {
            subType = getSqlType(attrClass).getName();
        }
        if (unitDef.value != null) {
            String unitName = unitDef.value.getName();
            metaInfo.setColumnInfo(dbTable.getName().getName(), subType, sqlColName, DbExtMetaInfo.TAG_COL_UNIT, unitName);
        }
        if (mText.value) {
            metaInfo.setColumnInfo(dbTable.getName().getName(), subType, sqlColName, DbExtMetaInfo.TAG_COL_TEXTKIND, DbExtMetaInfo.TAG_COL_TEXTKIND_MTEXT);
        }
        if (dbCol.value instanceof DbColGeometry) {
            metaInfo.setColumnInfo(dbTable.getName().getName(), subType, sqlColName, DbExtMetaInfo.TAG_COL_C1_MIN, Double.toString(((DbColGeometry) dbCol.value).getMin1()));
            metaInfo.setColumnInfo(dbTable.getName().getName(), subType, sqlColName, DbExtMetaInfo.TAG_COL_C1_MAX, Double.toString(((DbColGeometry) dbCol.value).getMax1()));
            metaInfo.setColumnInfo(dbTable.getName().getName(), subType, sqlColName, DbExtMetaInfo.TAG_COL_C2_MIN, Double.toString(((DbColGeometry) dbCol.value).getMin2()));
            metaInfo.setColumnInfo(dbTable.getName().getName(), subType, sqlColName, DbExtMetaInfo.TAG_COL_C2_MAX, Double.toString(((DbColGeometry) dbCol.value).getMax2()));
            if (((DbColGeometry) dbCol.value).getDimension() == 3) {
                metaInfo.setColumnInfo(dbTable.getName().getName(), subType, sqlColName, DbExtMetaInfo.TAG_COL_C3_MIN, Double.toString(((DbColGeometry) dbCol.value).getMin3()));
                metaInfo.setColumnInfo(dbTable.getName().getName(), subType, sqlColName, DbExtMetaInfo.TAG_COL_C3_MAX, Double.toString(((DbColGeometry) dbCol.value).getMax3()));
            }
        }
        String dispName = attr.getMetaValues().getValue(IliMetaAttrNames.METAATTR_DISPNAME);
        if (dispName != null) {
            metaInfo.setColumnInfo(dbTable.getName().getName(), subType, sqlColName, DbExtMetaInfo.TAG_COL_DISPNAME, dispName);
        }
        customMapping.fixupAttribute(dbTable, dbCol.value, attr);
        dbTable.addColumn(dbCol.value);
    }
    for (DbColumn dbColExt : dbColExts) {
        customMapping.fixupAttribute(dbTable, dbColExt, attr);
        dbTable.addColumn(dbColExt);
    }
    if (dbCol.value == null && dbColExts.size() == 0) {
        customMapping.fixupAttribute(dbTable, null, attr);
    }
}
Also used : DbColumn(ch.ehi.sqlgen.repository.DbColumn) SurfaceOrAreaType(ch.interlis.ili2c.metamodel.SurfaceOrAreaType) ArrayList(java.util.ArrayList) ViewableWrapper(ch.ehi.ili2db.mapping.ViewableWrapper) Unit(ch.interlis.ili2c.metamodel.Unit) SurfaceOrAreaType(ch.interlis.ili2c.metamodel.SurfaceOrAreaType) AreaType(ch.interlis.ili2c.metamodel.AreaType) CompositionType(ch.interlis.ili2c.metamodel.CompositionType) ReferenceType(ch.interlis.ili2c.metamodel.ReferenceType) DbColGeometry(ch.ehi.sqlgen.repository.DbColGeometry) AttributeDef(ch.interlis.ili2c.metamodel.AttributeDef) DbColBoolean(ch.ehi.sqlgen.repository.DbColBoolean) PolylineType(ch.interlis.ili2c.metamodel.PolylineType) MultiPointMapping(ch.ehi.ili2db.mapping.MultiPointMapping) Holder(javax.xml.ws.Holder) DbColVarchar(ch.ehi.sqlgen.repository.DbColVarchar) EnumerationType(ch.interlis.ili2c.metamodel.EnumerationType) SurfaceType(ch.interlis.ili2c.metamodel.SurfaceType) MultiSurfaceMapping(ch.ehi.ili2db.mapping.MultiSurfaceMapping) PolylineType(ch.interlis.ili2c.metamodel.PolylineType) Type(ch.interlis.ili2c.metamodel.Type) BasketType(ch.interlis.ili2c.metamodel.BasketType) ReferenceType(ch.interlis.ili2c.metamodel.ReferenceType) SurfaceOrAreaType(ch.interlis.ili2c.metamodel.SurfaceOrAreaType) SurfaceType(ch.interlis.ili2c.metamodel.SurfaceType) CompositionType(ch.interlis.ili2c.metamodel.CompositionType) TextType(ch.interlis.ili2c.metamodel.TextType) EnumerationType(ch.interlis.ili2c.metamodel.EnumerationType) NumericType(ch.interlis.ili2c.metamodel.NumericType) BlackboxType(ch.interlis.ili2c.metamodel.BlackboxType) AreaType(ch.interlis.ili2c.metamodel.AreaType) ObjectType(ch.interlis.ili2c.metamodel.ObjectType) CoordType(ch.interlis.ili2c.metamodel.CoordType) ArrayMapping(ch.ehi.ili2db.mapping.ArrayMapping) Viewable(ch.interlis.ili2c.metamodel.Viewable) MultiLineMapping(ch.ehi.ili2db.mapping.MultiLineMapping) DbColId(ch.ehi.sqlgen.repository.DbColId) CoordType(ch.interlis.ili2c.metamodel.CoordType)

Example 4 with DbColumn

use of ch.ehi.sqlgen.repository.DbColumn in project ili2db by claeis.

the class FromIliRecordConverter method generateTable.

public void generateTable(ViewableWrapper def, int pass) throws Ili2dbException {
    if (!def.isSecondaryTable()) {
        surfaceAttrs = new ArrayList<AttributeDef>();
    }
    // EhiLogger.debug("viewable "+def);
    if (pass == 1) {
        DbTableName sqlName = new DbTableName(schema.getName(), def.getSqlTablename());
        DbTable dbTable = new DbTable();
        dbTable.setName(sqlName);
        schema.addTable(dbTable);
        return;
    }
    // second pass; add columns
    DbTableName sqlName = new DbTableName(schema.getName(), def.getSqlTablename());
    DbTable dbTable = schema.findTable(sqlName);
    ViewableWrapper base = def.getExtending();
    {
        StringBuffer cmt = new StringBuffer();
        String cmtSep = "";
        if (!def.isSecondaryTable()) {
            dbTable.setIliName(def.getViewable().getScopedName(null));
            if (def.getViewable().getDocumentation() != null) {
                cmt.append(cmtSep + def.getViewable().getDocumentation());
                cmtSep = nl;
            }
            cmt.append(cmtSep + "@iliname " + def.getViewable().getScopedName(null));
            cmtSep = nl;
        }
        if (cmt.length() > 0) {
            dbTable.setComment(cmt.toString());
        }
    }
    if (deleteExistingData) {
        dbTable.setDeleteDataIfTableExists(true);
    }
    if (base == null && !def.isSecondaryTable()) {
        dbTable.setRequiresSequence(true);
    }
    String baseRef = "";
    DbColId dbColId = addKeyCol(dbTable);
    if (base != null) {
        dbColId.setScriptComment("REFERENCES " + base.getViewable().getScopedName(null));
        if (createFk) {
            dbColId.setReferencedTable(getSqlType(base.getViewable()));
        }
    } else if (def.isSecondaryTable()) {
        if (createFk) {
            dbColId.setReferencedTable(new DbTableName(schema.getName(), def.getMainTable().getSqlTablename()));
        }
    }
    if (createBasketCol) {
        // add basketCol
        DbColId t_basket = new DbColId();
        t_basket.setName(DbNames.T_BASKET_COL);
        t_basket.setNotNull(true);
        t_basket.setScriptComment("REFERENCES " + DbNames.BASKETS_TAB);
        if (createFk) {
            t_basket.setReferencedTable(new DbTableName(schema.getName(), DbNames.BASKETS_TAB));
        }
        if (createFkIdx) {
            t_basket.setIndex(true);
        }
        dbTable.addColumn(t_basket);
    }
    if (createDatasetCol) {
        DbColVarchar t_dsName = new DbColVarchar();
        t_dsName.setName(DbNames.T_DATASET_COL);
        t_dsName.setSize(DbNames.DATASETNAME_COL_SIZE);
        t_dsName.setNotNull(true);
        t_dsName.setIndex(true);
        dbTable.addColumn(t_dsName);
    }
    DbColumn dbCol;
    if (base == null && !def.isSecondaryTable()) {
        if (createTypeDiscriminator || def.includesMultipleTypes()) {
            dbCol = createSqlTypeCol(DbNames.T_TYPE_COL);
            dbTable.addColumn(dbCol);
        }
        // if CLASS
        if (!def.isStructure()) {
            if (createIliTidCol || def.getOid() != null) {
                addIliTidCol(dbTable, def.getOid());
            }
        }
        // if STRUCTURE, add ref to parent
        if (def.isStructure()) {
            if (createGenericStructRef) {
                // add parentid
                DbColId dbParentId = new DbColId();
                dbParentId.setName(DbNames.T_PARENT_ID_COL);
                dbParentId.setNotNull(true);
                dbParentId.setPrimaryKey(false);
                dbTable.addColumn(dbParentId);
                // add parent_type
                dbCol = createSqlTypeCol(DbNames.T_PARENT_TYPE_COL);
                dbTable.addColumn(dbCol);
                // add parent_attr
                dbCol = createSqlTypeCol(DbNames.T_PARENT_ATTR_COL);
                dbTable.addColumn(dbCol);
            } else {
            // add reference to parent for each structAttr when generating structAttr
            }
            // add sequence attr
            DbColId dbSeq = new DbColId();
            dbSeq.setName(DbNames.T_SEQ_COL);
            // dbSeq.setNotNull(true); // must be optional for cases where struct is exdended by a class
            dbSeq.setPrimaryKey(false);
            dbTable.addColumn(dbSeq);
        }
    }
    // body
    Iterator<ViewableTransferElement> iter = def.getAttrIterator();
    while (iter.hasNext()) {
        ViewableTransferElement obj = iter.next();
        if (obj.obj instanceof AttributeDef) {
            AttributeDef attr = (AttributeDef) obj.obj;
            if (attr.getExtending() == null) {
                try {
                    if (createItfLineTables && attr.getDomainResolvingAll() instanceof SurfaceOrAreaType) {
                        surfaceAttrs.add(attr);
                    }
                    if (!attr.isTransient()) {
                        Type proxyType = attr.getDomain();
                        if (proxyType != null && (proxyType instanceof ObjectType)) {
                        // skip implicit particles (base-viewables) of views
                        } else {
                            generateAttr(dbTable, def.getViewable(), attr);
                        }
                    }
                } catch (Exception ex) {
                    throw new Ili2dbException(attr.getContainer().getScopedName(null) + "." + attr.getName(), ex);
                }
            } else {
                if (attr.isDomainBoolean()) {
                } else if (createEnumColAsItfCode && attr.getDomainResolvingAll() instanceof EnumerationType) {
                    throw new Ili2dbException("EXTENDED attributes with type enumeration not supported");
                }
            }
        }
        if (obj.obj instanceof RoleDef) {
            RoleDef role = (RoleDef) obj.obj;
            if (role.getExtending() == null) {
                // not an embedded role and roledef not defined in a lightweight association?
                if (!obj.embedded && !def.isAssocLightweight()) {
                    ArrayList<ViewableWrapper> targetTables = getTargetTables(role.getDestination());
                    for (ViewableWrapper targetTable : targetTables) {
                        dbColId = new DbColId();
                        DbTableName targetSqlTableName = targetTable.getSqlTable();
                        String roleSqlName = ili2sqlName.mapIliRoleDef(role, sqlName.getName(), targetSqlTableName.getName(), targetTables.size() > 1);
                        dbColId.setName(roleSqlName);
                        boolean notNull = false;
                        if (!sqlEnableNull) {
                            if (targetTables.size() > 1) {
                                // multiple alternative FK columns
                                notNull = false;
                            } else {
                                notNull = true;
                            }
                        }
                        dbColId.setNotNull(notNull);
                        dbColId.setPrimaryKey(false);
                        if (createFk) {
                            dbColId.setReferencedTable(targetSqlTableName);
                        }
                        if (createFkIdx) {
                            dbColId.setIndex(true);
                        }
                        String cmt = role.getDocumentation();
                        if (cmt != null && cmt.length() > 0) {
                            dbColId.setComment(cmt);
                        }
                        dbTable.addColumn(dbColId);
                        // handle ordered
                        if (role.isOrdered()) {
                            // add seqeunce attr
                            DbColId dbSeq = new DbColId();
                            dbSeq.setName(roleSqlName + "_" + DbNames.T_SEQ_COL);
                            dbSeq.setNotNull(notNull);
                            dbSeq.setPrimaryKey(false);
                            dbTable.addColumn(dbSeq);
                        }
                    }
                }
                // a role of an embedded association?
                if (obj.embedded) {
                    AssociationDef roleOwner = (AssociationDef) role.getContainer();
                    if (roleOwner.getDerivedFrom() == null) {
                        // role is oppend;
                        ArrayList<ViewableWrapper> targetTables = getTargetTables(role.getDestination());
                        for (ViewableWrapper targetTable : targetTables) {
                            dbColId = new DbColId();
                            DbTableName targetSqlTableName = targetTable.getSqlTable();
                            String roleSqlName = ili2sqlName.mapIliRoleDef(role, sqlName.getName(), targetSqlTableName.getName(), targetTables.size() > 1);
                            dbColId.setName(roleSqlName);
                            boolean notNull = false;
                            if (!sqlEnableNull) {
                                if (targetTables.size() > 1) {
                                    // multiple alternative FK columns
                                    notNull = false;
                                } else if (role.getOppEnd().getDestination() != def.getViewable()) {
                                    // other subtypes in of def don't have this FK
                                    notNull = false;
                                } else {
                                    if (role.getCardinality().getMinimum() == 0) {
                                        notNull = false;
                                    } else {
                                        notNull = true;
                                    }
                                }
                            }
                            dbColId.setNotNull(notNull);
                            dbColId.setPrimaryKey(false);
                            if (createFk) {
                                dbColId.setReferencedTable(targetSqlTableName);
                            }
                            if (createFkIdx) {
                                dbColId.setIndex(true);
                            }
                            String cmt = role.getDocumentation();
                            if (cmt != null && cmt.length() > 0) {
                                dbColId.setComment(cmt);
                            }
                            customMapping.fixupEmbeddedLink(dbTable, dbColId, roleOwner, role, targetSqlTableName, colT_ID);
                            dbTable.addColumn(dbColId);
                            // handle ordered
                            if (role.getOppEnd().isOrdered()) {
                                // add seqeunce attr
                                DbColId dbSeq = new DbColId();
                                dbSeq.setName(roleSqlName + "_" + DbNames.T_SEQ_COL);
                                dbSeq.setNotNull(notNull);
                                dbSeq.setPrimaryKey(false);
                                dbTable.addColumn(dbSeq);
                            }
                        }
                    }
                }
            }
        }
    }
    if (createStdCols) {
        addStdCol(dbTable);
    }
    if (createUnique && !def.isStructure()) {
        // check if UNIQUE mappable
        HashSet wrapperCols = getWrapperCols(def.getAttrv());
        Viewable aclass = def.getViewable();
        Iterator it = aclass.iterator();
        while (it.hasNext()) {
            Object cnstro = it.next();
            if (cnstro instanceof UniquenessConstraint) {
                UniquenessConstraint cnstr = (UniquenessConstraint) cnstro;
                HashSet attrs = getUniqueAttrs(cnstr, wrapperCols);
                // mappable?
                if (attrs != null) {
                    DbIndex dbIndex = new DbIndex();
                    dbIndex.setPrimary(false);
                    dbIndex.setUnique(true);
                    for (Object attro : attrs) {
                        String attrSqlName = null;
                        if (attro instanceof AttributeDef) {
                            attrSqlName = ili2sqlName.mapIliAttributeDef((AttributeDef) attro, def.getSqlTablename(), null);
                        } else if (attro instanceof RoleDef) {
                            RoleDef role = (RoleDef) attro;
                            DbTableName targetSqlTableName = getSqlType(role.getDestination());
                            attrSqlName = ili2sqlName.mapIliRoleDef(role, def.getSqlTablename(), targetSqlTableName.getName());
                        } else {
                            throw new IllegalStateException("unexpected attr " + attro);
                        }
                        DbColumn idxCol = dbTable.getColumn(attrSqlName);
                        dbIndex.addAttr(idxCol);
                    }
                    dbTable.addIndex(dbIndex);
                }
            }
        }
    }
    if (!def.isSecondaryTable()) {
        customMapping.fixupViewable(dbTable, def.getViewable());
    }
}
Also used : DbColumn(ch.ehi.sqlgen.repository.DbColumn) Ili2dbException(ch.ehi.ili2db.base.Ili2dbException) SurfaceOrAreaType(ch.interlis.ili2c.metamodel.SurfaceOrAreaType) RoleDef(ch.interlis.ili2c.metamodel.RoleDef) ViewableWrapper(ch.ehi.ili2db.mapping.ViewableWrapper) DbIndex(ch.ehi.sqlgen.repository.DbIndex) ObjectType(ch.interlis.ili2c.metamodel.ObjectType) AssociationDef(ch.interlis.ili2c.metamodel.AssociationDef) Iterator(java.util.Iterator) AttributeDef(ch.interlis.ili2c.metamodel.AttributeDef) HashSet(java.util.HashSet) ViewableTransferElement(ch.interlis.ili2c.metamodel.ViewableTransferElement) DbColVarchar(ch.ehi.sqlgen.repository.DbColVarchar) EnumerationType(ch.interlis.ili2c.metamodel.EnumerationType) Ili2dbException(ch.ehi.ili2db.base.Ili2dbException) PolylineType(ch.interlis.ili2c.metamodel.PolylineType) Type(ch.interlis.ili2c.metamodel.Type) BasketType(ch.interlis.ili2c.metamodel.BasketType) ReferenceType(ch.interlis.ili2c.metamodel.ReferenceType) SurfaceOrAreaType(ch.interlis.ili2c.metamodel.SurfaceOrAreaType) SurfaceType(ch.interlis.ili2c.metamodel.SurfaceType) CompositionType(ch.interlis.ili2c.metamodel.CompositionType) TextType(ch.interlis.ili2c.metamodel.TextType) EnumerationType(ch.interlis.ili2c.metamodel.EnumerationType) NumericType(ch.interlis.ili2c.metamodel.NumericType) BlackboxType(ch.interlis.ili2c.metamodel.BlackboxType) AreaType(ch.interlis.ili2c.metamodel.AreaType) ObjectType(ch.interlis.ili2c.metamodel.ObjectType) CoordType(ch.interlis.ili2c.metamodel.CoordType) Viewable(ch.interlis.ili2c.metamodel.Viewable) DbColId(ch.ehi.sqlgen.repository.DbColId) UniquenessConstraint(ch.interlis.ili2c.metamodel.UniquenessConstraint) DbTableName(ch.ehi.sqlgen.repository.DbTableName) DbTable(ch.ehi.sqlgen.repository.DbTable)

Example 5 with DbColumn

use of ch.ehi.sqlgen.repository.DbColumn in project ili2db by claeis.

the class AbstractRecordConverter method addStdCol.

public static void addStdCol(DbTable table) {
    DbColumn dbCol = new DbColDateTime();
    dbCol.setName(DbNames.T_LAST_CHANGE_COL);
    dbCol.setNotNull(true);
    table.addColumn(dbCol);
    dbCol = new DbColDateTime();
    dbCol.setName(DbNames.T_CREATE_DATE_COL);
    dbCol.setNotNull(true);
    table.addColumn(dbCol);
    DbColVarchar dbColUsr = new DbColVarchar();
    dbColUsr.setName(DbNames.T_USER_COL);
    dbColUsr.setNotNull(true);
    dbColUsr.setSize(40);
    table.addColumn(dbColUsr);
}
Also used : DbColumn(ch.ehi.sqlgen.repository.DbColumn) DbColVarchar(ch.ehi.sqlgen.repository.DbColVarchar) DbColDateTime(ch.ehi.sqlgen.repository.DbColDateTime)

Aggregations

DbColumn (ch.ehi.sqlgen.repository.DbColumn)5 DbColVarchar (ch.ehi.sqlgen.repository.DbColVarchar)3 Iterator (java.util.Iterator)3 ViewableWrapper (ch.ehi.ili2db.mapping.ViewableWrapper)2 DbColId (ch.ehi.sqlgen.repository.DbColId)2 DbTable (ch.ehi.sqlgen.repository.DbTable)2 AreaType (ch.interlis.ili2c.metamodel.AreaType)2 AttributeDef (ch.interlis.ili2c.metamodel.AttributeDef)2 BasketType (ch.interlis.ili2c.metamodel.BasketType)2 BlackboxType (ch.interlis.ili2c.metamodel.BlackboxType)2 CompositionType (ch.interlis.ili2c.metamodel.CompositionType)2 CoordType (ch.interlis.ili2c.metamodel.CoordType)2 EnumerationType (ch.interlis.ili2c.metamodel.EnumerationType)2 NumericType (ch.interlis.ili2c.metamodel.NumericType)2 ObjectType (ch.interlis.ili2c.metamodel.ObjectType)2 PolylineType (ch.interlis.ili2c.metamodel.PolylineType)2 ReferenceType (ch.interlis.ili2c.metamodel.ReferenceType)2 SurfaceOrAreaType (ch.interlis.ili2c.metamodel.SurfaceOrAreaType)2 SurfaceType (ch.interlis.ili2c.metamodel.SurfaceType)2 TextType (ch.interlis.ili2c.metamodel.TextType)2