method2testcases
stringlengths 118
6.63k
|
---|
### Question:
Main { protected void configureClassLoader() throws CommandLineParsingException { final List<URL> urls = new ArrayList<URL>(); if (this.classpath != null) { String[] classpath; if (isWindows()) { classpath = this.classpath.split(";"); } else { classpath = this.classpath.split(":"); } for (String classpathEntry : classpath) { File classPathFile = new File(classpathEntry); if (!classPathFile.exists()) { throw new CommandLineParsingException(classPathFile.getAbsolutePath() + " does not exist"); } try { if (classpathEntry.endsWith(".war")) { addWarFileClasspathEntries(classPathFile, urls); } else if (classpathEntry.endsWith(".ear")) { JarFile earZip = new JarFile(classPathFile); Enumeration<? extends JarEntry> entries = earZip.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().toLowerCase().endsWith(".jar")) { File jar = extract(earZip, entry); urls.add(new URL("jar:" + jar.toURL() + "!/")); jar.deleteOnExit(); } else if (entry.getName().toLowerCase().endsWith("war")) { File warFile = extract(earZip, entry); addWarFileClasspathEntries(warFile, urls); } } } else { urls.add(new File(classpathEntry).toURL()); } } catch (Exception e) { throw new CommandLineParsingException(e); } } } if (includeSystemClasspath) { classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() { public URLClassLoader run() { return new URLClassLoader(urls.toArray(new URL[urls.size()]), Thread.currentThread().getContextClassLoader()); } }); } else { classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() { public URLClassLoader run() { return new URLClassLoader(urls.toArray(new URL[urls.size()])); } }); } ServiceLocator.getInstance().setResourceAccessor(new ClassLoaderResourceAccessor(classLoader)); Thread.currentThread().setContextClassLoader(classLoader); } Main(); static void main(String args[]); boolean isWindows(); }### Answer:
@Test(expected = CommandLineParsingException.class) public void configureNonExistantClassloaderLocation() throws Exception { Main cli = new Main(); cli.classpath = "badClasspathLocation"; cli.configureClassLoader(); } |
### Question:
Main { protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException { Properties props = new Properties(); props.load(propertiesInputStream); for (Map.Entry entry : props.entrySet()) { try { if (entry.getKey().equals("promptOnNonLocalDatabase")) { continue; } if (((String) entry.getKey()).startsWith("parameter.")) { changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue()); } else { Field field = getClass().getDeclaredField((String) entry.getKey()); Object currentValue = field.get(this); if (currentValue == null) { String value = entry.getValue().toString().trim(); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + entry.getKey() + "'"); } } } Main(); static void main(String args[]); boolean isWindows(); }### Answer:
@Test public void propertiesFileWithNoOtherArgs() throws Exception { Main cli = new Main(); Properties props = new Properties(); props.setProperty("driver", "DRIVER"); props.setProperty("username", "USERNAME"); props.setProperty("password", "PASSWD"); props.setProperty("url", "URL"); props.setProperty("changeLogFile", "FILE"); props.setProperty("classpath", "CLASSPAHT"); props.setProperty("contexts", "CONTEXTS"); props.setProperty("promptForNonLocalDatabase", "TRUE"); ByteArrayOutputStream propFile = new ByteArrayOutputStream(); props.store(propFile, ""); cli.parsePropertiesFile(new ByteArrayInputStream(propFile.toByteArray())); assertEquals("DRIVER", cli.driver); assertEquals("USERNAME", cli.username); assertEquals("PASSWD", cli.password); assertEquals("URL", cli.url); assertEquals("FILE", cli.changeLogFile); assertEquals("CLASSPAHT", cli.classpath); assertEquals("CONTEXTS", cli.contexts); assertEquals(Boolean.TRUE, cli.promptForNonLocalDatabase); }
@Test public void propertiesFileWithOtherArgs() throws Exception { Main cli = new Main(); cli.username = "PASSED USERNAME"; cli.password = "PASSED PASSWD"; Properties props = new Properties(); props.setProperty("driver", "DRIVER"); props.setProperty("username", "USERNAME"); props.setProperty("password", "PASSWD"); props.setProperty("url", "URL"); props.setProperty("changeLogFile", "FILE"); props.setProperty("classpath", "CLASSPAHT"); props.setProperty("contexts", "CONTEXTS"); props.setProperty("promptForNonLocalDatabase", "TRUE"); ByteArrayOutputStream propFile = new ByteArrayOutputStream(); props.store(propFile, ""); cli.parsePropertiesFile(new ByteArrayInputStream(propFile.toByteArray())); assertEquals("DRIVER", cli.driver); assertEquals("PASSED USERNAME", cli.username); assertEquals("PASSED PASSWD", cli.password); assertEquals("URL", cli.url); assertEquals("FILE", cli.changeLogFile); assertEquals("CLASSPAHT", cli.classpath); assertEquals("CONTEXTS", cli.contexts); assertEquals(Boolean.TRUE, cli.promptForNonLocalDatabase); }
@Test(expected = CommandLineParsingException.class) public void propertiesFileWithBadArgs() throws Exception { Main cli = new Main(); Properties props = new Properties(); props.setProperty("driver", "DRIVER"); props.setProperty("username", "USERNAME"); props.setProperty("badArg", "ARG"); ByteArrayOutputStream propFile = new ByteArrayOutputStream(); props.store(propFile, ""); cli.parsePropertiesFile(new ByteArrayInputStream(propFile.toByteArray())); } |
### Question:
Main { protected void applyDefaults() { if (this.promptForNonLocalDatabase == null) { this.promptForNonLocalDatabase = Boolean.FALSE; } if (this.logLevel == null) { this.logLevel = "info"; } if (this.includeSystemClasspath == null) { this.includeSystemClasspath = Boolean.TRUE; } } Main(); static void main(String args[]); boolean isWindows(); }### Answer:
@Test public void applyDefaults() { Main cli = new Main(); cli.promptForNonLocalDatabase = Boolean.TRUE; cli.applyDefaults(); assertEquals(Boolean.TRUE, cli.promptForNonLocalDatabase); cli.promptForNonLocalDatabase = Boolean.FALSE; cli.applyDefaults(); assertEquals(Boolean.FALSE, cli.promptForNonLocalDatabase); cli.promptForNonLocalDatabase = null; cli.applyDefaults(); assertEquals(Boolean.FALSE, cli.promptForNonLocalDatabase); } |
### Question:
Main { protected List<String> checkSetup() { List<String> messages = new ArrayList<String>(); if (command == null) { messages.add("Command not passed"); } else if (!isCommand(command)) { messages.add("Unknown command: " + command); } else { if (url == null) { messages.add("--url is required"); } if (isChangeLogRequired(command) && changeLogFile == null) { messages.add("--changeLogFile is required"); } if (isNoArgCommand(command) && !commandParams.isEmpty()) { messages.add("unexpected command parameters: "+commandParams); } else { validateCommandParameters(messages); } } return messages; } Main(); static void main(String args[]); boolean isWindows(); }### Answer:
@Test public void checkSetup() { Main cli = new Main(); assertTrue(cli.checkSetup().size() > 0); cli.driver = "driver"; cli.username = "username"; cli.password = "pwd"; cli.url = "url"; cli.changeLogFile = "file"; cli.classpath = "classpath"; assertTrue(cli.checkSetup().size() > 0); cli.command = "BadCommand"; assertTrue(cli.checkSetup().size() > 0); cli.command = "migrate"; assertEquals(0, cli.checkSetup().size()); String[] noArgCommand = { "migrate", "migrateSQL", "update", "updateSQL", "futureRollbackSQL", "updateTestingRollback", "listLocks", "dropAll", "releaseLocks", "validate", "help", "generateChangeLog", "clearCheckSums", "changelogSync", "changelogSyncSQL", "markNextChangeSetRan", "markNextChangeSetRanSQL" }; cli.commandParams.clear(); cli.commandParams.add("--logLevel=debug"); for(int i=0; i<noArgCommand.length; i++) { cli.command = noArgCommand[i]; assertEquals(1, cli.checkSetup().size()); } cli.command = "update"; cli.commandParams.clear(); cli.changeLogParameters.clear(); cli.changeLogParameters.put("engine", "myisam"); assertEquals(0, cli.checkSetup().size()); cli.commandParams.clear(); for(int i=0; i<noArgCommand.length; i++) { cli.command = noArgCommand[i]; assertEquals(0, cli.checkSetup().size()); } String[] singleArgCommand = { "updateCount", "updateCountSQL", "rollback", "rollbackToDate", "rollbackCount", "rollbackSQL", "rollbackToDateSQL", "rollbackCountSQL", "tag", "dbDoc" }; cli.commandParams.add("--logLevel=debug"); for(int i=0; i<singleArgCommand.length; i++) { cli.command = singleArgCommand[i]; assertEquals(1, cli.checkSetup().size()); } cli.commandParams.clear(); cli.commandParams.add("someCommandValue"); for(int i=0; i<singleArgCommand.length; i++) { cli.command = singleArgCommand[i]; assertEquals(0, cli.checkSetup().size()); } cli.command = "status"; cli.commandParams.clear(); assertEquals(0, cli.checkSetup().size()); cli.commandParams.add("--verbose"); assertEquals(0, cli.checkSetup().size()); cli.commandParams.clear(); cli.commandParams.add("--logLevel=debug"); assertEquals(1, cli.checkSetup().size()); String[] multiArgCommand = { "diff", "diffChangeLog" }; cli.commandParams.clear(); for(int i=0; i<multiArgCommand.length; i++) { cli.command = multiArgCommand[i]; assertEquals(0, cli.checkSetup().size()); } String[] cmdParms = { "--referenceUsername=USERNAME", "--referencePassword=PASSWORD", "--referenceUrl=URL", "--referenceDriver=DRIVER"}; for (String param : cmdParms) { cli.commandParams.add(param); } assertEquals(0, cli.checkSetup().size()); cli.commandParams.add("--logLevel=debug"); assertEquals(1, cli.checkSetup().size()); } |
### Question:
StreamUtil { public static String getStreamContents(InputStream ins) throws IOException { InputStreamReader reader = new InputStreamReader(ins); return getReaderContents(reader); } static String getLineSeparator(); static String getStreamContents(InputStream ins); static String getStreamContents(InputStream ins, String charsetName); static String getReaderContents(Reader reader); static void copy(InputStream inputStream, OutputStream outputStream); final static String lineSeparator; }### Answer:
@Test public void testGetStreamContents() throws IOException { byte[] contents = "TEST2".getBytes(); ByteArrayInputStream stream = new ByteArrayInputStream(contents); String result = StreamUtil.getStreamContents(stream); assertEquals("TEST2", result); } |
### Question:
Main { protected void printHelp(List<String> errorMessages, PrintStream stream) { stream.println("Errors:"); for (String message : errorMessages) { stream.println(" " + message); } stream.println(); printHelp(stream); } Main(); static void main(String args[]); boolean isWindows(); }### Answer:
@Test public void printHelp() throws Exception { ByteArrayOutputStream stream = new ByteArrayOutputStream(); Main cli = new Main(); cli.printHelp(new PrintStream(stream)); BufferedReader reader = new BufferedReader(new StringReader(new String(stream.toByteArray()))); String line; while ((line = reader.readLine()) != null) { if (line.length() > 80) { fail("'" + line + "' is longer than 80 chars"); } } } |
### Question:
Main { protected String[] fixupArgs(String[] args) { List<String> fixedArgs = new ArrayList<String>(); for (int i = 0; i < args.length; i++) { String arg = args[i]; if ((arg.startsWith("--") || arg.startsWith("-D")) && !arg.contains("=")) { String nextArg = null; if (i + 1 < args.length) { nextArg = args[i + 1]; } if (nextArg != null && !nextArg.startsWith("--") && !isCommand(nextArg)) { arg = arg + "=" + nextArg; i++; } } fixedArgs.add(arg); } return fixedArgs.toArray(new String[fixedArgs.size()]); } Main(); static void main(String args[]); boolean isWindows(); }### Answer:
@Test public void fixArgs() { Main liquibase = new Main(); String[] fixedArgs = liquibase.fixupArgs(new String[] {"--defaultsFile","liquibase.properties", "migrate"}); assertEquals("--defaultsFile=liquibase.properties migrate", StringUtils.join(Arrays.asList(fixedArgs), " ")); fixedArgs = liquibase.fixupArgs(new String[] {"--defaultsFile=liquibase.properties", "migrate"}); assertEquals("--defaultsFile=liquibase.properties migrate", StringUtils.join(Arrays.asList(fixedArgs), " ")); fixedArgs = liquibase.fixupArgs(new String[] {"--driver=DRIVER", "--username=USERNAME", "--password=PASSWORD", "--url=URL", "--changeLogFile=FILE", "--classpath=CLASSPATH;CLASSPATH2", "--contexts=CONTEXT1,CONTEXT2", "--promptForNonLocalDatabase=true", "migrate" }); assertEquals("--driver=DRIVER --username=USERNAME --password=PASSWORD --url=URL --changeLogFile=FILE --classpath=CLASSPATH;CLASSPATH2 --contexts=CONTEXT1,CONTEXT2 --promptForNonLocalDatabase=true migrate", StringUtils.join(Arrays.asList(fixedArgs), " ")); } |
### Question:
Main { public static void main(String args[]) throws CommandLineParsingException, IOException { try { String shouldRunProperty = System.getProperty(Liquibase.SHOULD_RUN_SYSTEM_PROPERTY); if (shouldRunProperty != null && !Boolean.valueOf(shouldRunProperty)) { System.err.println("Liquibase did not run because '" + Liquibase.SHOULD_RUN_SYSTEM_PROPERTY + "' system property was set to false"); return; } Main main = new Main(); if (args.length == 1 && "--help".equals(args[0])) { main.printHelp(System.err); return; } else if (args.length == 1 && "--version".equals(args[0])) { System.err.println("Liquibase Version: " + LiquibaseUtil.getBuildVersion() + StreamUtil.getLineSeparator()); return; } try { main.parseOptions(args); } catch (CommandLineParsingException e) { main.printHelp(Arrays.asList(e.getMessage()), System.err); System.exit(-2); } File propertiesFile = new File(main.defaultsFile); File localPropertiesFile = new File(main.defaultsFile.replaceFirst("(\\.[^\\.]+)$", ".local$1")); if (localPropertiesFile.exists()) { main.parsePropertiesFile(new FileInputStream(localPropertiesFile)); } if (propertiesFile.exists()) { main.parsePropertiesFile(new FileInputStream(propertiesFile)); } List<String> setupMessages = main.checkSetup(); if (setupMessages.size() > 0) { main.printHelp(setupMessages, System.err); return; } try { main.applyDefaults(); main.configureClassLoader(); main.doMigration(); } catch (Throwable e) { String message = e.getMessage(); if (e.getCause() != null) { message = e.getCause().getMessage(); } if (message == null) { message = "Unknown Reason"; } if (e.getCause() instanceof ValidationFailedException) { ((ValidationFailedException) e.getCause()).printDescriptiveError(System.err); } else { System.err.println("Liquibase Update Failed: " + message); LogFactory.getLogger().severe(message, e); System.err.println(generateLogLevelWarningMessage()); } System.exit(-1); } if ("update".equals(main.command)) { System.err.println("Liquibase Update Successful"); } else if (main.command.startsWith("rollback") && !main.command.endsWith("SQL")) { System.err.println("Liquibase Rollback Successful"); } else if (!main.command.endsWith("SQL")) { System.err.println("Liquibase '"+main.command+"' Successful"); } } catch (Throwable e) { String message = "Unexpected error running Liquibase: " + e.getMessage(); System.err.println(message); try { LogFactory.getLogger().severe(message, e); } catch (Exception e1) { e.printStackTrace(); } System.exit(-3); } System.exit(0); } Main(); static void main(String args[]); boolean isWindows(); }### Answer:
@Test public void testVersionArg() throws IOException, CommandLineParsingException { Main.main(new String[] {"--version"}); } |
### Question:
ColumnConfig { public void setValue(String value) { this.value = value; } ColumnConfig(Column columnStructure); ColumnConfig(ColumnConfig column); ColumnConfig(); String getName(); ColumnConfig setName(String name); String getType(); ColumnConfig setType(String type); String getValue(); void setValue(String value); Number getValueNumeric(); ColumnConfig setValueNumeric(String valueNumeric); ColumnConfig setValueNumeric(Number valueNumeric); Boolean getValueBoolean(); ColumnConfig setValueBoolean(Boolean valueBoolean); DatabaseFunction getValueComputed(); ColumnConfig setValueComputed(DatabaseFunction valueComputed); Date getValueDate(); ColumnConfig setValueDate(Date valueDate); ColumnConfig setValueDate(String valueDate); Object getValueObject(); String getDefaultValue(); ColumnConfig setDefaultValue(String defaultValue); Number getDefaultValueNumeric(); ColumnConfig setDefaultValueNumeric(Number defaultValueNumeric); ColumnConfig setDefaultValueNumeric(String defaultValueNumeric); Date getDefaultValueDate(); ColumnConfig setDefaultValueDate(String defaultValueDate); ColumnConfig setDefaultValueDate(Date defaultValueDate); Boolean getDefaultValueBoolean(); ColumnConfig setDefaultValueBoolean(Boolean defaultValueBoolean); DatabaseFunction getDefaultValueComputed(); ColumnConfig setDefaultValueComputed(DatabaseFunction defaultValueComputed); Object getDefaultValueObject(); ConstraintsConfig getConstraints(); ColumnConfig setConstraints(ConstraintsConfig constraints); Boolean isAutoIncrement(); ColumnConfig setAutoIncrement(Boolean autoIncrement); BigInteger getStartWith(); ColumnConfig setStartWith(BigInteger startWith); BigInteger getIncrementBy(); ColumnConfig setIncrementBy(BigInteger incrementBy); boolean isPrimaryKey(); boolean isNullable(); boolean hasDefaultValue(); String getRemarks(); ColumnConfig setRemarks(String remarks); }### Answer:
@Test public void setValue() throws Exception { ColumnConfig column = new ColumnConfig(); column.setValue(null); assertNull(column.getValue()); column.setValue("abc"); assertEquals("abc", column.getValue()); column.setValue(null); assertEquals("passed null should override the value", null, column.getValue()); column.setValue(""); assertEquals("passed empty strings should override the value", "", column.getValue()); } |
### Question:
DropPrimaryKeyChange extends AbstractChange { public String getConfirmationMessage() { return "Primary key dropped from "+getTableName(); } DropPrimaryKeyChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getConstraintName(); void setConstraintName(String constraintName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { DropPrimaryKeyChange change = new DropPrimaryKeyChange(); change.setSchemaName("SCHEMA_NAME"); change.setTableName("TABLE_NAME"); change.setConstraintName("PK_NAME"); assertEquals("Primary key dropped from TABLE_NAME", change.getConfirmationMessage()); } |
### Question:
DropDefaultValueChange extends AbstractChange { public String getConfirmationMessage() { return "Default value dropped from "+getTableName()+"."+getColumnName(); } DropDefaultValueChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnName(); void setColumnName(String columnName); String getColumnDataType(); void setColumnDataType(String columnDataType); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { DropDefaultValueChange change = new DropDefaultValueChange(); change.setTableName("TABLE_NAME"); change.setColumnName("COL_HERE"); assertEquals("Default value dropped from TABLE_NAME.COL_HERE", change.getConfirmationMessage()); } |
### Question:
AddColumnChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public void addColumn(ColumnConfig column) { columns.add(column); } AddColumnChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void addColumn(ColumnConfig column); void removeColumn(ColumnConfig column); @Override ValidationErrors validate(Database database); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Test public void addColumn() throws Exception { AddColumnChange change = new AddColumnChange(); assertEquals(0, change.getColumns().size()); change.addColumn(new ColumnConfig().setName("a")); assertEquals(1, change.getColumns().size()); change.addColumn(new ColumnConfig().setName("b")); assertEquals(2, change.getColumns().size()); } |
### Question:
StreamUtil { public static String getReaderContents(Reader reader) throws IOException { try { StringBuffer result = new StringBuffer(); char[] buffer = new char[2048]; int read; while ((read = reader.read(buffer)) > -1) { result.append(buffer, 0, read); } return result.toString(); } finally { try { reader.close(); } catch (IOException ioe) { } } } static String getLineSeparator(); static String getStreamContents(InputStream ins); static String getStreamContents(InputStream ins, String charsetName); static String getReaderContents(Reader reader); static void copy(InputStream inputStream, OutputStream outputStream); final static String lineSeparator; }### Answer:
@Test public void testGetReaderContents() throws IOException { String contents = "TEST"; StringReader reader = new StringReader(contents); String result = StreamUtil.getReaderContents(reader); assertEquals(contents, result); } |
### Question:
AddColumnChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public void removeColumn(ColumnConfig column) { columns.remove(column); } AddColumnChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void addColumn(ColumnConfig column); void removeColumn(ColumnConfig column); @Override ValidationErrors validate(Database database); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Test public void removeColumn() throws Exception { ColumnConfig columnA = new ColumnConfig().setName("a"); ColumnConfig columnB = new ColumnConfig().setName("b"); AddColumnChange change = new AddColumnChange(); assertEquals(0, change.getColumns().size()); change.removeColumn(columnA); assertEquals(0, change.getColumns().size()); change.addColumn(columnA); assertEquals(1, change.getColumns().size()); change.removeColumn(columnB); assertEquals(1, change.getColumns().size()); change.removeColumn(columnA); assertEquals(0, change.getColumns().size()); } |
### Question:
AddColumnChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { List<String> names = new ArrayList<String>(columns.size()); for (ColumnConfig col : columns) { names.add(col.getName() + "(" + col.getType() + ")"); } return "Columns " + StringUtils.join(names, ",") + " added to " + tableName; } AddColumnChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void addColumn(ColumnConfig column); void removeColumn(ColumnConfig column); @Override ValidationErrors validate(Database database); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { AddColumnChange refactoring = new AddColumnChange(); refactoring.setTableName("TAB"); ColumnConfig column = new ColumnConfig(); column.setName("NEWCOL"); column.setType("TYP"); refactoring.addColumn(column); assertEquals("Columns NEWCOL(TYP) added to TAB", refactoring.getConfirmationMessage()); } |
### Question:
CreateProcedureChange extends AbstractChange { public String getConfirmationMessage() { return "Stored procedure created"; } CreateProcedureChange(); String getProcedureBody(); void setProcedureBody(String procedureBody); String getComments(); void setComments(String comments); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { CreateProcedureChange refactoring = new CreateProcedureChange(); assertEquals("Stored procedure created", refactoring.getConfirmationMessage()); } |
### Question:
RenameTableChange extends AbstractChange { public String getConfirmationMessage() { return "Table " + oldTableName + " renamed to " + newTableName; } RenameTableChange(); String getSchemaName(); void setSchemaName(String schemaName); String getOldTableName(); void setOldTableName(String oldTableName); String getNewTableName(); void setNewTableName(String newTableName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { refactoring.setOldTableName("OLD_NAME"); refactoring.setNewTableName("NEW_NAME"); assertEquals("Table OLD_NAME renamed to NEW_NAME", refactoring.getConfirmationMessage()); } |
### Question:
RawSQLChange extends AbstractSQLChange { public String getConfirmationMessage() { return "Custom SQL executed"; } RawSQLChange(); RawSQLChange(String sql); String getComments(); void setComments(String comments); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { assertEquals("Custom SQL executed", refactoring.getConfirmationMessage()); } |
### Question:
DropIndexChange extends AbstractChange { public String getConfirmationMessage() { return "Index " + getIndexName() + " dropped from table " + getTableName(); } DropIndexChange(); String getSchemaName(); void setSchemaName(String schemaName); String getIndexName(); void setIndexName(String indexName); String getTableName(); void setTableName(String tableName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); String getAssociatedWith(); void setAssociatedWith(String associatedWith); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { DropIndexChange refactoring = new DropIndexChange(); refactoring.setIndexName("IDX_NAME"); refactoring.setTableName("TABLE_NAME"); assertEquals("Index IDX_NAME dropped from table TABLE_NAME", refactoring.getConfirmationMessage()); } |
### Question:
TagDatabaseChange extends AbstractChange { public String getConfirmationMessage() { return "Tag '"+tag+"' applied to database"; } TagDatabaseChange(); String getTag(); void setTag(String tag); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { refactoring.setTag("TAG_NAME"); assertEquals("Tag 'TAG_NAME' applied to database", refactoring.getConfirmationMessage()); } |
### Question:
AddForeignKeyConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Foreign key contraint added to " + getBaseTableName() + " (" + getBaseColumnNames() + ")"; } AddForeignKeyConstraintChange(); String getBaseTableSchemaName(); void setBaseTableSchemaName(String baseTableSchemaName); String getBaseTableName(); void setBaseTableName(String baseTableName); String getBaseColumnNames(); void setBaseColumnNames(String baseColumnNames); String getReferencedTableSchemaName(); void setReferencedTableSchemaName(String referencedTableSchemaName); String getReferencedTableName(); void setReferencedTableName(String referencedTableName); String getReferencedColumnNames(); void setReferencedColumnNames(String referencedColumnNames); String getConstraintName(); void setConstraintName(String constraintName); Boolean getDeferrable(); void setDeferrable(Boolean deferrable); Boolean getInitiallyDeferred(); void setInitiallyDeferred(Boolean initiallyDeferred); void setDeleteCascade(Boolean deleteCascade); void setOnUpdate(String rule); String getOnUpdate(); void setOnDelete(String onDelete); String getOnDelete(); Boolean getReferencesUniqueColumn(); void setReferencesUniqueColumn(Boolean referencesUniqueColumn); void setOnDelete(ForeignKeyConstraintType rule); void setOnUpdate(ForeignKeyConstraintType rule); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { AddForeignKeyConstraintChange change = new AddForeignKeyConstraintChange(); change.setConstraintName("FK_NAME"); change.setBaseTableSchemaName("SCHEMA_NAME"); change.setBaseTableName("TABLE_NAME"); change.setBaseColumnNames("COL_NAME"); assertEquals("Foreign key contraint added to TABLE_NAME (COL_NAME)", change.getConfirmationMessage()); } |
### Question:
RenameColumnChange extends AbstractChange { public String getConfirmationMessage() { return "Column "+tableName+"."+ oldColumnName + " renamed to " + newColumnName; } RenameColumnChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getOldColumnName(); void setOldColumnName(String oldColumnName); String getNewColumnName(); void setNewColumnName(String newColumnName); String getColumnDataType(); void setColumnDataType(String columnDataType); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { assertEquals("Column TABLE_NAME.oldColName renamed to newColName", refactoring.getConfirmationMessage()); } |
### Question:
AlterSequenceChange extends AbstractChange { public String getConfirmationMessage() { return "Sequence " + getSequenceName() + " altered"; } AlterSequenceChange(); String getSchemaName(); void setSchemaName(String schemaName); String getSequenceName(); void setSequenceName(String sequenceName); BigInteger getIncrementBy(); void setIncrementBy(BigInteger incrementBy); BigInteger getMaxValue(); void setMaxValue(BigInteger maxValue); BigInteger getMinValue(); void setMinValue(BigInteger minValue); Boolean isOrdered(); void setOrdered(Boolean ordered); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { AlterSequenceChange refactoring = new AlterSequenceChange(); refactoring.setSequenceName("SEQ_NAME"); assertEquals("Sequence SEQ_NAME altered", refactoring.getConfirmationMessage()); } |
### Question:
MD5Util { public static String computeMD5(String input) { if (input == null) { return null; } MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); digest.update(input.getBytes("UTF-8")); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } byte[] digestBytes = digest.digest(); String returnString = new String(encodeHex(digestBytes)); LogFactory.getLogger().debug("Computed checksum for "+input+" as "+returnString); return returnString; } static String computeMD5(String input); static String computeMD5(InputStream stream); }### Answer:
@Test public void testComputeMD5() throws Exception { String hash = MD5Util.computeMD5(TEST_STRING); assertEquals(TEST_STRING_MD5_HASH, hash); String hash2 = MD5Util.computeMD5(TEST_STRING2); assertEquals(TEST_STRING2_MD5_HASH, hash2); String hash3 = MD5Util.computeMD5(TEST_STRING3); assertEquals(TEST_STRING3_MD5_HASH, hash3); }
@Test public void testComputeMD5InputStream() { ByteArrayInputStream bais = new ByteArrayInputStream(TEST_STRING.getBytes()); String hexString = MD5Util.computeMD5(bais); assertEquals(TEST_STRING_MD5_HASH, hexString); } |
### Question:
DropForeignKeyConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Foreign key " + getConstraintName() + " dropped"; } DropForeignKeyConstraintChange(); String getBaseTableSchemaName(); void setBaseTableSchemaName(String baseTableSchemaName); String getBaseTableName(); void setBaseTableName(String baseTableName); String getConstraintName(); void setConstraintName(String constraintName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { DropForeignKeyConstraintChange change = new DropForeignKeyConstraintChange(); change.setBaseTableSchemaName("SCHEMA_NAME"); change.setBaseTableName("TABLE_NAME"); change.setConstraintName("FK_NAME"); assertEquals("Foreign key FK_NAME dropped", change.getConfirmationMessage()); } |
### Question:
DropTableChange extends AbstractChange { public String getConfirmationMessage() { return "Table " + getTableName() + " dropped"; } DropTableChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); Boolean isCascadeConstraints(); void setCascadeConstraints(Boolean cascadeConstraints); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { assertEquals("Table TAB_NAME dropped", change.getConfirmationMessage()); } |
### Question:
LoadUpdateDataChange extends LoadDataChange { @Override public SqlStatement[] generateStatements(Database database) { return super.generateStatements(database); } LoadUpdateDataChange(); @Override SqlStatement[] generateStatements(Database database); void setPrimaryKey(String primaryKey); String getPrimaryKey(); @Override SqlStatement[] generateRollbackStatements(Database database); }### Answer:
@Test public void getStatements() throws Exception { MockDatabase database = new MockDatabase(); LoadUpdateDataChange change = new LoadUpdateDataChange(); change.setSchemaName("SCHEMA_NAME"); change.setTableName("TABLE_NAME"); change.setFile("liquibase/change/core/sample.data1.csv"); change.setResourceAccessor(new ClassLoaderResourceAccessor()); SqlStatement[] statements = change.generateStatements(database); assertNotNull(statements); assertEquals(InsertOrUpdateStatement.class,statements[0].getClass()); }
@Test public void generateSql(){ MockDatabase database = new MockDatabase(); LoadUpdateDataChange change = new LoadUpdateDataChange(); change.setSchemaName("SCHEMA_NAME"); change.setTableName("TABLE_NAME"); change.setFile("liquibase/change/core/sample.data1.csv"); change.setResourceAccessor(new ClassLoaderResourceAccessor()); SqlStatement[] statements = change.generateStatements(database); assertNotNull(statements); assertEquals(InsertOrUpdateStatement.class,statements[0].getClass()); } |
### Question:
LoadUpdateDataChange extends LoadDataChange { public void setPrimaryKey(String primaryKey) throws LiquibaseException { if (primaryKey == null) { throw new LiquibaseException("primaryKey cannot be null."); } this.primaryKey = primaryKey; } LoadUpdateDataChange(); @Override SqlStatement[] generateStatements(Database database); void setPrimaryKey(String primaryKey); String getPrimaryKey(); @Override SqlStatement[] generateRollbackStatements(Database database); }### Answer:
@Test public void primaryKeyNullThrowsException() { LoadUpdateDataChange change = new LoadUpdateDataChange(); try { change.setPrimaryKey(null); fail("setPrimaryKey did not throw InvalidArgumentException as expected."); } catch(LiquibaseException e) { } } |
### Question:
LoadUpdateDataChange extends LoadDataChange { private String getWhereClause(InsertOrUpdateStatement insertOrUpdateStatement, Database database) { StringBuffer where = new StringBuffer(); String[] pkColumns = insertOrUpdateStatement.getPrimaryKey().split(","); for(String thisPkColumn:pkColumns) { where.append(database.escapeColumnName(insertOrUpdateStatement.getSchemaName(), insertOrUpdateStatement.getTableName(), thisPkColumn) + " = " ); Object newValue = insertOrUpdateStatement.getColumnValues().get(thisPkColumn); if (newValue == null || newValue.toString().equals("NULL")) { where.append("NULL"); } else if (newValue instanceof String && database.shouldQuoteValue(((String) newValue))) { where.append("'").append(database.escapeStringForDatabase((String) newValue)).append("'"); } else if (newValue instanceof Date) { where.append(database.getDateLiteral(((Date) newValue))); } else if (newValue instanceof Boolean) { if (((Boolean) newValue)) { where.append(TypeConverterFactory.getInstance().findTypeConverter(database).getBooleanType().getTrueBooleanValue()); } else { where.append(TypeConverterFactory.getInstance().findTypeConverter(database).getBooleanType().getFalseBooleanValue()); } } else { where.append(newValue); } where.append(" AND "); } where.delete(where.lastIndexOf(" AND "),where.lastIndexOf(" AND ") + " AND ".length()); return where.toString(); } LoadUpdateDataChange(); @Override SqlStatement[] generateStatements(Database database); void setPrimaryKey(String primaryKey); String getPrimaryKey(); @Override SqlStatement[] generateRollbackStatements(Database database); }### Answer:
@Test public void getWhereClause() throws LiquibaseException { MockDatabase database = new MockDatabase(); LoadUpdateDataChange change = new LoadUpdateDataChange(); change.setSchemaName("SCHEMA_NAME"); change.setTableName("TABLE_NAME"); change.setFile("liquibase/change/core/sample.data1.csv"); change.setResourceAccessor(new ClassLoaderResourceAccessor()); change.setPrimaryKey("name"); SqlStatement[] statements = change.generateStatements(database); Object[] args ; String result ; args = new Object[] { statements[0], database }; result = (String)invokePrivateMethod(change,"getWhereClause",args); assertEquals("name = 'Bob Johnson'",result.trim()); args = new Object[] { statements[1], database }; result = (String)invokePrivateMethod(change,"getWhereClause",args); assertEquals("name = 'John Doe'",result.trim()); } |
### Question:
AddUniqueConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Unique constraint added to "+getTableName()+"("+getColumnNames()+")"; } AddUniqueConstraintChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnNames(); void setColumnNames(String columnNames); String getConstraintName(); void setConstraintName(String constraintName); String getTablespace(); void setTablespace(String tablespace); Boolean getDeferrable(); void setDeferrable(Boolean deferrable); Boolean getInitiallyDeferred(); void setInitiallyDeferred(Boolean initiallyDeferred); Boolean getDisabled(); void setDisabled(Boolean disabled); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { AddUniqueConstraintChange change = new AddUniqueConstraintChange(); change.setTableName("TABLE_NAME"); change.setColumnNames("COL_HERE"); assertEquals("Unique constraint added to TABLE_NAME(COL_HERE)", change.getConfirmationMessage()); } |
### Question:
AddNotNullConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Null constraint has been added to " + getTableName() + "." + getColumnName(); } AddNotNullConstraintChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnName(); void setColumnName(String columnName); String getDefaultNullValue(); void setDefaultNullValue(String defaultNullValue); String getColumnDataType(); void setColumnDataType(String columnDataType); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { AddNotNullConstraintChange change = new AddNotNullConstraintChange(); change.setTableName("TABLE_NAME"); change.setColumnName("COL_HERE"); assertEquals("Null constraint has been added to TABLE_NAME.COL_HERE", change.getConfirmationMessage()); } |
### Question:
RenameViewChange extends AbstractChange { public String getConfirmationMessage() { return "View " + oldViewName + " renamed to " + newViewName; } RenameViewChange(); String getSchemaName(); void setSchemaName(String schemaName); String getOldViewName(); void setOldViewName(String oldViewName); String getNewViewName(); void setNewViewName(String newViewName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { refactoring.setOldViewName("OLD_NAME"); refactoring.setNewViewName("NEW_NAME"); assertEquals("View OLD_NAME renamed to NEW_NAME", refactoring.getConfirmationMessage()); } |
### Question:
LoadDataChange extends AbstractChange implements ChangeWithColumns<LoadDataColumnConfig> { public String getConfirmationMessage() { return "Data loaded from "+getFile()+" into "+getTableName(); } LoadDataChange(); protected LoadDataChange(String changeName, String changeDescription); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getFile(); void setFile(String file); String getEncoding(); void setEncoding(String encoding); String getSeparator(); void setSeparator(String separator); String getQuotchar(); void setQuotchar(String quotchar); void addColumn(LoadDataColumnConfig column); List<LoadDataColumnConfig> getColumns(); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); @Override CheckSum generateCheckSum(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { LoadDataChange refactoring = new LoadDataChange(); refactoring.setTableName("TABLE_NAME"); refactoring.setFile("FILE_NAME"); assertEquals("Data loaded from FILE_NAME into TABLE_NAME", refactoring.getConfirmationMessage()); } |
### Question:
LoadDataChange extends AbstractChange implements ChangeWithColumns<LoadDataColumnConfig> { @Override public CheckSum generateCheckSum() { InputStream stream = null; try { stream = getResourceAccessor().getResourceAsStream(getFile()); if (stream == null) { throw new RuntimeException(getFile() + " could not be found"); } return CheckSum.compute(stream); } catch (IOException e) { throw new RuntimeException(e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { ; } } } } LoadDataChange(); protected LoadDataChange(String changeName, String changeDescription); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getFile(); void setFile(String file); String getEncoding(); void setEncoding(String encoding); String getSeparator(); void setSeparator(String separator); String getQuotchar(); void setQuotchar(String quotchar); void addColumn(LoadDataColumnConfig column); List<LoadDataColumnConfig> getColumns(); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); @Override CheckSum generateCheckSum(); }### Answer:
@Override @Test public void generateCheckSum() throws Exception { LoadDataChange refactoring = new LoadDataChange(); refactoring.setSchemaName("SCHEMA_NAME"); refactoring.setTableName("TABLE_NAME"); refactoring.setFile("liquibase/change/core/sample.data1.csv"); refactoring.setResourceAccessor(new ClassLoaderResourceAccessor()); String md5sum1 = refactoring.generateCheckSum().toString(); refactoring.setFile("liquibase/change/core/sample.data2.csv"); String md5sum2 = refactoring.generateCheckSum().toString(); assertTrue(!md5sum1.equals(md5sum2)); assertEquals(md5sum2, refactoring.generateCheckSum().toString()); } |
### Question:
CreateViewChange extends AbstractChange { public String getConfirmationMessage() { return "View " + getViewName() + " created"; } CreateViewChange(); String getSchemaName(); void setSchemaName(String schemaName); String getViewName(); void setViewName(String viewName); String getSelectQuery(); void setSelectQuery(String selectQuery); Boolean getReplaceIfExists(); void setReplaceIfExists(Boolean replaceIfExists); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { CreateViewChange change = new CreateViewChange(); change.setViewName("VIEW_NAME"); assertEquals("View VIEW_NAME created", change.getConfirmationMessage()); } |
### Question:
DropUniqueConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Unique constraint "+getConstraintName()+" dropped from "+getTableName(); } DropUniqueConstraintChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getConstraintName(); void setConstraintName(String constraintName); String getUniqueColumns(); void setUniqueColumns(String uniqueColumns); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { assertEquals("Unique constraint UQ_CONSTRAINT dropped from TAB_NAME", change.getConfirmationMessage()); } |
### Question:
CreateTableChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { return "Table " + tableName + " created"; } CreateTableChange(); SqlStatement[] generateStatements(Database database); List<ColumnConfig> getColumns(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getTablespace(); void setTablespace(String tablespace); void addColumn(ColumnConfig column); String getRemarks(); void setRemarks(String remarks); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { change.setTableName("TAB_NAME"); assertEquals("Table TAB_NAME created", change.getConfirmationMessage()); } |
### Question:
InsertDataChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public SqlStatement[] generateStatements(Database database) { InsertStatement statement = new InsertStatement(getSchemaName() == null?database.getDefaultSchemaName():getSchemaName(), getTableName()); for (ColumnConfig column : columns) { if (database.supportsAutoIncrement() && column.isAutoIncrement() != null && column.isAutoIncrement()) { continue; } statement.addColumnValue(column.getName(), column.getValueObject()); } return new SqlStatement[]{ statement }; } InsertDataChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void setColumns(List<ColumnConfig> columns); void addColumn(ColumnConfig column); void removeColumn(ColumnConfig column); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void generateStatement() throws Exception { SqlStatement[] sqlStatements = refactoring.generateStatements(new MockDatabase()); assertEquals(1, sqlStatements.length); assertTrue(sqlStatements[0] instanceof InsertStatement); assertEquals("123", ((InsertStatement) sqlStatements[0]).getColumnValue("id").toString()); assertEquals("Andrew", ((InsertStatement) sqlStatements[0]).getColumnValue("name").toString()); assertEquals("21", ((InsertStatement) sqlStatements[0]).getColumnValue("age").toString()); assertEquals("1.78", ((InsertStatement) sqlStatements[0]).getColumnValue("height").toString()); } |
### Question:
InsertDataChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { return "New row inserted into " + getTableName(); } InsertDataChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void setColumns(List<ColumnConfig> columns); void addColumn(ColumnConfig column); void removeColumn(ColumnConfig column); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { assertEquals("New row inserted into TABLE_NAME", refactoring.getConfirmationMessage()); } |
### Question:
DropViewChange extends AbstractChange { public String getConfirmationMessage() { return "View "+getViewName()+" dropped"; } DropViewChange(); String getSchemaName(); void setSchemaName(String schemaName); String getViewName(); void setViewName(String viewName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { DropViewChange change = new DropViewChange(); change.setViewName("VIEW_NAME"); assertEquals("View VIEW_NAME dropped", change.getConfirmationMessage()); } |
### Question:
DropColumnChange extends AbstractChange { public String getConfirmationMessage() { return "Column " + getTableName() + "." + getColumnName() + " dropped"; } DropColumnChange(); String getColumnName(); void setColumnName(String columnName); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { DropColumnChange change = new DropColumnChange(); change.setTableName("TABLE_NAME"); change.setColumnName("COL_HERE"); assertEquals("Column TABLE_NAME.COL_HERE dropped", change.getConfirmationMessage()); } |
### Question:
DropNotNullConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Null constraint dropped from " + getTableName() + "." + getColumnName(); } DropNotNullConstraintChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnName(); void setColumnName(String columnName); String getColumnDataType(); void setColumnDataType(String columnDataType); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { DropNotNullConstraintChange change = new DropNotNullConstraintChange(); change.setTableName("TABLE_NAME"); change.setColumnName("COL_HERE"); assertEquals("Null constraint dropped from TABLE_NAME.COL_HERE", change.getConfirmationMessage()); } |
### Question:
AddDefaultValueChange extends AbstractChange { public String getConfirmationMessage() { return "Default value added to " + getTableName() + "." + getColumnName(); } AddDefaultValueChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnName(); void setColumnName(String columnName); String getColumnDataType(); void setColumnDataType(String columnDataType); String getDefaultValue(); void setDefaultValue(String defaultValue); String getDefaultValueNumeric(); void setDefaultValueNumeric(String defaultValueNumeric); String getDefaultValueDate(); void setDefaultValueDate(String defaultValueDate); Boolean getDefaultValueBoolean(); void setDefaultValueBoolean(Boolean defaultValueBoolean); DatabaseFunction getDefaultValueComputed(); void setDefaultValueComputed(DatabaseFunction defaultValueComputed); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { AddDefaultValueChange change = new AddDefaultValueChange(); change.setSchemaName("SCHEMA_NAME"); change.setTableName("TABLE_NAME"); change.setColumnName("COLUMN_NAME"); assertEquals("Default value added to TABLE_NAME.COLUMN_NAME", change.getConfirmationMessage()); } |
### Question:
RegexMatcher { public boolean allMatchedInSequentialOrder() { return allMatched; } RegexMatcher(String text,String [] regexToMatch); boolean allMatchedInSequentialOrder(); }### Answer:
@Test public void testMatchingInSequentialOrder() { matcher=new RegexMatcher(text,new String[]{"Pulp","Reservoir","Kill"}); assertTrue("All matched",matcher.allMatchedInSequentialOrder()); matcher=new RegexMatcher(text,new String[]{"Pulp","ion"}); assertTrue("All matched",matcher.allMatchedInSequentialOrder()); matcher=new RegexMatcher(text,new String[]{"Pu.p","^Ki.+ll$"}); assertTrue("All matched",matcher.allMatchedInSequentialOrder()); matcher=new RegexMatcher(text,new String[]{"pulP","kiLL"}); assertTrue("Case insensitive",matcher.allMatchedInSequentialOrder()); matcher=new RegexMatcher(text,new String[]{"Reservoir","Pulp","Dogs"}); assertFalse("Not in order",matcher.allMatchedInSequentialOrder()); matcher=new RegexMatcher(text,new String[]{"Memento"}); assertFalse("Not found",matcher.allMatchedInSequentialOrder()); } |
### Question:
DropSequenceChange extends AbstractChange { public String getConfirmationMessage() { return "Sequence " + getSequenceName() + " dropped"; } DropSequenceChange(); String getSchemaName(); void setSchemaName(String schemaName); String getSequenceName(); void setSequenceName(String sequenceName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { assertEquals("Sequence SEQ_NAME dropped", change.getConfirmationMessage()); } |
### Question:
SQLFileChange extends AbstractSQLChange { @Override public void setSql(String sql) { if (getChangeLogParameters() != null) { sql = getChangeLogParameters().expandExpressions(sql); } super.setSql(sql); } SQLFileChange(); String getPath(); void setPath(String fileName); String getEncoding(); void setEncoding(String encoding); Boolean isRelativeToChangelogFile(); void setRelativeToChangelogFile(Boolean relativeToChangelogFile); @Override void init(); @Override ValidationErrors validate(Database database); @Override Warnings warn(Database database); @Override CheckSum generateCheckSum(); String getConfirmationMessage(); @Override void setSql(String sql); }### Answer:
@Test public void multilineComment2() { String original = "--\r\n"+ "-- This is a comment\r\n" + "UPDATE tablename SET column = 1;\r\n" + "GO"; SQLFileChange change = new SQLFileChange(); change.setSql(original); change.setSplitStatements(true); change.setStripComments(true); SqlStatement[] out = change.generateStatements(new MockDatabase()); assertEquals(2, out.length); assertEquals("UPDATE tablename SET column = 1", out[0].toString()); }
@Test public void testStatementsWithSemicolons() { AbstractSQLChange change2 = new SQLFileChange(); String insertWithSemicolon = "insert into table ( col ) values (' value with; semicolon ');"; change2.setSql(insertWithSemicolon); Database database = new MockDatabase(); SqlStatement[] statements = change2.generateStatements(database); assertEquals("Unexpected amount of statements returned",1, statements.length); String insertWithoutTrailingSemicolon = insertWithSemicolon.substring(0, insertWithSemicolon.length() - 1); assertEquals("unexpected SQL statement returned", insertWithoutTrailingSemicolon, statements[0].toString()); }
@Test public void replacementOfProperties() throws Exception { SQLFileChange change = new SQLFileChange(); ChangeLogParameters changeLogParameters = new ChangeLogParameters(); changeLogParameters.set("table.prefix", "prfx"); changeLogParameters.set("some.other.prop", "nofx"); change.setChangeLogParameters(changeLogParameters); String fakeSql = "create ${table.prefix}_customer (${some.other.prop} INTEGER NOT NULL, PRIMARY KEY (${some.other.prop}));"; change.setSql(fakeSql); String expected = "create prfx_customer (nofx INTEGER NOT NULL, PRIMARY KEY (nofx));"; assertEquals(expected, change.getSql()); } |
### Question:
SQLFileChange extends AbstractSQLChange { public String getConfirmationMessage() { return "SQL in file " + path + " executed"; } SQLFileChange(); String getPath(); void setPath(String fileName); String getEncoding(); void setEncoding(String encoding); Boolean isRelativeToChangelogFile(); void setRelativeToChangelogFile(Boolean relativeToChangelogFile); @Override void init(); @Override ValidationErrors validate(Database database); @Override Warnings warn(Database database); @Override CheckSum generateCheckSum(); String getConfirmationMessage(); @Override void setSql(String sql); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { change.setPath(fileName); assertEquals("SQL in file " + fileName + " executed", change.getConfirmationMessage()); } |
### Question:
CreateIndexChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { return "Index " + getIndexName() + " created"; } CreateIndexChange(); String getIndexName(); void setIndexName(String indexName); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void setColumns(List<ColumnConfig> columns); void addColumn(ColumnConfig column); String getTablespace(); void setTablespace(String tablespace); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); void setUnique(Boolean isUnique); Boolean isUnique(); String getAssociatedWith(); void setAssociatedWith(String associatedWith); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { CreateIndexChange refactoring = new CreateIndexChange(); refactoring.setIndexName("IDX_TEST"); assertEquals("Index IDX_TEST created", refactoring.getConfirmationMessage()); } |
### Question:
AddAutoIncrementChange extends AbstractChange { public String getConfirmationMessage() { return "Auto-increment added to " + getTableName() + "." + getColumnName(); } AddAutoIncrementChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnName(); void setColumnName(String columnName); String getColumnDataType(); void setColumnDataType(String columnDataType); BigInteger getStartWith(); void setStartWith(BigInteger startWith); BigInteger getIncrementBy(); void setIncrementBy(BigInteger incrementBy); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { AddAutoIncrementChange change = new AddAutoIncrementChange(); change.setSchemaName("SCHEMA_NAME"); change.setTableName("TABLE_NAME"); change.setColumnName("COLUMN_NAME"); change.setColumnDataType("DATATYPE(255)"); assertEquals("Auto-increment added to TABLE_NAME.COLUMN_NAME", change.getConfirmationMessage()); } |
### Question:
AddPrimaryKeyChange extends AbstractChange { public String getConfirmationMessage() { return "Primary key added to " + getTableName() + " (" + getColumnNames() + ")"; } AddPrimaryKeyChange(); String getTableName(); void setTableName(String tableName); String getSchemaName(); void setSchemaName(String schemaName); String getColumnNames(); void setColumnNames(String columnNames); String getConstraintName(); void setConstraintName(String constraintName); String getTablespace(); void setTablespace(String tablespace); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { AddPrimaryKeyChange change = new AddPrimaryKeyChange(); change.setTableName("TABLE_NAME"); change.setColumnNames("COL_HERE"); assertEquals("Primary key added to TABLE_NAME (COL_HERE)", change.getConfirmationMessage()); } |
### Question:
CreateSequenceChange extends AbstractChange { public String getConfirmationMessage() { return "Sequence " + getSequenceName() + " created"; } CreateSequenceChange(); String getSchemaName(); void setSchemaName(String schemaName); String getSequenceName(); void setSequenceName(String sequenceName); BigInteger getStartValue(); void setStartValue(BigInteger startValue); BigInteger getIncrementBy(); void setIncrementBy(BigInteger incrementBy); BigInteger getMaxValue(); void setMaxValue(BigInteger maxValue); BigInteger getMinValue(); void setMinValue(BigInteger minValue); Boolean isOrdered(); void setOrdered(Boolean ordered); Boolean getCycle(); void setCycle(Boolean cycle); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer:
@Override @Test public void getConfirmationMessage() throws Exception { CreateSequenceChange change = new CreateSequenceChange(); change.setSequenceName("SEQ_NAME"); assertEquals("Sequence SEQ_NAME created", change.getConfirmationMessage()); } |
### Question:
AbstractChange implements Change { public CheckSum generateCheckSum() { return CheckSum.compute(new StringChangeLogSerializer().serialize(this)); } protected AbstractChange(String changeName, String changeDescription, int priority); ChangeMetaData getChangeMetaData(); ChangeSet getChangeSet(); void setChangeSet(ChangeSet changeSet); boolean requiresUpdatedDatabaseMetadata(Database database); boolean supports(Database database); Warnings warn(Database database); ValidationErrors validate(Database database); SqlStatement[] generateRollbackStatements(Database database); boolean supportsRollback(Database database); CheckSum generateCheckSum(); void setResourceAccessor(ResourceAccessor resourceAccessor); ResourceAccessor getResourceAccessor(); void init(); Set<DatabaseObject> getAffectedDatabaseObjects(Database database); void setChangeLogParameters(ChangeLogParameters changeLogParameters); }### Answer:
@Test public void generateCheckSum() throws Exception { Change change = createClassUnderTest(); if (change == null) { return; } CheckSum checkSum = change.generateCheckSum(); assertNotNull(checkSum); assertEquals(CheckSum.getCurrentVersion(), checkSum.getVersion()); assertTrue(checkSum.toString().startsWith(CheckSum.getCurrentVersion()+":")); Map<String, String> seenCheckSums = new HashMap<String, String>(); for (Field field : change.getClass().getDeclaredFields()) { field.setAccessible(true); if (field.getName().startsWith("$VR") || field.getName().equals("serialVersionUID")) { } else if (field.getName().equals("associatedWith")) { } else if (String.class.isAssignableFrom(field.getType())) { field.set(change, "asdghasdgasdg"); checkThatChecksumIsNew(change, seenCheckSums, field); field.set(change, "gsgasdgasdggasdg sdg a"); checkThatChecksumIsNew(change, seenCheckSums, field); } else if (Boolean.class.isAssignableFrom(field.getType())) { field.set(change, Boolean.TRUE); checkThatChecksumIsNew(change, seenCheckSums, field); field.set(change, Boolean.FALSE); checkThatChecksumIsNew(change, seenCheckSums, field); } else if (Integer.class.isAssignableFrom(field.getType())) { field.set(change, 6532); checkThatChecksumIsNew(change, seenCheckSums, field); field.set(change, -52352); checkThatChecksumIsNew(change, seenCheckSums, field); } else if (DatabaseFunction.class.isAssignableFrom(field.getType())) { field.set(change, new DatabaseFunction("FUNC1")); checkThatChecksumIsNew(change, seenCheckSums, field); field.set(change, new DatabaseFunction("FUNC 2")); checkThatChecksumIsNew(change, seenCheckSums, field); } else if (BigInteger.class.isAssignableFrom(field.getType())) { field.set(change, new BigInteger("6532")); checkThatChecksumIsNew(change, seenCheckSums, field); field.set(change, new BigInteger("-52352")); checkThatChecksumIsNew(change, seenCheckSums, field); } else if (List.class.isAssignableFrom(field.getType())) { ColumnConfig column1 = new ColumnConfig(); ((List) field.get(change)).add(column1); column1.setName("ghsdgasdg"); checkThatChecksumIsNew(change, seenCheckSums, field); column1.setType("gasdgasdg"); checkThatChecksumIsNew(change, seenCheckSums, field); ColumnConfig column2 = new ColumnConfig(); ((List) field.get(change)).add(column2); column2.setName("87682346asgasdg"); checkThatChecksumIsNew(change, seenCheckSums, field); } else if (field.getName().equalsIgnoreCase("changeLogParameters")) { } else { throw new RuntimeException("Unknown field type: "+field.getType()+" for "+field.getName()); } } } |
### Question:
AbstractChange implements Change { public boolean supports(Database database) { for (SqlStatement statement : generateStatements(database)) { if (!SqlGeneratorFactory.getInstance().supports(statement, database)) { return false; } } return true; } protected AbstractChange(String changeName, String changeDescription, int priority); ChangeMetaData getChangeMetaData(); ChangeSet getChangeSet(); void setChangeSet(ChangeSet changeSet); boolean requiresUpdatedDatabaseMetadata(Database database); boolean supports(Database database); Warnings warn(Database database); ValidationErrors validate(Database database); SqlStatement[] generateRollbackStatements(Database database); boolean supportsRollback(Database database); CheckSum generateCheckSum(); void setResourceAccessor(ResourceAccessor resourceAccessor); ResourceAccessor getResourceAccessor(); void init(); Set<DatabaseObject> getAffectedDatabaseObjects(Database database); void setChangeLogParameters(ChangeLogParameters changeLogParameters); }### Answer:
@Test public void isSupported() throws Exception { Change change = createClassUnderTest(); if (change == null) { return; } for (Database database : TestContext.getInstance().getAllDatabases()) { assertEquals("Unexpected availablity on "+database.getTypeName(), !changeIsUnsupported(database), change.supports(database)); } } |
### Question:
AbstractChange implements Change { public ValidationErrors validate(Database database) { ValidationErrors changeValidationErrors = new ValidationErrors(); for (SqlStatement statement : generateStatements(database)) { boolean supported = SqlGeneratorFactory.getInstance().supports(statement, database); if (!supported) { if (statement.skipOnUnsupported()) { LogFactory.getLogger().info(getChangeMetaData().getName()+" is not supported on "+database.getTypeName()+" but will continue"); } else { changeValidationErrors.addError(getChangeMetaData().getName()+" is not supported on "+database.getTypeName()); } } else { changeValidationErrors.addAll(SqlGeneratorFactory.getInstance().validate(statement, database)); } } return changeValidationErrors; } protected AbstractChange(String changeName, String changeDescription, int priority); ChangeMetaData getChangeMetaData(); ChangeSet getChangeSet(); void setChangeSet(ChangeSet changeSet); boolean requiresUpdatedDatabaseMetadata(Database database); boolean supports(Database database); Warnings warn(Database database); ValidationErrors validate(Database database); SqlStatement[] generateRollbackStatements(Database database); boolean supportsRollback(Database database); CheckSum generateCheckSum(); void setResourceAccessor(ResourceAccessor resourceAccessor); ResourceAccessor getResourceAccessor(); void init(); Set<DatabaseObject> getAffectedDatabaseObjects(Database database); void setChangeLogParameters(ChangeLogParameters changeLogParameters); }### Answer:
@Test public void validate() throws Exception { Change change = createClassUnderTest(); if (change == null) { return; } for (Database database : TestContext.getInstance().getAllDatabases()) { if (change.supports(database)) { ValidationErrors validationErrors = change.validate(database); assertTrue("no errors found for "+database.getClass().getName(), validationErrors.hasErrors()); } } } |
### Question:
LiquibaseEntityResolver implements EntityResolver2 { public InputSource resolveEntity(String name, String publicId, String baseURI, String systemId) throws SAXException, IOException { InputSource resolved=null; if(systemId!=null && systemId.toLowerCase().endsWith(".xsd")) { resolved=tryResolveLiquibaseSchema(systemId, publicId); } if(resolved==null && resourceAccessor!=null && basePath!=null && systemId!=null) { resolved=tryResolveFromResourceAccessor(systemId); } return resolved; } LiquibaseEntityResolver(); void useResoureAccessor(ResourceAccessor resourceAccessor,String basePath); InputSource resolveEntity(String name, String publicId, String baseURI, String systemId); InputSource getExternalSubset(String name, String baseURI); InputSource resolveEntity(String publicId, String systemId); }### Answer:
@Test public void resolveSchemas() throws Exception { LiquibaseEntityResolver liquibaseSchemaResolver = new LiquibaseEntityResolver(); assertNotNull(liquibaseSchemaResolver.resolveEntity(null, null, null, "http: assertNull(liquibaseSchemaResolver.resolveEntity(null,null,null, "http: } |
### Question:
FormattedSqlChangeLogParser implements ChangeLogParser { public boolean supports(String changeLogFile, ResourceAccessor resourceAccessor) { BufferedReader reader = null; try { if (changeLogFile.endsWith(".sql")) { reader = new BufferedReader(new InputStreamReader(openChangeLogFile(changeLogFile, resourceAccessor))); return reader.readLine().matches("\\-\\-\\s*liquibase formatted.*"); } else { return false; } } catch (IOException e) { LogFactory.getLogger().debug("Exception reading " + changeLogFile, e); return false; } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { LogFactory.getLogger().debug("Exception closing " + changeLogFile, e); } } } } boolean supports(String changeLogFile, ResourceAccessor resourceAccessor); int getPriority(); DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor); }### Answer:
@Test public void supports() throws Exception { assertTrue(new MockFormattedSqlChangeLogParser(VALID_CHANGELOG).supports("asdf.sql", new JUnitResourceAccessor())); assertFalse(new MockFormattedSqlChangeLogParser(INVALID_CHANGELOG).supports("asdf.sql", new JUnitResourceAccessor())); } |
### Question:
ChangeLogParserFactory { public static ChangeLogParserFactory getInstance() { if (instance == null) { instance = new ChangeLogParserFactory(); } return instance; } private ChangeLogParserFactory(); static void reset(); static ChangeLogParserFactory getInstance(); List<ChangeLogParser> getParsers(); ChangeLogParser getParser(String fileNameOrExtension, ResourceAccessor resourceAccessor); void register(ChangeLogParser changeLogParser); void unregister(ChangeLogParser changeLogParser); }### Answer:
@Test public void getInstance() { assertNotNull(ChangeLogParserFactory.getInstance()); assertTrue(ChangeLogParserFactory.getInstance() == ChangeLogParserFactory.getInstance()); } |
### Question:
ChangeLogParserFactory { public void register(ChangeLogParser changeLogParser) { parsers.add(changeLogParser); Collections.sort(parsers, changelogParserComparator); } private ChangeLogParserFactory(); static void reset(); static ChangeLogParserFactory getInstance(); List<ChangeLogParser> getParsers(); ChangeLogParser getParser(String fileNameOrExtension, ResourceAccessor resourceAccessor); void register(ChangeLogParser changeLogParser); void unregister(ChangeLogParser changeLogParser); }### Answer:
@Test public void register() { ChangeLogParserFactory.getInstance().getParsers().clear(); assertEquals(0, ChangeLogParserFactory.getInstance().getParsers().size()); ChangeLogParserFactory.getInstance().register(new MockChangeLogParser("mock")); assertEquals(1, ChangeLogParserFactory.getInstance().getParsers().size()); } |
### Question:
CacheDatabase extends AbstractDatabase { @Override public boolean supportsSequences() { return false; } String getCurrentDateTimeFunction(); String getDefaultDriver(String url); int getPriority(); String getTypeName(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); boolean supportsInitiallyDeferrableColumns(); @Override String getLineComment(); @Override boolean supportsSequences(); boolean supportsTablespaces(); @Override boolean supportsAutoIncrement(); @Override String getViewDefinition(String schemaName, String viewName); static final String PRODUCT_NAME; }### Answer:
@Test public void supportsSequences() { assertFalse(database.supportsSequences()); } |
### Question:
ChangeLogParserFactory { public static void reset() { instance = new ChangeLogParserFactory(); } private ChangeLogParserFactory(); static void reset(); static ChangeLogParserFactory getInstance(); List<ChangeLogParser> getParsers(); ChangeLogParser getParser(String fileNameOrExtension, ResourceAccessor resourceAccessor); void register(ChangeLogParser changeLogParser); void unregister(ChangeLogParser changeLogParser); }### Answer:
@Test public void reset() { ChangeLogParserFactory instance1 = ChangeLogParserFactory.getInstance(); ChangeLogParserFactory.reset(); assertFalse(instance1 == ChangeLogParserFactory.getInstance()); } |
### Question:
ChangeLogParserFactory { public List<ChangeLogParser> getParsers() { return parsers; } private ChangeLogParserFactory(); static void reset(); static ChangeLogParserFactory getInstance(); List<ChangeLogParser> getParsers(); ChangeLogParser getParser(String fileNameOrExtension, ResourceAccessor resourceAccessor); void register(ChangeLogParser changeLogParser); void unregister(ChangeLogParser changeLogParser); }### Answer:
@Test public void getParsers() throws Exception { ChangeLogParser parser = ChangeLogParserFactory.getInstance().getParser("asdf.xml", new JUnitResourceAccessor()); assertNotNull(parser); assertTrue(parser instanceof XMLChangeLogSAXParser); } |
### Question:
ServiceLocator { public static void reset() { instance = new ServiceLocator(); } protected ServiceLocator(); protected ServiceLocator(ResourceAccessor accessor); protected ServiceLocator(PackageScanClassResolver classResolver); protected ServiceLocator(PackageScanClassResolver classResolver, ResourceAccessor accessor); static ServiceLocator getInstance(); static void setInstance(ServiceLocator newInstance); void setResourceAccessor(ResourceAccessor resourceAccessor); void addPackageToScan(String packageName); Class findClass(Class requiredInterface); Class[] findClasses(Class requiredInterface); Object newInstance(Class requiredInterface); static void reset(); }### Answer:
@Test public void reset() { ServiceLocator instance1 = ServiceLocator.getInstance(); ServiceLocator.reset(); assertFalse(instance1 == ServiceLocator.getInstance()); } |
### Question:
ServiceLocator { public Class[] findClasses(Class requiredInterface) throws ServiceNotFoundException { logger.debug("ServiceLocator.findClasses for "+requiredInterface.getName()); try { Class.forName(requiredInterface.getName()); if (!classesBySuperclass.containsKey(requiredInterface)) { classesBySuperclass.put(requiredInterface, findClassesImpl(requiredInterface)); } } catch (Exception e) { throw new ServiceNotFoundException(e); } List<Class> classes = classesBySuperclass.get(requiredInterface); HashSet<Class> uniqueClasses = new HashSet<Class>(classes); return uniqueClasses.toArray(new Class[uniqueClasses.size()]); } protected ServiceLocator(); protected ServiceLocator(ResourceAccessor accessor); protected ServiceLocator(PackageScanClassResolver classResolver); protected ServiceLocator(PackageScanClassResolver classResolver, ResourceAccessor accessor); static ServiceLocator getInstance(); static void setInstance(ServiceLocator newInstance); void setResourceAccessor(ResourceAccessor resourceAccessor); void addPackageToScan(String packageName); Class findClass(Class requiredInterface); Class[] findClasses(Class requiredInterface); Object newInstance(Class requiredInterface); static void reset(); }### Answer:
@Test public void getClasses() throws Exception { Class[] classes = serviceLocator.findClasses(ChangeLogParser.class); assertTrue(classes.length > 0); } |
### Question:
ServiceLocator { public Class findClass(Class requiredInterface) throws ServiceNotFoundException { if (requiredInterface == Logger.class ) { return DefaultLogger.class; } else if ( requiredInterface == Executor.class ) { return JdbcExecutor.class; } else { throw new ServiceNotFoundException("Could not find implementation of " + requiredInterface.getName()); } } protected ServiceLocator(); protected ServiceLocator(ResourceAccessor accessor); protected ServiceLocator(PackageScanClassResolver classResolver); protected ServiceLocator(PackageScanClassResolver classResolver, ResourceAccessor accessor); static ServiceLocator getInstance(); static void setInstance(ServiceLocator newInstance); void setResourceAccessor(ResourceAccessor resourceAccessor); void addPackageToScan(String packageName); Class findClass(Class requiredInterface); Class[] findClasses(Class requiredInterface); Object newInstance(Class requiredInterface); static void reset(); }### Answer:
@Test public void findClass() throws Exception { Class[] classes = serviceLocator.findClasses(Database.class); for (Class clazz : classes) { assertFalse(clazz.getName()+" is abstract", Modifier.isAbstract(clazz.getModifiers())); assertFalse(clazz.getName()+" is an interface", Modifier.isInterface(clazz.getModifiers())); assertNotNull(clazz.getConstructors()); } assertTrue(classes.length > 0); } |
### Question:
LockService { public static LockService getInstance(Database database) { if (!instances.containsKey(database)) { instances.put(database, new LockService(database)); } return instances.get(database); } private LockService(Database database); static LockService getInstance(Database database); void setChangeLogLockWaitTime(long changeLogLockWaitTime); void setChangeLogLockRecheckTime(long changeLogLocRecheckTime); boolean hasChangeLogLock(); void waitForLock(); boolean acquireLock(); void releaseLock(); DatabaseChangeLogLock[] listLocks(); void forceReleaseLock(); void reset(); static void resetAll(); }### Answer:
@Test public void getInstance() { final Database oracle1 = new OracleDatabase() { @Override public boolean equals(Object o) { return o == this; } }; final Database oracle2 = new OracleDatabase() { @Override public boolean equals(Object o) { return o == this; } }; final Database mysql = new MySQLDatabase() { @Override public boolean equals(Object o) { return o == this; } }; assertNotNull(LockService.getInstance(oracle1)); assertNotNull(LockService.getInstance(oracle2)); assertNotNull(LockService.getInstance(mysql)); assertTrue(LockService.getInstance(oracle1) == LockService.getInstance(oracle1)); assertTrue(LockService.getInstance(oracle2) == LockService.getInstance(oracle2)); assertTrue(LockService.getInstance(mysql) == LockService.getInstance(mysql)); assertTrue(LockService.getInstance(oracle1) != LockService.getInstance(oracle2)); assertTrue(LockService.getInstance(oracle1) != LockService.getInstance(mysql)); } |
### Question:
CacheDatabase extends AbstractDatabase { @Override public String getLineComment() { return "--"; } String getCurrentDateTimeFunction(); String getDefaultDriver(String url); int getPriority(); String getTypeName(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); boolean supportsInitiallyDeferrableColumns(); @Override String getLineComment(); @Override boolean supportsSequences(); boolean supportsTablespaces(); @Override boolean supportsAutoIncrement(); @Override String getViewDefinition(String schemaName, String viewName); static final String PRODUCT_NAME; }### Answer:
@Test public void getLineComment() { Assert.assertEquals("--", database.getLineComment()); } |
### Question:
CacheDatabase extends AbstractDatabase { public String getDefaultDriver(String url) { if (url.startsWith("jdbc:Cache")) { return "com.intersys.jdbc.CacheDriver"; } return null; } String getCurrentDateTimeFunction(); String getDefaultDriver(String url); int getPriority(); String getTypeName(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); boolean supportsInitiallyDeferrableColumns(); @Override String getLineComment(); @Override boolean supportsSequences(); boolean supportsTablespaces(); @Override boolean supportsAutoIncrement(); @Override String getViewDefinition(String schemaName, String viewName); static final String PRODUCT_NAME; }### Answer:
@Test public void getDefaultDriver() { Assert.assertEquals("com.intersys.jdbc.CacheDriver", database.getDefaultDriver("jdbc:Cache: } |
### Question:
CacheDatabase extends AbstractDatabase { public String getTypeName() { return "cache"; } String getCurrentDateTimeFunction(); String getDefaultDriver(String url); int getPriority(); String getTypeName(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); boolean supportsInitiallyDeferrableColumns(); @Override String getLineComment(); @Override boolean supportsSequences(); boolean supportsTablespaces(); @Override boolean supportsAutoIncrement(); @Override String getViewDefinition(String schemaName, String viewName); static final String PRODUCT_NAME; }### Answer:
@Test public void getTypeName() { Assert.assertEquals("cache", database.getTypeName()); } |
### Question:
CacheDatabase extends AbstractDatabase { public String getCurrentDateTimeFunction() { if (currentDateTimeFunction != null) { return currentDateTimeFunction; } return "SYSDATE"; } String getCurrentDateTimeFunction(); String getDefaultDriver(String url); int getPriority(); String getTypeName(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); boolean supportsInitiallyDeferrableColumns(); @Override String getLineComment(); @Override boolean supportsSequences(); boolean supportsTablespaces(); @Override boolean supportsAutoIncrement(); @Override String getViewDefinition(String schemaName, String viewName); static final String PRODUCT_NAME; }### Answer:
@Override @Test public void getCurrentDateTimeFunction() { Assert.assertEquals("SYSDATE", database.getCurrentDateTimeFunction()); } |
### Question:
CacheDatabase extends AbstractDatabase { public boolean supportsInitiallyDeferrableColumns() { return false; } String getCurrentDateTimeFunction(); String getDefaultDriver(String url); int getPriority(); String getTypeName(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); boolean supportsInitiallyDeferrableColumns(); @Override String getLineComment(); @Override boolean supportsSequences(); boolean supportsTablespaces(); @Override boolean supportsAutoIncrement(); @Override String getViewDefinition(String schemaName, String viewName); static final String PRODUCT_NAME; }### Answer:
@Override @Test public void supportsInitiallyDeferrableColumns() { assertFalse(database.supportsInitiallyDeferrableColumns()); } |
### Question:
PostgresDatabase extends AbstractDatabase { public boolean supportsInitiallyDeferrableColumns() { return true; } PostgresDatabase(); @Override void setConnection(DatabaseConnection conn); String getTypeName(); @Override Set<String> getSystemTablesAndViews(); int getPriority(); boolean supportsInitiallyDeferrableColumns(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); String getDefaultDriver(String url); @Override boolean supportsSequences(); String getCurrentDateTimeFunction(); @Override String getDefaultCatalogName(); @Override String getDatabaseChangeLogTableName(); @Override String getDatabaseChangeLogLockTableName(); @Override boolean isSystemTable(String catalogName, String schemaName, String tableName); boolean supportsTablespaces(); @Override String getAutoIncrementClause(); @Override boolean generateAutoIncrementStartWith(BigInteger startWith); @Override boolean generateAutoIncrementBy(BigInteger incrementBy); @Override String convertRequestedSchemaToSchema(String requestedSchema); @Override String convertRequestedSchemaToCatalog(String requestedSchema); @Override String escapeDatabaseObject(String objectName); @Override boolean isReservedWord(String tableName); @Override String escapeIndexName(String schemaName, String indexName); static final String PRODUCT_NAME; }### Answer:
@Override @Test public void supportsInitiallyDeferrableColumns() { assertTrue(getDatabase().supportsInitiallyDeferrableColumns()); } |
### Question:
PostgresDatabase extends AbstractDatabase { public String getCurrentDateTimeFunction() { if (currentDateTimeFunction != null) { return currentDateTimeFunction; } return "NOW()"; } PostgresDatabase(); @Override void setConnection(DatabaseConnection conn); String getTypeName(); @Override Set<String> getSystemTablesAndViews(); int getPriority(); boolean supportsInitiallyDeferrableColumns(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); String getDefaultDriver(String url); @Override boolean supportsSequences(); String getCurrentDateTimeFunction(); @Override String getDefaultCatalogName(); @Override String getDatabaseChangeLogTableName(); @Override String getDatabaseChangeLogLockTableName(); @Override boolean isSystemTable(String catalogName, String schemaName, String tableName); boolean supportsTablespaces(); @Override String getAutoIncrementClause(); @Override boolean generateAutoIncrementStartWith(BigInteger startWith); @Override boolean generateAutoIncrementBy(BigInteger incrementBy); @Override String convertRequestedSchemaToSchema(String requestedSchema); @Override String convertRequestedSchemaToCatalog(String requestedSchema); @Override String escapeDatabaseObject(String objectName); @Override boolean isReservedWord(String tableName); @Override String escapeIndexName(String schemaName, String indexName); static final String PRODUCT_NAME; }### Answer:
@Override @Test public void getCurrentDateTimeFunction() { Assert.assertEquals("NOW()", getDatabase().getCurrentDateTimeFunction()); } |
### Question:
OracleDatabase extends AbstractDatabase { public boolean supportsInitiallyDeferrableColumns() { return true; } OracleDatabase(); int getPriority(); @Override void setConnection(DatabaseConnection conn); String getTypeName(); @Override String generatePrimaryKeyName(String tableName); boolean supportsInitiallyDeferrableColumns(); @Override String escapeDatabaseObject(String objectName); @Override boolean isReservedWord(String objectName); @Override boolean supportsSequences(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); String getDefaultDriver(String url); String getCurrentDateTimeFunction(); @Override String escapeIndexName(String schemaName, String indexName); @Override String getDateLiteral(String isoDate); @Override boolean isSystemTable(String catalogName, String schemaName, String tableName); @Override boolean shouldQuoteValue(String value); boolean supportsTablespaces(); @Override boolean supportsAutoIncrement(); @Override boolean supportsRestrictForeignKeys(); static final String PRODUCT_NAME; }### Answer:
@Override @Test public void supportsInitiallyDeferrableColumns() { assertTrue(getDatabase().supportsInitiallyDeferrableColumns()); } |
### Question:
OracleDatabase extends AbstractDatabase { public String getCurrentDateTimeFunction() { if (currentDateTimeFunction != null) { return currentDateTimeFunction; } return "SYSTIMESTAMP"; } OracleDatabase(); int getPriority(); @Override void setConnection(DatabaseConnection conn); String getTypeName(); @Override String generatePrimaryKeyName(String tableName); boolean supportsInitiallyDeferrableColumns(); @Override String escapeDatabaseObject(String objectName); @Override boolean isReservedWord(String objectName); @Override boolean supportsSequences(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); String getDefaultDriver(String url); String getCurrentDateTimeFunction(); @Override String escapeIndexName(String schemaName, String indexName); @Override String getDateLiteral(String isoDate); @Override boolean isSystemTable(String catalogName, String schemaName, String tableName); @Override boolean shouldQuoteValue(String value); boolean supportsTablespaces(); @Override boolean supportsAutoIncrement(); @Override boolean supportsRestrictForeignKeys(); static final String PRODUCT_NAME; }### Answer:
@Override @Test public void getCurrentDateTimeFunction() { Assert.assertEquals("SYSTIMESTAMP", getDatabase().getCurrentDateTimeFunction()); } |
### Question:
SybaseDatabase extends AbstractDatabase { boolean isSybaseProductName(String dbProductName) { return "Adaptive Server Enterprise".equals(dbProductName) || "Sybase SQL Server".equals(dbProductName) || "sql server".equals(dbProductName) || "ASE".equals(dbProductName); } SybaseDatabase(); String getProductName(); String getTypeName(); int getPriority(); @Override boolean supportsDDLInTransaction(); @Override Set<String> getSystemTablesAndViews(); boolean supportsInitiallyDeferrableColumns(); @Override boolean supportsSequences(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); String getDefaultDriver(String url); String getCurrentDateTimeFunction(); @Override String getDefaultCatalogName(); @Override String getConcatSql(String... values); boolean supportsTablespaces(); @Override boolean isSystemTable(String catalogName, String schemaName, String tableName); @Override boolean isSystemView(String catalogName, String schemaName, String viewName); String generateDefaultConstraintName(String tableName, String columnName); @Override String convertRequestedSchemaToCatalog(String requestedSchema); @Override String convertRequestedSchemaToSchema(String requestedSchema); @Override boolean supportsRestrictForeignKeys(); @Override String escapeDatabaseObject(String objectName); @Override String getViewDefinition(String schemaName, String viewName); @Override int getDatabaseMajorVersion(); @Override int getDatabaseMinorVersion(); @Override String escapeIndexName(String schemaName, String indexName); static final String PRODUCT_NAME; }### Answer:
@Test public void testIsSybaseProductName() { SybaseDatabase database = new SybaseDatabase(); assertTrue("Sybase SQL Server is a valid product name", database.isSybaseProductName("Sybase SQL Server")); assertTrue("sql server is a valid product name", database.isSybaseProductName("sql server")); assertTrue("ASE is a valid product name", database.isSybaseProductName("ASE")); assertTrue("Adaptive Server Enterprise is a valid product name", database.isSybaseProductName("Adaptive Server Enterprise")); } |
### Question:
SybaseDatabase extends AbstractDatabase { @Override public String getViewDefinition(String schemaName, String viewName) throws DatabaseException { GetViewDefinitionStatement statement = new GetViewDefinitionStatement(convertRequestedSchemaToSchema(schemaName), viewName); Executor executor = ExecutorService.getInstance().getExecutor(this); @SuppressWarnings("unchecked") List<String> definitionRows = (List<String>) executor.queryForList(statement, String.class); StringBuilder definition = new StringBuilder(); for (String d : definitionRows) { definition.append(d); } return definition.toString(); } SybaseDatabase(); String getProductName(); String getTypeName(); int getPriority(); @Override boolean supportsDDLInTransaction(); @Override Set<String> getSystemTablesAndViews(); boolean supportsInitiallyDeferrableColumns(); @Override boolean supportsSequences(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); String getDefaultDriver(String url); String getCurrentDateTimeFunction(); @Override String getDefaultCatalogName(); @Override String getConcatSql(String... values); boolean supportsTablespaces(); @Override boolean isSystemTable(String catalogName, String schemaName, String tableName); @Override boolean isSystemView(String catalogName, String schemaName, String viewName); String generateDefaultConstraintName(String tableName, String columnName); @Override String convertRequestedSchemaToCatalog(String requestedSchema); @Override String convertRequestedSchemaToSchema(String requestedSchema); @Override boolean supportsRestrictForeignKeys(); @Override String escapeDatabaseObject(String objectName); @Override String getViewDefinition(String schemaName, String viewName); @Override int getDatabaseMajorVersion(); @Override int getDatabaseMinorVersion(); @Override String escapeIndexName(String schemaName, String indexName); static final String PRODUCT_NAME; }### Answer:
@Test public void testGetViewDefinitionWhenNoRows() throws Exception { SybaseDatabase database = new SybaseDatabase(); configureExecutor(database); assertEquals("", database.getViewDefinition("dbo", "view_name")); }
@Test public void testGetViewDefinitionWhenSingleRow() throws Exception { SybaseDatabase database = new SybaseDatabase(); configureExecutor(database, "foo"); assertEquals("foo", database.getViewDefinition("dbo", "view_name")); }
@Test public void testGetViewDefinitionWhenMultipleRows() throws Exception { SybaseDatabase database = new SybaseDatabase(); configureExecutor(database, "foo", " bar", " bat"); assertEquals("foo bar bat", database.getViewDefinition("dbo", "view_name")); } |
### Question:
SybaseDatabase extends AbstractDatabase { @Override public int getDatabaseMajorVersion() throws DatabaseException { try { return getConnection().getDatabaseMajorVersion(); } catch (UnsupportedOperationException e) { LogFactory.getLogger() .warning("Your JDBC driver does not support getDatabaseMajorVersion(). Consider upgrading it."); return -1; } } SybaseDatabase(); String getProductName(); String getTypeName(); int getPriority(); @Override boolean supportsDDLInTransaction(); @Override Set<String> getSystemTablesAndViews(); boolean supportsInitiallyDeferrableColumns(); @Override boolean supportsSequences(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); String getDefaultDriver(String url); String getCurrentDateTimeFunction(); @Override String getDefaultCatalogName(); @Override String getConcatSql(String... values); boolean supportsTablespaces(); @Override boolean isSystemTable(String catalogName, String schemaName, String tableName); @Override boolean isSystemView(String catalogName, String schemaName, String viewName); String generateDefaultConstraintName(String tableName, String columnName); @Override String convertRequestedSchemaToCatalog(String requestedSchema); @Override String convertRequestedSchemaToSchema(String requestedSchema); @Override boolean supportsRestrictForeignKeys(); @Override String escapeDatabaseObject(String objectName); @Override String getViewDefinition(String schemaName, String viewName); @Override int getDatabaseMajorVersion(); @Override int getDatabaseMinorVersion(); @Override String escapeIndexName(String schemaName, String indexName); static final String PRODUCT_NAME; }### Answer:
@Test public void testGetDatabaseMajorVersionWhenImplemented() throws Exception { DatabaseConnection connection = createNiceMock(DatabaseConnection.class); expect(connection.getDatabaseMajorVersion()).andReturn(15); replay(connection); SybaseDatabase database = new SybaseDatabase(); database.setConnection(connection); assertEquals(15, database.getDatabaseMajorVersion()); }
@Test public void testGetDatabaseMajorVersionWhenNotImplemented() throws Exception { DatabaseConnection connection = createNiceMock(DatabaseConnection.class); expect(connection.getDatabaseMajorVersion()).andThrow(new UnsupportedOperationException()); replay(connection); SybaseDatabase database = new SybaseDatabase(); database.setConnection(connection); assertEquals(-1, database.getDatabaseMajorVersion()); } |
### Question:
SybaseDatabase extends AbstractDatabase { @Override public int getDatabaseMinorVersion() throws DatabaseException { try { return getConnection().getDatabaseMinorVersion(); } catch (UnsupportedOperationException e) { LogFactory.getLogger() .warning("Your JDBC driver does not support getDatabaseMajorVersion(). Consider upgrading it."); return -1; } } SybaseDatabase(); String getProductName(); String getTypeName(); int getPriority(); @Override boolean supportsDDLInTransaction(); @Override Set<String> getSystemTablesAndViews(); boolean supportsInitiallyDeferrableColumns(); @Override boolean supportsSequences(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); String getDefaultDriver(String url); String getCurrentDateTimeFunction(); @Override String getDefaultCatalogName(); @Override String getConcatSql(String... values); boolean supportsTablespaces(); @Override boolean isSystemTable(String catalogName, String schemaName, String tableName); @Override boolean isSystemView(String catalogName, String schemaName, String viewName); String generateDefaultConstraintName(String tableName, String columnName); @Override String convertRequestedSchemaToCatalog(String requestedSchema); @Override String convertRequestedSchemaToSchema(String requestedSchema); @Override boolean supportsRestrictForeignKeys(); @Override String escapeDatabaseObject(String objectName); @Override String getViewDefinition(String schemaName, String viewName); @Override int getDatabaseMajorVersion(); @Override int getDatabaseMinorVersion(); @Override String escapeIndexName(String schemaName, String indexName); static final String PRODUCT_NAME; }### Answer:
@Test public void testGetDatabaseMinorVersionWhenImplemented() throws Exception { DatabaseConnection connection = createNiceMock(DatabaseConnection.class); expect(connection.getDatabaseMinorVersion()).andReturn(5); replay(connection); SybaseDatabase database = new SybaseDatabase(); database.setConnection(connection); assertEquals(5, database.getDatabaseMinorVersion()); }
@Test public void testGetDatabaseMinorVersionWhenNotImplemented() throws Exception { DatabaseConnection connection = createNiceMock(DatabaseConnection.class); expect(connection.getDatabaseMinorVersion()).andThrow(new UnsupportedOperationException()); replay(connection); SybaseDatabase database = new SybaseDatabase(); database.setConnection(connection); assertEquals(-1, database.getDatabaseMinorVersion()); } |
### Question:
H2Database extends AbstractDatabase { public boolean supportsInitiallyDeferrableColumns() { return false; } H2Database(); String getTypeName(); String getDefaultDriver(String url); int getPriority(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); boolean supportsTablespaces(); @Override String getViewDefinition(String schemaName, String name); @Override Date parseDate(String dateAsString); @Override boolean isLocalDatabase(); @Override boolean supportsSequences(); @Override String getConcatSql(String... values); @Override String getDateLiteral(String isoDate); @Override String convertRequestedSchemaToSchema(String requestedSchema); @Override String escapeDatabaseObject(String objectName); @Override boolean isReservedWord(String objectName); boolean supportsInitiallyDeferrableColumns(); String getCurrentDateTimeFunction(); }### Answer:
@Override @Test public void supportsInitiallyDeferrableColumns() { assertFalse(getDatabase().supportsInitiallyDeferrableColumns()); } |
### Question:
H2Database extends AbstractDatabase { public String getCurrentDateTimeFunction() { if (currentDateTimeFunction != null) { return currentDateTimeFunction; } return "NOW()"; } H2Database(); String getTypeName(); String getDefaultDriver(String url); int getPriority(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); boolean supportsTablespaces(); @Override String getViewDefinition(String schemaName, String name); @Override Date parseDate(String dateAsString); @Override boolean isLocalDatabase(); @Override boolean supportsSequences(); @Override String getConcatSql(String... values); @Override String getDateLiteral(String isoDate); @Override String convertRequestedSchemaToSchema(String requestedSchema); @Override String escapeDatabaseObject(String objectName); @Override boolean isReservedWord(String objectName); boolean supportsInitiallyDeferrableColumns(); String getCurrentDateTimeFunction(); }### Answer:
@Override @Test public void getCurrentDateTimeFunction() { Assert.assertEquals("NOW()", getDatabase().getCurrentDateTimeFunction()); } |
### Question:
H2Database extends AbstractDatabase { public String getDefaultDriver(String url) { if (url.startsWith("jdbc:h2")) { return "org.h2.Driver"; } return null; } H2Database(); String getTypeName(); String getDefaultDriver(String url); int getPriority(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); boolean supportsTablespaces(); @Override String getViewDefinition(String schemaName, String name); @Override Date parseDate(String dateAsString); @Override boolean isLocalDatabase(); @Override boolean supportsSequences(); @Override String getConcatSql(String... values); @Override String getDateLiteral(String isoDate); @Override String convertRequestedSchemaToSchema(String requestedSchema); @Override String escapeDatabaseObject(String objectName); @Override boolean isReservedWord(String objectName); boolean supportsInitiallyDeferrableColumns(); String getCurrentDateTimeFunction(); }### Answer:
@Test public void testGetDefaultDriver() { Database database = getDatabase(); assertEquals("org.h2.Driver", database.getDefaultDriver("jdbc:h2:mem:liquibase")); assertNull(database.getDefaultDriver("jdbc:db2: } |
### Question:
MySQLDatabase extends AbstractDatabase { public boolean supportsInitiallyDeferrableColumns() { return false; } String getTypeName(); int getPriority(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); String getDefaultDriver(String url); @Override boolean supportsSequences(); boolean supportsInitiallyDeferrableColumns(); String getCurrentDateTimeFunction(); @Override String getLineComment(); @Override String getConcatSql(String ... values); boolean supportsTablespaces(); @Override String convertRequestedSchemaToSchema(String requestedSchema); @Override String convertRequestedSchemaToCatalog(String requestedSchema); @Override String escapeDatabaseObject(String objectName); @Override String escapeIndexName(String schemaName, String indexName); @Override boolean supportsForeignKeyDisable(); @Override boolean disableForeignKeyChecks(); @Override void enableForeignKeyChecks(); static final String PRODUCT_NAME; }### Answer:
@Override @Test public void supportsInitiallyDeferrableColumns() { assertFalse(getDatabase().supportsInitiallyDeferrableColumns()); } |
### Question:
MySQLDatabase extends AbstractDatabase { public String getCurrentDateTimeFunction() { if (currentDateTimeFunction != null) { return currentDateTimeFunction; } return "NOW()"; } String getTypeName(); int getPriority(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); String getDefaultDriver(String url); @Override boolean supportsSequences(); boolean supportsInitiallyDeferrableColumns(); String getCurrentDateTimeFunction(); @Override String getLineComment(); @Override String getConcatSql(String ... values); boolean supportsTablespaces(); @Override String convertRequestedSchemaToSchema(String requestedSchema); @Override String convertRequestedSchemaToCatalog(String requestedSchema); @Override String escapeDatabaseObject(String objectName); @Override String escapeIndexName(String schemaName, String indexName); @Override boolean supportsForeignKeyDisable(); @Override boolean disableForeignKeyChecks(); @Override void enableForeignKeyChecks(); static final String PRODUCT_NAME; }### Answer:
@Override @Test public void getCurrentDateTimeFunction() { Assert.assertEquals("NOW()", getDatabase().getCurrentDateTimeFunction()); } |
### Question:
MSSQLDatabase extends AbstractDatabase { public boolean supportsInitiallyDeferrableColumns() { return false; } MSSQLDatabase(); String getTypeName(); int getPriority(); @Override Set<String> getSystemTablesAndViews(); boolean supportsInitiallyDeferrableColumns(); @Override boolean supportsSequences(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); String getDefaultDriver(String url); String getCurrentDateTimeFunction(); @Override String getDefaultCatalogName(); @Override String getConcatSql(String... values); @Override String escapeIndexName(String schemaName, String indexName); boolean supportsTablespaces(); @Override boolean isSystemTable(String catalogName, String schemaName, String tableName); @Override boolean isSystemView(String catalogName, String schemaName, String viewName); String generateDefaultConstraintName(String tableName, String columnName); @Override String escapeDatabaseObject(String objectName); @Override String convertRequestedSchemaToCatalog(String requestedSchema); @Override String convertRequestedSchemaToSchema(String requestedSchema); @Override String getDateLiteral(String isoDate); @Override boolean supportsRestrictForeignKeys(); @Override boolean supportsDropTableCascadeConstraints(); @Override String getDefaultSchemaName(); @Override String getViewDefinition(String schemaName, String viewName); static final String PRODUCT_NAME; }### Answer:
@Override @Test public void supportsInitiallyDeferrableColumns() { assertFalse(getDatabase().supportsInitiallyDeferrableColumns()); } |
### Question:
MSSQLDatabase extends AbstractDatabase { public String getCurrentDateTimeFunction() { if (currentDateTimeFunction != null) { return currentDateTimeFunction; } return "GETDATE()"; } MSSQLDatabase(); String getTypeName(); int getPriority(); @Override Set<String> getSystemTablesAndViews(); boolean supportsInitiallyDeferrableColumns(); @Override boolean supportsSequences(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); String getDefaultDriver(String url); String getCurrentDateTimeFunction(); @Override String getDefaultCatalogName(); @Override String getConcatSql(String... values); @Override String escapeIndexName(String schemaName, String indexName); boolean supportsTablespaces(); @Override boolean isSystemTable(String catalogName, String schemaName, String tableName); @Override boolean isSystemView(String catalogName, String schemaName, String viewName); String generateDefaultConstraintName(String tableName, String columnName); @Override String escapeDatabaseObject(String objectName); @Override String convertRequestedSchemaToCatalog(String requestedSchema); @Override String convertRequestedSchemaToSchema(String requestedSchema); @Override String getDateLiteral(String isoDate); @Override boolean supportsRestrictForeignKeys(); @Override boolean supportsDropTableCascadeConstraints(); @Override String getDefaultSchemaName(); @Override String getViewDefinition(String schemaName, String viewName); static final String PRODUCT_NAME; }### Answer:
@Override @Test public void getCurrentDateTimeFunction() { Assert.assertEquals("GETDATE()", getDatabase().getCurrentDateTimeFunction()); } |
### Question:
MSSQLDatabase extends AbstractDatabase { public String getDefaultDriver(String url) { if (url.startsWith("jdbc:sqlserver")) { return "com.microsoft.sqlserver.jdbc.SQLServerDriver"; } else if (url.startsWith("jdbc:jtds:sqlserver")) { return "net.sourceforge.jtds.jdbc.Driver"; } return null; } MSSQLDatabase(); String getTypeName(); int getPriority(); @Override Set<String> getSystemTablesAndViews(); boolean supportsInitiallyDeferrableColumns(); @Override boolean supportsSequences(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); String getDefaultDriver(String url); String getCurrentDateTimeFunction(); @Override String getDefaultCatalogName(); @Override String getConcatSql(String... values); @Override String escapeIndexName(String schemaName, String indexName); boolean supportsTablespaces(); @Override boolean isSystemTable(String catalogName, String schemaName, String tableName); @Override boolean isSystemView(String catalogName, String schemaName, String viewName); String generateDefaultConstraintName(String tableName, String columnName); @Override String escapeDatabaseObject(String objectName); @Override String convertRequestedSchemaToCatalog(String requestedSchema); @Override String convertRequestedSchemaToSchema(String requestedSchema); @Override String getDateLiteral(String isoDate); @Override boolean supportsRestrictForeignKeys(); @Override boolean supportsDropTableCascadeConstraints(); @Override String getDefaultSchemaName(); @Override String getViewDefinition(String schemaName, String viewName); static final String PRODUCT_NAME; }### Answer:
@Test public void getDefaultDriver() { Database database = new MSSQLDatabase(); assertEquals("com.microsoft.sqlserver.jdbc.SQLServerDriver", database.getDefaultDriver("jdbc:sqlserver: assertNull(database.getDefaultDriver("jdbc:oracle:thin: } |
### Question:
MSSQLDatabase extends AbstractDatabase { @Override public String getDefaultSchemaName() { String defaultSchemaName = super.getDefaultSchemaName(); if (defaultSchemaName == null) { return "dbo"; } else { return defaultSchemaName; } } MSSQLDatabase(); String getTypeName(); int getPriority(); @Override Set<String> getSystemTablesAndViews(); boolean supportsInitiallyDeferrableColumns(); @Override boolean supportsSequences(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); String getDefaultDriver(String url); String getCurrentDateTimeFunction(); @Override String getDefaultCatalogName(); @Override String getConcatSql(String... values); @Override String escapeIndexName(String schemaName, String indexName); boolean supportsTablespaces(); @Override boolean isSystemTable(String catalogName, String schemaName, String tableName); @Override boolean isSystemView(String catalogName, String schemaName, String viewName); String generateDefaultConstraintName(String tableName, String columnName); @Override String escapeDatabaseObject(String objectName); @Override String convertRequestedSchemaToCatalog(String requestedSchema); @Override String convertRequestedSchemaToSchema(String requestedSchema); @Override String getDateLiteral(String isoDate); @Override boolean supportsRestrictForeignKeys(); @Override boolean supportsDropTableCascadeConstraints(); @Override String getDefaultSchemaName(); @Override String getViewDefinition(String schemaName, String viewName); static final String PRODUCT_NAME; }### Answer:
@Test public void changeDefaultSchema() throws DatabaseException { Database database = new MSSQLDatabase(); assertEquals("dbo", database.getDefaultSchemaName()); database.setDefaultSchemaName("myschema"); assertEquals("myschema", database.getDefaultSchemaName()); } |
### Question:
DatabaseFactory { public static DatabaseFactory getInstance() { if (instance == null) { instance = new DatabaseFactory(); } return instance; } protected DatabaseFactory(); static DatabaseFactory getInstance(); static void reset(); List<Database> getImplementedDatabases(); void register(Database database); Database findCorrectDatabaseImplementation(DatabaseConnection connection); String findDefaultDriver(String url); void clearRegistry(); }### Answer:
@Test public void getInstance() { assertNotNull(DatabaseFactory.getInstance()); } |
### Question:
TypeConverterFactory { public TypeConverter findTypeConverter(Database database) { SortedSet<TypeConverter> converters = new TreeSet<TypeConverter>(new Comparator<TypeConverter>() { public int compare(TypeConverter o1, TypeConverter o2) { return Integer.valueOf(o1.getPriority()).compareTo(o2.getPriority()); } }); for (TypeConverter converter : allConverters) { if (converter.supports(database)) { converters.add(converter); } } return converters.last(); } private TypeConverterFactory(); static TypeConverterFactory getInstance(); TypeConverter findTypeConverter(Database database); void register(TypeConverter typeConverter); void register(Class<? extends TypeConverter> typeConverterClass); }### Answer:
@Test public void findTypeConverter() { assertTrue(TypeConverterFactory.getInstance().findTypeConverter(new UnsupportedDatabase()) instanceof DefaultTypeConverter); assertTrue(TypeConverterFactory.getInstance().findTypeConverter(new H2Database()) instanceof H2TypeConverter); } |
### Question:
OracleTypeConverter extends AbstractTypeConverter { @Override public BooleanType getBooleanType() { return new BooleanType.NumericBooleanType("NUMBER(1)"); } int getPriority(); boolean supports(Database database); @Override String convertToDatabaseTypeString(Column referenceColumn, Database database); @Override Object convertDatabaseValueToObject(Object defaultValue, int dataType, int columnSize, int decimalDigits, Database database); @Override BooleanType getBooleanType(); @Override CurrencyType getCurrencyType(); @Override UUIDType getUUIDType(); @Override TimeType getTimeType(); @Override DateTimeType getDateTimeType(); @Override BigIntType getBigIntType(); @Override IntType getIntType(); @Override VarcharType getVarcharType(); @Override NVarcharType getNVarcharType(); @Override DoubleType getDoubleType(); @Override TinyIntType getTinyIntType(); }### Answer:
@Test public void getBooleanType() { assertEquals("NUMBER(1)", new OracleTypeConverter().getBooleanType().toString()); } |
### Question:
OracleTypeConverter extends AbstractTypeConverter { @Override public CurrencyType getCurrencyType() { return new CurrencyType("NUMBER(15, 2)"); } int getPriority(); boolean supports(Database database); @Override String convertToDatabaseTypeString(Column referenceColumn, Database database); @Override Object convertDatabaseValueToObject(Object defaultValue, int dataType, int columnSize, int decimalDigits, Database database); @Override BooleanType getBooleanType(); @Override CurrencyType getCurrencyType(); @Override UUIDType getUUIDType(); @Override TimeType getTimeType(); @Override DateTimeType getDateTimeType(); @Override BigIntType getBigIntType(); @Override IntType getIntType(); @Override VarcharType getVarcharType(); @Override NVarcharType getNVarcharType(); @Override DoubleType getDoubleType(); @Override TinyIntType getTinyIntType(); }### Answer:
@Test public void getCurrencyType() { assertEquals("NUMBER(15, 2)", new OracleTypeConverter().getCurrencyType().toString()); } |
### Question:
OracleTypeConverter extends AbstractTypeConverter { @Override public UUIDType getUUIDType() { return new UUIDType("RAW(16)"); } int getPriority(); boolean supports(Database database); @Override String convertToDatabaseTypeString(Column referenceColumn, Database database); @Override Object convertDatabaseValueToObject(Object defaultValue, int dataType, int columnSize, int decimalDigits, Database database); @Override BooleanType getBooleanType(); @Override CurrencyType getCurrencyType(); @Override UUIDType getUUIDType(); @Override TimeType getTimeType(); @Override DateTimeType getDateTimeType(); @Override BigIntType getBigIntType(); @Override IntType getIntType(); @Override VarcharType getVarcharType(); @Override NVarcharType getNVarcharType(); @Override DoubleType getDoubleType(); @Override TinyIntType getTinyIntType(); }### Answer:
@Test public void getUUIDType() { assertEquals("RAW(16)", new OracleTypeConverter().getUUIDType().toString()); } |
### Question:
OracleTypeConverter extends AbstractTypeConverter { @Override public DateTimeType getDateTimeType() { return new DateTimeType("TIMESTAMP"); } int getPriority(); boolean supports(Database database); @Override String convertToDatabaseTypeString(Column referenceColumn, Database database); @Override Object convertDatabaseValueToObject(Object defaultValue, int dataType, int columnSize, int decimalDigits, Database database); @Override BooleanType getBooleanType(); @Override CurrencyType getCurrencyType(); @Override UUIDType getUUIDType(); @Override TimeType getTimeType(); @Override DateTimeType getDateTimeType(); @Override BigIntType getBigIntType(); @Override IntType getIntType(); @Override VarcharType getVarcharType(); @Override NVarcharType getNVarcharType(); @Override DoubleType getDoubleType(); @Override TinyIntType getTinyIntType(); }### Answer:
@Test public void getDateTimeType() { assertEquals("TIMESTAMP", new OracleTypeConverter().getDateTimeType().toString()); } |
### Question:
MSSQLTypeConverter extends AbstractTypeConverter { @Override public BlobType getBlobType() { return new BlobType("VARBINARY(MAX)"); } int getPriority(); boolean supports(Database database); @Override Object convertDatabaseValueToObject(Object defaultValue, int dataType, int columnSize, int decimalDigits, Database database); @Override DataType getDataType(String columnTypeString, Boolean autoIncrement); @Override DateType getDateType(); @Override TimeType getTimeType(); @Override BooleanType getBooleanType(); @Override CurrencyType getCurrencyType(); @Override UUIDType getUUIDType(); @Override ClobType getClobType(); @Override BlobType getBlobType(); @Override NumberType getNumberType(); @Override DoubleType getDoubleType(); }### Answer:
@Test public void getBlobType() { assertEquals("VARBINARY(MAX)", new MSSQLTypeConverter().getBlobType().toString()); } |
### Question:
MSSQLTypeConverter extends AbstractTypeConverter { @Override public BooleanType getBooleanType() { return new BooleanType.NumericBooleanType("BIT"); } int getPriority(); boolean supports(Database database); @Override Object convertDatabaseValueToObject(Object defaultValue, int dataType, int columnSize, int decimalDigits, Database database); @Override DataType getDataType(String columnTypeString, Boolean autoIncrement); @Override DateType getDateType(); @Override TimeType getTimeType(); @Override BooleanType getBooleanType(); @Override CurrencyType getCurrencyType(); @Override UUIDType getUUIDType(); @Override ClobType getClobType(); @Override BlobType getBlobType(); @Override NumberType getNumberType(); @Override DoubleType getDoubleType(); }### Answer:
@Test public void getBooleanType() { assertEquals("BIT", new MSSQLTypeConverter().getBooleanType().toString()); } |
### Question:
MSSQLTypeConverter extends AbstractTypeConverter { @Override public CurrencyType getCurrencyType() { return new CurrencyType("MONEY"); } int getPriority(); boolean supports(Database database); @Override Object convertDatabaseValueToObject(Object defaultValue, int dataType, int columnSize, int decimalDigits, Database database); @Override DataType getDataType(String columnTypeString, Boolean autoIncrement); @Override DateType getDateType(); @Override TimeType getTimeType(); @Override BooleanType getBooleanType(); @Override CurrencyType getCurrencyType(); @Override UUIDType getUUIDType(); @Override ClobType getClobType(); @Override BlobType getBlobType(); @Override NumberType getNumberType(); @Override DoubleType getDoubleType(); }### Answer:
@Test public void getCurrencyType() { assertEquals("MONEY", new MSSQLTypeConverter().getCurrencyType().toString()); } |
### Question:
MSSQLTypeConverter extends AbstractTypeConverter { @Override public UUIDType getUUIDType() { return new UUIDType("UNIQUEIDENTIFIER"); } int getPriority(); boolean supports(Database database); @Override Object convertDatabaseValueToObject(Object defaultValue, int dataType, int columnSize, int decimalDigits, Database database); @Override DataType getDataType(String columnTypeString, Boolean autoIncrement); @Override DateType getDateType(); @Override TimeType getTimeType(); @Override BooleanType getBooleanType(); @Override CurrencyType getCurrencyType(); @Override UUIDType getUUIDType(); @Override ClobType getClobType(); @Override BlobType getBlobType(); @Override NumberType getNumberType(); @Override DoubleType getDoubleType(); }### Answer:
@Test public void getUUIDType() { assertEquals("UNIQUEIDENTIFIER", new MSSQLTypeConverter().getUUIDType().toString()); } |
### Question:
MSSQLTypeConverter extends AbstractTypeConverter { @Override public ClobType getClobType() { return new ClobType("NVARCHAR(MAX)"); } int getPriority(); boolean supports(Database database); @Override Object convertDatabaseValueToObject(Object defaultValue, int dataType, int columnSize, int decimalDigits, Database database); @Override DataType getDataType(String columnTypeString, Boolean autoIncrement); @Override DateType getDateType(); @Override TimeType getTimeType(); @Override BooleanType getBooleanType(); @Override CurrencyType getCurrencyType(); @Override UUIDType getUUIDType(); @Override ClobType getClobType(); @Override BlobType getBlobType(); @Override NumberType getNumberType(); @Override DoubleType getDoubleType(); }### Answer:
@Test public void getClobType() { assertEquals("NVARCHAR(MAX)", new MSSQLTypeConverter().getClobType().toString()); } |
### Question:
MSSQLTypeConverter extends AbstractTypeConverter { @Override public DateType getDateType() { return new DateType("SMALLDATETIME"); } int getPriority(); boolean supports(Database database); @Override Object convertDatabaseValueToObject(Object defaultValue, int dataType, int columnSize, int decimalDigits, Database database); @Override DataType getDataType(String columnTypeString, Boolean autoIncrement); @Override DateType getDateType(); @Override TimeType getTimeType(); @Override BooleanType getBooleanType(); @Override CurrencyType getCurrencyType(); @Override UUIDType getUUIDType(); @Override ClobType getClobType(); @Override BlobType getBlobType(); @Override NumberType getNumberType(); @Override DoubleType getDoubleType(); }### Answer:
@Test public void getDateType() { assertEquals("SMALLDATETIME", new MSSQLTypeConverter().getDateType().toString()); } |
### Question:
MSSQLTypeConverter extends AbstractTypeConverter { @Override public NumberType getNumberType() { return new NumberType("NUMERIC"); } int getPriority(); boolean supports(Database database); @Override Object convertDatabaseValueToObject(Object defaultValue, int dataType, int columnSize, int decimalDigits, Database database); @Override DataType getDataType(String columnTypeString, Boolean autoIncrement); @Override DateType getDateType(); @Override TimeType getTimeType(); @Override BooleanType getBooleanType(); @Override CurrencyType getCurrencyType(); @Override UUIDType getUUIDType(); @Override ClobType getClobType(); @Override BlobType getBlobType(); @Override NumberType getNumberType(); @Override DoubleType getDoubleType(); }### Answer:
@Test public void getNumberType() { assertEquals("NUMERIC", new MSSQLTypeConverter().getNumberType().toString()); } |