Skip to content

Instantly share code, notes, and snippets.

@thuytrinh
Created January 18, 2015 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thuytrinh/da9e7b9dbe61f6fa52a6 to your computer and use it in GitHub Desktop.
Save thuytrinh/da9e7b9dbe61f6fa52a6 to your computer and use it in GitHub Desktop.
public class DbField {
public final String name;
public final String type;
public final String constraint;
public DbField(String name, String type) {
this(name, type, null);
}
public DbField(String name, String type, String constraint) {
this.name = name;
this.type = type;
this.constraint = constraint;
}
@Override
public String toString() {
return name;
}
}
public class DbTable {
public final String name;
public final DbField[] fields;
public final String[] customScripts;
public DbTable(String name, DbField[] fields, String... customScripts) {
this.name = name;
this.fields = fields;
this.customScripts = customScripts;
}
@Override
public String toString() {
return name;
}
public String getDropSql() {
return "DROP TABLE IF EXISTS " + name;
}
public String getCreateSql() {
StringBuilder sqlBuilder = new StringBuilder()
.append("CREATE TABLE ").append(name).append(" (");
// Ensure that a comma does not appear on the last iteration
String comma = "";
for (DbField field : fields) {
sqlBuilder.append(comma);
comma = ",";
sqlBuilder.append(field.name).append(" ").append(field.type).append(" ");
if (field.constraint != null) {
sqlBuilder.append(field.constraint);
}
}
sqlBuilder.append(")");
return sqlBuilder.toString();
}
public String[] getFieldNames() {
String[] fieldNames = new String[fields.length];
for (int i = 0; i < fields.length; i++) {
fieldNames[i] = fields[i].name;
}
return fieldNames;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment