Skip to content

Commit

Permalink
#13309 - MSSQL Upsert SQL
Browse files Browse the repository at this point in the history
  • Loading branch information
acurionedotcms committed Jan 5, 2018
1 parent de84e31 commit 13c33af
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2305,6 +2305,14 @@ private void deleteInsertPermission(Permissionable permissionable, String type,
dc1.executeUpdate(query, permissionId, newReference.getPermissionId(), type,
permissionId, newReference.getPermissionId(), type);
}
if (DbConnectionFactory.isMsSql()) {
String query = SQLUtil.generateUpsertSQL("permission_reference", "asset_id", "?",
new String[]{"asset_id", "reference_id", "permission_type"},
new String[]{"?", "?", "?"});
dc1.executeUpdate(query, permissionId, permissionId,
permissionId, newReference.getPermissionId(), type,
permissionId, newReference.getPermissionId(), type);
}
}

} catch(Exception exception){
Expand Down
18 changes: 18 additions & 0 deletions dotCMS/src/main/java/com/dotmarketing/common/util/SQLUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import net.sourceforge.squirrel_sql.plugins.mysql.tokenizer.MysqlQueryTokenizer;
import net.sourceforge.squirrel_sql.plugins.oracle.prefs.OraclePreferenceBean;
import net.sourceforge.squirrel_sql.plugins.oracle.tokenizer.OracleQueryTokenizer;
import org.quartz.utils.DBConnectionManager;

/**
* Util class for sanitize, tokenize, etc
Expand Down Expand Up @@ -319,6 +320,14 @@ private static boolean isValidSQLCharacter (final char c) {
"INSERT INTO %s (%s) "
+ "VALUES (%s) ON DUPLICATE KEY "
+ "UPDATE %s";
private final static String MSSQL_UPSERT_QUERY =
"MERGE INTO %s USING "
+ "(SELECT %s [conditional]) AS dummy([conditional]) ON %s = %s "
+ "WHEN MATCHED THEN "
+ " UPDATE SET %s "
+ "WHEN NOT MATCHED THEN "
+ " INSERT (%s) "
+ " VALUES (%s);";

public static String generateUpsertSQL (String table, String conditionalColumn, String conditionalValue, String[] columns, String[] values) {
String query = null;
Expand All @@ -345,6 +354,15 @@ public static String generateUpsertSQL (String table, String conditionalColumn,
StringUtil.merge(values),
buffer.toString());
}
if (DbConnectionFactory.isMsSql()) {
query = String.format(MSSQL_UPSERT_QUERY, table,
conditionalValue,
conditionalColumn,
conditionalValue,
buffer.toString(),
StringUtil.merge(columns),
StringUtil.merge(values));
}

return query;
}
Expand Down

0 comments on commit 13c33af

Please sign in to comment.