Skip to content

Commit

Permalink
Convert user ref insertion SQL to platform-agnostic syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanrdoherty committed Aug 15, 2024
1 parent 9dc5bbb commit 8a0e426
Showing 1 changed file with 12 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down Expand Up @@ -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")
Expand All @@ -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<UserReference> getUserReference(long userId) throws WdkModelException {
try {
Expand Down

0 comments on commit 8a0e426

Please sign in to comment.