Java Reference
In-Depth Information
assertForeignKeysDoesNotHaveFunnyNames(sql);
}
};
analyzeSchema(handler);
}
private static final String FK_LINE_REGEXP =
"alter table (.*) add constraint (.*) foreign key .*";
private static final Pattern FK_LINE_PATTERN =
Pattern.compile(FK_LINE_REGEXP);
private static final Matcher FK_LINE_MATCHER =
FK_LINE_PATTERN.matcher("");
private static final String FK_REGEXP = "fk_[a-z]+_[a-z]+$";
private static final Pattern FK_PATTERN = Pattern.compile(FK_REGEXP);
private static final Matcher FK_MATCHER = FK_PATTERN.matcher("");
D
E
private void assertForeignKeysDoesNotHaveFunnyNames(String sql) {
String[] lines = sql.split("\n");
StringBuilder buffer = new StringBuilder();
for ( String line : lines ) {
FK_LINE_MATCHER.reset(line);
if ( FK_LINE_MATCHER.find() ) {
String table = FK_LINE_MATCHER.group(1);
String fk = FK_LINE_MATCHER.group(2);
if ( ! isValidFk(fk) ) {
buffer.append(table).append("(").append(fk).append(") ");
}
}
}
String violations = buffer.toString();
if ( violations.length() > 0 ) {
fail( "One or more tables have weird FK names: " + violations );
}
}
F
G
H
I
private boolean isValidFk(String fk) {
FK_MATCHER.reset(fk);
return FK_MATCHER.find();
}
}
Although we're testing only foreign key names, we could test other aspects of the gen-
erated schema, so we create a generic SchemaTest class.
The test case method by itself is quite simple: it calls the superclass analyzeSchema()
method (described shortly), passing as a parameter an inner class that will do the job.
This regular expression is used to identify whether a line defines a foreign key.
This regular expression is used to extract the foreign key name.
The SQL representing the schema generation is parsed in two levels: first, split() is
used to break the lines, and then a regular expression D checks for lines that define a
foreign key. We could use only one regular expression to handle both, but the result
would be more complex.
B
C
D
E
F
Search WWH ::




Custom Search