use of ch.ehi.sqlgen.repository.DbTableName in project ili2db by claeis.
the class TransferFromXtf method dropExistingStructEles.
private void dropExistingStructEles(String topic, long basketSqlId) {
// get all structs that are reachable from this topic
HashSet<AbstractClassDef> classv = getStructs(topic);
// delete all structeles
HashSet<ViewableWrapper> visitedTables = new HashSet<ViewableWrapper>();
for (AbstractClassDef aclass1 : classv) {
ViewableWrapper wrapper = class2wrapper.get(aclass1);
while (wrapper != null) {
{
if (!visitedTables.contains(wrapper)) {
visitedTables.add(wrapper);
// if table exists?
// get sql name
DbTableName sqlName = wrapper.getSqlTable();
if (DbUtility.tableExists(conn, sqlName)) {
// delete it
dropRecords(sqlName, basketSqlId);
} else {
// skip it; no table
}
}
}
wrapper = wrapper.getExtending();
}
}
}
use of ch.ehi.sqlgen.repository.DbTableName in project ili2db by claeis.
the class PgSequenceBasedIdGen method initDbDefs.
@Override
public void initDbDefs(ch.ehi.sqlgen.generator.Generator gen) {
DbTableName sqlName = new DbTableName(schema, SQL_ILI2DB_SEQ_NAME);
String stmt = "CREATE SEQUENCE " + sqlName.getQName();
if (minValue != null) {
stmt = stmt + " MINVALUE " + minValue;
}
if (maxValue != null) {
stmt = stmt + " MAXVALUE " + maxValue;
}
stmt = stmt + ";";
if (gen instanceof GeneratorJdbc) {
((GeneratorJdbc) gen).addCreateLine(((GeneratorJdbc) gen).new Stmt(stmt));
((GeneratorJdbc) gen).addDropLine(((GeneratorJdbc) gen).new Stmt("DROP SEQUENCE " + sqlName.getQName() + ";"));
}
if (DbUtility.sequenceExists(conn, sqlName)) {
return;
}
EhiLogger.traceBackendCmd(stmt);
java.sql.PreparedStatement updstmt = null;
try {
updstmt = conn.prepareStatement(stmt);
updstmt.execute();
} catch (java.sql.SQLException ex) {
EhiLogger.logError("failed to create sequence " + sqlName.getQName(), ex);
} finally {
if (updstmt != null) {
try {
updstmt.close();
} catch (java.sql.SQLException ex) {
EhiLogger.logError(ex);
}
}
}
}
use of ch.ehi.sqlgen.repository.DbTableName in project ili2db by claeis.
the class Enum23Test method importWithBeautify.
@Test
public void importWithBeautify() throws Exception {
Connection jdbcConnection = null;
try {
Class driverClass = Class.forName("org.postgresql.Driver");
jdbcConnection = DriverManager.getConnection(dburl, dbuser, dbpwd);
stmt = jdbcConnection.createStatement();
stmt.execute("DROP SCHEMA IF EXISTS " + DBSCHEMA + " CASCADE");
{
File data = new File("test/data/Enum23/Enum23.ili");
Config config = initConfig(data.getPath(), DBSCHEMA, data.getPath() + ".log");
config.setFunction(Config.FC_SCHEMAIMPORT);
config.setCreateFk(config.CREATE_FK_YES);
config.setTidHandling(Config.TID_HANDLING_PROPERTY);
config.setBasketHandling(config.BASKET_HANDLING_READWRITE);
config.setCreateEnumDefs(Config.CREATE_ENUM_DEFS_MULTI);
config.setBeautifyEnumDispName(Config.BEAUTIFY_ENUM_DISPNAME_UNDERSCORE);
config.setCatalogueRefTrafo(null);
config.setMultiSurfaceTrafo(null);
config.setMultilingualTrafo(null);
config.setInheritanceTrafo(null);
Ili2db.readSettingsFromDb(config);
Ili2db.run(config, null);
{
String stmtTxt = "SELECT dispName FROM " + DBSCHEMA + ".enum1 WHERE ilicode ='Test2_ele'";
Assert.assertTrue(stmt.execute(stmtTxt));
ResultSet rs = stmt.getResultSet();
Assert.assertTrue(rs.next());
Assert.assertEquals("Test2 ele", rs.getString(1));
}
{
String stmtTxt = "SELECT dispName FROM " + DBSCHEMA + ".enum1 WHERE ilicode ='Test3.ele_2'";
Assert.assertTrue(stmt.execute(stmtTxt));
ResultSet rs = stmt.getResultSet();
Assert.assertTrue(rs.next());
Assert.assertEquals("Test3.ele 2", rs.getString(1));
}
{
String stmtTxt = "SELECT dispName FROM " + DBSCHEMA + ".classa1_attr3 WHERE ilicode ='Test2_ele'";
Assert.assertTrue(stmt.execute(stmtTxt));
ResultSet rs = stmt.getResultSet();
Assert.assertTrue(rs.next());
Assert.assertEquals("Test2 ele", rs.getString(1));
}
{
String stmtTxt = "SELECT dispName FROM " + DBSCHEMA + ".classa1_attr3 WHERE ilicode ='Test3.ele_2'";
Assert.assertTrue(stmt.execute(stmtTxt));
ResultSet rs = stmt.getResultSet();
Assert.assertTrue(rs.next());
Assert.assertEquals("Test3.ele 2", rs.getString(1));
}
Assert.assertFalse(DbUtility.tableExists(jdbcConnection, new DbTableName(DBSCHEMA, "boolean")));
Assert.assertFalse(DbUtility.tableExists(jdbcConnection, new DbTableName(DBSCHEMA, "classa1_attr2")));
Assert.assertFalse(DbUtility.tableExists(jdbcConnection, new DbTableName(DBSCHEMA, "classa1_attr4")));
}
} finally {
if (jdbcConnection != null) {
jdbcConnection.close();
}
}
}
use of ch.ehi.sqlgen.repository.DbTableName in project ili2db by claeis.
the class DbExtMetaInfo method saveColumnTab.
private void saveColumnTab(Connection conn, String schemaName) throws Ili2dbException {
DbTableName tabName = new DbTableName(schemaName, DbNames.META_INFO_COLUMN_TAB);
String sqlName = tabName.getQName();
HashMap<ColKey, HashMap<String, String>> exstEntries = readColumnTab(conn, sqlName);
try {
// insert entries
String insStmt = "INSERT INTO " + sqlName + " (" + DbNames.META_INFO_COLUMN_TAB_TABLENAME_COL + "," + DbNames.META_INFO_COLUMN_TAB_SUBTYPE_COL + "," + DbNames.META_INFO_COLUMN_TAB_COLUMNNAME_COL + "," + DbNames.META_INFO_COLUMN_TAB_TAG_COL + "," + DbNames.META_INFO_COLUMN_TAB_SETTING_COL + ") VALUES (?,?,?,?,?)";
EhiLogger.traceBackendCmd(insStmt);
java.sql.PreparedStatement insPrepStmt = conn.prepareStatement(insStmt);
try {
for (ColKey colKey : colInfo.keySet()) {
HashMap<String, String> exstValues = exstEntries.get(colKey);
if (exstValues == null) {
exstValues = new HashMap<String, String>();
}
HashMap<String, String> newValues = colInfo.get(colKey);
for (String tag : newValues.keySet()) {
if (!exstValues.containsKey(tag)) {
String value = newValues.get(tag);
insPrepStmt.setString(1, colKey.getTable());
insPrepStmt.setString(2, colKey.getSubtype());
insPrepStmt.setString(3, colKey.getColumn());
insPrepStmt.setString(4, tag);
insPrepStmt.setString(5, value);
insPrepStmt.executeUpdate();
}
}
}
} catch (java.sql.SQLException ex) {
throw new Ili2dbException("failed to insert meta info values to " + sqlName, ex);
} finally {
insPrepStmt.close();
}
} catch (java.sql.SQLException ex) {
throw new Ili2dbException("failed to update meta-info table " + sqlName, ex);
}
}
use of ch.ehi.sqlgen.repository.DbTableName 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());
}
}
Aggregations