use of com.github.drinkjava2.jdialects.model.Column in project jDialects by drinkjava2.
the class DDLTest method testFKEY.
@Test
public void testFKEY() {
// FKEY
TableModel t1 = new TableModel("master1");
t1.column("id").INTEGER().pkey();
TableModel t2 = new TableModel("master2");
t2.column("name").VARCHAR(20).pkey();
t2.column("address").VARCHAR(20).pkey();
t2.column("fid").INTEGER().singleFKey("master1");
TableModel t3 = new TableModel("child");
t3.column("id").INTEGER().pkey();
t3.column("masterid1").INTEGER().singleFKey("master1", "id").fkeyTail("ON DELETE CASCADE ON UPDATE CASCADE").fkeyName("fknm");
t3.column("myname").VARCHAR(20).singleFKey("master2", "name").fkeyTail("ON DELETE CASCADE ON UPDATE CASCADE");
t3.column("myaddress").VARCHAR(20).singleFKey("master2", "address");
t3.fkey().columns("masterid1").refs("master1", "id").fkeyTail("ON DELETE CASCADE ON UPDATE CASCADE");
;
t3.fkey("FKNAME1").columns("myname", "myaddress").refs("master2", "name", "address");
t3.fkey("FKNAME2").columns("myname", "myaddress").refs("master2");
TableModel t4 = new TableModel("child2");
t4.column("id").INTEGER().pkey();
t4.column("masterid2").INTEGER();
t4.column("myname2").VARCHAR(20);
t4.column("myaddress2").VARCHAR(20);
t4.fkey().columns("masterid2").refs("master1", "id");
t4.fkey().columns("myname2", "myaddress2").refs("master2", "name", "address");
printAllDialectsDDLs(t1, t2, t3);
printOneDialectsDDLs(Dialect.MySQL5InnoDBDialect, t1, t2, t3, t4);
testOnCurrentRealDatabase(t1, t2, t3, t4);
}
use of com.github.drinkjava2.jdialects.model.Column in project jDialects by drinkjava2.
the class DDLCreateUtils method transferTableToObjectList.
/**
* Transfer table to a mixed DDL String or TableGen Object list
*/
/**
* @param dialect
* @param t
* @param objectResultList
*/
private static void transferTableToObjectList(Dialect dialect, TableModel t, List<Object> objectResultList) {
DDLFeatures features = dialect.ddlFeatures;
StringBuilder buf = new StringBuilder();
boolean hasPkey = false;
String pkeys = "";
String tableName = t.getTableName();
List<ColumnModel> columns = t.getColumns();
// Reserved words check
dialect.checkNotEmptyReservedWords(tableName, "Table name can not be empty");
// check index names
List<IndexModel> idexChks = t.getIndexConsts();
if (idexChks != null && !idexChks.isEmpty())
for (IndexModel index : idexChks) dialect.checkReservedWords(index.getName());
// check unique names
List<UniqueModel> ukChks = t.getUniqueConsts();
if (ukChks != null && !ukChks.isEmpty())
for (UniqueModel unique : ukChks) dialect.checkReservedWords(unique.getName());
// check Fkey names
List<FKeyModel> fkeyChks = t.getFkeyConstraints();
if (fkeyChks != null && !fkeyChks.isEmpty())
for (FKeyModel fkey : fkeyChks) dialect.checkReservedWords(fkey.getFkeyName());
for (// check column names
ColumnModel col : // check column names
columns) dialect.checkNotEmptyReservedWords(col.getColumnName(), "Column name can not be empty");
// idGenerator
for (IdGenerator idGen : t.getIdGenerators()) objectResultList.add(idGen);
// Foreign key
for (FKeyModel fkey : t.getFkeyConstraints()) objectResultList.add(fkey);
// check and cache prime keys
for (ColumnModel col : columns) {
if (col.getTransientable())
continue;
if (col.getPkey()) {
hasPkey = true;
if (StrUtils.isEmpty(pkeys))
pkeys = col.getColumnName();
else
pkeys += "," + col.getColumnName();
}
}
// create table
buf.append(hasPkey ? dialect.ddlFeatures.createTableString : dialect.ddlFeatures.createMultisetTableString).append(" ").append(tableName).append(" ( ");
for (ColumnModel c : columns) {
if (c.getTransientable())
continue;
if (c.getColumnType() == null)
DialectException.throwEX("Type not set on column \"" + c.getColumnName() + "\" at table \"" + tableName + "\"");
// column definition
buf.append(c.getColumnName()).append(" ");
// Identity
if (GenerationType.IDENTITY.equals(c.getIdGenerationType()) && !features.supportsIdentityColumns)
DialectException.throwEX("Unsupported identity setting for dialect \"" + dialect + "\" on column \"" + c.getColumnName() + "\" at table \"" + tableName + "\"");
// Column type definition
if (GenerationType.IDENTITY.equals(c.getIdGenerationType())) {
if (features.hasDataTypeInIdentityColumn)
buf.append(dialect.translateToDDLType(c.getColumnType(), c.getLengths()));
buf.append(' ');
if (Type.BIGINT.equals(c.getColumnType()))
buf.append(features.identityColumnStringBigINT);
else
buf.append(features.identityColumnString);
} else {
buf.append(dialect.translateToDDLType(c.getColumnType(), c.getLengths()));
// Default
String defaultValue = c.getDefaultValue();
if (defaultValue != null) {
buf.append(" default ").append(defaultValue);
}
// Not null
if (!c.getNullable())
buf.append(" not null");
else
buf.append(features.nullColumnString);
}
// Check
if (!StrUtils.isEmpty(c.getCheck())) {
if (features.supportsColumnCheck)
buf.append(" check (").append(c.getCheck()).append(")");
else
logger.warn("Ignore unsupported check setting for dialect \"" + dialect + "\" on column \"" + c.getColumnName() + "\" at table \"" + tableName + "\" with value: " + c.getCheck());
}
// Comments
if (c.getComment() != null) {
if (StrUtils.isEmpty(features.columnComment) && !features.supportsCommentOn)
logger.warn("Ignore unsupported comment setting for dialect \"" + dialect + "\" on column \"" + c.getColumnName() + "\" at table \"" + tableName + "\" with value: " + c.getComment());
else
buf.append(StrUtils.replace(features.columnComment, "_COMMENT", c.getComment()));
}
// tail String
if (!StrUtils.isEmpty(c.getTail()))
buf.append(c.getTail());
buf.append(",");
}
// PKEY
if (!StrUtils.isEmpty(pkeys)) {
buf.append(" primary key (").append(pkeys).append("),");
}
// Table Check
if (!StrUtils.isEmpty(t.getCheck())) {
if (features.supportsTableCheck)
buf.append(" check (").append(t.getCheck()).append("),");
else
logger.warn("Ignore unsupported table check setting for dialect \"" + dialect + "\" on table \"" + tableName + "\" with value: " + t.getCheck());
}
buf.setLength(buf.length() - 1);
buf.append(")");
// Engine for MariaDB & MySql only, for example "engine=innoDB"
String tableTypeString = features.tableTypeString;
if (!StrUtils.isEmpty(tableTypeString) && !DDLFeatures.NOT_SUPPORT.equals(tableTypeString)) {
buf.append(tableTypeString);
// EngineTail, for example:" DEFAULT CHARSET=utf8"
if (!StrUtils.isEmpty(t.getEngineTail()))
buf.append(t.getEngineTail());
}
objectResultList.add(buf.toString());
// table comment on
if (t.getComment() != null) {
if (features.supportsCommentOn)
objectResultList.add("comment on table " + t.getTableName() + " is '" + t.getComment() + "'");
else
logger.warn("Ignore unsupported table comment setting for dialect \"" + dialect + "\" on table \"" + tableName + "\" with value: " + t.getComment());
}
// column comment on
for (ColumnModel c : columns) {
if (features.supportsCommentOn && c.getComment() != null && StrUtils.isEmpty(features.columnComment))
objectResultList.add("comment on column " + tableName + '.' + c.getColumnName() + " is '" + c.getComment() + "'");
}
// index
buildIndexDLL(dialect, objectResultList, t);
// unique
buildUniqueDLL(dialect, objectResultList, t);
}
use of com.github.drinkjava2.jdialects.model.Column in project jDialects by drinkjava2.
the class TableModelUtilsOfEntity method entity2ModelIgnoreConfigMethod.
/**
* Convert a Java entity class or JPA annotated entity classes to
* "TableModel" Object, ignore config method
*/
private static TableModel entity2ModelIgnoreConfigMethod(Class<?> entityClass) {
DialectException.assureNotNull(entityClass, "entity2Model method does not accept a null class");
// Entity
String tableName = null;
Map<String, Object> entityMap = getFirstEntityAnno(entityClass, "Entity");
tableName = (String) entityMap.get("name");
// Table
Map<String, Object> tableMap = getFirstEntityAnno(entityClass, "Table");
if (!StrUtils.isEmpty(tableMap.get("name")))
tableName = (String) tableMap.get("name");
if (StrUtils.isEmpty(tableName))
tableName = entityClass.getSimpleName();
// Build the tableModel
TableModel model = new TableModel(tableName);
if (!tableMap.isEmpty()) {
// Index
Annotation[] indexes = (Annotation[]) tableMap.get("indexes");
if (indexes != null && indexes.length > 0)
for (Annotation anno : indexes) {
Map<String, Object> mp = changeAnnotationValuesToMap(anno, anno.annotationType());
String columnListString = (String) mp.get("columnList");
String[] columns;
if (columnListString.indexOf(',') >= 0)
columns = columnListString.split(",");
else
columns = new String[] { columnListString };
if (columns.length > 0)
model.index((String) mp.get("name")).columns(columns).setUnique((Boolean) mp.get("unique"));
}
// Unique
Annotation[] uniques = (Annotation[]) tableMap.get("uniqueConstraints");
if (uniques != null && uniques.length > 0)
for (Annotation anno : uniques) {
Map<String, Object> mp = changeAnnotationValuesToMap(anno, anno.annotationType());
String[] columnNames = (String[]) mp.get("columnNames");
if (columnNames != null && columnNames.length > 0)
model.unique((String) mp.get("name")).columns(columnNames);
}
}
// SequenceGenerator
Map<String, Object> seqMap = getFirstEntityAnno(entityClass, "SequenceGenerator");
if (!seqMap.isEmpty()) {
model.sequenceGenerator((String) seqMap.get("name"), (String) seqMap.get("sequenceName"), (Integer) seqMap.get("initialValue"), (Integer) seqMap.get("allocationSize"));
}
// TableGenerator
Map<String, Object> tableGenMap = getFirstEntityAnno(entityClass, "TableGenerator");
if (!tableGenMap.isEmpty()) {
model.tableGenerator((String) tableGenMap.get("name"), (String) tableGenMap.get("table"), (String) tableGenMap.get("pkColumnName"), (String) tableGenMap.get("valueColumnName"), (String) tableGenMap.get("pkColumnValue"), (Integer) tableGenMap.get("initialValue"), (Integer) tableGenMap.get("allocationSize"));
}
// UUIDAny
Map<String, Object> uuidAnyMp = getFirstEntityAnno(entityClass, "UUIDAny");
if (!uuidAnyMp.isEmpty()) {
model.uuidAny((String) uuidAnyMp.get("name"), (Integer) uuidAnyMp.get("length"));
}
// FKey
List<Map<String, Object>> fkeys = getEntityAnnos(entityClass, "FKey");
for (Map<String, Object> map : fkeys) {
Boolean ddl = (Boolean) map.get("ddl");
if (ddl == null)
ddl = true;
model.fkey((String) map.get("name")).columns((String[]) map.get("columns")).refs((String[]) map.get("refs")).ddl(ddl);
}
BeanInfo beanInfo = null;
PropertyDescriptor[] pds = null;
try {
beanInfo = Introspector.getBeanInfo(entityClass);
pds = beanInfo.getPropertyDescriptors();
} catch (Exception e) {
DialectException.throwEX("entity2Model can not get bean info", e);
}
for (PropertyDescriptor pd : pds) {
String entityfieldName = pd.getName();
if ("class".equals(entityfieldName) || "simpleName".equals(entityfieldName) || "canonicalName".equals(entityfieldName) || "box".equals(entityfieldName))
continue;
Class<?> propertyClass = pd.getPropertyType();
if (TypeUtils.canMapToSqlType(propertyClass)) {
Field field = ReflectionUtils.findField(entityClass, entityfieldName);
if (field == null)
continue;
if (!getFirstEntityAnno(field, "Transient").isEmpty()) {
ColumnModel col = new ColumnModel(entityfieldName);
col.setColumnType(TypeUtils.toType(propertyClass));
col.setLengths(new Integer[] { 255, 0, 0 });
col.setTransientable(true);
col.setTableModel(model);
model.addColumn(col);
} else {
// SequenceGenerator
Map<String, Object> map = getFirstEntityAnno(field, "SequenceGenerator");
if (!map.isEmpty()) {
model.sequenceGenerator((String) map.get("name"), (String) map.get("sequenceName"), (Integer) map.get("initialValue"), (Integer) map.get("allocationSize"));
}
// TableGenerator
map = getFirstEntityAnno(field, "TableGenerator");
if (!map.isEmpty()) {
model.tableGenerator((String) map.get("name"), (String) map.get("table"), (String) map.get("pkColumnName"), (String) map.get("valueColumnName"), (String) map.get("pkColumnValue"), (Integer) map.get("initialValue"), (Integer) map.get("allocationSize"));
}
// UUIDAny
map = getFirstEntityAnno(field, "UUIDAny");
if (!map.isEmpty()) {
model.uuidAny((String) map.get("name"), (Integer) map.get("length"));
}
ColumnModel col = new ColumnModel(entityfieldName);
col.entityField(entityfieldName);
// Column
Map<String, Object> colMap = getFirstEntityAnno(field, "Column");
if (!colMap.isEmpty()) {
if (!(Boolean) colMap.get("nullable"))
col.setNullable(false);
if (!StrUtils.isEmpty(colMap.get("name")))
col.setColumnName((String) colMap.get("name"));
col.setLength((Integer) colMap.get("length"));
col.setPrecision((Integer) colMap.get("precision"));
col.setScale((Integer) colMap.get("scale"));
col.setLengths(new Integer[] { col.getLength(), col.getPrecision(), col.getScale() });
if (!StrUtils.isEmpty(colMap.get("columnDefinition")))
col.setColumnType(TypeUtils.toType((String) colMap.get("columnDefinition")));
else
col.setColumnType(TypeUtils.toType(propertyClass));
col.setInsertable((Boolean) colMap.get("insertable"));
col.setUpdatable((Boolean) colMap.get("updatable"));
} else {
col.setColumnType(TypeUtils.toType(propertyClass));
col.setLengths(new Integer[] { 255, 0, 0 });
}
// Id
if (!getFirstEntityAnno(field, "Id").isEmpty() || !getFirstEntityAnno(field, "PKey").isEmpty())
col.pkey();
col.setEntityField(entityfieldName);
col.setTableModel(model);
// col will also set TableModel field point to its owner
model.addColumn(col);
// shortcut Id generator annotations
if (existEntityAnno(field, "AutoId"))
col.autoId();
if (existEntityAnno(field, "IdentityId"))
col.identityId();
if (existEntityAnno(field, "TimeStampId"))
col.timeStampId();
if (existEntityAnno(field, "UUID25"))
col.uuid25();
if (existEntityAnno(field, "UUID32"))
col.uuid32();
if (existEntityAnno(field, "UUID36"))
col.uuid36();
// GeneratedValue
Map<String, Object> gvMap = getFirstEntityAnno(field, "GeneratedValue");
if (!gvMap.isEmpty()) {
Object strategy = gvMap.get("strategy");
if (strategy != null) {
String strategyStr = strategy.toString();
if ("AUTO".equals(strategyStr))
col.autoId();
else if ("IDENTITY".equals(strategyStr))
col.identityId();
else if ("UUID25".equals(strategyStr))
col.uuid25();
else if ("UUID32".equals(strategyStr))
col.uuid32();
else if ("UUID36".equals(strategyStr))
col.uuid36();
else if ("TIMESTAMP".equals(strategyStr))
col.timeStampId();
else {
String generator = (String) gvMap.get("generator");
if (StrUtils.isEmpty(generator))
throw new DialectException("GeneratedValue strategy '" + strategyStr + "' can not find a generator");
col.idGenerator(generator);
}
}
}
// SingleFKey is a shortcut format of FKey, only for 1
// column
Map<String, Object> refMap = getFirstEntityAnno(field, "SingleFKey");
if (!refMap.isEmpty()) {
Boolean ddl = (Boolean) refMap.get("ddl");
if (ddl == null)
ddl = true;
model.fkey((String) refMap.get("name")).columns(col.getColumnName()).refs((String[]) refMap.get("refs")).ddl(ddl);
}
// SingleIndex is a ShortCut format of Index, only for 1
// column
Map<String, Object> idxMap = getFirstEntityAnno(field, "SingleIndex");
if (!idxMap.isEmpty())
model.index((String) idxMap.get("name")).columns(col.getColumnName());
// SingleUnique is a ShortCut format of Unique, only for 1
// column
Map<String, Object> uniMap = getFirstEntityAnno(field, "SingleUnique");
if (!uniMap.isEmpty())
model.unique((String) uniMap.get("name")).columns(col.getColumnName());
}
}
}
// End of columns loop
return model;
}
use of com.github.drinkjava2.jdialects.model.Column in project jDialects by drinkjava2.
the class DDLTest method singleXxxMethodTest.
@Test
public void singleXxxMethodTest() {
// Test singleXxx methods
TableModel t1 = new TableModel("customers");
t1.column("name").STRING(20).singleUnique();
t1.column("email").VARCHAR(50).defaultValue("'Beijing'").comment("address comment").singleIndex("IDX1");
TableModel t2 = new TableModel("orders");
t2.column("item").STRING(20).singleUnique("A");
t2.column("name").STRING(20).singleFKey("customers", "name");
String[] dropAndCreateDDL = Dialect.H2Dialect.toDropAndCreateDDL(t1, t2);
for (String ddl : dropAndCreateDDL) System.out.println(ddl);
testOnCurrentRealDatabase(t1, t2);
}
use of com.github.drinkjava2.jdialects.model.Column in project jDialects by drinkjava2.
the class DDLCreateUtils method toCreateDDL.
/**
* Transfer tables to DDL by given dialect and without format it, if want get a
* formatted DDL, use DDLFormatter.format(DDLs) method to format it
*/
public static String[] toCreateDDL(Dialect dialect, TableModel... tables) {
// Store mixed DDL String, TableGen Object, SequenceGen Object ...
List<Object> objectResultList = new ArrayList<Object>();
for (TableModel table : tables) transferTableToObjectList(dialect, table, objectResultList);
boolean hasAutoIdGenerator = false;
for (TableModel table : tables) {
for (ColumnModel column : table.getColumns()) if (GenerationType.AUTO.equals(column.getIdGenerationType())) {
hasAutoIdGenerator = true;
break;
}
for (IdGenerator idGens : table.getIdGenerators()) if (hasAutoIdGenerator || idGens.dependOnAutoIdGenerator()) {
hasAutoIdGenerator = true;
break;
}
}
List<String> stringResultList = new ArrayList<String>();
List<TableIdGenerator> tbGeneratorList = new ArrayList<TableIdGenerator>();
List<SequenceIdGenerator> sequenceList = new ArrayList<SequenceIdGenerator>();
List<FKeyModel> fKeyConstraintList = new ArrayList<FKeyModel>();
for (Object strOrObj : objectResultList) {
if (!StrUtils.isEmpty(strOrObj)) {
if (strOrObj instanceof String)
stringResultList.add((String) strOrObj);
else if (strOrObj instanceof TableIdGenerator)
tbGeneratorList.add((TableIdGenerator) strOrObj);
else if (strOrObj instanceof SequenceIdGenerator)
sequenceList.add((SequenceIdGenerator) strOrObj);
else if (strOrObj instanceof FKeyModel)
fKeyConstraintList.add((FKeyModel) strOrObj);
}
}
if (hasAutoIdGenerator) {
IdGenerator realIdGen = AutoIdGenerator.INSTANCE.getSequenceOrTableIdGenerator(dialect);
if (realIdGen instanceof TableIdGenerator)
tbGeneratorList.add((TableIdGenerator) realIdGen);
else if (realIdGen instanceof SequenceIdGenerator)
sequenceList.add((SequenceIdGenerator) realIdGen);
else
throw new DialectException("Unknow exception happen for realIdGen, please report this bug");
}
buildSequenceDDL(dialect, stringResultList, sequenceList);
buildTableGeneratorDDL(dialect, stringResultList, tbGeneratorList);
outputFKeyConstraintDDL(dialect, stringResultList, fKeyConstraintList);
String[] result = stringResultList.toArray(new String[stringResultList.size()]);
if (Dialect.getGlobalAllowShowSql())
Dialect.logger.info("Create DDL:\r" + StrUtils.arrayToString(result, "\r"));
return result;
}
Aggregations