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

Test | Fix DB Metadata tests + fix maven warnings + clean all objects #1060

Merged
merged 7 commits into from May 29, 2019
Merged
Show file tree
Hide file tree
Changes from 2 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
Expand Up @@ -1090,6 +1090,10 @@ void checkClosed() throws SQLServerException {

/**
* Returns if Federated Authentication is in use or is about to expire soon
*
* @return true/false
* @throws SQLServerException
* if an error occurs.
*/
protected boolean needsReconnect() throws SQLServerException {
return (null != fedAuthToken && Util.checkIfNeedNewAccessToken(this, fedAuthToken.expiresOn));
Expand Down
91 changes: 71 additions & 20 deletions src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java
Expand Up @@ -24,8 +24,6 @@
import java.util.Locale;
import java.util.ResourceBundle;

import com.microsoft.sqlserver.testframework.AbstractSQLGenerator;
import com.microsoft.sqlserver.testframework.Constants;
import com.microsoft.sqlserver.testframework.sqlType.SqlBigInt;
import com.microsoft.sqlserver.testframework.sqlType.SqlBinary;
import com.microsoft.sqlserver.testframework.sqlType.SqlBit;
Expand Down Expand Up @@ -61,14 +59,15 @@
* @since 6.1.2
*/
public class TestUtils {
// private static SqlType types = null;
private static ArrayList<SqlType> types = null;
private static final char[] HEXCHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
'F'};

final static int ENGINE_EDITION_FOR_SQL_AZURE = 5;
final static int ENGINE_EDITION_FOR_SQL_AZURE_DW = 6;
final static int ENGINE_EDITION_FOR_SQL_AZURE_MI = 8;

cheenamalhotra marked this conversation as resolved.
Show resolved Hide resolved
@SuppressWarnings("unused")
private static Boolean isAzure = null;
private static Boolean isAzureDW = null;
private static Boolean isAzureMI = null;
Expand Down Expand Up @@ -279,36 +278,82 @@ public static String getCurrentClassPath() {
}

/**
* mimic "DROP TABLE IF EXISTS ..." for older versions of SQL Server
* mimic "DROP TABLE ..."
*/
public static void dropTableIfExists(String tableName, java.sql.Statement stmt) throws SQLException {
dropObjectIfExists(tableName, "IsTable", stmt);
dropObjectIfExists(tableName, "U", stmt);
}

/**
* mimic "DROP PROCEDURE IF EXISTS ..." for older versions of SQL Server
* mimic "DROP PROCEDURE ..."
*/
public static void dropProcedureIfExists(String procName, java.sql.Statement stmt) throws SQLException {
dropObjectIfExists(procName, "IsProcedure", stmt);
dropObjectIfExists(procName, "P", stmt);
}

public static void dropDatabaseIfExists(String databaseName, java.sql.Statement stmt) throws SQLException {
stmt.executeUpdate("USE MASTER; IF EXISTS(SELECT * from sys.databases WHERE name='"
+ escapeSingleQuotes(databaseName) + "') DROP DATABASE [" + databaseName + "]");
/**
* mimic "DROP FUNCTION ..."
*/
public static void dropFunctionIfExists(String functionName, java.sql.Statement stmt) throws SQLException {
dropObjectIfExists(functionName, "FN", stmt);
}

/**
* mimic "DROP TRIGGER ..."
*/
public static void dropTriggerIfExists(String triggerName, java.sql.Statement stmt) throws SQLException {
stmt.execute("IF EXISTS (\r\n" + " SELECT *\r\n" + " FROM sys.objects\r\n"
+ " WHERE [type] = 'TR' AND [name] = '" + TestUtils.escapeSingleQuotes(triggerName) + "'\r\n"
+ " )\r\n" + " DROP TRIGGER " + AbstractSQLGenerator.escapeIdentifier(triggerName)
+ Constants.SEMI_COLON);
dropObjectIfExists(triggerName, "TR", stmt);
}

/**
* mimic "DROP TYPE ..."
*/
public static void dropTypeIfExists(String typeName, java.sql.Statement stmt) throws SQLException {
dropObjectIfExists(typeName, "TT", stmt);
}

/**
* mimic "DROP DATABASE ..."
*/
public static void dropDatabaseIfExists(String databaseName, java.sql.Statement stmt) throws SQLException {
stmt.executeUpdate("USE MASTER; IF EXISTS(SELECT * from sys.databases WHERE name='"
+ escapeSingleQuotes(databaseName) + "') DROP DATABASE [" + databaseName + "]");
}

/**
* actually perform the "DROP TABLE / PROCEDURE"
* <pre>
* This method drop objects for below types:
cheenamalhotra marked this conversation as resolved.
Show resolved Hide resolved
*
* TT - TYPE_TABLE
* TR - TRIGGER
* FN - SQL_SCALAR_FUNCTION
* P -- SQL_STORED_PROCEDURE
* U -- USER_TABLE
*
* </pre>
*/
private static void dropObjectIfExists(String objectName, String objectProperty,
private static void dropObjectIfExists(String objectName, String objectType,
java.sql.Statement stmt) throws SQLException {
String typeName = "";
switch (objectType) {
case "TT":
typeName = "TYPE";
break;
case "TR":
typeName = "TRIGGER";
break;
case "FN":
typeName = "FUNCTION";
break;
case "P":
typeName = "PROCEDURE";
break;
case "U":
typeName = "TABLE";
default:
break;
}

StringBuilder sb = new StringBuilder();
if (!objectName.startsWith("[")) {
sb.append("[");
Expand All @@ -317,11 +362,17 @@ private static void dropObjectIfExists(String objectName, String objectProperty,
if (!objectName.endsWith("]")) {
sb.append("]");
}

String bracketedObjectName = sb.toString();
String sql = String.format("IF EXISTS " + "( " + "SELECT * from sys.objects "
+ "WHERE object_id = OBJECT_ID(N'%s') AND OBJECTPROPERTY(object_id, N'%s') = 1 " + ") " + "DROP %s %s ",
escapeSingleQuotes(bracketedObjectName), objectProperty,
"IsProcedure".equals(objectProperty) ? "PROCEDURE" : "TABLE", bracketedObjectName);
String whereClause = "";
if (objectType != "TT") {
whereClause = "WHERE object_id = OBJECT_ID(N'" + escapeSingleQuotes(bracketedObjectName) + "')";
} else {
whereClause = "WHERE name LIKE '%" + escapeSingleQuotes(objectName) + "%'";
}

String sql = "IF EXISTS ( SELECT * from sys.objects " + whereClause + " AND type='" + objectType + "') DROP "
+ typeName + " " + bracketedObjectName;
try {
stmt.executeUpdate(sql);
} catch (SQLException e) {
Expand Down
Expand Up @@ -74,7 +74,8 @@ public void datatypestest() throws Exception {
}
} finally {
try (Statement stmt = connection.createStatement()) {
TestUtils.dropTableIfExists(escapedTableName, stmt);
TestUtils.dropTableIfExists(tableName, stmt);
TestUtils.dropProcedureIfExists(procName, stmt);
}
}
}
Expand Down
Expand Up @@ -28,15 +28,19 @@
import java.util.jar.Attributes;
import java.util.jar.Manifest;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;

import com.microsoft.sqlserver.jdbc.RandomUtil;
import com.microsoft.sqlserver.jdbc.SQLServerDatabaseMetaData;
import com.microsoft.sqlserver.jdbc.StringUtils;
import com.microsoft.sqlserver.jdbc.TestResource;
import com.microsoft.sqlserver.jdbc.TestUtils;
import com.microsoft.sqlserver.testframework.AbstractSQLGenerator;
import com.microsoft.sqlserver.testframework.AbstractTest;
import com.microsoft.sqlserver.testframework.Constants;

Expand All @@ -47,6 +51,9 @@
@RunWith(JUnitPlatform.class)
public class DatabaseMetaDataTest extends AbstractTest {

private static final String tableName = RandomUtil.getIdentifier("DBMetadataTable");
private static final String functionName = RandomUtil.getIdentifier("DBMetadataFunction");

/**
* Verify DatabaseMetaData#isWrapperFor and DatabaseMetaData#unwrap.
*
Expand Down Expand Up @@ -291,10 +298,6 @@ public void testDBSchemasForDashedCatalogNameWithPattern() throws SQLException {
* @throws SQLException
*/
@Test
/*
* try (ResultSet rsCatalog = connection.getMetaData().getCatalogs(); ResultSet rs = connection.getMetaData()
* .getTables(rsCatalog.getString("TABLE_CAT"), null, "%", new String[] {"TABLE"})) {
*/
public void testDBTables() throws SQLException {

try (Connection con = getConnection()) {
Expand Down Expand Up @@ -337,15 +340,20 @@ public void testGetDBColumn() throws SQLException {

String[] types = {"TABLE"};
try (ResultSet rs = databaseMetaData.getTables(null, null, "%", types)) {

// Fetch one table
MessageFormat form1 = new MessageFormat(TestResource.getResource("R_atLeastOneFound"));
Object[] msgArgs1 = {"table"};
assertTrue(rs.next(), form1.format(msgArgs1));

if(rs.next()) {
boolean tableFound = false;
do {
if(rs.getString("TABLE_NAME").equalsIgnoreCase(tableName)) {
tableFound=true;
}
} while(!tableFound && rs.next());
cheenamalhotra marked this conversation as resolved.
Show resolved Hide resolved
} else {
MessageFormat form1 = new MessageFormat(TestResource.getResource("R_atLeastOneFound"));
Object[] msgArgs1 = {"table"};
fail(form1.format(msgArgs1));
}
// Go through all columns.
try (ResultSet rs1 = databaseMetaData.getColumns(null, null, rs.getString("TABLE_NAME"), "%")) {

try (ResultSet rs1 = databaseMetaData.getColumns(null, null, AbstractSQLGenerator.escapeIdentifier(tableName), "%")) {
MessageFormat form2 = new MessageFormat(TestResource.getResource("R_nameEmpty"));
Object[][] msgArgs2 = {{"Category"}, {"SCHEMA"}, {"Table"}, {"COLUMN"}, {"Data Type"}, {"Type"},
{"Column Size"}, {"Nullable value"}, {"IS_NULLABLE"}, {"IS_AUTOINCREMENT"}};
Expand Down Expand Up @@ -384,14 +392,20 @@ public void testGetColumnPrivileges() throws SQLException {
try (Connection conn = getConnection()) {
DatabaseMetaData databaseMetaData = conn.getMetaData();
String[] types = {"TABLE"};
try (ResultSet rsTables = databaseMetaData.getTables(null, null, "%", types)) {

// Fetch one table
MessageFormat form1 = new MessageFormat(TestResource.getResource("R_atLeastOneFound"));
Object[] msgArgs1 = {"table"};
assertTrue(rsTables.next(), form1.format(msgArgs1));

try (ResultSet rs1 = databaseMetaData.getColumnPrivileges(null, null, rsTables.getString("TABLE_NAME"),
try (ResultSet rs = databaseMetaData.getTables(null, null, "%", types)) {
if(rs.next()) {
boolean tableFound = false;
do {
if(rs.getString("TABLE_NAME").equalsIgnoreCase(tableName)) {
tableFound=true;
}
} while(!tableFound && rs.next());
} else {
MessageFormat form1 = new MessageFormat(TestResource.getResource("R_atLeastOneFound"));
Object[] msgArgs1 = {"table"};
fail(form1.format(msgArgs1));
}
try (ResultSet rs1 = databaseMetaData.getColumnPrivileges(null, null, AbstractSQLGenerator.escapeIdentifier(tableName),
"%")) {

MessageFormat form2 = new MessageFormat(TestResource.getResource("R_nameEmpty"));
Expand Down Expand Up @@ -466,14 +480,20 @@ public void testGetFunctionColumns() throws SQLException {
DatabaseMetaData databaseMetaData = conn.getMetaData();

try (ResultSet rsFunctions = databaseMetaData.getFunctions(null, null, "%")) {

// Fetch one Function
MessageFormat form1 = new MessageFormat(TestResource.getResource("R_atLeastOneFound"));
Object[] msgArgs1 = {"function"};
assertTrue(rsFunctions.next(), form1.format(msgArgs1));

if(rsFunctions.next()) {
boolean tableFound = false;
do {
if(rsFunctions.getString("FUNCTION_NAME").equalsIgnoreCase(functionName)) {
tableFound=true;
}
} while(!tableFound && rsFunctions.next());
} else {
MessageFormat form1 = new MessageFormat(TestResource.getResource("R_atLeastOneFound"));
Object[] msgArgs1 = {"table"};
fail(form1.format(msgArgs1));
}
try (ResultSet rs = databaseMetaData.getFunctionColumns(null, null,
rsFunctions.getString("FUNCTION_NAME"), "%")) {
AbstractSQLGenerator.escapeIdentifier(functionName), "%")) {

MessageFormat form2 = new MessageFormat(TestResource.getResource("R_nameNull"));
Object[][] msgArgs2 = {{"FUNCTION_CAT"}, {"FUNCTION_SCHEM"}, {"FUNCTION_NAME"}, {"COLUMN_NAME"},
Expand Down Expand Up @@ -563,4 +583,20 @@ public void testGetMaxConnections() throws SQLException {
fail(e.getMessage());
}
}

@BeforeAll
public static void setupTable() throws SQLException {
try (Statement stmt = connection.createStatement()){
stmt.execute("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 int NOT NULL, col2 varchar(200), col3 decimal(15,2))");
stmt.execute("CREATE FUNCTION " + AbstractSQLGenerator.escapeIdentifier(functionName) + " (@p1 INT, @p2 INT) RETURNS INT AS BEGIN DECLARE @result INT; SET @result = @p1 + @p2; RETURN @result; END");
}
}

@AfterAll
public static void terminate() throws SQLException {
try (Statement stmt = connection.createStatement()){
TestUtils.dropTableIfExists(tableName, stmt);
TestUtils.dropFunctionIfExists(functionName, stmt);
}
}
}
Expand Up @@ -195,8 +195,8 @@ private void setupVariation(boolean setSelectMethod, Statement stmt) throws SQLE
tvpName = RandomUtil.getIdentifier("TVP");
procedureName = RandomUtil.getIdentifier("TVP");

TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procedureName), stmt);
TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tvpName), stmt);
TestUtils.dropProcedureIfExists(procedureName, stmt);
TestUtils.dropTypeIfExists(tvpName, stmt);

try (DBConnection dbConnection = new DBConnection(connectionString);
DBStatement dbStmt = dbConnection.createStatement()) {
Expand All @@ -217,9 +217,11 @@ private void setupVariation(boolean setSelectMethod, Statement stmt) throws SQLE
private void terminateVariation() throws SQLException {
try (Statement stmt = connection.createStatement()) {
TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procedureName), stmt);
TestUtils.dropTableIfExists(tableSrc.getEscapedTableName(), stmt);
TestUtils.dropTableIfExists(tableDest.getEscapedTableName(), stmt);
TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tvpName), stmt);
if (null != tableSrc)
TestUtils.dropTableIfExists(tableSrc.getTableName(), stmt);
if (null != tableDest)
TestUtils.dropTableIfExists(tableDest.getTableName(), stmt);
TestUtils.dropTypeIfExists(tvpName, stmt);
}
}
}