Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle empty or null schema for CreateView with replace option DAT-16446 #5695

Merged
merged 3 commits into from
Mar 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
package liquibase.command.core

import liquibase.Scope
import liquibase.command.CommandScope
import liquibase.command.core.helpers.DbUrlConnectionArgumentsCommandStep
import liquibase.command.util.CommandUtil
import liquibase.extension.testing.testsystem.DatabaseTestSystem
import liquibase.extension.testing.testsystem.TestSystemFactory
import liquibase.extension.testing.testsystem.spock.LiquibaseIntegrationTest
import liquibase.resource.SearchPathResourceAccessor
import liquibase.util.FileUtil
import liquibase.util.StringUtil
import spock.lang.Shared
import spock.lang.Specification

Expand Down Expand Up @@ -71,4 +75,75 @@ class GenerateChangeLogMSSQLIntegrationTest extends Specification {
where:
fileType << ['xml', 'json', 'yml']
}

def "Should include schema when generating changelog with view and using 'use-or-replace-option'"() {
when:
String changelogFile = "target/test-classes/changelogs/" + StringUtil.randomIdentifer(10) + "/formatted.mssql.sql"
String updateChangelogFile = "target/test-classes/changelogs/" + StringUtil.randomIdentifer(10) + "/formatted.sql"

def contents =
"""
-- liquibase formatted sql

-- changeset liquibase:1 label:basic
CREATE TABLE Employees (
EmployeeID INT,
FirstName NVARCHAR(50)
);
-- rollback drop table Employees

--changeset wesley:1575473414720-9 splitStatements:false
CREATE VIEW employees_view AS SELECT FirstName FROM [dbo].Employees;

"""
File f = new File(updateChangelogFile)
f.getParentFile().mkdirs()
f.write(contents + "\n")

CommandScope updateCommandScope = new CommandScope(UpdateCommandStep.COMMAND_NAME)
updateCommandScope.addArgumentValue(UpdateCommandStep.CHANGELOG_FILE_ARG, updateChangelogFile)
updateCommandScope.addArgumentValue(DbUrlConnectionArgumentsCommandStep.USERNAME_ARG, mssql.getUsername())
updateCommandScope.addArgumentValue(DbUrlConnectionArgumentsCommandStep.PASSWORD_ARG, mssql.getPassword())
updateCommandScope.addArgumentValue(DbUrlConnectionArgumentsCommandStep.URL_ARG, mssql.getConnectionUrl())

CommandScope commandScope = new CommandScope(GenerateChangelogCommandStep.COMMAND_NAME)
commandScope.addArgumentValue(GenerateChangelogCommandStep.CHANGELOG_FILE_ARG, changelogFile)
commandScope.addArgumentValue(DbUrlConnectionArgumentsCommandStep.USERNAME_ARG, mssql.getUsername())
commandScope.addArgumentValue(DbUrlConnectionArgumentsCommandStep.PASSWORD_ARG, mssql.getPassword())
commandScope.addArgumentValue(DbUrlConnectionArgumentsCommandStep.URL_ARG, mssql.getConnectionUrl())
commandScope.addArgumentValue(GenerateChangelogCommandStep.USE_OR_REPLACE_OPTION, true);
OutputStream outputStream = new ByteArrayOutputStream()
commandScope.setOutput(outputStream)
Map<String, Object> scopeValues = new HashMap<>()
outputStream.flush()

scopeValues.put("liquibase.pro.sql.inline", true)
scopeValues.put(Scope.Attr.resourceAccessor.name(), new SearchPathResourceAccessor("."))
Scope.child(scopeValues, new Scope.ScopedRunner() {
@Override
void run() throws Exception {
updateCommandScope.execute()
commandScope.execute()
}
})
def generatedChangelog = new File(changelogFile)
def generatedChangelogContents = FileUtil.getContents(generatedChangelog)

then:
noExceptionThrown()
generatedChangelogContents.contains("N'CREATE VIEW [employees_view] AS SELECT '")

cleanup:
try {
generatedChangelog.delete()
} catch (Exception ignored) {

}

CommandUtil.runDropAll(mssql)

if (mssql.getConnection()) {
mssql.getConnection().close()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import liquibase.structure.core.Relation;
import liquibase.structure.core.View;
import liquibase.util.StringClauses;
import liquibase.util.StringUtil;

import java.util.ArrayList;
import java.util.List;
Expand Down Expand Up @@ -93,12 +94,13 @@ public Sql[] generateSql(CreateViewStatement statement, Database database, SqlGe
//from http://stackoverflow.com/questions/163246/sql-server-equivalent-to-oracles-create-or-replace-view
CatalogAndSchema schema = new CatalogAndSchema(
statement.getCatalogName(), statement.getSchemaName()).customize(database);
String schemaSpec = determineSchemaSpec(schema.getSchemaName());
sql.add(new UnparsedSql(
"IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'["
+ schema.getSchemaName()
+ "].[" + statement.getViewName()
"IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'"
+ schemaSpec
+ "[" + statement.getViewName()
+ "]'))\n"
+ " EXEC sp_executesql N'CREATE VIEW [" + schema.getSchemaName() + "].["
+ " EXEC sp_executesql N'CREATE VIEW " + schemaSpec + "["
+ statement.getViewName()
+ "] AS SELECT " +
"''This is a code stub which will be replaced by an Alter Statement'' as [code_stub]'"));
Expand All @@ -123,6 +125,13 @@ public Sql[] generateSql(CreateViewStatement statement, Database database, SqlGe
return sql.toArray(EMPTY_SQL);
}

private String determineSchemaSpec(String schemaName) {
if (StringUtil.isEmpty(schemaName)) {
return "";
}
return "[" + schemaName + "].";
}

//
// Check to see if the collection of clauses are in the view definition
//
Expand Down