From 8a0e426a0d60d7b7a20161d44dde905f42067fcb Mon Sep 17 00:00:00 2001 From: Ryan Doherty Date: Thu, 15 Aug 2024 02:01:59 -0400 Subject: [PATCH] Convert user ref insertion SQL to platform-agnostic syntax --- .../wdk/model/user/UserReferenceFactory.java | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/Model/src/main/java/org/gusdb/wdk/model/user/UserReferenceFactory.java b/Model/src/main/java/org/gusdb/wdk/model/user/UserReferenceFactory.java index 2673c9cc6..b2d6e77f5 100644 --- a/Model/src/main/java/org/gusdb/wdk/model/user/UserReferenceFactory.java +++ b/Model/src/main/java/org/gusdb/wdk/model/user/UserReferenceFactory.java @@ -30,15 +30,8 @@ class UserReferenceFactory { public static final String USER_SCHEMA_MACRO = "$$USER_SCHEMA$$"; private static final String IS_GUEST_VALUE_MACRO = "$$IS_GUEST$$"; - // SQL and types to insert previously unknown user refs into the users table - private static final String INSERT_USER_REF_SQL = - "insert" + - " when not exists (select 1 from " + USER_SCHEMA_MACRO + TABLE_USERS + " where " + COL_USER_ID + " = ?)" + - " then" + - " into " + USER_SCHEMA_MACRO + TABLE_USERS + " (" + COL_USER_ID + "," + COL_IS_GUEST + "," + COL_FIRST_ACCESS +")" + - " select ?, " + IS_GUEST_VALUE_MACRO + ", ? from dual"; - - private static final Integer[] INSERT_USER_REF_PARAM_TYPES = { Types.BIGINT, Types.BIGINT, Types.TIMESTAMP }; + // types used by SQL returned by getInsertUserRefSql() below + private static final Integer[] INSERT_USER_REF_PARAM_TYPES = { Types.BIGINT, Types.TIMESTAMP }; // SQL and types to select user ref by ID private static final String SELECT_USER_REF_BY_ID_SQL = @@ -80,7 +73,7 @@ public int addUserReference(User user) throws WdkModelException { long userId = user.getUserId(); boolean isGuest = user.isGuest(); Timestamp insertedOn = new Timestamp(new Date().getTime()); - String sql = INSERT_USER_REF_SQL + String sql = getInsertUserRefSql() .replace(USER_SCHEMA_MACRO, _userSchema) .replace(IS_GUEST_VALUE_MACRO, _userDb.getPlatform().convertBoolean(isGuest).toString()); return new SQLRunner(_userDb.getDataSource(), sql, "insert-user-ref") @@ -91,6 +84,15 @@ public int addUserReference(User user) throws WdkModelException { } } + private String getInsertUserRefSql() { + return "MERGE INTO " + USER_SCHEMA_MACRO + TABLE_USERS + " tgt " + + "USING (SELECT ? AS user_id, ? AS first_access, " + IS_GUEST_VALUE_MACRO + " AS is_guest" + _userDb.getPlatform().getDummyTable() + ") src " + + "ON (tgt." + COL_USER_ID + " = src.user_id) " + + "WHEN NOT MATCHED THEN " + + "INSERT (" + COL_USER_ID + ", " + COL_IS_GUEST + ", " + COL_FIRST_ACCESS + ") " + + "VALUES (src.user_id, src.is_guest, src.first_access)"; + } + // FIXME: see if this is actually needed anywhere? E.g. do we ever need to look up user refs by user ID to find last login? public Optional getUserReference(long userId) throws WdkModelException { try {