From 548730bf0af635b050c4a89bf7053c5744b1f671 Mon Sep 17 00:00:00 2001
From: Matt Rajkowski
Date: Mon, 31 Aug 2026 21:30:08 -0400
Subject: [PATCH 01/16] Change to use DB library
---
.../cms/CheckFolderPermissionCommand.java | 47 +-
.../cms/LoadContentListCommand.java | 6 +-
.../datasets/DeleteDatasetItemsCommand.java | 3 +-
.../ecommerce/LoadProductListCommand.java | 3 +-
.../application/ecommerce/OrderCommand.java | 3 +-
.../ecommerce/OrderStatusCommand.java | 26 +-
.../CheckCollectionPermissionCommand.java | 51 +-
.../CheckItemFolderPermissionCommand.java | 47 +-
.../items/LoadActivityListCommand.java | 12 +-
.../infrastructure/database/AutoRollback.java | 48 -
.../database/AutoStartTransaction.java | 43 -
.../platform/infrastructure/database/DB.java | 998 ------------------
.../database/DataConstraints.java | 213 ----
.../infrastructure/database/DataResult.java | 59 --
.../infrastructure/database/SqlJoins.java | 44 -
.../infrastructure/database/SqlUtils.java | 220 ----
.../infrastructure/database/SqlValue.java | 253 -----
.../infrastructure/database/SqlWhere.java | 324 ------
.../persistence/AppRepository.java | 71 +-
.../persistence/BlockedIPRepository.java | 88 +-
.../admin/PermissionGroupRepository.java | 24 +-
.../PerformanceMetricRepository.java | 29 +-
.../persistence/cms/BlogPostRepository.java | 191 ++--
.../persistence/cms/BlogRepository.java | 85 +-
.../cms/CalendarEventRepository.java | 194 ++--
.../persistence/cms/CalendarRepository.java | 92 +-
.../persistence/cms/ContentRepository.java | 150 ++-
.../persistence/cms/FileItemRepository.java | 338 +++---
.../cms/FileVersionRepository.java | 153 +--
.../cms/FolderCategoryRepository.java | 95 +-
.../cms/FolderGroupRepository.java | 104 +-
.../persistence/cms/FolderRepository.java | 165 ++-
.../persistence/cms/FormDataRepository.java | 131 +--
.../cms/GitPublishSettingsRepository.java | 89 +-
.../persistence/cms/ImageRepository.java | 135 +--
.../cms/ImageVersionRepository.java | 71 +-
.../persistence/cms/MenuItemRepository.java | 102 +-
.../persistence/cms/MenuTabRepository.java | 106 +-
.../persistence/cms/StylesheetRepository.java | 71 +-
.../persistence/cms/SubFolderRepository.java | 155 ++-
.../cms/TableOfContentsRepository.java | 70 +-
.../persistence/cms/ThemeRepository.java | 58 +-
.../cms/WebContainerRepository.java | 86 +-
.../cms/WebPageHierarchyRepository.java | 84 +-
.../persistence/cms/WebPageHitRepository.java | 54 +-
.../persistence/cms/WebPageRepository.java | 355 +++----
.../persistence/items/ActivityRepository.java | 92 +-
.../persistence/items/CategoryRepository.java | 137 +--
.../persistence/maps/WorldCityRepository.java | 44 +-
.../persistence/maps/ZipCodeRepository.java | 11 +-
.../medicine/MedicineLogRepository.java | 128 +--
.../medicine/MedicineReminderRepository.java | 117 +-
.../medicine/MedicineRepository.java | 167 +--
.../medicine/MedicineScheduleRepository.java | 120 ++-
.../medicine/MedicineTimeRepository.java | 80 +-
.../medicine/PrescriptionRepository.java | 97 +-
.../socialmedia/InstagramMediaRepository.java | 74 +-
.../OrderManagementProcessNewOrders.java | 2 +-
...OrderManagementProcessShippingUpdates.java | 3 +-
.../medicine/ProcessMedicineSchedulesJob.java | 3 +-
.../widgets/admin/BlockedIPListWidget.java | 19 +-
.../widgets/admin/cms/FormDataListWidget.java | 8 +-
.../admin/datasets/DatasetSyncWidget.java | 21 +-
.../admin/ecommerce/CustomerListWidget.java | 10 +-
.../admin/ecommerce/OrderListWidget.java | 20 +-
.../items/CollectionItemsListWidget.java | 5 +-
.../widgets/admin/login/UsersListWidget.java | 31 +-
.../admin/xapi/XapiStatementListWidget.java | 13 +-
.../calendar/CalendarSearchResultsWidget.java | 2 +-
.../UpcomingCalendarEventsWidget.java | 28 +-
.../widgets/cms/AlbumGalleryWidget.java | 14 +-
.../cms/AnalyticsActivityLoadAjax.java | 2 +-
.../widgets/cms/BlogPostListWidget.java | 17 +-
.../cms/BlogPostSearchResultsWidget.java | 3 +-
.../widgets/cms/ContentGetJsonService.java | 2 +-
.../cms/ContentPreviewJsonService.java | 2 +-
.../cms/ContentPublishJsonService.java | 4 +-
.../cms/ContentSaveDraftJsonService.java | 4 +-
.../widgets/cms/DocumentAnalyticsAjax.java | 2 +-
.../widgets/cms/DocumentFileListAjax.java | 4 +-
.../widgets/cms/DocumentLibraryAjax.java | 2 +-
.../widgets/cms/DocumentSubfoldersAjax.java | 2 +-
.../widgets/cms/FileListByFolderWidget.java | 21 +-
.../widgets/cms/FileListByYearWidget.java | 20 +-
.../widgets/cms/FileListWidget.java | 14 +-
.../widgets/cms/ImageLibraryAjax.java | 2 +-
.../widgets/cms/InstagramWidget.java | 9 +-
.../cms/PageAddToHierarchyJsonService.java | 6 +-
.../PageRemoveFromHierarchyJsonService.java | 6 +-
.../widgets/cms/PageReorderJsonService.java | 6 +-
.../widgets/cms/PhotoGalleryWidget.java | 13 +-
.../widgets/cms/PhotoListAjax.java | 2 +-
.../widgets/cms/WebPageListAjax.java | 4 +-
.../cms/WebPageSearchResultsWidget.java | 2 +-
.../cms/WebPageTitleSearchResultsWidget.java | 11 +-
.../editor/CRMCustomersJsonService.java | 2 +-
.../editor/CRMFormSubmissionsJsonService.java | 2 +-
.../editor/CRMFormsListJsonService.java | 2 +-
.../CRMMailingListMembersJsonService.java | 2 +-
.../widgets/editor/CRMOrdersJsonService.java | 2 +-
.../widgets/editor/CRMUsersJsonService.java | 2 +-
.../widgets/editor/CollectionItemsAjax.java | 13 +-
.../widgets/items/ActivityListAjax.java | 12 +-
.../widgets/items/ActivityListWidget.java | 10 +-
.../widgets/items/ItemFileListWidget.java | 22 +-
.../widgets/items/ItemsListWidget.java | 2 +-
.../items/ItemsSearchResultsWidget.java | 2 +-
.../MailingListMembersWidget.java | 27 +-
.../controller/ServiceResponseCommand.java | 2 +-
.../rest/services/items/ItemFilesService.java | 2 +-
.../rest/services/items/ItemListService.java | 2 +-
.../services/medicine/DrugListService.java | 19 +-
.../medicine/MedicineListService.java | 29 +-
.../medicine/MedicineLogListService.java | 29 +-
.../medicine/MedicineReminderListService.java | 27 +-
.../application/cms/LoadPageTreeCommand.java | 2 +-
.../persistence/RegionRepository.java | 63 +-
.../cms/ContentVersionRepository.java | 56 +-
.../persistence/cms/PageFileRepository.java | 140 +--
.../cms/WebPageVersionRepository.java | 53 +-
.../items/ItemVersionRepository.java | 43 +-
.../services/ActivityListPageJsonService.java | 2 +-
.../services/ItemVersionsAjax.java | 2 +-
.../services/UsersJsonService.java | 2 +-
.../WebPageFileVersionUploadJson.java | 6 +-
.../widgets/cms/FileSearchResultsWidget.java | 2 +-
.../widgets/userprofile/MyActivityWidget.java | 2 +-
.../zeroio/platform/rest/WebPagesService.java | 2 +-
128 files changed, 2822 insertions(+), 4915 deletions(-)
delete mode 100644 src/main/java/com/simisinc/platform/infrastructure/database/AutoRollback.java
delete mode 100644 src/main/java/com/simisinc/platform/infrastructure/database/AutoStartTransaction.java
delete mode 100644 src/main/java/com/simisinc/platform/infrastructure/database/DB.java
delete mode 100644 src/main/java/com/simisinc/platform/infrastructure/database/DataConstraints.java
delete mode 100644 src/main/java/com/simisinc/platform/infrastructure/database/DataResult.java
delete mode 100644 src/main/java/com/simisinc/platform/infrastructure/database/SqlJoins.java
delete mode 100644 src/main/java/com/simisinc/platform/infrastructure/database/SqlUtils.java
delete mode 100644 src/main/java/com/simisinc/platform/infrastructure/database/SqlValue.java
delete mode 100644 src/main/java/com/simisinc/platform/infrastructure/database/SqlWhere.java
diff --git a/src/main/java/com/simisinc/platform/application/cms/CheckFolderPermissionCommand.java b/src/main/java/com/simisinc/platform/application/cms/CheckFolderPermissionCommand.java
index d205294c9..ad5caaf7e 100644
--- a/src/main/java/com/simisinc/platform/application/cms/CheckFolderPermissionCommand.java
+++ b/src/main/java/com/simisinc/platform/application/cms/CheckFolderPermissionCommand.java
@@ -1,4 +1,5 @@
/*
+ * Copyright 2026 Matt Rajkowski (https://github.com/rajkowski)
* Copyright 2022 SimIS Inc. (https://www.simiscms.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -16,7 +17,7 @@
package com.simisinc.platform.application.cms;
-import com.simisinc.platform.infrastructure.database.DB;
+import com.github.rajkowski.database.DB;
/**
* Determines user access to folders
@@ -27,34 +28,38 @@
public class CheckFolderPermissionCommand {
public static boolean userHasAddPermission(long folderId, long userId) {
- // SELECT COUNT(*) FROM user_groups WHERE user_id = 2 AND group_id IN (SELECT group_id FROM folder_groups WHERE folder_id = 9 AND add_permission = true);
- long count = DB.selectCountFrom("user_groups",
- DB.WHERE("user_id = ?", userId)
- .AND("group_id IN (SELECT group_id FROM folder_groups WHERE folder_id = ? AND add_permission = true)", folderId));
- return (count > 0);
+ long count = DB.SELECT("COUNT(*)")
+ .FROM("user_groups")
+ .WHERE("user_id = ?", userId)
+ .AND("group_id IN (SELECT group_id FROM folder_groups WHERE folder_id = ? AND add_permission = ?)", folderId, true)
+ .returnCount();
+ return count > 0;
}
public static boolean userHasViewPermission(long folderId, long userId) {
- // SELECT COUNT(*) FROM user_groups WHERE user_id = 2 AND group_id IN (SELECT group_id FROM folder_groups WHERE folder_id = 9 AND view_permission = true);
- long count = DB.selectCountFrom("user_groups",
- DB.WHERE("user_id = ?", userId)
- .AND("group_id IN (SELECT group_id FROM folder_groups WHERE folder_id = ? AND view_permission = true)", folderId));
- return (count > 0);
+ long count = DB.SELECT("COUNT(*)")
+ .FROM("user_groups")
+ .WHERE("user_id = ?", userId)
+ .AND("group_id IN (SELECT group_id FROM folder_groups WHERE folder_id = ? AND view_permission = ?)", folderId, true)
+ .returnCount();
+ return count > 0;
}
public static boolean userHasEditPermission(long folderId, long userId) {
- // SELECT COUNT(*) FROM user_groups WHERE user_id = 2 AND group_id IN (SELECT group_id FROM folder_groups WHERE folder_id = 9 AND edit_permission = true);
- long count = DB.selectCountFrom("user_groups",
- DB.WHERE("user_id = ?", userId)
- .AND("group_id IN (SELECT group_id FROM folder_groups WHERE folder_id = ? AND edit_permission = true)", folderId));
- return (count > 0);
+ long count = DB.SELECT("COUNT(*)")
+ .FROM("user_groups")
+ .WHERE("user_id = ?", userId)
+ .AND("group_id IN (SELECT group_id FROM folder_groups WHERE folder_id = ? AND edit_permission = ?)", folderId, true)
+ .returnCount();
+ return count > 0;
}
public static boolean userHasDeletePermission(long folderId, long userId) {
- // SELECT COUNT(*) FROM user_groups WHERE user_id = 2 AND group_id IN (SELECT group_id FROM folder_groups WHERE folder_id = 9 AND delete_permission = true);
- long count = DB.selectCountFrom("user_groups",
- DB.WHERE("user_id = ?", userId)
- .AND("group_id IN (SELECT group_id FROM folder_groups WHERE folder_id = ? AND delete_permission = true)", folderId));
- return (count > 0);
+ long count = DB.SELECT("COUNT(*)")
+ .FROM("user_groups")
+ .WHERE("user_id = ?", userId)
+ .AND("group_id IN (SELECT group_id FROM folder_groups WHERE folder_id = ? AND delete_permission = ?)", folderId, true)
+ .returnCount();
+ return count > 0;
}
}
diff --git a/src/main/java/com/simisinc/platform/application/cms/LoadContentListCommand.java b/src/main/java/com/simisinc/platform/application/cms/LoadContentListCommand.java
index e985f5d3c..c5ad3f2e1 100644
--- a/src/main/java/com/simisinc/platform/application/cms/LoadContentListCommand.java
+++ b/src/main/java/com/simisinc/platform/application/cms/LoadContentListCommand.java
@@ -17,7 +17,7 @@
package com.simisinc.platform.application.cms;
import com.simisinc.platform.domain.model.cms.Content;
-import com.simisinc.platform.infrastructure.database.DataConstraints;
+import com.github.rajkowski.database.DataConstraints;
import com.simisinc.platform.infrastructure.persistence.cms.ContentRepository;
import com.simisinc.platform.infrastructure.persistence.cms.ContentSpecification;
import org.apache.commons.lang3.StringUtils;
@@ -85,13 +85,11 @@ public static List loadContentList(String searchTerm, int offset, int l
// Query repository
List contentList = ContentRepository.findAll(specification, constraints);
-
- if (contentList == null) {
+ if (contentList == null || contentList.isEmpty()) {
LOG.debug("No content found for search term: " + searchTerm);
} else {
LOG.debug("Found " + contentList.size() + " content blocks");
}
-
return contentList;
}
}
diff --git a/src/main/java/com/simisinc/platform/application/datasets/DeleteDatasetItemsCommand.java b/src/main/java/com/simisinc/platform/application/datasets/DeleteDatasetItemsCommand.java
index 48dedf4bd..e3d216c64 100644
--- a/src/main/java/com/simisinc/platform/application/datasets/DeleteDatasetItemsCommand.java
+++ b/src/main/java/com/simisinc/platform/application/datasets/DeleteDatasetItemsCommand.java
@@ -1,4 +1,5 @@
/*
+ * Copyright 2026 Matt Rajkowski (https://github.com/rajkowski)
* Copyright 2022 SimIS Inc. (https://www.simiscms.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -18,7 +19,7 @@
import com.simisinc.platform.domain.model.datasets.Dataset;
import com.simisinc.platform.domain.model.items.Item;
-import com.simisinc.platform.infrastructure.database.DataConstraints;
+import com.github.rajkowski.database.DataConstraints;
import com.simisinc.platform.infrastructure.persistence.items.ItemRepository;
import com.simisinc.platform.infrastructure.persistence.items.ItemSpecification;
import org.apache.commons.logging.Log;
diff --git a/src/main/java/com/simisinc/platform/application/ecommerce/LoadProductListCommand.java b/src/main/java/com/simisinc/platform/application/ecommerce/LoadProductListCommand.java
index 9cef71976..47971e79a 100644
--- a/src/main/java/com/simisinc/platform/application/ecommerce/LoadProductListCommand.java
+++ b/src/main/java/com/simisinc/platform/application/ecommerce/LoadProductListCommand.java
@@ -1,4 +1,5 @@
/*
+ * Copyright 2026 Matt Rajkowski (https://github.com/rajkowski)
* Copyright 2022 SimIS Inc. (https://www.simiscms.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -17,7 +18,7 @@
package com.simisinc.platform.application.ecommerce;
import com.simisinc.platform.domain.model.ecommerce.Product;
-import com.simisinc.platform.infrastructure.database.DataConstraints;
+import com.github.rajkowski.database.DataConstraints;
import com.simisinc.platform.infrastructure.persistence.ecommerce.ProductRepository;
import com.simisinc.platform.infrastructure.persistence.ecommerce.ProductSpecification;
import org.apache.commons.logging.Log;
diff --git a/src/main/java/com/simisinc/platform/application/ecommerce/OrderCommand.java b/src/main/java/com/simisinc/platform/application/ecommerce/OrderCommand.java
index 1ed1faeb1..e2d06c8a4 100644
--- a/src/main/java/com/simisinc/platform/application/ecommerce/OrderCommand.java
+++ b/src/main/java/com/simisinc/platform/application/ecommerce/OrderCommand.java
@@ -1,4 +1,5 @@
/*
+ * Copyright 2026 Matt Rajkowski (https://github.com/rajkowski)
* Copyright 2022 SimIS Inc. (https://www.simiscms.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -30,6 +31,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.DB;
import com.sanctionco.jmail.JMail;
import com.simisinc.platform.application.DataException;
import com.simisinc.platform.application.admin.LoadSitePropertyCommand;
@@ -41,7 +43,6 @@
import com.simisinc.platform.domain.model.ecommerce.PricingRule;
import com.simisinc.platform.domain.model.ecommerce.ProductSku;
import com.simisinc.platform.domain.model.ecommerce.ShippingRate;
-import com.simisinc.platform.infrastructure.database.DB;
import com.simisinc.platform.infrastructure.persistence.SitePropertyRepository;
import com.simisinc.platform.infrastructure.persistence.ecommerce.CartItemRepository;
import com.simisinc.platform.infrastructure.persistence.ecommerce.CartRepository;
diff --git a/src/main/java/com/simisinc/platform/application/ecommerce/OrderStatusCommand.java b/src/main/java/com/simisinc/platform/application/ecommerce/OrderStatusCommand.java
index b262a6102..bb58ed11d 100644
--- a/src/main/java/com/simisinc/platform/application/ecommerce/OrderStatusCommand.java
+++ b/src/main/java/com/simisinc/platform/application/ecommerce/OrderStatusCommand.java
@@ -1,4 +1,5 @@
/*
+ * Copyright 2026 Matt Rajkowski (https://github.com/rajkowski)
* Copyright 2022 SimIS Inc. (https://www.simiscms.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -20,9 +21,9 @@
import org.apache.commons.lang3.StringUtils;
+import com.github.rajkowski.database.DB;
import com.simisinc.platform.domain.model.ecommerce.Order;
import com.simisinc.platform.domain.model.ecommerce.OrderItem;
-import com.simisinc.platform.infrastructure.database.DB;
import com.simisinc.platform.infrastructure.persistence.ecommerce.OrderItemRepository;
/**
@@ -50,25 +51,34 @@ public static int retrieveStatusId(String code) {
if (StringUtils.isBlank(code)) {
return -1;
}
- return (int) DB.selectFunction("status_id", "lookup_order_status",
- DB.WHERE("LOWER(code) = ?", code.toLowerCase()));
+ return DB.SELECT("status_id")
+ .FROM("lookup_order_status")
+ .WHERE("LOWER(code) = ?", code.toLowerCase())
+ .returnValue(Long.class).intValue();
}
public static String status(int statusId) {
if (statusId == -1) {
return null;
}
- return DB.selectStringValue("title", "lookup_order_status", DB.WHERE("status_id = ?", statusId));
+ return DB.SELECT("title")
+ .FROM("lookup_order_status")
+ .WHERE("status_id = ?", statusId)
+ .returnValue(String.class);
}
public static String currentStatus(int statusId) {
if (statusId == -1) {
return null;
}
- String code = DB.selectStringValue(
- "code",
- "lookup_order_status",
- DB.WHERE("status_id = ?", statusId)).toUpperCase();
+ String code = DB.SELECT("code")
+ .FROM("lookup_order_status")
+ .WHERE("status_id = ?", statusId)
+ .returnValue(String.class);
+ if (code == null) {
+ return null;
+ }
+ code = code.toUpperCase();
if (CREATED.equals(code)) {
return "New order";
} else if (PAID.equals(code)) {
diff --git a/src/main/java/com/simisinc/platform/application/items/CheckCollectionPermissionCommand.java b/src/main/java/com/simisinc/platform/application/items/CheckCollectionPermissionCommand.java
index 55106236f..52f122092 100644
--- a/src/main/java/com/simisinc/platform/application/items/CheckCollectionPermissionCommand.java
+++ b/src/main/java/com/simisinc/platform/application/items/CheckCollectionPermissionCommand.java
@@ -1,4 +1,5 @@
/*
+ * Copyright 2026 Matt Rajkowski (https://github.com/rajkowski)
* Copyright 2022 SimIS Inc. (https://www.simiscms.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -16,7 +17,7 @@
package com.simisinc.platform.application.items;
-import com.simisinc.platform.infrastructure.database.DB;
+import com.github.rajkowski.database.DB;
/**
* Methods to check collection object permissions
@@ -27,38 +28,38 @@
public class CheckCollectionPermissionCommand {
public static boolean userHasAddPermission(long collectionId, long userId) {
- // SELECT COUNT(*) FROM user_groups WHERE user_id = 2 AND group_id IN (SELECT group_id FROM collection_groups WHERE collection_id = 14 AND add_permission = true);
- long count = DB.selectCountFrom("user_groups",
- DB.WHERE("user_id = ?", userId)
- .AND("group_id IN (SELECT group_id FROM collection_groups WHERE collection_id = ? AND add_permission = true)",
- collectionId));
- return (count > 0);
+ long count = DB.SELECT("COUNT(*)")
+ .FROM("user_groups")
+ .WHERE("user_id = ?", userId)
+ .AND("group_id IN (SELECT group_id FROM collection_groups WHERE collection_id = ? AND add_permission = ?)", collectionId, true)
+ .returnCount();
+ return count > 0;
}
public static boolean userHasViewPermission(long collectionId, long userId) {
- // SELECT COUNT(*) FROM user_groups WHERE user_id = 2 AND group_id IN (SELECT group_id FROM collection_groups WHERE collection_id = 14 AND view_permission = true);
- long count = DB.selectCountFrom("user_groups",
- DB.WHERE("user_id = ?", userId)
- .AND("group_id IN (SELECT group_id FROM collection_groups WHERE collection_id = ? AND view_permission = true)",
- collectionId));
- return (count > 0);
+ long count = DB.SELECT("COUNT(*)")
+ .FROM("user_groups")
+ .WHERE("user_id = ?", userId)
+ .AND("group_id IN (SELECT group_id FROM collection_groups WHERE collection_id = ? AND view_permission = ?)", collectionId, true)
+ .returnCount();
+ return count > 0;
}
public static boolean userHasEditPermission(long collectionId, long userId) {
- // SELECT COUNT(*) FROM user_groups WHERE user_id = 2 AND group_id IN (SELECT group_id FROM collection_groups WHERE collection_id = 14 AND edit_permission = true);
- long count = DB.selectCountFrom("user_groups",
- DB.WHERE("user_id = ?", userId)
- .AND("group_id IN (SELECT group_id FROM collection_groups WHERE collection_id = ? AND edit_permission = true)",
- collectionId));
- return (count > 0);
+ long count = DB.SELECT("COUNT(*)")
+ .FROM("user_groups")
+ .WHERE("user_id = ?", userId)
+ .AND("group_id IN (SELECT group_id FROM collection_groups WHERE collection_id = ? AND edit_permission = ?)", collectionId, true)
+ .returnCount();
+ return count > 0;
}
public static boolean userHasDeletePermission(long collectionId, long userId) {
- // SELECT COUNT(*) FROM user_groups WHERE user_id = 2 AND group_id IN (SELECT group_id FROM collection_groups WHERE collection_id = 14 AND delete_permission = true);
- long count = DB.selectCountFrom("user_groups",
- DB.WHERE("user_id = ?", userId)
- .AND("group_id IN (SELECT group_id FROM collection_groups WHERE collection_id = ? AND delete_permission = true)",
- collectionId));
- return (count > 0);
+ long count = DB.SELECT("COUNT(*)")
+ .FROM("user_groups")
+ .WHERE("user_id = ?", userId)
+ .AND("group_id IN (SELECT group_id FROM collection_groups WHERE collection_id = ? AND delete_permission = ?)", collectionId, true)
+ .returnCount();
+ return count > 0;
}
}
diff --git a/src/main/java/com/simisinc/platform/application/items/CheckItemFolderPermissionCommand.java b/src/main/java/com/simisinc/platform/application/items/CheckItemFolderPermissionCommand.java
index e296915dc..255e3268c 100644
--- a/src/main/java/com/simisinc/platform/application/items/CheckItemFolderPermissionCommand.java
+++ b/src/main/java/com/simisinc/platform/application/items/CheckItemFolderPermissionCommand.java
@@ -1,4 +1,5 @@
/*
+ * Copyright 2026 Matt Rajkowski (https://github.com/rajkowski)
* Copyright 2022 SimIS Inc. (https://www.simiscms.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -16,7 +17,7 @@
package com.simisinc.platform.application.items;
-import com.simisinc.platform.infrastructure.database.DB;
+import com.github.rajkowski.database.DB;
/**
* Methods to check item folder object permissions
@@ -27,34 +28,38 @@
public class CheckItemFolderPermissionCommand {
public static boolean userHasAddPermission(long folderId, long userId) {
- // SELECT COUNT(*) FROM user_groups WHERE user_id = 2 AND group_id IN (SELECT group_id FROM folder_groups WHERE folder_id = 9 AND add_permission = true);
- long count = DB.selectCountFrom("user_groups",
- DB.WHERE("user_id = ?", userId)
- .AND("group_id IN (SELECT group_id FROM item_folder_groups WHERE folder_id = ? AND add_permission = true)", folderId));
- return (count > 0);
+ long count = DB.SELECT("COUNT(*)")
+ .FROM("user_groups")
+ .WHERE("user_id = ?", userId)
+ .AND("group_id IN (SELECT group_id FROM item_folder_groups WHERE folder_id = ? AND add_permission = ?)", folderId, true)
+ .returnCount();
+ return count > 0;
}
public static boolean userHasViewPermission(long folderId, long userId) {
- // SELECT COUNT(*) FROM user_groups WHERE user_id = 2 AND group_id IN (SELECT group_id FROM folder_groups WHERE folder_id = 9 AND view_permission = true);
- long count = DB.selectCountFrom("user_groups",
- DB.WHERE("user_id = ?", userId)
- .AND("group_id IN (SELECT group_id FROM item_folder_groups WHERE folder_id = ? AND view_permission = true)", folderId));
- return (count > 0);
+ long count = DB.SELECT("COUNT(*)")
+ .FROM("user_groups")
+ .WHERE("user_id = ?", userId)
+ .AND("group_id IN (SELECT group_id FROM item_folder_groups WHERE folder_id = ? AND view_permission = ?)", folderId, true)
+ .returnCount();
+ return count > 0;
}
public static boolean userHasEditPermission(long folderId, long userId) {
- // SELECT COUNT(*) FROM user_groups WHERE user_id = 2 AND group_id IN (SELECT group_id FROM folder_groups WHERE folder_id = 9 AND edit_permission = true);
- long count = DB.selectCountFrom("user_groups",
- DB.WHERE("user_id = ?", userId)
- .AND("group_id IN (SELECT group_id FROM item_folder_groups WHERE folder_id = ? AND edit_permission = true)", folderId));
- return (count > 0);
+ long count = DB.SELECT("COUNT(*)")
+ .FROM("user_groups")
+ .WHERE("user_id = ?", userId)
+ .AND("group_id IN (SELECT group_id FROM item_folder_groups WHERE folder_id = ? AND edit_permission = ?)", folderId, true)
+ .returnCount();
+ return count > 0;
}
public static boolean userHasDeletePermission(long folderId, long userId) {
- // SELECT COUNT(*) FROM user_groups WHERE user_id = 2 AND group_id IN (SELECT group_id FROM folder_groups WHERE folder_id = 9 AND delete_permission = true);
- long count = DB.selectCountFrom("user_groups",
- DB.WHERE("user_id = ?", userId)
- .AND("group_id IN (SELECT group_id FROM item_folder_groups WHERE folder_id = ? AND delete_permission = true)", folderId));
- return (count > 0);
+ long count = DB.SELECT("COUNT(*)")
+ .FROM("user_groups")
+ .WHERE("user_id = ?", userId)
+ .AND("group_id IN (SELECT group_id FROM item_folder_groups WHERE folder_id = ? AND delete_permission = ?)", folderId, true)
+ .returnCount();
+ return count > 0;
}
}
diff --git a/src/main/java/com/simisinc/platform/application/items/LoadActivityListCommand.java b/src/main/java/com/simisinc/platform/application/items/LoadActivityListCommand.java
index 2f663f5a8..15749f52f 100644
--- a/src/main/java/com/simisinc/platform/application/items/LoadActivityListCommand.java
+++ b/src/main/java/com/simisinc/platform/application/items/LoadActivityListCommand.java
@@ -1,4 +1,5 @@
/*
+ * Copyright 2026 Matt Rajkowski (https://github.com/rajkowski)
* Copyright 2022 SimIS Inc. (https://www.simiscms.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -16,14 +17,15 @@
package com.simisinc.platform.application.items;
-import com.simisinc.platform.domain.model.items.Activity;
-import com.simisinc.platform.infrastructure.database.DataConstraints;
-import com.simisinc.platform.infrastructure.persistence.items.ActivityRepository;
-import com.simisinc.platform.infrastructure.persistence.items.ActivitySpecification;
+import java.util.List;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import java.util.List;
+import com.github.rajkowski.database.DataConstraints;
+import com.simisinc.platform.domain.model.items.Activity;
+import com.simisinc.platform.infrastructure.persistence.items.ActivityRepository;
+import com.simisinc.platform.infrastructure.persistence.items.ActivitySpecification;
/**
* Loads an activity list from cache or storage
diff --git a/src/main/java/com/simisinc/platform/infrastructure/database/AutoRollback.java b/src/main/java/com/simisinc/platform/infrastructure/database/AutoRollback.java
deleted file mode 100644
index f7871ee72..000000000
--- a/src/main/java/com/simisinc/platform/infrastructure/database/AutoRollback.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright 2022 SimIS Inc. (https://www.simiscms.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.simisinc.platform.infrastructure.database;
-
-import java.sql.Connection;
-import java.sql.SQLException;
-
-/**
- * Part of the auto handling of transactions
- *
- * @author matt rajkowski
- * @created 1/22/19 12:12 PM
- */
-public class AutoRollback implements AutoCloseable {
-
- private Connection connection;
- private boolean committed;
-
- public AutoRollback(Connection connection) {
- this.connection = connection;
- }
-
- public void commit() throws SQLException {
- connection.commit();
- committed = true;
- }
-
- @Override
- public void close() throws SQLException {
- if (!committed) {
- connection.rollback();
- }
- }
-}
diff --git a/src/main/java/com/simisinc/platform/infrastructure/database/AutoStartTransaction.java b/src/main/java/com/simisinc/platform/infrastructure/database/AutoStartTransaction.java
deleted file mode 100644
index c55320c81..000000000
--- a/src/main/java/com/simisinc/platform/infrastructure/database/AutoStartTransaction.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright 2022 SimIS Inc. (https://www.simiscms.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.simisinc.platform.infrastructure.database;
-
-import java.sql.Connection;
-import java.sql.SQLException;
-
-/**
- * Part of the auto handling of transactions
- *
- * @author matt rajkowski
- * @created 1/22/19 12:12 PM
- */
-public class AutoStartTransaction implements AutoCloseable {
-
- private Connection connection;
- private boolean originalAutoCommit;
-
- public AutoStartTransaction(Connection connection) throws SQLException {
- this.connection = connection;
- originalAutoCommit = connection.getAutoCommit();
- connection.setAutoCommit(false);
- }
-
- @Override
- public void close() throws SQLException {
- connection.setAutoCommit(originalAutoCommit);
- }
-}
diff --git a/src/main/java/com/simisinc/platform/infrastructure/database/DB.java b/src/main/java/com/simisinc/platform/infrastructure/database/DB.java
deleted file mode 100644
index 6aca88be0..000000000
--- a/src/main/java/com/simisinc/platform/infrastructure/database/DB.java
+++ /dev/null
@@ -1,998 +0,0 @@
-/*
- * Copyright 2026 Matt Rajkowski (https://github.com/rajkowski)
- * Copyright 2022 SimIS Inc. (https://www.simiscms.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.simisinc.platform.infrastructure.database;
-
-import java.io.File;
-import java.math.BigDecimal;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Timestamp;
-import java.sql.Types;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.function.Function;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.postgresql.util.PGInterval;
-
-import com.simisinc.platform.domain.model.Entity;
-import com.univocity.parsers.csv.CsvRoutines;
-import com.univocity.parsers.csv.CsvWriterSettings;
-
-/**
- * Functions to interface with the database and handle special cases
- *
- * @author matt rajkowski
- * @created 1/13/22 7:56 AM
- */
-public class DB {
-
- private static Log LOG = LogFactory.getLog(DB.class);
- private static long LONG_QUERY_MS = 20;
-
- public static Connection getConnection() throws SQLException {
- return ConnectionPool.getApplicationDataSource().getConnection();
- }
-
- public static SqlUtils SELECT(String... fieldNames) {
- return new SqlUtils().addNames(fieldNames);
- }
-
- public static SqlJoins JOIN(String value) {
- return new SqlJoins().add(value);
- }
-
- public static SqlWhere WHERE() {
- return new SqlWhere();
- }
-
- public static SqlWhere WHERE(String clause) {
- return new SqlWhere().AND(clause);
- }
-
- public static SqlWhere WHERE(String clause, long value) {
- return new SqlWhere().AND(clause, value);
- }
-
- public static SqlWhere WHERE(String name, Long[] value) {
- return new SqlWhere().AND(new SqlValue(name, value));
- }
-
- public static SqlWhere WHERE(String clause, int value) {
- return new SqlWhere().AND(clause, value);
- }
-
- public static SqlWhere WHERE(String clause, String value) {
- return new SqlWhere().AND(clause, value);
- }
-
- public static SqlWhere WHERE(String clause, boolean value) {
- return new SqlWhere().AND(clause, value);
- }
-
- public static SqlWhere WHERE(String name, Timestamp value) {
- return new SqlWhere().AND(name, value);
- }
-
- public static SqlWhere WHERE(String name, Timestamp[] value) {
- return new SqlWhere().AND(name, value);
- }
-
- private static PreparedStatement createPreparedStatement(Connection connection, String sqlQuery, SqlWhere where)
- throws SQLException {
- PreparedStatement pst = connection.prepareStatement(sqlQuery);
- prepareValues(connection, pst, where);
- return pst;
- }
-
- private static PreparedStatement createPreparedStatement(Connection connection, String sqlQuery,
- SqlUtils insertValues, String[] primaryKey) throws SQLException {
- if (LOG.isDebugEnabled()) {
- LOG.debug("SQL_INSERT_QUERY: " + sqlQuery);
- }
- PreparedStatement pst;
- if (primaryKey != null) {
- pst = connection.prepareStatement(sqlQuery, primaryKey);
- } else {
- pst = connection.prepareStatement(sqlQuery);
- }
- prepareValues(connection, pst, insertValues);
- return pst;
- }
-
- private static int prepareValues(Connection connection, PreparedStatement pst, SqlUtils sqlUtils) throws SQLException {
- return prepareValues(connection, pst, sqlUtils, 0);
- }
-
- private static int prepareValues(Connection connection, PreparedStatement pst, SqlUtils sqlUtils, int fieldIdx)
- throws SQLException {
- if (sqlUtils == null || sqlUtils.getValues() == null || sqlUtils.getValues().isEmpty()) {
- return fieldIdx;
- }
- return prepareValues(connection, pst, sqlUtils.getValues(), fieldIdx);
- }
-
- private static int prepareValues(Connection connection, PreparedStatement pst, SqlWhere sqlWhere)
- throws SQLException {
- return prepareValues(connection, pst, sqlWhere, 0);
- }
-
- private static int prepareValues(Connection connection, PreparedStatement pst, SqlWhere sqlWhere, int fieldIdx)
- throws SQLException {
- if (sqlWhere == null || sqlWhere.getValues() == null || sqlWhere.getValues().isEmpty()) {
- return fieldIdx;
- }
- return prepareValues(connection, pst, sqlWhere.getValues(), fieldIdx);
- }
-
- private static int prepareValues(Connection connection, PreparedStatement pst, List sqlValues, int fieldIdx)
- throws SQLException {
- if (sqlValues == null || sqlValues.isEmpty()) {
- return fieldIdx;
- }
- for (SqlValue sqlValue : sqlValues) {
- if (!sqlValue.hasValue()) {
- continue;
- }
- if (sqlValue.getSqlType() == Types.ARRAY) {
- pst.setArray(++fieldIdx, connection.createArrayOf("text", sqlValue.getStringValues()));
- } else if (sqlValue.getSqlType() == Types.VARCHAR) {
- if (sqlValue.getStringValues() != null) {
- for (String value : sqlValue.getStringValues()) {
- pst.setString(++fieldIdx, value);
- }
- } else {
- pst.setString(++fieldIdx, sqlValue.getStringValue());
- }
- } else if (sqlValue.getSqlType() == Types.BIGINT) {
- if (sqlValue.getLongValues() != null) {
- for (Long value : sqlValue.getLongValues()) {
- pst.setLong(++fieldIdx, value);
- }
- } else {
- if (sqlValue.isNull()) {
- pst.setNull(++fieldIdx, Types.BIGINT);
- } else {
- pst.setLong(++fieldIdx, sqlValue.getLongValue());
- }
- }
- } else if (sqlValue.getSqlType() == Types.INTEGER) {
- if (sqlValue.isNull()) {
- pst.setNull(++fieldIdx, Types.INTEGER);
- } else {
- pst.setInt(++fieldIdx, sqlValue.getIntValue());
- }
- } else if (sqlValue.getSqlType() == Types.DOUBLE) {
- if (sqlValue.isNull()) {
- pst.setNull(++fieldIdx, Types.DOUBLE);
- } else {
- pst.setDouble(++fieldIdx, sqlValue.getDoubleValue());
- }
- } else if (sqlValue.getSqlType() == Types.NUMERIC) {
- if (sqlValue.isNull()) {
- pst.setNull(++fieldIdx, Types.NUMERIC);
- } else {
- pst.setBigDecimal(++fieldIdx, sqlValue.getBigDecimalValue());
- }
- } else if (sqlValue.getSqlType() == Types.TIMESTAMP) {
- if (sqlValue.getTimestampValues() != null) {
- for (Timestamp value : sqlValue.getTimestampValues()) {
- pst.setTimestamp(++fieldIdx, value);
- }
- } else {
- if (sqlValue.isNull()) {
- pst.setNull(++fieldIdx, Types.TIMESTAMP);
- } else {
- pst.setTimestamp(++fieldIdx, sqlValue.getTimestampValue());
- }
- }
- } else if (sqlValue.getSqlType() == Types.JAVA_OBJECT) {
- // Set multiple java objects
- if (sqlValue.getObjectValues() != null) {
- for (Object value : sqlValue.getObjectValues()) {
- // Determine the type and value
- if (value instanceof String) {
- pst.setString(++fieldIdx, (String) value);
- } else if (value instanceof Integer) {
- pst.setInt(++fieldIdx, (Integer) value);
- } else if (value instanceof Long) {
- pst.setLong(++fieldIdx, (Long) value);
- } else if (value instanceof Double) {
- pst.setDouble(++fieldIdx, (Double) value);
- } else if (value instanceof Boolean) {
- pst.setBoolean(++fieldIdx, (Boolean) value);
- } else if (value instanceof Timestamp) {
- pst.setTimestamp(++fieldIdx, (Timestamp) value);
- } else if (value instanceof BigDecimal) {
- pst.setBigDecimal(++fieldIdx, (BigDecimal) value);
- } else {
- throw new SQLException("Type not implemented for " + value.getClass());
- }
- }
- }
- } else if (sqlValue.getSqlType() == Types.BOOLEAN) {
- if (sqlValue.isNull()) {
- pst.setNull(++fieldIdx, Types.BOOLEAN);
- } else {
- pst.setBoolean(++fieldIdx, sqlValue.getBooleanValue());
- }
- } else if (sqlValue.getSqlType() == Types.OTHER && sqlValue.getCastType() == SqlValue.INTERVAL_TYPE) {
- if (sqlValue.isNull()) {
- pst.setNull(++fieldIdx, Types.OTHER);
- } else {
- pst.setObject(++fieldIdx, new PGInterval(sqlValue.getStringValue()));
- }
- }
- }
- return fieldIdx;
- }
-
- public static long selectCountFrom(String tableName) {
- return selectCountFrom(tableName, null);
- }
-
- public static long selectCountFrom(String tableName, SqlWhere where) {
- return selectFunction("COUNT(*)", tableName, where);
- }
-
- public static long selectNextSequenceValue(String sequenceName) {
- long nextVal = -1;
- String sqlNextVal = "SELECT nextval('" + sequenceName + "')";
- try (Connection connection = getConnection();
- PreparedStatement pst = createPreparedStatement(connection, sqlNextVal, null);
- ResultSet rs = pst.executeQuery()) {
- if (rs.next()) {
- nextVal = rs.getLong(1);
- }
- } catch (SQLException se) {
- LOG.error(sqlNextVal);
- LOG.error("Next Sequence Value SQLException: " + se.getMessage());
- }
- return nextVal;
- }
-
- public static long resetSequence(String sequenceName, long value) {
- long nextVal = -1;
- String sqlRestartSequence = "ALTER SEQUENCE " + sequenceName + " RESTART WITH " + value;
- try (Connection connection = getConnection();
- PreparedStatement pst = createPreparedStatement(connection, sqlRestartSequence, null)) {
- pst.execute();
- } catch (SQLException se) {
- LOG.error(sqlRestartSequence);
- LOG.error("Reset Sequence SQLException: " + se.getMessage());
- }
- return nextVal;
- }
-
- public static long selectFunction(String sql, String tableName, SqlWhere where) {
- // Construct the where clause
- StringBuilder whereSb = createWhereClause(where);
- long value = 0;
- String selectFunction = "SELECT " + sql + " FROM " + tableName + whereSb.toString();
- long startQueryTime = System.currentTimeMillis();
- try (Connection connection = getConnection();
- PreparedStatement pst = createPreparedStatement(connection, selectFunction, where);
- ResultSet rs = pst.executeQuery()) {
- if (rs.next()) {
- value = rs.getLong(1);
- }
- } catch (SQLException se) {
- LOG.error(selectFunction);
- LOG.error("Count SQLException: " + se.getMessage());
- }
- if (LOG.isDebugEnabled()) {
- long endQueryTime = System.currentTimeMillis();
- long totalTime = endQueryTime - startQueryTime;
- if (totalTime > LONG_QUERY_MS) {
- LOG.debug(selectFunction);
- LOG.debug("Query took " + totalTime + "ms");
- }
- }
- return value;
- }
-
- public static List selectFunctionAsLongList(String sqlFields, String tableName, SqlWhere where,
- SqlUtils orderBy) {
-
- // Prepare the query
- StringBuilder sb = new StringBuilder();
- sb.append("SELECT ").append(sqlFields).append(" ");
- sb.append("FROM ").append(tableName);
- sb.append(createWhereClause(where));
-
- // Apply sorting, paging
- if (orderBy != null) {
- sb.append(appendSortClause(orderBy, null));
- }
- String sql = sb.toString();
-
- // Construct the where clause
- List records = new ArrayList<>();
- try (Connection connection = getConnection();
- PreparedStatement pst = createPreparedStatement(connection, sql, where);
- ResultSet rs = pst.executeQuery()) {
- while (rs.next()) {
- long value = rs.getLong(1);
- records.add(value);
- }
- } catch (SQLException se) {
- LOG.error(sql);
- LOG.error("selectFunctionAsLongList SQLException: " + se.getMessage());
- }
- return records;
- }
-
- public static String selectStringValue(String sql, String tableName, SqlWhere where) {
- // Construct the where clause
- StringBuilder whereSb = createWhereClause(where);
- String value = null;
- String sqlCount = "SELECT " + sql + " FROM " + tableName + whereSb.toString();
- try (Connection connection = getConnection();
- PreparedStatement pst = createPreparedStatement(connection, sqlCount, where);
- ResultSet rs = pst.executeQuery()) {
- if (rs.next()) {
- value = rs.getString(1);
- }
- } catch (SQLException se) {
- LOG.error(sqlCount);
- LOG.error("Count SQLException: " + se.getMessage());
- }
- return value;
- }
-
- public static Object selectRecordFrom(String tableName, SqlWhere where, Function buildRecord) {
- return selectRecordFrom(tableName, null, null, where, buildRecord);
- }
-
- public static Object selectRecordFrom(String tableName, SqlUtils select, SqlJoins joins, SqlWhere where,
- Function buildRecord) {
- // Construct the where clause
- StringBuilder joinsSb = createJoins(joins);
- StringBuilder whereSb = createWhereClause(where);
-
- // Prepare the query
- StringBuilder sb = new StringBuilder();
- sb.append("SELECT ").append(tableName).append(".*");
- if (select != null) {
- sb.append(createAdditionalSelectFields(select));
- }
- sb.append(" FROM ").append(tableName);
- sb.append(joinsSb);
- sb.append(whereSb);
-
- // Prepare the query
- long startQueryTime = System.currentTimeMillis();
- try (Connection connection = getConnection();
- PreparedStatement pst = createPreparedStatement(connection, sb.toString(), where);
- ResultSet rs = pst.executeQuery()) {
- if (rs.next()) {
- return (buildRecord.apply(rs));
- }
- } catch (SQLException se) {
- LOG.debug(sb.toString());
- LOG.error("SQLException: " + se.getMessage());
- } finally {
- if (LOG.isDebugEnabled()) {
- long endQueryTime = System.currentTimeMillis();
- long totalTime = endQueryTime - startQueryTime;
- if (totalTime > LONG_QUERY_MS) {
- LOG.debug(sb.toString());
- LOG.debug("Query took " + totalTime + "ms");
- }
- }
- }
- return null;
- }
-
- public static DataResult selectAllFrom(String tableName, SqlWhere where, DataConstraints constraints,
- Function buildRecord) {
- return selectAllFrom(tableName, null, null, where, null, constraints, buildRecord);
- }
-
- public static DataResult selectAllFrom(String tableName, SqlJoins joins, SqlWhere where, DataConstraints constraints,
- Function buildRecord) {
- return selectAllFrom(tableName, null, joins, where, null, constraints, buildRecord);
- }
-
- public static DataResult selectAllFrom(String tableName, SqlUtils select, SqlWhere where, SqlUtils orderBy,
- DataConstraints constraints, Function buildRecord) {
- return selectAllFrom(tableName, select, null, where, orderBy, constraints, buildRecord);
- }
-
- public static DataResult selectAllFrom(String tableName, SqlUtils select, SqlJoins joins, SqlWhere where,
- SqlUtils orderBy, DataConstraints constraints, Function buildRecord) {
- // This method creates a TABLE_NAME.* column automatically (but may be deprecated in the future)
- if (select == null) {
- select = DB.SELECT();
- }
- // At the front of the columns, add the table's full columns for backwards compatibility
- select.getValues().add(0, new SqlValue(tableName + ".*"));
- return selectFrom(tableName, select, joins, where, orderBy, constraints, buildRecord);
- }
-
- /**
- * Select records from the database with the specified parameters.
- *
- * @param tableName the name of the table
- * @param columns the columns values
- * @param joins the join clauses
- * @param where the where clause
- * @param orderBy the order by clause
- * @param constraints the data constraints
- * @param buildRecord the function to build an entity from the result set
- * @return the data result containing the records
- */
- public static DataResult selectFrom(String tableName, SqlUtils columns, SqlJoins joins, SqlWhere where,
- SqlUtils orderBy, DataConstraints constraints, Function buildRecord) {
-
- // Determine the max records based on the where conditions
- DataResult dataResult = new DataResult();
-
- StringBuilder joinsSb = createJoins(joins);
- StringBuilder whereSb = createWhereClause(where);
-
- // Count the max records
- if (constraints == null || constraints.useCount()) {
- long recordCount = 0;
- String sqlCount = "SELECT COUNT(*) FROM " + tableName + joinsSb.toString() + whereSb.toString();
- long startQueryTime = System.currentTimeMillis();
- try (Connection connection = getConnection();
- PreparedStatement pst = createPreparedStatement(connection, sqlCount, where);
- ResultSet rs = pst.executeQuery()) {
- if (rs.next()) {
- recordCount = rs.getLong(1);
- }
- } catch (SQLException se) {
- LOG.error(sqlCount);
- LOG.error("Count SQLException: " + se.getMessage());
- }
- if (LOG.isDebugEnabled()) {
- long endQueryTime = System.currentTimeMillis();
- long totalTime = endQueryTime - startQueryTime;
- if (totalTime > LONG_QUERY_MS) {
- LOG.debug(sqlCount);
- LOG.debug("Query took " + totalTime + "ms");
- }
- }
- dataResult.setTotalRecordCount(recordCount);
- if (constraints != null) {
- constraints.setTotalRecordCount(recordCount);
- }
- if (recordCount == 0) {
- List records = new ArrayList<>();
- dataResult.setRecords(records);
- return dataResult;
- }
- }
-
- // Prepare the query
- StringBuilder sb = new StringBuilder();
- sb.append("SELECT ");
- sb.append(createSelectFields(columns));
- sb.append(" FROM ").append(tableName);
- sb.append(joinsSb);
- sb.append(whereSb);
-
- // Apply sorting, paging
- if (constraints != null) {
- if (constraints.hasSortOrder()) {
- sb.append(appendSortClause(orderBy, constraints));
- }
-
- // Apply the constraints
- if (constraints.getPageNumber() > 1) {
- sb.append(" OFFSET ").append((constraints.getPageNumber() - 1) * constraints.getPageSize());
- }
- if (constraints.getPageSize() > 0) {
- sb.append(" LIMIT ").append(constraints.getPageSize());
- }
- }
-
- // Get a connection, execute the query, return the data
- List records = null;
- long startQueryTime = System.currentTimeMillis();
- try (Connection connection = getConnection();
- PreparedStatement pst = createPreparedStatement(connection, sb.toString(), columns, where, orderBy);
- ResultSet rs = pst.executeQuery()) {
- records = new ArrayList<>();
- while (rs.next()) {
- records.add(buildRecord.apply(rs));
- }
- } catch (SQLException se) {
- LOG.debug(sb.toString());
- LOG.error("List SQLException: " + se.getMessage());
- }
- if (LOG.isDebugEnabled()) {
- long endQueryTime = System.currentTimeMillis();
- long totalTime = endQueryTime - startQueryTime;
- if (totalTime > LONG_QUERY_MS) {
- LOG.debug(sb.toString());
- LOG.debug("Query took " + totalTime + "ms");
- }
- }
- dataResult.setRecords(records);
- return dataResult;
- }
-
- private static StringBuilder createAdditionalSelectFields(SqlUtils select) {
- StringBuilder sb = new StringBuilder();
- if (select != null && !select.getValues().isEmpty()) {
- for (SqlValue sqlValue : select.getValues()) {
- sb.append(", ").append(sqlValue.getFieldOrClause());
- }
- }
- return sb;
- }
-
- private static StringBuilder createSelectFields(SqlUtils select) {
- boolean foundFirst = false;
- StringBuilder sb = new StringBuilder();
- if (select != null && !select.getValues().isEmpty()) {
- for (SqlValue sqlValue : select.getValues()) {
- if (foundFirst) {
- sb.append(", ");
- }
- sb.append(sqlValue.getFieldOrClause());
- if (!foundFirst) {
- foundFirst = true;
- }
- }
- }
- return sb;
- }
-
- private static StringBuilder createJoins(SqlJoins joins) {
- StringBuilder joinsSb = new StringBuilder();
- if (joins != null && !joins.getValues().isEmpty()) {
- for (String join : joins.getValues()) {
- joinsSb.append(" ");
- joinsSb.append(join);
- }
- }
- return joinsSb;
- }
-
- private static StringBuilder createWhereClause(SqlWhere where) {
- StringBuilder whereSb = new StringBuilder();
- if (where == null || where.getValues() == null || where.getValues().isEmpty()) {
- return whereSb;
- }
- whereSb.append(" WHERE ");
- boolean isFirst = true;
- for (SqlValue sqlValue : where.getValues()) {
- if (!isFirst) {
- whereSb.append(" AND ");
- }
- // Add the clause, but make sure to isolate the ANDs with ORs
- String clause = sqlValue.getFieldOrClause();
- if (clause.contains(" OR ") && !clause.contains("(")) {
- whereSb.append("(").append(clause).append(")");
- } else {
- whereSb.append(clause);
- }
- if (isFirst) {
- isFirst = false;
- }
- }
- return whereSb;
- }
-
- private static StringBuilder appendSortClause(SqlUtils orderBy, DataConstraints constraints) {
- StringBuilder sb = new StringBuilder(" ORDER BY ");
- if (orderBy != null && !orderBy.getValues().isEmpty()) {
- // Use the SqlValue when a prepared statement is needed
- boolean isFirst = true;
- for (SqlValue sqlValue : orderBy.getValues()) {
- if (!isFirst) {
- sb.append(", ");
- }
- sb.append(sqlValue.getFieldOrClause());
- if (isFirst) {
- isFirst = false;
- }
- }
- } else if (constraints.getColumnsToSortBy() != null) {
- // Use the specified columns
- int idx = 0;
- for (String a : constraints.getColumnsToSortBy()) {
- if (idx > 0) {
- sb.append(", ");
- }
- sb.append(a);
- if (constraints.getSortOrder() != null && idx < constraints.getSortOrder().length) {
- sb.append(" ").append(constraints.getSortOrder()[idx]);
- }
- ++idx;
- }
- } else if (constraints.getDefaultColumnToSortBy() != null) {
- // Use the default columns
- sb.append(constraints.getDefaultColumnToSortBy());
- }
- return sb;
- }
-
- /**
- *
- * @param pst
- * @return if a row count was returned
- * @throws SQLException
- */
- private static boolean executeInsert(PreparedStatement pst) throws SQLException {
- int rowCount = pst.executeUpdate();
- if (rowCount > 0) {
- return true;
- }
- return false;
- }
-
- /**
- *
- * @param pst
- * @return the long value of the generated key
- * @throws SQLException
- */
- private static long executeInsertGetGeneratedKeys(PreparedStatement pst) throws SQLException {
- long id = -1;
- if (pst.executeUpdate() > 0) {
- ResultSet generatedKeys = pst.getGeneratedKeys();
- if (generatedKeys.next()) {
- id = generatedKeys.getLong(1);
- }
- generatedKeys.close();
- }
- if (id == -1) {
- throw new SQLException("Id not found");
- }
- return id;
- }
-
- public static boolean insertIntoWithConflict(String tableName, SqlUtils insertValues, String onConflict) {
- try (Connection connection = getConnection();
- PreparedStatement pst = createPreparedStatementForInsert(connection, tableName, insertValues, null,
- onConflict)) {
- return executeInsert(pst);
- } catch (SQLException se) {
- LOG.error("SQLException: " + se.getMessage());
- }
- return false;
- }
-
- public static long insertInto(String tableName, SqlUtils insertValues, String[] primaryKey) {
- try (Connection connection = getConnection();
- PreparedStatement pst = createPreparedStatementForInsert(connection, tableName, insertValues, primaryKey,
- null)) {
- return executeInsertGetGeneratedKeys(pst);
- } catch (SQLException se) {
- LOG.error("SQLException: " + se.getMessage());
- }
- return -1;
- }
-
- public static long insertInto(Connection connection, String tableName, SqlUtils insertValues, String[] primaryKey)
- throws SQLException {
- try (PreparedStatement pst = createPreparedStatementForInsert(connection, tableName, insertValues, primaryKey,
- null)) {
- return executeInsertGetGeneratedKeys(pst);
- } catch (SQLException se) {
- throw new SQLException("insertInto record failed [" + tableName + "]: " + se.getMessage(), se);
- }
- }
-
- private static PreparedStatement createPreparedStatementForInsert(Connection connection, String tableName,
- SqlUtils insertValues, String[] primaryKey, String onConflict) throws SQLException {
- String SQL_INSERT_QUERY = "INSERT INTO " + tableName + " " +
- createInsertValues(insertValues) + (onConflict != null ? " " + onConflict : "");
- return createPreparedStatement(connection, SQL_INSERT_QUERY, insertValues, primaryKey);
- }
-
- private static String createInsertValues(SqlUtils insertValues) {
- StringBuilder fieldNamesSb = new StringBuilder();
- StringBuilder valuesSb = new StringBuilder();
- boolean isFirst = true;
- for (SqlValue sqlValue : insertValues.getValues()) {
- if (!isFirst) {
- fieldNamesSb.append(", ");
- valuesSb.append(", ");
- }
- fieldNamesSb.append(sqlValue.getFieldOrClause());
- if (sqlValue.hasValue()) {
- valuesSb.append("?");
- if (sqlValue.getCastType() == SqlValue.JSONB_TYPE) {
- valuesSb.append("::jsonb");
- }
- } else {
- valuesSb.append(sqlValue.getStringValue());
- }
- if (isFirst) {
- isFirst = false;
- }
- }
- return "(" + fieldNamesSb.toString() + ") VALUES (" + valuesSb.toString() + ")";
- }
-
- public static boolean update(String tableName, SqlUtils updateValues, SqlWhere where) {
- try (Connection connection = getConnection();
- PreparedStatement pst = createPreparedStatementForUpdate(connection, tableName, updateValues, where)) {
- if (pst.executeUpdate() > 0) {
- return true;
- }
- } catch (SQLException se) {
- LOG.error("Update SQLException: [" + tableName + "]: " + se.getMessage());
- }
- return false;
- }
-
- public static boolean update(Connection connection, String tableName, SqlUtils updateValues, SqlWhere where)
- throws SQLException {
- try (PreparedStatement pst = createPreparedStatementForUpdate(connection, tableName, updateValues, where)) {
- if (pst.executeUpdate() > 0) {
- return true;
- }
- } catch (SQLException se) {
- throw new SQLException("Update SQLException: [" + tableName + "]: " + se.getMessage(), se);
- }
- return false;
- }
-
- public static boolean update(String tableName, String statement, SqlWhere where) {
- try (Connection connection = getConnection();
- PreparedStatement pst = createPreparedStatementForUpdate(connection, tableName, statement, where)) {
- if (pst.executeUpdate() > 0) {
- return true;
- }
- } catch (SQLException se) {
- LOG.error("Update SQLException: [" + tableName + "]: " + se.getMessage());
- }
- return false;
- }
-
- private static PreparedStatement createPreparedStatementForUpdate(Connection connection, String tableName,
- String statement, SqlWhere where) throws SQLException {
- if (statement == null) {
- return null;
- }
- String SQL_UPDATE_QUERY = "UPDATE " + tableName +
- " SET " +
- statement +
- createWhereClause(where);
- //LOG.debug("SQL_UPDATE_QUERY: " + SQL_UPDATE_QUERY);
- return createPreparedStatement(connection, SQL_UPDATE_QUERY, where);
- }
-
- private static PreparedStatement createPreparedStatementForUpdate(Connection connection, String tableName,
- SqlUtils updateValues, SqlWhere where) throws SQLException {
- if (updateValues == null) {
- return null;
- }
- String SQL_UPDATE_QUERY = "UPDATE " + tableName +
- " SET " +
- createUpdateValues(updateValues) +
- createWhereClause(where);
- if (LOG.isDebugEnabled()) {
- LOG.debug("SQL_UPDATE_QUERY: " + SQL_UPDATE_QUERY);
- }
- return createPreparedStatement(connection, SQL_UPDATE_QUERY, updateValues, where, null);
- }
-
- private static PreparedStatement createPreparedStatement(Connection connection, String sqlQuery,
- SqlUtils selectOrUpdate, SqlWhere where, SqlUtils orderBy) throws SQLException {
- PreparedStatement pst = connection.prepareStatement(sqlQuery);
- int fieldIdx = prepareValues(connection, pst, selectOrUpdate);
- fieldIdx = prepareValues(connection, pst, where, fieldIdx);
- prepareValues(connection, pst, orderBy, fieldIdx);
- return pst;
- }
-
- private static String createUpdateValues(SqlUtils sqlUtils) {
- StringBuilder fieldNamesSb = new StringBuilder();
- boolean isFirst = true;
- for (SqlValue sqlValue : sqlUtils.getValues()) {
- if (!isFirst) {
- fieldNamesSb.append(", ");
- }
- if (sqlValue.hasValue()) {
- String updateString = sqlValue.getFieldOrClause();
- fieldNamesSb.append(updateString);
- if (!updateString.contains("?")) {
- fieldNamesSb.append(" = ?");
- }
- if (sqlValue.getCastType() == SqlValue.JSONB_TYPE) {
- fieldNamesSb.append("::jsonb");
- }
- } else {
- if (sqlValue.getFieldOrClause().contains("=")) {
- fieldNamesSb.append(sqlValue.getFieldOrClause());
- } else {
- fieldNamesSb.append(sqlValue.getFieldOrClause()).append(" = ").append(sqlValue.getStringValue());
- }
- }
- if (isFirst) {
- isFirst = false;
- }
- }
- return fieldNamesSb.toString();
- }
-
- public static int deleteFrom(String tableName, SqlWhere where) {
- try (Connection connection = getConnection();
- PreparedStatement pst = createPreparedStatementForDelete(connection, tableName, where)) {
- return pst.executeUpdate();
- } catch (SQLException se) {
- LOG.error("SQLException deleteFrom failed: " + se.getMessage());
- }
- return -1;
- }
-
- public static int deleteFrom(Connection connection, String tableName, SqlWhere where) throws SQLException {
- try (PreparedStatement pst = createPreparedStatementForDelete(connection, tableName, where)) {
- return pst.executeUpdate();
- } catch (SQLException se) {
- throw new SQLException("deleteFrom failed [" + tableName + "] " + se.getMessage(), se);
- }
- }
-
- private static PreparedStatement createPreparedStatementForDelete(Connection connection, String tableName,
- SqlWhere where) throws SQLException {
-
- // Construct the where clause
- StringBuilder whereSb = createWhereClause(where);
-
- // Prepare the query
- StringBuilder sb = new StringBuilder();
- sb.append("DELETE FROM ").append(tableName);
- sb.append(whereSb);
-
- return createPreparedStatement(connection, sb.toString(), where);
- }
-
- public static long getLong(ResultSet rs, String field, long valueWhenNull) throws SQLException {
- long value = rs.getLong(field);
- if (rs.wasNull()) {
- return valueWhenNull;
- }
- return value;
- }
-
- public static double getDouble(ResultSet rs, String field, double valueWhenNull) throws SQLException {
- double value = rs.getDouble(field);
- if (rs.wasNull()) {
- return valueWhenNull;
- }
- return value;
- }
-
- public static int getInt(ResultSet rs, String field, int valueWhenNull) throws SQLException {
- int value = rs.getInt(field);
- if (rs.wasNull()) {
- return valueWhenNull;
- }
- return value;
- }
-
- public static String getPeriod(ResultSet rs, String field) throws SQLException {
- PGInterval pgi = (PGInterval) rs.getObject(field);
- if (rs.wasNull()) {
- return null;
- }
- // convert to ISO 8601
- StringBuilder sb = new StringBuilder("P");
- if (pgi.getYears() > 0) {
- sb.append(pgi.getYears()).append("Y");
- }
- if (pgi.getMonths() > 0) {
- sb.append(pgi.getMonths()).append("M");
- }
- if (pgi.getDays() > 0) {
- sb.append(pgi.getDays()).append("D");
- }
- // Determine if just the period is shown
- if (sb.length() > 1 && pgi.getHours() == 0 && pgi.getMinutes() == 0 && pgi.getWholeSeconds() == 0) {
- return sb.toString();
- }
- // Show the time, even if it's 0
- sb.append("T");
- boolean foundTime = false;
- if (pgi.getHours() > 0) {
- foundTime = true;
- sb.append(pgi.getHours()).append("H");
- }
- if (pgi.getMinutes() > 0) {
- foundTime = true;
- sb.append(pgi.getMinutes()).append("M");
- }
- // Show 0 if there's no other time
- if (!foundTime || pgi.getWholeSeconds() > 0) {
- sb.append(pgi.getWholeSeconds()).append("S");
- }
- return sb.toString();
- }
-
- public static void exportToCsvAllFrom(String tableName, SqlUtils selectFields, SqlJoins joins, SqlWhere where,
- SqlUtils orderBy, DataConstraints constraints, File file) {
-
- StringBuilder joinsSb = createJoins(joins);
- StringBuilder whereSb = createWhereClause(where);
-
- // Prepare the query
- StringBuilder sb = new StringBuilder();
- if (selectFields == null) {
- sb.append("SELECT ").append(tableName).append(".*");
- } else {
- sb.append("SELECT ").append(createSelectFields(selectFields));
- }
- sb.append(" FROM ").append(tableName);
- sb.append(joinsSb);
- sb.append(whereSb);
-
- // Apply sorting, paging
- if (constraints != null) {
- if (constraints.hasSortOrder()) {
- sb.append(appendSortClause(orderBy, constraints));
- }
-
- // Apply the constraints
- if (constraints.getPageNumber() > 1) {
- sb.append(" OFFSET ").append((constraints.getPageNumber() - 1) * constraints.getPageSize());
- }
- if (constraints.getPageSize() > 0) {
- sb.append(" LIMIT ").append(constraints.getPageSize());
- }
- }
-
- // Prepare the writer
- CsvWriterSettings writerSettings = new CsvWriterSettings();
- writerSettings.getFormat().setLineSeparator("\r\n");
- writerSettings.getFormat().setDelimiter(',');
- writerSettings.setQuoteAllFields(true);
- writerSettings.setHeaderWritingEnabled(true);
- // writerSettings.setHeaders("email", "created", "master_unsub", "unsubscribed", "is_valid");
- CsvRoutines routines = new CsvRoutines(writerSettings);
-
- // Get a connection, execute the query, return the data
- long startQueryTime = System.currentTimeMillis();
- try (Connection connection = getConnection();
- PreparedStatement pst = createPreparedStatement(connection, sb.toString(), selectFields, where, orderBy);
- ResultSet rs = pst.executeQuery()) {
- // Stream the result set to the file
- routines.write(rs, file);
- } catch (SQLException se) {
- LOG.debug(sb.toString());
- LOG.error("Export SQLException", se);
- }
- if (LOG.isDebugEnabled()) {
- long endQueryTime = System.currentTimeMillis();
- long totalTime = endQueryTime - startQueryTime;
- if (totalTime > LONG_QUERY_MS) {
- LOG.debug(sb.toString());
- LOG.debug("Query took " + totalTime + "ms");
- }
- }
- }
-
- public static boolean hasColumn(ResultSet rs, String column) {
- try {
- rs.findColumn(column);
- return true;
- } catch (SQLException ex) {
- return false;
- }
- }
-}
diff --git a/src/main/java/com/simisinc/platform/infrastructure/database/DataConstraints.java b/src/main/java/com/simisinc/platform/infrastructure/database/DataConstraints.java
deleted file mode 100644
index 6ee9d087a..000000000
--- a/src/main/java/com/simisinc/platform/infrastructure/database/DataConstraints.java
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- * Copyright 2022 SimIS Inc. (https://www.simiscms.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.simisinc.platform.infrastructure.database;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * The record paging and column sorting context
- *
- * @author matt rajkowski
- * @created 1/22/19 12:12 PM
- */
-public class DataConstraints implements Serializable {
-
- private static final long serialVersionUID = 8345648404174283569L;
-
- private int pageNumber = 1;
- private int pageSize = -1;
- // Helpers set by the data source
- private long totalRecordCount = -1L;
- private int maxPageNumber = 1;
-
- private String defaultColumnToSortBy = null;
- private String[] columnsToSortBy = null;
- private String[] sortOrder = null;
-
- private boolean useCount = true;
-
- public DataConstraints() {
- }
-
- public DataConstraints(int pageNumber, int pageSize) {
- this.pageNumber = pageNumber;
- this.pageSize = pageSize;
- }
-
- public DataConstraints(int pageNumber, int pageSize, String columnToSortBy) {
- this.pageNumber = pageNumber;
- this.pageSize = pageSize;
- setColumnToSortBy(columnToSortBy, null);
- }
-
- public DataConstraints(int pageNumber, int pageSize, String columnToSortBy, String ascOrDesc) {
- this.pageNumber = pageNumber;
- this.pageSize = pageSize;
- setColumnToSortBy(columnToSortBy, ascOrDesc);
- }
-
- public int getPageNumber() {
- return pageNumber;
- }
-
- public void setPageNumber(int pageNumber) {
- this.pageNumber = pageNumber;
- }
-
- public String getPageNumberAsString() {
- return String.valueOf(pageNumber);
- }
-
- public int getPageSize() {
- return pageSize;
- }
-
- public void setPageSize(int pageSize) {
- this.pageSize = pageSize;
- }
-
- public long getTotalRecordCount() {
- return totalRecordCount;
- }
-
- public void setTotalRecordCount(long totalRecordCount) {
- this.totalRecordCount = totalRecordCount;
- if (totalRecordCount > 0 && pageSize > 0) {
- maxPageNumber = (int) (totalRecordCount + pageSize - 1) / pageSize;
- if (maxPageNumber < 1) {
- maxPageNumber = 1;
- }
- }
- }
-
- public int getMaxPageNumber() {
- return maxPageNumber;
- }
-
- public String getDefaultColumnToSortBy() {
- return defaultColumnToSortBy;
- }
-
- /**
- * Used by the repository objects to define a define
- *
- * @param columnToSortBy
- * @return
- */
- public DataConstraints setDefaultColumnToSortBy(String columnToSortBy) {
- this.defaultColumnToSortBy = columnToSortBy;
- return this;
- }
-
- /**
- * Used by the application to override the default sort
- *
- * @param name
- */
- public void setColumnToSortBy(String name) {
- columnsToSortBy = new String[]{name};
- }
-
- /**
- * Used by the application to override the default sort
- *
- * @param name
- * @param ascOrDesc
- */
- public void setColumnToSortBy(String name, String ascOrDesc) {
- columnsToSortBy = new String[]{name};
- if ("desc".equalsIgnoreCase(ascOrDesc)) {
- sortOrder = new String[]{"desc"};
- }
- }
-
- public String[] getColumnsToSortBy() {
- return columnsToSortBy;
- }
-
- /**
- * Used by the application to override the default sort
- *
- * @param columnsToSortBy
- */
- public void setColumnsToSortBy(String[] columnsToSortBy) {
- this.columnsToSortBy = columnsToSortBy;
- }
-
- public String[] getSortOrder() {
- return sortOrder;
- }
-
- public void setSortOrder(String[] sortOrder) {
- this.sortOrder = sortOrder;
- }
-
- public boolean containsColumnToSortBy(String name) {
- if (columnsToSortBy == null) {
- return false;
- }
- for (String column : columnsToSortBy) {
- if (name.equals(column)) {
- return true;
- }
- }
- return false;
- }
-
- public boolean hasSortOrder() {
- return defaultColumnToSortBy != null || columnsToSortBy != null;
- }
-
- public List getPageList() {
- int current = pageNumber,
- last = maxPageNumber,
- delta = 2,
- left = current - delta,
- right = current + delta + 1;
- List range = new ArrayList<>();
- List rangeWithDots = new ArrayList<>();
- int l = 0;
- for (int i = 1; i <= last; i++) {
- if (i == 1 || i == last || i >= left && i < right) {
- range.add("" + i);
- }
- }
- for (String i : range) {
- if (l > 0) {
- if (Integer.parseInt(i) - l == 2) {
- rangeWithDots.add("" + (l + 1));
- } else if (Integer.parseInt(i) - l != 1) {
- rangeWithDots.add("...");
- }
- }
- rangeWithDots.add(i);
- l = Integer.parseInt(i);
- }
- return rangeWithDots;
- }
-
- public boolean useCount() {
- return useCount;
- }
-
- public DataConstraints setUseCount(boolean useCount) {
- this.useCount = useCount;
- return this;
- }
-}
diff --git a/src/main/java/com/simisinc/platform/infrastructure/database/DataResult.java b/src/main/java/com/simisinc/platform/infrastructure/database/DataResult.java
deleted file mode 100644
index 41419ff19..000000000
--- a/src/main/java/com/simisinc/platform/infrastructure/database/DataResult.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright 2022 SimIS Inc. (https://www.simiscms.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.simisinc.platform.infrastructure.database;
-
-import com.simisinc.platform.domain.model.Entity;
-
-import java.io.Serializable;
-import java.util.List;
-
-/**
- * Encapsulates the records being returned and the record count for paging
- *
- * @author matt rajkowski
- * @created 1/22/19 12:12 PM
- */
-public class DataResult implements Serializable {
-
- private static final long serialVersionUID = 8345648404174283569L;
-
- private List extends Entity> records = null;
- private long totalRecordCount = -1;
-
- public DataResult() {
- }
-
- public List extends Entity> getRecords() {
- return records;
- }
-
- public void setRecords(List extends Entity> records) {
- this.records = records;
- }
-
- public boolean hasRecords() {
- return records != null && !records.isEmpty();
- }
-
- public long getTotalRecordCount() {
- return totalRecordCount;
- }
-
- public void setTotalRecordCount(long totalRecordCount) {
- this.totalRecordCount = totalRecordCount;
- }
-}
diff --git a/src/main/java/com/simisinc/platform/infrastructure/database/SqlJoins.java b/src/main/java/com/simisinc/platform/infrastructure/database/SqlJoins.java
deleted file mode 100644
index 85af52f43..000000000
--- a/src/main/java/com/simisinc/platform/infrastructure/database/SqlJoins.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright 2022 SimIS Inc. (https://www.simiscms.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.simisinc.platform.infrastructure.database;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * A list of joins
- *
- * @author matt rajkowski
- * @created 1/22/19 12:12 PM
- */
-public class SqlJoins {
-
- private List values = new ArrayList<>();
-
- public SqlJoins() {
- }
-
- public SqlJoins add(String join) {
- values.add(join);
- return this;
- }
-
- public List getValues() {
- return values;
- }
-
-}
diff --git a/src/main/java/com/simisinc/platform/infrastructure/database/SqlUtils.java b/src/main/java/com/simisinc/platform/infrastructure/database/SqlUtils.java
deleted file mode 100644
index 64b1ee4a8..000000000
--- a/src/main/java/com/simisinc/platform/infrastructure/database/SqlUtils.java
+++ /dev/null
@@ -1,220 +0,0 @@
-/*
- * Copyright 2022 SimIS Inc. (https://www.simiscms.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.simisinc.platform.infrastructure.database;
-
-import com.simisinc.platform.presentation.controller.DataConstants;
-
-import java.math.BigDecimal;
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * A list of insert/update/where properties and values
- *
- * @author matt rajkowski
- * @created 1/22/19 12:12 PM
- */
-public class SqlUtils {
-
- private List values = new ArrayList<>();
-
- public SqlUtils add(SqlValue object) {
- values.add(object);
- return this;
- }
-
- public SqlUtils add(String name) {
- values.add(new SqlValue(name));
- return this;
- }
-
- public SqlUtils addNames(String... names) {
- if (names.length > 0) {
- for (String name : names) {
- values.add(new SqlValue(name));
- }
- }
- return this;
- }
-
- public SqlUtils add(String name, String value) {
- values.add(new SqlValue(name, value));
- return this;
- }
-
- public SqlUtils add(String name, String[] value) {
- values.add(new SqlValue(name, value));
- return this;
- }
-
- public SqlUtils add(String name, String value, int maxLength) {
- if (value != null && value.length() > maxLength) {
- value = value.substring(0, maxLength);
- }
- values.add(new SqlValue(name, value));
- return this;
- }
-
- public SqlUtils addIfExists(String name, String value) {
- if (value != null) {
- values.add(new SqlValue(name, value));
- }
- return this;
- }
-
- public SqlUtils addIfExists(String name, String value, int maxLength) {
- if (value != null) {
- if (value.length() > maxLength) {
- value = value.substring(0, maxLength);
- }
- values.add(new SqlValue(name, value));
- }
- return this;
- }
-
- public SqlUtils add(String name, long value) {
- values.add(new SqlValue(name, value));
- return this;
- }
-
- public SqlUtils add(String name, Long[] value) {
- values.add(new SqlValue(name, value));
- return this;
- }
-
- public SqlUtils addIfExists(String name, long value, long emptyValue) {
- if (value != emptyValue) {
- values.add(new SqlValue(name, value));
- }
- return this;
- }
-
- public SqlUtils add(String name, long value, long nullValue) {
- if (value == nullValue) {
- values.add(new SqlValue(name, value, true));
- } else {
- values.add(new SqlValue(name, value));
- }
- return this;
- }
-
- public SqlUtils add(String name, int value) {
- values.add(new SqlValue(name, value));
- return this;
- }
-
- public SqlUtils addIfExists(String name, int value, int emptyValue) {
- if (value != emptyValue) {
- values.add(new SqlValue(name, value));
- }
- return this;
- }
-
- public SqlUtils add(String name, int value, int nullValue) {
- if (value == nullValue) {
- values.add(new SqlValue(name, value, true));
- } else {
- values.add(new SqlValue(name, value));
- }
- return this;
- }
-
- public SqlUtils add(String name, double value) {
- values.add(new SqlValue(name, value));
- return this;
- }
-
- public SqlUtils addIfExists(String name, double value, double emptyValue) {
- if (value != emptyValue) {
- values.add(new SqlValue(name, value));
- }
- return this;
- }
-
- public SqlUtils add(String name, double value, double nullValue) {
- if (value == nullValue) {
- values.add(new SqlValue(name, value, true));
- } else {
- values.add(new SqlValue(name, value));
- }
- return this;
- }
-
- public SqlUtils addWhen(String name, boolean value, boolean checkValue) {
- if (value == checkValue) {
- values.add(new SqlValue(name, value));
- }
- return this;
- }
-
- public SqlUtils addIfDataConstantExists(String name, int value) {
- if (value != DataConstants.UNDEFINED) {
- add(name, value == DataConstants.TRUE);
- }
- return this;
- }
-
- public SqlUtils add(String name, Timestamp value) {
- values.add(new SqlValue(name, value));
- return this;
- }
-
- public SqlUtils add(String name, Timestamp[] value) {
- values.add(new SqlValue(name, value));
- return this;
- }
-
- public SqlUtils add(String name, Object[] value) {
- values.add(new SqlValue(name, value));
- return this;
- }
-
- public SqlUtils addIfExists(String name, Timestamp value) {
- if (value != null) {
- values.add(new SqlValue(name, value));
- }
- return this;
- }
-
- public SqlUtils add(String name, BigDecimal value) {
- values.add(new SqlValue(name, value));
- return this;
- }
-
- public SqlUtils addIfExists(String name, BigDecimal value) {
- if (value != null) {
- values.add(new SqlValue(name, value));
- }
- return this;
- }
-
- public SqlUtils add(String name, boolean value) {
- values.add(new SqlValue(name, value));
- return this;
- }
-
- public SqlUtils addGeomPoint(String name, double latitude, double longitude) {
- values.add(new SqlValue(name, SqlValue.GEOM_TYPE, latitude, longitude));
- return this;
- }
-
- public List getValues() {
- return values;
- }
-
-}
diff --git a/src/main/java/com/simisinc/platform/infrastructure/database/SqlValue.java b/src/main/java/com/simisinc/platform/infrastructure/database/SqlValue.java
deleted file mode 100644
index 9d844ff2f..000000000
--- a/src/main/java/com/simisinc/platform/infrastructure/database/SqlValue.java
+++ /dev/null
@@ -1,253 +0,0 @@
-/*
- * Copyright 2026 Matt Rajkowski (https://github.com/rajkowski)
- * Copyright 2022 SimIS Inc. (https://www.simiscms.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.simisinc.platform.infrastructure.database;
-
-import java.math.BigDecimal;
-import java.sql.Timestamp;
-import java.sql.Types;
-
-import org.apache.commons.lang3.StringUtils;
-
-/**
- * Represents a database value used in insert/update statements and where clause
- *
- * @author matt rajkowski
- * @created 1/22/19 12:12 PM
- */
-public class SqlValue {
-
- public static final int GEOM_TYPE = 2018052314;
- public static final int JSONB_TYPE = 2018053112;
- public static final int INTERVAL_TYPE = 2022080914;
- public static final int AS_IS = 2023032612;
-
- // Name/condition/field
- private String field;
- private int sqlType;
- private int castType = -1;
- private boolean isNull = false;
- private boolean hasValue = true;
-
- // Value by Type
- private String stringValue;
- private String[] stringValues;
- private Long longValue;
- private Long[] longValues;
- private Integer intValue;
- private Double doubleValue;
- private Timestamp timestampValue;
- private Timestamp[] timestampValues;
- private BigDecimal bigDecimalValue;
- private Boolean booleanValue;
- private Object[] objectValues;
-
- public SqlValue(String fieldOrClause) {
- this.field = fieldOrClause;
- this.hasValue = false;
- }
-
- public SqlValue(String fieldOrClause, String stringValue) {
- this.field = fieldOrClause;
- this.stringValue = stringValue;
- this.sqlType = Types.VARCHAR;
- }
-
- public SqlValue(String fieldOrClause, String[] stringValues) {
- this.field = fieldOrClause;
- this.stringValues = stringValues;
- this.sqlType = Types.VARCHAR;
- }
-
- public SqlValue(String fieldOrClause, String[] stringValues, int sqlType) {
- this.field = fieldOrClause;
- this.stringValues = stringValues;
- this.sqlType = sqlType;
- }
-
- public SqlValue(String fieldOrClause, long longValue) {
- this.field = fieldOrClause;
- this.longValue = longValue;
- this.sqlType = Types.BIGINT;
- }
-
- public SqlValue(String fieldOrClause, Long[] longValues) {
- this.field = fieldOrClause;
- this.longValues = longValues;
- this.sqlType = Types.BIGINT;
- }
-
- public SqlValue(String fieldOrClause, long longValue, boolean isNull) {
- this.field = fieldOrClause;
- this.longValue = longValue;
- this.sqlType = Types.BIGINT;
- this.isNull = isNull;
- }
-
- public SqlValue(String fieldOrClause, int intValue) {
- this.field = fieldOrClause;
- this.intValue = intValue;
- this.sqlType = Types.INTEGER;
- }
-
- public SqlValue(String fieldOrClause, int intValue, boolean isNull) {
- this.field = fieldOrClause;
- this.intValue = intValue;
- this.sqlType = Types.INTEGER;
- this.isNull = isNull;
- }
-
- public SqlValue(String fieldOrClause, double doubleValue) {
- this.field = fieldOrClause;
- this.doubleValue = doubleValue;
- this.sqlType = Types.DOUBLE;
- }
-
- public SqlValue(String fieldOrClause, double doubleValue, boolean isNull) {
- this.field = fieldOrClause;
- this.doubleValue = doubleValue;
- this.sqlType = Types.DOUBLE;
- this.isNull = isNull;
- }
-
- public SqlValue(String fieldOrClause, Timestamp timestampValue) {
- this.field = fieldOrClause;
- this.timestampValue = timestampValue;
- this.sqlType = Types.TIMESTAMP;
- }
-
- public SqlValue(String fieldOrClause, Timestamp[] timestampValues) {
- this.field = fieldOrClause;
- this.timestampValues = timestampValues;
- this.sqlType = Types.TIMESTAMP;
- }
-
- public SqlValue(String fieldOrClause, BigDecimal bigDecimalValue) {
- this.field = fieldOrClause;
- this.bigDecimalValue = bigDecimalValue;
- this.sqlType = Types.NUMERIC;
- }
-
- public SqlValue(String fieldOrClause, Boolean booleanValue) {
- this.field = fieldOrClause;
- this.booleanValue = booleanValue;
- this.sqlType = Types.BOOLEAN;
- }
-
- public SqlValue(String fieldName, int castType, String value) {
- this.field = fieldName;
- this.stringValue = value;
- this.castType = castType;
- if (castType == JSONB_TYPE) {
- this.sqlType = Types.VARCHAR;
- } else if (castType == INTERVAL_TYPE) {
- this.sqlType = Types.OTHER;
- if (StringUtils.isBlank(value)) {
- stringValue = null;
- isNull = true;
- }
- } else if (castType == AS_IS) {
- this.hasValue = false;
- }
- }
-
- public SqlValue(String fieldOrClause, Object[] objectValues) {
- this.field = fieldOrClause;
- this.objectValues = objectValues;
- this.sqlType = Types.JAVA_OBJECT;
- }
-
- public SqlValue(String fieldName, int type, double latitude, double longitude) {
- this.field = fieldName;
- if (type == GEOM_TYPE) {
- if (latitude == 0 && longitude == 0) {
- this.stringValue = "NULL";
- } else {
- this.stringValue = "ST_SetSRID(ST_MakePoint(" + latitude + ", " + longitude + "), 4326)";
- }
- }
- this.hasValue = false;
- }
-
- public String getFieldOrClause() {
- return field;
- }
-
- public String getStringValue() {
- return stringValue;
- }
-
- public String[] getStringValues() {
- return stringValues;
- }
-
- public Long getLongValue() {
- return longValue;
- }
-
- public Long[] getLongValues() {
- return longValues;
- }
-
- public Integer getIntValue() {
- return intValue;
- }
-
- public Double getDoubleValue() {
- return doubleValue;
- }
-
- public Timestamp getTimestampValue() {
- return timestampValue;
- }
-
- public Timestamp[] getTimestampValues() {
- return timestampValues;
- }
-
- public Object[] getObjectValues() {
- return objectValues;
- }
-
- public BigDecimal getBigDecimalValue() {
- return bigDecimalValue;
- }
-
- public Boolean getBooleanValue() {
- return booleanValue;
- }
-
- public int getSqlType() {
- return sqlType;
- }
-
- public boolean isNull() {
- return isNull;
- }
-
- public void setNull(boolean aNull) {
- isNull = aNull;
- }
-
- public boolean hasValue() {
- return hasValue;
- }
-
- public int getCastType() {
- return castType;
- }
-}
diff --git a/src/main/java/com/simisinc/platform/infrastructure/database/SqlWhere.java b/src/main/java/com/simisinc/platform/infrastructure/database/SqlWhere.java
deleted file mode 100644
index f6fd4a65f..000000000
--- a/src/main/java/com/simisinc/platform/infrastructure/database/SqlWhere.java
+++ /dev/null
@@ -1,324 +0,0 @@
-/*
- * Copyright 2025-2026 Matt Rajkowski (https://github.com/rajkowski)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.simisinc.platform.infrastructure.database;
-
-import java.math.BigDecimal;
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.commons.lang3.StringUtils;
-
-import com.simisinc.platform.presentation.controller.DataConstants;
-
-/**
- * A list of where properties and values, using function names similar to SQL syntax
- *
- * @author matt rajkowski
- * @created 2/15/2025 3:11 PM
- */
-public class SqlWhere {
-
- public static final String AND_OPERATOR = "AND";
- public static final String OR_OPERATOR = "OR";
- public static final String NOT_AND_OPERATOR = "NOT AND";
- public static final String NOT_OR_OPERATOR = "OR";
-
- private List values = new ArrayList<>();
-
- public SqlWhere AND(SqlValue object) {
- values.add(object);
- return this;
- }
-
- public SqlWhere AND(String name) {
- values.add(new SqlValue(name));
- return this;
- }
-
- public SqlWhere AND(String name, String value) {
- values.add(new SqlValue(name, value));
- return this;
- }
-
- public SqlWhere AND(String name, String[] value) {
- values.add(new SqlValue(name, value));
- return this;
- }
-
- public SqlWhere AND(String name, String[] value, int sqlType) {
- values.add(new SqlValue(name, value, sqlType));
- return this;
- }
-
- public SqlWhere andAddIfHasValue(String name, String value) {
- if (value != null) {
- values.add(new SqlValue(name, value));
- }
- return this;
- }
-
- public SqlWhere andAddIfHasValue(String name, String value, int maxLength) {
- if (value != null) {
- if (value.length() > maxLength) {
- value = value.substring(0, maxLength);
- }
- values.add(new SqlValue(name, value));
- }
- return this;
- }
-
- public SqlWhere AND(String name, long value) {
- values.add(new SqlValue(name, value));
- return this;
- }
-
- public SqlWhere AND(String name, Long[] value) {
- values.add(new SqlValue(name, value));
- return this;
- }
-
- public SqlWhere andAddIfHasValue(String name, long value, long emptyValue) {
- if (value != emptyValue) {
- values.add(new SqlValue(name, value));
- }
- return this;
- }
-
- public SqlWhere AND(String name, long value, long nullValue) {
- if (value == nullValue) {
- values.add(new SqlValue(name, value, true));
- } else {
- values.add(new SqlValue(name, value));
- }
- return this;
- }
-
- public SqlWhere AND(String name, int value) {
- values.add(new SqlValue(name, value));
- return this;
- }
-
- public SqlWhere andAddIfHasValue(String name, int value, int emptyValue) {
- if (value != emptyValue) {
- values.add(new SqlValue(name, value));
- }
- return this;
- }
-
- public SqlWhere AND(String name, int value, int nullValue) {
- if (value == nullValue) {
- values.add(new SqlValue(name, value, true));
- } else {
- values.add(new SqlValue(name, value));
- }
- return this;
- }
-
- public SqlWhere AND(String name, double value) {
- values.add(new SqlValue(name, value));
- return this;
- }
-
- public SqlWhere andAddIfHasValue(String name, double value, double emptyValue) {
- if (value != emptyValue) {
- values.add(new SqlValue(name, value));
- }
- return this;
- }
-
- public SqlWhere AND(String name, double value, double nullValue) {
- if (value == nullValue) {
- values.add(new SqlValue(name, value, true));
- } else {
- values.add(new SqlValue(name, value));
- }
- return this;
- }
-
- public SqlWhere andAddWhen(String name, boolean value, boolean checkValue) {
- if (value == checkValue) {
- values.add(new SqlValue(name, value));
- }
- return this;
- }
-
- public SqlWhere andAddIfDataConstantExists(String name, int value) {
- if (value != DataConstants.UNDEFINED) {
- AND(name, value == DataConstants.TRUE);
- }
- return this;
- }
-
- public SqlWhere AND(String name, Timestamp value) {
- values.add(new SqlValue(name, value));
- return this;
- }
-
- public SqlWhere AND(String name, Timestamp[] value) {
- values.add(new SqlValue(name, value));
- return this;
- }
-
- public SqlWhere AND(String name, Object[] value) {
- values.add(new SqlValue(name, value));
- return this;
- }
-
- public SqlWhere andAddIfHasValue(String name, Timestamp value) {
- if (value != null) {
- values.add(new SqlValue(name, value));
- }
- return this;
- }
-
- public SqlWhere AND(String name, BigDecimal value) {
- values.add(new SqlValue(name, value));
- return this;
- }
-
- public SqlWhere andAddIfHasValue(String name, BigDecimal value) {
- if (value != null) {
- values.add(new SqlValue(name, value));
- }
- return this;
- }
-
- public SqlWhere AND(String name, boolean value) {
- values.add(new SqlValue(name, value));
- return this;
- }
-
- public SqlWhere andGeomPoint(String name, double latitude, double longitude) {
- values.add(new SqlValue(name, SqlValue.GEOM_TYPE, latitude, longitude));
- return this;
- }
-
- public List getValues() {
- return values;
- }
-
- public SqlWhere AND(String jsonbColumnName, String[] arrayValues, String operator) {
- String whereStatement = arrayToSqlStatementList(jsonbColumnName, arrayValues, operator);
- if (StringUtils.isBlank(whereStatement)) {
- return this;
- }
-
- // Each placeholder is cast to jsonb, so each value must be its own single-element JSON array
- String[] jsonArrayValues = new String[arrayValues.length];
- for (int i = 0; i < arrayValues.length; i++) {
- jsonArrayValues[i] = toJsonArrayLiteral(arrayValues[i]);
- }
-
- values.add(new SqlValue(whereStatement, jsonArrayValues));
- return this;
- }
-
- /**
- * Wraps a single string value as a one-element JSON array literal, escaping characters
- * as required by the JSON spec, so it can be bound to a {@code ?::jsonb} placeholder
- * used in a {@code @>} containment check (e.g. {@code value} → {@code ["value"]}).
- *
- * @param value the value to wrap
- * @return a JSON array literal containing the single value
- */
- private static String toJsonArrayLiteral(String value) {
- StringBuilder sql = new StringBuilder("[\"");
- if (value != null) {
- for (int i = 0; i < value.length(); i++) {
- char c = value.charAt(i);
- switch (c) {
- case '"':
- sql.append("\\\"");
- break;
- case '\\':
- sql.append("\\\\");
- break;
- case '\n':
- sql.append("\\n");
- break;
- case '\r':
- sql.append("\\r");
- break;
- case '\t':
- sql.append("\\t");
- break;
- default:
- if (c < 0x20) {
- sql.append(String.format("\\u%04x", (int) c));
- } else {
- sql.append(c);
- }
- }
- }
- }
- sql.append("\"]");
- return sql.toString();
- }
-
- /**
- * Builds a parameterized SQL condition for filtering a JSONB array column against multiple values.
- *
- * PostgreSQL has no single operator to test JSONB array containment against a list of values
- * using ANY()/ALL() semantics, so this method expands the values into individual
- * {@code sqlColumn @> ?::jsonb} containment checks and joins them with the given logical
- * operator, wrapped in parenthesis:
- *
- * - {@code "OR"} → {@code (sqlColumn @> ?::jsonb OR sqlColumn @> ?::jsonb)}
- * - any other value (including null) → defaults to AND
- *
- *
- *
- * The returned condition contains one {@code ?} placeholder per value, in order. The caller
- * is responsible for binding each value (individually wrapped as a JSON array, e.g.
- * {@code toJsonArray(new String[]{value})}) to its corresponding placeholder, such as via
- * {@code SqlWhere.AND(condition, Object[] values)}.
- *
- * @param sqlColumn the JSONB column to filter (may include a table prefix, e.g. "files.tags")
- * @param values the values to match against the JSONB column
- * @param operator logical operator used to combine conditions ("AND" or "OR")
- * @return a parenthesized SQL condition string with one "?" placeholder per value, or {@code null}
- * if {@code sqlColumn} is blank or {@code values} is null or empty
- */
- private static String arrayToSqlStatementList(String jsonbColumnName, String[] arrayValues, String operator) {
- if (StringUtils.isBlank(jsonbColumnName) || arrayValues == null || arrayValues.length == 0) {
- return null;
- }
- StringBuilder sql = new StringBuilder();
-
- // Default to AND if operator is null or invalid
- String op = (OR_OPERATOR.equalsIgnoreCase(operator) || NOT_OR_OPERATOR.equalsIgnoreCase(operator))
- ? OR_OPERATOR
- : AND_OPERATOR;
-
- // If the operator is a NOT variant, prepend "NOT " to the condition
- if (NOT_AND_OPERATOR.equalsIgnoreCase(operator) || NOT_OR_OPERATOR.equalsIgnoreCase(operator)) {
- sql.append("NOT ");
- }
-
- // Build the condition with one placeholder per value
- sql.append("(");
- for (int i = 0; i < arrayValues.length; i++) {
- if (i > 0) {
- sql.append(" ").append(op).append(" ");
- }
- sql.append(jsonbColumnName).append(" @> ?::jsonb");
- }
- sql.append(")");
- return sql.toString();
- }
-}
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/AppRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/AppRepository.java
index b311041b3..6e51ed460 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/AppRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/AppRepository.java
@@ -24,13 +24,14 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.DB;
+import com.github.rajkowski.database.DataConstraints;
+import com.github.rajkowski.database.DataResult;
+import com.github.rajkowski.database.Insert;
+import com.github.rajkowski.database.Select;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.domain.model.App;
import com.simisinc.platform.infrastructure.cache.CacheManager;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.DataConstraints;
-import com.simisinc.platform.infrastructure.database.DataResult;
-import com.simisinc.platform.infrastructure.database.SqlUtils;
-import com.simisinc.platform.infrastructure.database.SqlWhere;
/**
* Persists and retrieves app objects
@@ -45,34 +46,40 @@ public class AppRepository {
private static String TABLE_NAME = "apps";
private static String[] PRIMARY_KEY = new String[] { "app_id" };
- private static DataResult query(AppSpecification specification, DataConstraints constraints) {
- SqlWhere where = null;
+ private static DataResult query(AppSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("apps.*").FROM(TABLE_NAME).WHERE();
if (specification != null) {
- where = DB.WHERE()
- .andAddIfHasValue("app_id = ?", specification.getId(), -1)
- .andAddIfHasValue("public_key = ?", specification.getPublicKey());
+ if (specification.getId() > -1) {
+ select.AND("app_id = ?", specification.getId());
+ }
+ if (StringUtils.isNotBlank(specification.getPublicKey())) {
+ select.AND("public_key = ?", specification.getPublicKey());
+ }
}
- return DB.selectAllFrom(TABLE_NAME, where, constraints, AppRepository::buildRecord);
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(AppRepository::buildRecord);
}
public static App findByPublicKey(String publicKey) {
if (StringUtils.isBlank(publicKey)) {
return null;
}
- return (App) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("public_key = ?", publicKey),
- AppRepository::buildRecord);
+ return DB.SELECT("apps.*")
+ .FROM(TABLE_NAME)
+ .WHERE("public_key = ?", publicKey)
+ .returnRecord(AppRepository::buildRecord);
}
public static App findById(long id) {
if (id == -1) {
return null;
}
- return (App) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("app_id = ?", id),
- AppRepository::buildRecord);
+ return DB.SELECT("apps.*")
+ .FROM(TABLE_NAME)
+ .WHERE("app_id = ?", id)
+ .returnRecord(AppRepository::buildRecord);
}
public static List findAll() {
@@ -84,8 +91,7 @@ public static List findAll(AppSpecification specification, DataConstraints
constraints = new DataConstraints();
}
constraints.setDefaultColumnToSortBy("name");
- DataResult result = query(specification, constraints);
- return (List) result.getRecords();
+ return query(specification, constraints).getRecords();
}
public static App save(App record) {
@@ -96,13 +102,13 @@ public static App save(App record) {
}
private static App add(App record) {
- SqlUtils insertValues = new SqlUtils()
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("summary", StringUtils.trimToNull(record.getSummary()))
- .add("public_key", record.getPublicKey())
- .add("private_key", record.getPrivateKey())
- .add("created_by", record.getCreatedBy());
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("name", StringUtils.trimToNull(record.getName()))
+ .FIELD("summary", StringUtils.trimToNull(record.getSummary()))
+ .FIELD("public_key", record.getPublicKey())
+ .FIELD("private_key", record.getPrivateKey())
+ .FIELD("created_by", record.getCreatedBy());
+ record.setId(insert.execute());
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -111,10 +117,11 @@ private static App add(App record) {
}
private static App update(App record) {
- SqlUtils updateValues = new SqlUtils()
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("summary", StringUtils.trimToNull(record.getSummary()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("app_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("name", StringUtils.trimToNull(record.getName()))
+ .SET("summary", StringUtils.trimToNull(record.getSummary()))
+ .WHERE("app_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
CacheManager.invalidateKey(CacheManager.APP_CACHE, record.getPublicKey());
return record;
}
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/BlockedIPRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/BlockedIPRepository.java
index 1d7c27178..d28647297 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/BlockedIPRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/BlockedIPRepository.java
@@ -17,6 +17,7 @@
package com.simisinc.platform.infrastructure.persistence;
import java.io.File;
+import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
@@ -26,13 +27,15 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.AutoRollback;
+import com.github.rajkowski.database.AutoStartTransaction;
+import com.github.rajkowski.database.DB;
+import com.github.rajkowski.database.DataConstraints;
+import com.github.rajkowski.database.DataResult;
+import com.github.rajkowski.database.Insert;
+import com.github.rajkowski.database.Select;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.domain.model.BlockedIP;
-import com.simisinc.platform.infrastructure.database.AutoRollback;
-import com.simisinc.platform.infrastructure.database.AutoStartTransaction;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.DataConstraints;
-import com.simisinc.platform.infrastructure.database.DataResult;
-import com.simisinc.platform.infrastructure.database.SqlUtils;
/**
* Persists and retrieves blocked IP objects
@@ -47,8 +50,12 @@ public class BlockedIPRepository {
private static String TABLE_NAME = "block_list";
private static String[] PRIMARY_KEY = new String[] { "block_list_id" };
- private static DataResult query(DataConstraints constraints) {
- return DB.selectAllFrom(TABLE_NAME, null, constraints, BlockedIPRepository::buildRecord);
+ private static DataResult query(DataConstraints constraints) {
+ Select select = DB.SELECT("block_list.*").FROM(TABLE_NAME);
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(BlockedIPRepository::buildRecord);
}
public static List findAll() {
@@ -60,28 +67,27 @@ public static List findAll(DataConstraints constraints) {
constraints = new DataConstraints();
}
constraints.setDefaultColumnToSortBy("created DESC");
- DataResult result = query(constraints);
- return (List) result.getRecords();
+ return query(constraints).getRecords();
}
public static BlockedIP findById(long id) {
if (id == -1) {
return null;
}
- return (BlockedIP) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("block_list_id = ?", id),
- BlockedIPRepository::buildRecord);
+ return DB.SELECT("block_list.*")
+ .FROM(TABLE_NAME)
+ .WHERE("block_list_id = ?", id)
+ .returnRecord(BlockedIPRepository::buildRecord);
}
public static BlockedIP findByIpAddress(String ipAddress) {
if (StringUtils.isBlank(ipAddress)) {
return null;
}
- return (BlockedIP) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("ip_address = ?", ipAddress),
- BlockedIPRepository::buildRecord);
+ return DB.SELECT("block_list.*")
+ .FROM(TABLE_NAME)
+ .WHERE("ip_address = ?", ipAddress)
+ .returnRecord(BlockedIPRepository::buildRecord);
}
public static BlockedIP save(BlockedIP record) {
@@ -92,11 +98,11 @@ public static BlockedIP save(BlockedIP record) {
}
public static BlockedIP add(BlockedIP record) {
- SqlUtils insertValues = new SqlUtils()
- .add("ip_address", StringUtils.trimToNull(record.getIpAddress()))
- .addIfExists("reason", StringUtils.trimToNull(record.getReason()))
- .addIfExists("created", record.getCreated());
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("ip_address", StringUtils.trimToNull(record.getIpAddress()))
+ .FIELD("reason", StringUtils.trimToNull(record.getReason()))
+ .FIELD("created", record.getCreated());
+ record.setId(insert.execute());
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -105,11 +111,11 @@ public static BlockedIP add(BlockedIP record) {
}
public static BlockedIP update(BlockedIP record) {
- SqlUtils updateValues = new SqlUtils()
- .add("ip_address", StringUtils.trimToNull(record.getIpAddress()))
- .addIfExists("reason", StringUtils.trimToNull(record.getReason()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("block_list_id = ?", record.getId()))) {
- // CacheManager.invalidateKey(CacheManager.CONTENT_UNIQUE_ID_CACHE, record.getUniqueId());
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("ip_address", StringUtils.trimToNull(record.getIpAddress()))
+ .SET("reason", StringUtils.trimToNull(record.getReason()))
+ .WHERE("block_list_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("The update failed!");
@@ -120,13 +126,7 @@ public static boolean remove(BlockedIP record) {
try (Connection connection = DB.getConnection();
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
- // Delete the references
- // ItemCategoryRepository.removeAll(connection, record);
- // CollectionRepository.updateItemCount(connection, record.getCollectionId(), -1);
- // CategoryRepository.updateItemCount(connection, record.getCategoryId(), -1);
- // Delete the record
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("block_list_id = ?", record.getId()));
- // Finish transaction
+ DB.DELETE().FROM(TABLE_NAME).WHERE("block_list_id = ?", record.getId()).execute(connection);
transaction.commit();
return true;
} catch (SQLException se) {
@@ -150,16 +150,20 @@ private static BlockedIP buildRecord(ResultSet rs) {
}
public static void export(DataConstraints constraints, File file) {
- // Use the specification to filter results
if (constraints == null) {
constraints = new DataConstraints();
}
constraints.setDefaultColumnToSortBy("block_list_id");
- DB.exportToCsvAllFrom(TABLE_NAME,
- DB.SELECT(
- "ip_address AS \"IP Address\"",
- "created AS \"Date\"",
- "reason AS \"Reason\""),
- null, null, null, constraints, file);
+ List records = findAll(constraints);
+ try (java.io.FileWriter writer = new java.io.FileWriter(file)) {
+ writer.write("IP Address,Date,Reason\n");
+ for (BlockedIP record : records) {
+ writer.write((record.getIpAddress() == null ? "" : record.getIpAddress()) + ","
+ + (record.getCreated() == null ? "" : record.getCreated()) + ","
+ + (record.getReason() == null ? "" : record.getReason().replace(",", " ")) + "\n");
+ }
+ } catch (IOException e) {
+ LOG.error("SQLException: " + e.getMessage(), e);
+ }
}
}
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/admin/PermissionGroupRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/admin/PermissionGroupRepository.java
index 58c8fa2ea..2c4d3f3f8 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/admin/PermissionGroupRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/admin/PermissionGroupRepository.java
@@ -27,10 +27,10 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.DB;
+import com.github.rajkowski.database.DataConstraints;
+import com.github.rajkowski.database.DataResult;
import com.simisinc.platform.domain.model.admin.PermissionGroup;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.DataConstraints;
-import com.simisinc.platform.infrastructure.database.DataResult;
/**
* Loads permission groups and their members from the database.
@@ -55,15 +55,15 @@ public class PermissionGroupRepository {
*/
@SuppressWarnings("unchecked")
public static List findAllPolicies() {
- DataResult result = DB.selectAllFrom(
- POLICIES_TABLE,
- DB.WHERE("enabled = ?", true),
- new DataConstraints().setDefaultColumnToSortBy("group_code"),
- PermissionGroupRepository::buildPolicy);
+ DataResult result = DB.SELECT("permission_policies.*")
+ .FROM(POLICIES_TABLE)
+ .WHERE("enabled = ?", true)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("group_code"))
+ .returnDataResult(PermissionGroupRepository::buildPolicy);
if (result == null) {
return new ArrayList<>();
}
- return (List) result.getRecords();
+ return result.getRecords();
}
/**
@@ -75,13 +75,13 @@ public static Map> findAllMembers() {
Map> memberMap = new LinkedHashMap<>();
String sql = "SELECT group_code, action_name, member_type FROM " + MEMBERS_TABLE + " ORDER BY group_code";
try (Connection conn = DB.getConnection();
- PreparedStatement pst = conn.prepareStatement(sql);
- ResultSet rs = pst.executeQuery()) {
+ PreparedStatement pst = conn.prepareStatement(sql);
+ ResultSet rs = pst.executeQuery()) {
while (rs.next()) {
String groupCode = rs.getString("group_code");
String actionName = rs.getString("action_name");
String memberType = rs.getString("member_type");
- memberMap.computeIfAbsent(groupCode, k -> new ArrayList<>()).add(new String[]{actionName, memberType});
+ memberMap.computeIfAbsent(groupCode, k -> new ArrayList<>()).add(new String[] { actionName, memberType });
}
} catch (SQLException e) {
LOG.error("PermissionGroupRepository.findAllMembers error", e);
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/analytics/PerformanceMetricRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/analytics/PerformanceMetricRepository.java
index 35860e1d8..8cf17d759 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/analytics/PerformanceMetricRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/analytics/PerformanceMetricRepository.java
@@ -23,13 +23,14 @@
import java.util.ArrayList;
import java.util.List;
+import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.github.rajkowski.database.DB;
+import com.github.rajkowski.database.Insert;
import com.simisinc.platform.domain.model.analytics.PerformanceMetric;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.SqlUtils;
/**
* Persists and retrieves performance metric records
@@ -45,14 +46,14 @@ public class PerformanceMetricRepository {
private static final String[] PRIMARY_KEY = new String[] { "metric_id" };
public static PerformanceMetric save(PerformanceMetric record) {
- SqlUtils insertValues = new SqlUtils()
- .add("request_type", record.getRequestType(), 10)
- .add("status_code", record.getStatusCode())
- .add("duration_ms", record.getDurationMs());
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("request_type", StringUtils.left(record.getRequestType(), 10))
+ .FIELD("status_code", record.getStatusCode())
+ .FIELD("duration_ms", record.getDurationMs());
if (record.getMetricDate() != null) {
- insertValues.add("metric_date", record.getMetricDate());
+ insert.FIELD("metric_date", record.getMetricDate());
}
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ record.setId(insert.execute());
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -131,16 +132,10 @@ public static List findStatusCodeBreakdown(int days) {
* Delete records older than the specified number of days.
*/
public static void deleteOlderThan(int days) {
- String SQL = "DELETE FROM " + TABLE_NAME + " WHERE metric_date < NOW() - (? || ' days')::interval";
- try (Connection connection = DB.getConnection();
- PreparedStatement pst = connection.prepareStatement(SQL)) {
- pst.setInt(1, days);
- int deleted = pst.executeUpdate();
- if (deleted > 0) {
- LOG.debug("Deleted " + deleted + " performance metric records older than " + days + " days");
- }
+ try (Connection connection = DB.getConnection()) {
+ DB.DELETE().FROM(TABLE_NAME).WHERE("metric_date < NOW() - (? || ' days')::interval", days).execute(connection);
} catch (SQLException se) {
- LOG.error("deleteOlderThan error: " + se.getMessage());
+ LOG.error("SQLException: " + se.getMessage());
}
}
}
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/BlogPostRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/BlogPostRepository.java
index 4cda36e45..3b1a28d8c 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/BlogPostRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/BlogPostRepository.java
@@ -1,4 +1,5 @@
/*
+ * Copyright 2026 Matt Rajkowski (https://github.com/rajkowski)
* Copyright 2022 SimIS Inc. (https://www.simiscms.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -26,16 +27,17 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.AutoRollback;
+import com.github.rajkowski.database.AutoStartTransaction;
+import com.github.rajkowski.database.DB;
+import com.github.rajkowski.database.DataConstraints;
+import com.github.rajkowski.database.DataResult;
+import com.github.rajkowski.database.Insert;
+import com.github.rajkowski.database.Select;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.application.cms.HtmlCommand;
import com.simisinc.platform.domain.model.cms.Blog;
import com.simisinc.platform.domain.model.cms.BlogPost;
-import com.simisinc.platform.infrastructure.database.AutoRollback;
-import com.simisinc.platform.infrastructure.database.AutoStartTransaction;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.DataConstraints;
-import com.simisinc.platform.infrastructure.database.DataResult;
-import com.simisinc.platform.infrastructure.database.SqlUtils;
-import com.simisinc.platform.infrastructure.database.SqlWhere;
import com.simisinc.platform.presentation.controller.DataConstants;
/**
@@ -51,74 +53,79 @@ public class BlogPostRepository {
private static String TABLE_NAME = "blog_posts";
private static String[] PRIMARY_KEY = new String[] { "post_id" };
- private static SqlWhere createWhereStatement(BlogPostSpecification specification) {
- SqlWhere where = null;
- if (specification != null) {
- where = DB.WHERE()
- .andAddIfHasValue("post_id = ?", specification.getId(), -1)
- .andAddIfHasValue("blog_id = ?", specification.getBlogId(), -1)
- .andAddIfHasValue("post_unique_id = ?", specification.getUniqueId());
- if (specification.getPublishedOnly() != DataConstants.UNDEFINED) {
- if (specification.getPublishedOnly() == DataConstants.TRUE) {
- where.AND("published IS NOT NULL");
- } else {
- where.AND("published IS NULL");
- }
- }
- if (specification.getStartDateIsBeforeNow() != DataConstants.UNDEFINED) {
- if (specification.getStartDateIsBeforeNow() == DataConstants.TRUE) {
- // Show the ones which are active
- where.AND("start_date <= NOW()");
- }
+ private static void appendWhereClause(Select select, BlogPostSpecification specification) {
+ if (specification == null) {
+ return;
+ }
+ if (specification.getId() > -1) {
+ select.AND("post_id = ?", specification.getId());
+ }
+ if (specification.getBlogId() > -1) {
+ select.AND("blog_id = ?", specification.getBlogId());
+ }
+ if (StringUtils.isNotBlank(specification.getUniqueId())) {
+ select.AND("post_unique_id = ?", specification.getUniqueId());
+ }
+ if (specification.getPublishedOnly() != DataConstants.UNDEFINED) {
+ if (specification.getPublishedOnly() == DataConstants.TRUE) {
+ select.AND("published IS NOT NULL");
+ } else {
+ select.AND("published IS NULL");
}
- if (specification.getIsWithinEndDate() != DataConstants.UNDEFINED) {
- if (specification.getIsWithinEndDate() == DataConstants.TRUE) {
- // Show the non-expiring and unexpired
- where.AND("(end_date IS NULL OR end_date >= NOW())");
- }
+ }
+ if (specification.getStartDateIsBeforeNow() != DataConstants.UNDEFINED) {
+ if (specification.getStartDateIsBeforeNow() == DataConstants.TRUE) {
+ // Show the ones which are active
+ select.AND("start_date <= NOW()");
}
- if (StringUtils.isNotBlank(specification.getSearchTerm())) {
- where.AND("tsv @@ websearch_to_tsquery('content_stem', ?)", specification.getSearchTerm().trim());
+ }
+ if (specification.getIsWithinEndDate() != DataConstants.UNDEFINED) {
+ if (specification.getIsWithinEndDate() == DataConstants.TRUE) {
+ // Show the non-expiring and unexpired
+ select.AND("(end_date IS NULL OR end_date >= NOW())");
}
}
- return where;
+ if (StringUtils.isNotBlank(specification.getSearchTerm())) {
+ select.AND("tsv @@ websearch_to_tsquery('content_stem', ?)", specification.getSearchTerm().trim());
+ }
}
- private static DataResult query(BlogPostSpecification specification, DataConstraints constraints) {
- SqlUtils select = new SqlUtils();
- SqlWhere where = createWhereStatement(specification);
- SqlUtils orderBy = null;
+ private static DataResult query(BlogPostSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT().FROM(TABLE_NAME);
+ appendWhereClause(select, specification);
if (specification != null && StringUtils.isNotBlank(specification.getSearchTerm())) {
- select.add(
+ String searchTerm = specification.getSearchTerm().trim();
+ select.SELECT(
"ts_headline('english', body_text, websearch_to_tsquery('content_stem', ?), 'StartSel=${b}, StopSel=${/b}, MaxWords=30, MinWords=15, ShortWord=3, HighlightAll=FALSE, MaxFragments=2, FragmentDelimiter=\" ... \"') AS highlight",
- specification.getSearchTerm().trim());
- select.add("ts_rank_cd(tsv, websearch_to_tsquery('content_stem', ?)) AS rank", specification.getSearchTerm().trim());
- // Override the order by for rank first
- orderBy = new SqlUtils();
- orderBy.add("rank DESC, post_id desc");
+ searchTerm);
+ select.SELECT("ts_rank_cd(tsv, websearch_to_tsquery('content_stem', ?)) AS rank", searchTerm);
+ select.ORDER_BY("rank DESC, post_id desc");
+ }
+ if (constraints != null) {
+ select.WITH(constraints);
}
- return DB.selectAllFrom(TABLE_NAME, select, where, orderBy, constraints, BlogPostRepository::buildRecord);
+ return select.returnDataResult(BlogPostRepository::buildRecord);
}
public static BlogPost findByUniqueId(Long blogId, String postUniqueId) {
if (StringUtils.isBlank(postUniqueId)) {
return null;
}
- return (BlogPost) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("blog_id = ?", blogId)
- .AND("post_unique_id = ?", postUniqueId),
- BlogPostRepository::buildRecord);
+ return DB.SELECT("blog_posts.*")
+ .FROM(TABLE_NAME)
+ .WHERE("blog_id = ?", blogId)
+ .AND("post_unique_id = ?", postUniqueId)
+ .returnRecord(BlogPostRepository::buildRecord);
}
public static BlogPost findById(Long blogPostId) {
if (blogPostId == -1) {
return null;
}
- return (BlogPost) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("post_id = ?", blogPostId),
- BlogPostRepository::buildRecord);
+ return DB.SELECT("blog_posts.*")
+ .FROM(TABLE_NAME)
+ .WHERE("post_id = ?", blogPostId)
+ .returnRecord(BlogPostRepository::buildRecord);
}
public static List findAll() {
@@ -130,12 +137,13 @@ public static List findAll(BlogPostSpecification specification, DataCo
constraints = new DataConstraints();
}
constraints.setDefaultColumnToSortBy("post_id");
- DataResult result = query(specification, constraints);
- return (List) result.getRecords();
+ return query(specification, constraints).getRecords();
}
public static long findCount(BlogPostSpecification specification) {
- return DB.selectCountFrom(TABLE_NAME, createWhereStatement(specification));
+ Select select = DB.SELECT().COUNT("*");
+ appendWhereClause(select, specification);
+ return select.returnCount();
}
public static BlogPost save(BlogPost record) {
@@ -146,22 +154,22 @@ public static BlogPost save(BlogPost record) {
}
public static BlogPost add(BlogPost record) {
- SqlUtils insertValues = new SqlUtils()
- .add("blog_id", record.getBlogId())
- .add("post_unique_id", StringUtils.trimToNull(record.getUniqueId()))
- .add("title", StringUtils.trimToNull(record.getTitle()))
- .add("body", StringUtils.trimToNull(record.getBody()))
- .add("body_text", HtmlCommand.text(StringUtils.trimToNull(record.getBody())))
- .add("summary", StringUtils.trimToNull(record.getSummary()))
- .add("keywords", StringUtils.trimToNull(record.getKeywords()))
- .add("image_url", StringUtils.trimToNull(record.getImageUrl()))
- .add("created_by", record.getCreatedBy())
- .add("modified_by", record.getModifiedBy())
- .add("published", record.getPublished())
- .add("archived", record.getArchived())
- .add("start_date", record.getStartDate())
- .add("end_date", record.getEndDate());
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("blog_id", record.getBlogId())
+ .FIELD("post_unique_id", StringUtils.trimToNull(record.getUniqueId()))
+ .FIELD("title", StringUtils.trimToNull(record.getTitle()))
+ .FIELD("body", StringUtils.trimToNull(record.getBody()))
+ .FIELD("body_text", HtmlCommand.text(StringUtils.trimToNull(record.getBody())))
+ .FIELD("summary", StringUtils.trimToNull(record.getSummary()))
+ .FIELD("keywords", StringUtils.trimToNull(record.getKeywords()))
+ .FIELD("image_url", StringUtils.trimToNull(record.getImageUrl()))
+ .FIELD("created_by", record.getCreatedBy())
+ .FIELD("modified_by", record.getModifiedBy())
+ .FIELD("published", record.getPublished())
+ .FIELD("archived", record.getArchived())
+ .FIELD("start_date", record.getStartDate())
+ .FIELD("end_date", record.getEndDate());
+ record.setId(insert.execute());
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -170,23 +178,22 @@ public static BlogPost add(BlogPost record) {
}
public static BlogPost update(BlogPost record) {
- SqlUtils updateValues = new SqlUtils()
- .add("post_unique_id", StringUtils.trimToNull(record.getUniqueId()))
- .add("title", StringUtils.trimToNull(record.getTitle()))
- .add("body", StringUtils.trimToNull(record.getBody()))
- .add("body_text", HtmlCommand.text(StringUtils.trimToNull(record.getBody())))
- .add("summary", StringUtils.trimToNull(record.getSummary()))
- .add("keywords", StringUtils.trimToNull(record.getKeywords()))
- .add("image_url", StringUtils.trimToNull(record.getImageUrl()))
- .add("modified_by", record.getModifiedBy())
- .add("modified", new Timestamp(System.currentTimeMillis()))
- .add("published", record.getPublished())
- .add("archived", record.getArchived())
- .add("start_date", record.getStartDate())
- .add("end_date", record.getEndDate());
- if (DB.update(TABLE_NAME, updateValues,
- DB.WHERE("post_id = ?", record.getId()))) {
- // CacheManager.invalidateKey(CacheManager.CONTENT_UNIQUE_ID_CACHE, record.getUniqueId());
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("post_unique_id", StringUtils.trimToNull(record.getUniqueId()))
+ .SET("title", StringUtils.trimToNull(record.getTitle()))
+ .SET("body", StringUtils.trimToNull(record.getBody()))
+ .SET("body_text", HtmlCommand.text(StringUtils.trimToNull(record.getBody())))
+ .SET("summary", StringUtils.trimToNull(record.getSummary()))
+ .SET("keywords", StringUtils.trimToNull(record.getKeywords()))
+ .SET("image_url", StringUtils.trimToNull(record.getImageUrl()))
+ .SET("modified_by", record.getModifiedBy())
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .SET("published", record.getPublished())
+ .SET("archived", record.getArchived())
+ .SET("start_date", record.getStartDate())
+ .SET("end_date", record.getEndDate())
+ .WHERE("post_id = ?", record.getId());
+ if (update.execute()) {
return record;
}
LOG.error("The update failed!");
@@ -202,7 +209,7 @@ public static boolean remove(BlogPost record) {
// CollectionRepository.updateItemCount(connection, record.getCollectionId(), -1);
// CategoryRepository.updateItemCount(connection, record.getCategoryId(), -1);
// Delete the record
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("post_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("post_id = ?", record.getId()).execute(connection);
// Finish transaction
transaction.commit();
return true;
@@ -213,7 +220,7 @@ public static boolean remove(BlogPost record) {
}
public static void removeAll(Connection connection, Blog blog) throws SQLException {
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("blog_id = ?", blog.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("blog_id = ?", blog.getId()).execute(connection);
}
private static BlogPost buildRecord(ResultSet rs) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/BlogRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/BlogRepository.java
index bd8e867da..cf8924ea7 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/BlogRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/BlogRepository.java
@@ -1,4 +1,5 @@
/*
+ * Copyright 2026 Matt Rajkowski (https://github.com/rajkowski)
* Copyright 2022 SimIS Inc. (https://www.simiscms.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -26,14 +27,15 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.AutoRollback;
+import com.github.rajkowski.database.AutoStartTransaction;
+import com.github.rajkowski.database.DB;
+import com.github.rajkowski.database.DataConstraints;
+import com.github.rajkowski.database.DataResult;
+import com.github.rajkowski.database.Insert;
+import com.github.rajkowski.database.Select;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.domain.model.cms.Blog;
-import com.simisinc.platform.infrastructure.database.AutoRollback;
-import com.simisinc.platform.infrastructure.database.AutoStartTransaction;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.DataConstraints;
-import com.simisinc.platform.infrastructure.database.DataResult;
-import com.simisinc.platform.infrastructure.database.SqlUtils;
-import com.simisinc.platform.infrastructure.database.SqlWhere;
/**
* Persists and retrieves blog objects
@@ -48,34 +50,40 @@ public class BlogRepository {
private static String TABLE_NAME = "blogs";
private static String[] PRIMARY_KEY = new String[] { "blog_id" };
- private static DataResult query(BlogSpecification specification, DataConstraints constraints) {
- SqlWhere where = null;
+ private static DataResult query(BlogSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("blogs.*").FROM(TABLE_NAME).WHERE();
if (specification != null) {
- where = DB.WHERE()
- .andAddIfHasValue("blog_id = ?", specification.getId(), -1)
- .andAddIfHasValue("blog_unique_id = ?", specification.getUniqueId());
+ if (specification.getId() > -1) {
+ select.AND("blog_id = ?", specification.getId());
+ }
+ if (StringUtils.isNotBlank(specification.getUniqueId())) {
+ select.AND("blog_unique_id = ?", specification.getUniqueId());
+ }
}
- return DB.selectAllFrom(TABLE_NAME, where, constraints, BlogRepository::buildRecord);
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(BlogRepository::buildRecord);
}
public static Blog findById(long blogId) {
if (blogId == -1) {
return null;
}
- return (Blog) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("blog_id = ?", blogId),
- BlogRepository::buildRecord);
+ return DB.SELECT("blogs.*")
+ .FROM(TABLE_NAME)
+ .WHERE("blog_id = ?", blogId)
+ .returnRecord(BlogRepository::buildRecord);
}
public static Blog findByUniqueId(String blogUniqueId) {
if (StringUtils.isBlank(blogUniqueId)) {
return null;
}
- return (Blog) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("blog_unique_id = ?", blogUniqueId),
- BlogRepository::buildRecord);
+ return DB.SELECT("blogs.*")
+ .FROM(TABLE_NAME)
+ .WHERE("blog_unique_id = ?", blogUniqueId)
+ .returnRecord(BlogRepository::buildRecord);
}
public static List findAll() {
@@ -99,14 +107,14 @@ public static Blog save(Blog record) {
}
public static Blog add(Blog record) {
- SqlUtils insertValues = new SqlUtils()
- .add("blog_unique_id", StringUtils.trimToNull(record.getUniqueId()))
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("description", StringUtils.trimToNull(record.getDescription()))
- .add("created_by", record.getCreatedBy())
- .add("modified_by", record.getModifiedBy())
- .add("enabled", record.getEnabled());
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("blog_unique_id", StringUtils.trimToNull(record.getUniqueId()))
+ .FIELD("name", StringUtils.trimToNull(record.getName()))
+ .FIELD("description", StringUtils.trimToNull(record.getDescription()))
+ .FIELD("created_by", record.getCreatedBy())
+ .FIELD("modified_by", record.getModifiedBy())
+ .FIELD("enabled", record.getEnabled());
+ record.setId(insert.execute());
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -115,14 +123,15 @@ public static Blog add(Blog record) {
}
public static Blog update(Blog record) {
- SqlUtils updateValues = new SqlUtils()
- .add("blog_unique_id", StringUtils.trimToNull(record.getUniqueId()))
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("description", StringUtils.trimToNull(record.getDescription()))
- .add("enabled", record.getEnabled())
- .add("modified_by", record.getModifiedBy())
- .add("modified", new Timestamp(System.currentTimeMillis()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("blog_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("blog_unique_id", StringUtils.trimToNull(record.getUniqueId()))
+ .SET("name", StringUtils.trimToNull(record.getName()))
+ .SET("description", StringUtils.trimToNull(record.getDescription()))
+ .SET("enabled", record.getEnabled())
+ .SET("modified_by", record.getModifiedBy())
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("blog_id = ?", record.getId());
+ if (update.execute()) {
// CacheManager.invalidateKey(CacheManager.CONTENT_UNIQUE_ID_CACHE, record.getUniqueId());
return record;
}
@@ -137,7 +146,7 @@ public static boolean remove(Blog record) {
// Delete the references
BlogPostRepository.removeAll(connection, record);
// Delete the record
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("blog_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("blog_id = ?", record.getId()).execute(connection);
// Finish transaction
transaction.commit();
return true;
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/CalendarEventRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/CalendarEventRepository.java
index 60643fdc1..3524b4c94 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/CalendarEventRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/CalendarEventRepository.java
@@ -1,4 +1,5 @@
/*
+ * Copyright 2026 Matt Rajkowski (https://github.com/rajkowski)
* Copyright 2022 SimIS Inc. (https://www.simiscms.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -26,15 +27,16 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.AutoRollback;
+import com.github.rajkowski.database.AutoStartTransaction;
+import com.github.rajkowski.database.DB;
+import com.github.rajkowski.database.DataConstraints;
+import com.github.rajkowski.database.DataResult;
+import com.github.rajkowski.database.Insert;
+import com.github.rajkowski.database.Select;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.domain.model.cms.Calendar;
import com.simisinc.platform.domain.model.cms.CalendarEvent;
-import com.simisinc.platform.infrastructure.database.AutoRollback;
-import com.simisinc.platform.infrastructure.database.AutoStartTransaction;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.DataConstraints;
-import com.simisinc.platform.infrastructure.database.DataResult;
-import com.simisinc.platform.infrastructure.database.SqlUtils;
-import com.simisinc.platform.infrastructure.database.SqlWhere;
import com.simisinc.platform.presentation.controller.DataConstants;
/**
@@ -50,89 +52,86 @@ public class CalendarEventRepository {
private static String TABLE_NAME = "calendar_events";
private static String[] PRIMARY_KEY = new String[] { "event_id" };
- private static SqlWhere createWhereStatement(CalendarEventSpecification specification) {
- SqlWhere where = DB.WHERE();
+ private static void appendWhereClause(Select select, CalendarEventSpecification specification) {
if (specification == null) {
- return where;
+ return;
+ }
+ if (specification.getId() > -1) {
+ select.AND("event_id = ?", specification.getId());
+ }
+ if (specification.getCalendarId() > -1) {
+ select.AND("calendar_id = ?", specification.getCalendarId());
+ }
+ if (StringUtils.isNotBlank(specification.getUniqueId())) {
+ select.AND("event_unique_id = ?", specification.getUniqueId());
}
- where
- .andAddIfHasValue("event_id = ?", specification.getId(), -1)
- .andAddIfHasValue("calendar_id = ?", specification.getCalendarId(), -1)
- .andAddIfHasValue("event_unique_id = ?", specification.getUniqueId());
if (specification.getPublishedOnly() != DataConstants.UNDEFINED) {
if (specification.getPublishedOnly() == DataConstants.TRUE) {
- where.AND("published IS NOT NULL");
+ select.AND("published IS NOT NULL");
} else {
- where.AND("published IS NULL");
+ select.AND("published IS NULL");
}
}
if (specification.getStartingDateRange() != null && specification.getEndingDateRange() != null) {
- where.AND("((start_date >= ? AND start_date < ?) OR (end_date >= ? AND end_date < ?))",
- new Timestamp[] { specification.getStartingDateRange(), specification.getEndingDateRange(),
- specification.getStartingDateRange(), specification.getEndingDateRange() });
+ select.AND("((start_date >= ? AND start_date < ?) OR (end_date >= ? AND end_date < ?))",
+ specification.getStartingDateRange(), specification.getEndingDateRange(), specification.getStartingDateRange(),
+ specification.getEndingDateRange());
} else if (specification.getStartingDateRange() != null) {
- where.AND("start_date >= ?",
- new Timestamp[] { specification.getStartingDateRange() });
+ select.AND("start_date >= ?", specification.getStartingDateRange());
} else if (specification.getEndingDateRange() != null) {
- where.AND("(start_date < ? AND end_date < ?)",
- new Timestamp[] { specification.getEndingDateRange(), specification.getEndingDateRange() });
+ select.AND("(start_date < ? AND end_date < ?)", specification.getEndingDateRange(), specification.getEndingDateRange());
}
- return where;
}
- private static DataResult query(CalendarEventSpecification specification, DataConstraints constraints) {
- SqlUtils select = new SqlUtils();
- SqlWhere where = createWhereStatement(specification);
- SqlUtils orderBy = null;
-
- if (specification != null) {
- if (StringUtils.isNotBlank(specification.getSearchTerm())) {
- select.add("ts_rank_cd(tsv, websearch_to_tsquery('title_stem', ?)) AS rank", specification.getSearchTerm().trim());
- where.AND("tsv @@ websearch_to_tsquery('title_stem', ?)", specification.getSearchTerm().trim());
- // Override the order by for rank first
- orderBy = new SqlUtils();
- if (specification.getStartingDateRange() != null) {
- // Show next occurring first
- orderBy.add("rank DESC, start_date");
- } else {
- // Show the future ones first
- orderBy.add("rank DESC, start_date DESC");
- }
+ private static DataResult query(CalendarEventSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("calendar_events.*").FROM(TABLE_NAME);
+ appendWhereClause(select, specification);
+ if (specification != null && StringUtils.isNotBlank(specification.getSearchTerm())) {
+ String searchTerm = specification.getSearchTerm().trim();
+ select.SELECT("ts_rank_cd(tsv, websearch_to_tsquery('title_stem', ?)) AS rank", searchTerm);
+ select.AND("tsv @@ websearch_to_tsquery('title_stem', ?)", searchTerm);
+ if (specification.getStartingDateRange() != null) {
+ select.ORDER_BY("rank DESC, start_date");
+ } else {
+ select.ORDER_BY("rank DESC, start_date DESC");
}
}
- return DB.selectAllFrom(TABLE_NAME, select, where, orderBy, constraints, CalendarEventRepository::buildRecord);
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(CalendarEventRepository::buildRecord);
}
public static CalendarEvent findByUniqueId(Long calendarId, String eventUniqueId) {
if (StringUtils.isBlank(eventUniqueId)) {
return null;
}
- return (CalendarEvent) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("calendar_id = ?", calendarId)
- .AND("event_unique_id = ?", eventUniqueId),
- CalendarEventRepository::buildRecord);
+ return DB.SELECT("calendar_events.*")
+ .FROM(TABLE_NAME)
+ .WHERE("calendar_id = ?", calendarId)
+ .AND("event_unique_id = ?", eventUniqueId)
+ .returnRecord(CalendarEventRepository::buildRecord);
}
public static CalendarEvent findByUniqueId(String eventUniqueId) {
if (StringUtils.isBlank(eventUniqueId)) {
return null;
}
- return (CalendarEvent) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("event_unique_id = ?", eventUniqueId),
- CalendarEventRepository::buildRecord);
+ return DB.SELECT("calendar_events.*")
+ .FROM(TABLE_NAME)
+ .WHERE("event_unique_id = ?", eventUniqueId)
+ .returnRecord(CalendarEventRepository::buildRecord);
}
public static CalendarEvent findById(Long calendarEventId) {
if (calendarEventId == -1) {
return null;
}
- return (CalendarEvent) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("event_id = ?", calendarEventId),
- CalendarEventRepository::buildRecord);
+ return DB.SELECT("calendar_events.*")
+ .FROM(TABLE_NAME)
+ .WHERE("event_id = ?", calendarEventId)
+ .returnRecord(CalendarEventRepository::buildRecord);
}
public static List findAll() {
@@ -149,7 +148,9 @@ public static List findAll(CalendarEventSpecification specificati
}
public static long findCount(CalendarEventSpecification specification) {
- return DB.selectCountFrom(TABLE_NAME, createWhereStatement(specification));
+ Select select = DB.SELECT().COUNT("*").FROM(TABLE_NAME);
+ appendWhereClause(select, specification);
+ return select.returnCount();
}
public static CalendarEvent save(CalendarEvent record) {
@@ -160,24 +161,24 @@ public static CalendarEvent save(CalendarEvent record) {
}
public static CalendarEvent add(CalendarEvent record) {
- SqlUtils insertValues = new SqlUtils()
- .add("calendar_id", record.getCalendarId())
- .add("event_unique_id", StringUtils.trimToNull(record.getUniqueId()))
- .add("title", StringUtils.trimToNull(record.getTitle()))
- .add("body", StringUtils.trimToNull(record.getBody()))
- .add("summary", StringUtils.trimToNull(record.getSummary()))
- .add("all_day", record.getAllDay())
- .add("start_date", record.getStartDate())
- .add("end_date", record.getEndDate())
- .add("details_url", StringUtils.trimToNull(record.getDetailsUrl()))
- .add("sign_up_url", StringUtils.trimToNull(record.getSignUpUrl()))
- .add("location_name", StringUtils.trimToNull(record.getLocation()))
- .add("image_url", StringUtils.trimToNull(record.getImageUrl()))
- .add("created_by", record.getCreatedBy())
- .add("modified_by", record.getModifiedBy())
- .add("published", record.getPublished())
- .add("archived", record.getArchived());
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("calendar_id", record.getCalendarId())
+ .FIELD("event_unique_id", StringUtils.trimToNull(record.getUniqueId()))
+ .FIELD("title", StringUtils.trimToNull(record.getTitle()))
+ .FIELD("body", StringUtils.trimToNull(record.getBody()))
+ .FIELD("summary", StringUtils.trimToNull(record.getSummary()))
+ .FIELD("all_day", record.getAllDay())
+ .FIELD("start_date", record.getStartDate())
+ .FIELD("end_date", record.getEndDate())
+ .FIELD("details_url", StringUtils.trimToNull(record.getDetailsUrl()))
+ .FIELD("sign_up_url", StringUtils.trimToNull(record.getSignUpUrl()))
+ .FIELD("location_name", StringUtils.trimToNull(record.getLocation()))
+ .FIELD("image_url", StringUtils.trimToNull(record.getImageUrl()))
+ .FIELD("created_by", record.getCreatedBy())
+ .FIELD("modified_by", record.getModifiedBy())
+ .FIELD("published", record.getPublished())
+ .FIELD("archived", record.getArchived());
+ record.setId(insert.execute());
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -186,25 +187,26 @@ public static CalendarEvent add(CalendarEvent record) {
}
public static CalendarEvent update(CalendarEvent record) {
- SqlUtils updateValues = new SqlUtils()
- .add("calendar_id", record.getCalendarId())
- .add("event_unique_id", StringUtils.trimToNull(record.getUniqueId()))
- .add("title", StringUtils.trimToNull(record.getTitle()))
- .add("body", StringUtils.trimToNull(record.getBody()))
- .add("summary", StringUtils.trimToNull(record.getSummary()))
- .add("all_day", record.getAllDay())
- .add("start_date", record.getStartDate())
- .add("end_date", record.getEndDate())
- .add("details_url", StringUtils.trimToNull(record.getDetailsUrl()))
- .add("sign_up_url", StringUtils.trimToNull(record.getSignUpUrl()))
- .add("location_name", StringUtils.trimToNull(record.getLocation()))
- .add("image_url", StringUtils.trimToNull(record.getImageUrl()))
- .add("modified_by", record.getModifiedBy())
- .add("modified", new Timestamp(System.currentTimeMillis()))
- .add("published", record.getPublished())
- .add("archived", record.getArchived());
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("event_id = ?", record.getId()))) {
- // CacheManager.invalidateKey(CacheManager.CONTENT_UNIQUE_ID_CACHE, record.getUniqueId());
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("calendar_id", record.getCalendarId())
+ .SET("event_unique_id", StringUtils.trimToNull(record.getUniqueId()))
+ .SET("title", StringUtils.trimToNull(record.getTitle()))
+ .SET("body", StringUtils.trimToNull(record.getBody()))
+ .SET("summary", StringUtils.trimToNull(record.getSummary()))
+ .SET("all_day", record.getAllDay())
+ .SET("start_date", record.getStartDate())
+ .SET("end_date", record.getEndDate())
+ .SET("details_url", StringUtils.trimToNull(record.getDetailsUrl()))
+ .SET("sign_up_url", StringUtils.trimToNull(record.getSignUpUrl()))
+ .SET("location_name", StringUtils.trimToNull(record.getLocation()))
+ .SET("image_url", StringUtils.trimToNull(record.getImageUrl()))
+ .SET("modified_by", record.getModifiedBy())
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .SET("published", record.getPublished())
+ .SET("archived", record.getArchived())
+ .WHERE("event_id = ?", record.getId());
+ if (update.execute()) {
+ // CacheManager.invalidateKey(CacheManager.CONTENT_UNIQUE_ID_CACHE, record.getUniqueId());
return record;
}
LOG.error("The update failed!");
@@ -220,7 +222,7 @@ public static boolean remove(CalendarEvent record) {
// CollectionRepository.updateItemCount(connection, record.getCollectionId(), -1);
// CategoryRepository.updateItemCount(connection, record.getCategoryId(), -1);
// Delete the record
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("event_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("event_id = ?", record.getId()).execute(connection);
// Finish transaction
transaction.commit();
return true;
@@ -231,7 +233,7 @@ public static boolean remove(CalendarEvent record) {
}
public static void removeAll(Connection connection, Calendar calendar) throws SQLException {
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("calendar_id = ?", calendar.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("calendar_id = ?", calendar.getId()).execute(connection);
}
private static CalendarEvent buildRecord(ResultSet rs) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/CalendarRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/CalendarRepository.java
index f771bdb35..2e73117cf 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/CalendarRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/CalendarRepository.java
@@ -1,4 +1,5 @@
/*
+ * Copyright 2026 Matt Rajkowski (https://github.com/rajkowski)
* Copyright 2022 SimIS Inc. (https://www.simiscms.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -26,14 +27,15 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.AutoRollback;
+import com.github.rajkowski.database.AutoStartTransaction;
+import com.github.rajkowski.database.DB;
+import com.github.rajkowski.database.DataConstraints;
+import com.github.rajkowski.database.DataResult;
+import com.github.rajkowski.database.Insert;
+import com.github.rajkowski.database.Select;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.domain.model.cms.Calendar;
-import com.simisinc.platform.infrastructure.database.AutoRollback;
-import com.simisinc.platform.infrastructure.database.AutoStartTransaction;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.DataConstraints;
-import com.simisinc.platform.infrastructure.database.DataResult;
-import com.simisinc.platform.infrastructure.database.SqlUtils;
-import com.simisinc.platform.infrastructure.database.SqlWhere;
/**
* Persists and retrieves calendar objects
@@ -48,34 +50,40 @@ public class CalendarRepository {
private static String TABLE_NAME = "calendars";
private static String[] PRIMARY_KEY = new String[] { "calendar_id" };
- private static DataResult query(CalendarSpecification specification, DataConstraints constraints) {
- SqlWhere where = null;
+ private static DataResult query(CalendarSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("calendars.*").FROM(TABLE_NAME).WHERE();
if (specification != null) {
- where = DB.WHERE()
- .andAddIfHasValue("calendar_id = ?", specification.getId(), -1)
- .andAddIfHasValue("calendar_unique_id = ?", specification.getUniqueId());
+ if (specification.getId() > -1) {
+ select.AND("calendar_id = ?", specification.getId());
+ }
+ if (StringUtils.isNotBlank(specification.getUniqueId())) {
+ select.AND("calendar_unique_id = ?", specification.getUniqueId());
+ }
}
- return DB.selectAllFrom(TABLE_NAME, where, constraints, CalendarRepository::buildRecord);
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(CalendarRepository::buildRecord);
}
public static Calendar findById(long calendarId) {
if (calendarId == -1) {
return null;
}
- return (Calendar) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("calendar_id = ?", calendarId),
- CalendarRepository::buildRecord);
+ return DB.SELECT("calendars.*")
+ .FROM(TABLE_NAME)
+ .WHERE("calendar_id = ?", calendarId)
+ .returnRecord(CalendarRepository::buildRecord);
}
public static Calendar findByUniqueId(String calendarUniqueId) {
if (StringUtils.isBlank(calendarUniqueId)) {
return null;
}
- return (Calendar) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("calendar_unique_id = ?", calendarUniqueId),
- CalendarRepository::buildRecord);
+ return DB.SELECT("calendars.*")
+ .FROM(TABLE_NAME)
+ .WHERE("calendar_unique_id = ?", calendarUniqueId)
+ .returnRecord(CalendarRepository::buildRecord);
}
public static List findAll() {
@@ -87,8 +95,7 @@ public static List findAll(CalendarSpecification specification, DataCo
constraints = new DataConstraints();
}
constraints.setDefaultColumnToSortBy("calendar_id");
- DataResult result = query(specification, constraints);
- return (List) result.getRecords();
+ return query(specification, constraints).getRecords();
}
public static Calendar save(Calendar record) {
@@ -99,15 +106,15 @@ public static Calendar save(Calendar record) {
}
public static Calendar add(Calendar record) {
- SqlUtils insertValues = new SqlUtils()
- .add("calendar_unique_id", StringUtils.trimToNull(record.getUniqueId()))
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("description", StringUtils.trimToNull(record.getDescription()))
- .add("color", StringUtils.trimToNull(record.getColor()))
- .add("created_by", record.getCreatedBy())
- .add("modified_by", record.getModifiedBy())
- .add("enabled", record.getEnabled());
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("calendar_unique_id", StringUtils.trimToNull(record.getUniqueId()))
+ .FIELD("name", StringUtils.trimToNull(record.getName()))
+ .FIELD("description", StringUtils.trimToNull(record.getDescription()))
+ .FIELD("color", StringUtils.trimToNull(record.getColor()))
+ .FIELD("created_by", record.getCreatedBy())
+ .FIELD("modified_by", record.getModifiedBy())
+ .FIELD("enabled", record.getEnabled());
+ record.setId(insert.execute());
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -116,15 +123,16 @@ public static Calendar add(Calendar record) {
}
public static Calendar update(Calendar record) {
- SqlUtils updateValues = new SqlUtils()
- .add("calendar_unique_id", StringUtils.trimToNull(record.getUniqueId()))
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("description", StringUtils.trimToNull(record.getDescription()))
- .add("color", StringUtils.trimToNull(record.getColor()))
- .add("enabled", record.getEnabled())
- .add("modified_by", record.getModifiedBy())
- .add("modified", new Timestamp(System.currentTimeMillis()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("calendar_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("calendar_unique_id", StringUtils.trimToNull(record.getUniqueId()))
+ .SET("name", StringUtils.trimToNull(record.getName()))
+ .SET("description", StringUtils.trimToNull(record.getDescription()))
+ .SET("color", StringUtils.trimToNull(record.getColor()))
+ .SET("enabled", record.getEnabled())
+ .SET("modified_by", record.getModifiedBy())
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("calendar_id = ?", record.getId());
+ if (update.execute()) {
// CacheManager.invalidateKey(CacheManager.CONTENT_UNIQUE_ID_CACHE, record.getUniqueId());
return record;
}
@@ -139,7 +147,7 @@ public static boolean remove(Calendar record) {
// Delete the references
CalendarEventRepository.removeAll(connection, record);
// Delete the record
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("calendar_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("calendar_id = ?", record.getId()).execute(connection);
// Finish transaction
transaction.commit();
return true;
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/ContentRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/ContentRepository.java
index e6c99ab3b..22ca8b574 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/ContentRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/ContentRepository.java
@@ -26,15 +26,16 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.DB;
+import com.github.rajkowski.database.DataConstraints;
+import com.github.rajkowski.database.DataResult;
+import com.github.rajkowski.database.Insert;
+import com.github.rajkowski.database.Select;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.application.cms.HtmlCommand;
import com.simisinc.platform.application.cms.ResolveContentDirectivesCommand;
import com.simisinc.platform.domain.model.cms.Content;
import com.simisinc.platform.infrastructure.cache.CacheManager;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.DataConstraints;
-import com.simisinc.platform.infrastructure.database.DataResult;
-import com.simisinc.platform.infrastructure.database.SqlUtils;
-import com.simisinc.platform.infrastructure.database.SqlWhere;
/**
* Persists and retrieves content objects
@@ -49,45 +50,45 @@ public class ContentRepository {
private static String TABLE_NAME = "content";
private static String[] PRIMARY_KEY = new String[] { "content_id" };
- private static DataResult query(ContentSpecification specification, DataConstraints constraints) {
- SqlUtils select = new SqlUtils();
- SqlWhere where = null;
- SqlUtils orderBy = null;
+ private static DataResult query(ContentSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("content.*").FROM(TABLE_NAME).WHERE();
if (specification != null) {
- where = DB.WHERE()
- .andAddIfHasValue("content_id = ?", specification.getId(), -1)
- .andAddIfHasValue("content_unique_id = ?", specification.getUniqueId());
+ if (specification.getId() > -1) {
+ select.AND("content_id = ?", specification.getId());
+ }
+ if (StringUtils.isNotBlank(specification.getUniqueId())) {
+ select.AND("content_unique_id = ?", specification.getUniqueId());
+ }
if (StringUtils.isNotBlank(specification.getSearchTerm())) {
-
String quotedSearchTerm = "\"" + specification.getSearchTerm().trim() + "\"";
String searchTermSeparated = specification.getSearchTerm().trim().replaceAll("\\s+", " OR ");
String searchToUse = quotedSearchTerm + " OR " + searchTermSeparated;
String searchTermPattern = "%" + specification.getSearchTerm().trim() + "%";
- select.add(
+ select.SELECT(
"ts_headline('english', content_text, websearch_to_tsquery('content_stem', ?), 'StartSel=${b}, StopSel=${/b}, MaxWords=30, MinWords=15, ShortWord=3, HighlightAll=FALSE, MaxFragments=2, FragmentDelimiter=\" ... \"') AS highlight",
specification.getSearchTerm().trim());
- select.add("ts_rank_cd(tsv, websearch_to_tsquery('content_stem', ?)) AS rank", searchToUse);
+ select.SELECT("ts_rank_cd(tsv, websearch_to_tsquery('content_stem', ?)) AS rank", searchToUse);
- where.AND("(tsv @@ websearch_to_tsquery('content_stem', ?) OR content_unique_id LIKE ?)",
- new String[] { searchToUse, searchTermPattern });
-
- // Override the order by for rank first
- orderBy = new SqlUtils();
- orderBy.add("rank DESC, content.modified DESC");
+ select.AND("(tsv @@ websearch_to_tsquery('content_stem', ?) OR content_unique_id LIKE ?)",
+ searchToUse, searchTermPattern);
+ select.ORDER_BY("rank DESC, content.modified DESC");
}
}
- return DB.selectAllFrom(TABLE_NAME, select, where, orderBy, constraints, ContentRepository::buildRecord);
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(ContentRepository::buildRecord);
}
public static Content findByUniqueId(String contentUniqueId) {
if (StringUtils.isBlank(contentUniqueId)) {
return null;
}
- return (Content) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("content_unique_id = ?", contentUniqueId),
- ContentRepository::buildRecord);
+ return DB.SELECT("content.*")
+ .FROM(TABLE_NAME)
+ .WHERE("content_unique_id = ?", contentUniqueId)
+ .returnRecord(ContentRepository::buildRecord);
}
public static List findAll() {
@@ -99,11 +100,7 @@ public static List findAll(ContentSpecification specification, DataCons
constraints = new DataConstraints();
}
constraints.setDefaultColumnToSortBy("content_unique_id");
- DataResult result = query(specification, constraints);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ return query(specification, constraints).getRecords();
}
public static Content save(Content record) {
@@ -114,16 +111,15 @@ public static Content save(Content record) {
}
public static Content add(Content record) {
- SqlUtils insertValues = new SqlUtils()
- .add("content_unique_id", StringUtils.trimToNull(record.getUniqueId()))
- .add("content", StringUtils.trimToNull(record.getContent()))
- .add("content_text",
- HtmlCommand
- .text(ResolveContentDirectivesCommand.resolveDirectives(StringUtils.trimToNull(record.getContent()))))
- .add("draft_content", StringUtils.trimToNull(record.getDraftContent()))
- .add("created_by", record.getCreatedBy())
- .add("modified_by", record.getModifiedBy());
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("content_unique_id", StringUtils.trimToNull(record.getUniqueId()))
+ .FIELD("content", StringUtils.trimToNull(record.getContent()))
+ .FIELD("content_text",
+ HtmlCommand.text(ResolveContentDirectivesCommand.resolveDirectives(StringUtils.trimToNull(record.getContent()))))
+ .FIELD("draft_content", StringUtils.trimToNull(record.getDraftContent()))
+ .FIELD("created_by", record.getCreatedBy())
+ .FIELD("modified_by", record.getModifiedBy());
+ record.setId(insert.execute());
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -132,17 +128,14 @@ public static Content add(Content record) {
}
public static Content update(Content record) {
- SqlUtils updateValues = new SqlUtils()
- .add("content", StringUtils.trimToNull(record.getContent()))
- .add("content_text",
- HtmlCommand
- .text(ResolveContentDirectivesCommand.resolveDirectives(StringUtils.trimToNull(record.getContent()))))
- .add("draft_content", StringUtils.trimToNull(record.getDraftContent()))
- .add("modified_by", record.getModifiedBy())
- .add("modified", new Timestamp(System.currentTimeMillis()));
- if (DB.update(TABLE_NAME,
- updateValues,
- DB.WHERE("content_unique_id = ?", StringUtils.trimToNull(record.getUniqueId())))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("content", StringUtils.trimToNull(record.getContent()))
+ .SET("content_text",
+ HtmlCommand.text(ResolveContentDirectivesCommand.resolveDirectives(StringUtils.trimToNull(record.getContent()))))
+ .SET("draft_content", StringUtils.trimToNull(record.getDraftContent()))
+ .SET("modified_by", record.getModifiedBy())
+ .SET("modified", new Timestamp(System.currentTimeMillis()));
+ if (update.WHERE("content_unique_id = ?", StringUtils.trimToNull(record.getUniqueId())).execute()) {
CacheManager.invalidateKey(CacheManager.CONTENT_UNIQUE_ID_CACHE, record.getUniqueId());
return record;
}
@@ -154,16 +147,13 @@ public static void publish(Content record) {
if (StringUtils.isBlank(record.getUniqueId())) {
return;
}
- // Handle publishing and making sure there is content to publish
- SqlUtils updateValues = new SqlUtils();
- updateValues.add("content = draft_content");
- updateValues.add("draft_content = null");
- updateValues.add("content_text", HtmlCommand
- .text(ResolveContentDirectivesCommand.resolveDirectives(StringUtils.trimToNull(record.getContent()))));
- if (DB.update(
- TABLE_NAME,
- updateValues,
- DB.WHERE("draft_content IS NOT NULL AND content_unique_id = ?", record.getUniqueId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("content", "draft_content")
+ .SET("draft_content", (String) null)
+ .SET("content_text", HtmlCommand
+ .text(ResolveContentDirectivesCommand.resolveDirectives(StringUtils.trimToNull(record.getContent()))))
+ .WHERE("draft_content IS NOT NULL AND content_unique_id = ?", record.getUniqueId());
+ if (update.execute()) {
CacheManager.invalidateKey(CacheManager.CONTENT_UNIQUE_ID_CACHE, record.getUniqueId());
}
}
@@ -175,17 +165,11 @@ public static List findAllEmbeddingReferences(String uniqueId) {
if (StringUtils.isBlank(uniqueId)) {
return null;
}
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- new SqlUtils(),
- DB.WHERE("content LIKE ?", "%${uniqueId:" + uniqueId + "}%"),
- null,
- null,
- ContentRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ DataResult result = DB.SELECT("content.*")
+ .FROM(TABLE_NAME)
+ .WHERE("content LIKE ?", "%${uniqueId:" + uniqueId + "}%")
+ .returnDataResult(ContentRepository::buildRecord);
+ return result.getRecords();
}
/**
@@ -193,16 +177,17 @@ public static List findAllEmbeddingReferences(String uniqueId) {
*/
public static void updateEmbeddingContentText(String uniqueId) {
List embeddingRecords = findAllEmbeddingReferences(uniqueId);
- if (embeddingRecords == null) {
+ if (embeddingRecords == null || embeddingRecords.isEmpty()) {
return;
}
for (Content embedding : embeddingRecords) {
- SqlUtils updateValues = new SqlUtils()
- .add("content_text",
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("content_text",
HtmlCommand.text(
ResolveContentDirectivesCommand.resolveDirectives(StringUtils.trimToNull(embedding.getContent()))))
- .add("modified", new Timestamp(System.currentTimeMillis()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("content_unique_id = ?", embedding.getUniqueId()))) {
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("content_unique_id = ?", embedding.getUniqueId());
+ if (update.execute()) {
CacheManager.invalidateKey(CacheManager.CONTENT_UNIQUE_ID_CACHE, embedding.getUniqueId());
LOG.debug("Updated content_text for embedding content: " + embedding.getUniqueId());
}
@@ -213,11 +198,10 @@ public static void removeDraft(Content record) {
if (record == null || StringUtils.isBlank(record.getUniqueId())) {
return;
}
- String updateValues = "draft_content = null";
- if (DB.update(
- TABLE_NAME,
- updateValues,
- DB.WHERE("content_unique_id = ?", record.getUniqueId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("draft_content", (String) null)
+ .WHERE("content_unique_id = ?", record.getUniqueId());
+ if (update.execute()) {
CacheManager.invalidateKey(CacheManager.CONTENT_UNIQUE_ID_CACHE, record.getUniqueId());
}
}
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FileItemRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FileItemRepository.java
index e958f7830..23825c92d 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FileItemRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FileItemRepository.java
@@ -22,7 +22,6 @@
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
-import java.sql.Types;
import java.util.Arrays;
import java.util.List;
@@ -30,19 +29,20 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.AutoRollback;
+import com.github.rajkowski.database.AutoStartTransaction;
+import com.github.rajkowski.database.CastType;
+import com.github.rajkowski.database.ConditionGroup;
+import com.github.rajkowski.database.DB;
+import com.github.rajkowski.database.DataConstraints;
+import com.github.rajkowski.database.DataResult;
+import com.github.rajkowski.database.Insert;
+import com.github.rajkowski.database.Select;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.application.json.JsonCommand;
import com.simisinc.platform.domain.model.cms.FileItem;
import com.simisinc.platform.domain.model.cms.Folder;
import com.simisinc.platform.domain.model.cms.SubFolder;
-import com.simisinc.platform.infrastructure.database.AutoRollback;
-import com.simisinc.platform.infrastructure.database.AutoStartTransaction;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.DataConstraints;
-import com.simisinc.platform.infrastructure.database.DataResult;
-import com.simisinc.platform.infrastructure.database.SqlJoins;
-import com.simisinc.platform.infrastructure.database.SqlUtils;
-import com.simisinc.platform.infrastructure.database.SqlValue;
-import com.simisinc.platform.infrastructure.database.SqlWhere;
import com.simisinc.platform.presentation.controller.DataConstants;
import com.simisinc.platform.presentation.controller.UserSession;
import com.zeroio.platform.infrastructure.persistence.cms.PageFileRepository;
@@ -61,8 +61,8 @@ public class FileItemRepository {
private static String[] PRIMARY_KEY = new String[] { "file_id" };
private static DataResult query(FileSpecification specification, DataConstraints constraints) {
-
- SqlUtils select = DB.SELECT(
+
+ Select select = DB.SELECT(
TABLE_NAME + ".file_id",
TABLE_NAME + ".folder_id",
TABLE_NAME + ".filename",
@@ -91,11 +91,9 @@ private static DataResult query(FileSpecification specification, DataConstraints
TABLE_NAME + ".sub_folder_id",
TABLE_NAME + ".category_id",
TABLE_NAME + ".web_path",
- TABLE_NAME + ".tags");
-
- SqlJoins joins = new SqlJoins();
- SqlWhere where = DB.WHERE();
- SqlUtils orderBy = new SqlUtils();
+ TABLE_NAME + ".tags")
+ .FROM(TABLE_NAME)
+ .WHERE();
final boolean includeDocumentText = specification != null && specification.getIncludeDocumentText();
@@ -103,25 +101,33 @@ private static DataResult query(FileSpecification specification, DataConstraints
// Only include this potentially-large field when requested
if (includeDocumentText) {
- select.add(TABLE_NAME + ".document_text");
+ select.SELECT(TABLE_NAME + ".document_text");
}
- joins.add("LEFT JOIN folders ON (files.folder_id = folders.folder_id)");
- where
- .andAddIfHasValue("file_id = ?", specification.getId(), -1)
- .andAddIfHasValue("folders.folder_id = ?", specification.getFolderId(), -1)
- .andAddIfHasValue("sub_folder_id = ?", specification.getSubFolderId(), -1)
- .andAddIfHasValue("barcode = ?", specification.getBarcode());
+ select.LEFT_JOIN("folders").ON("files.folder_id = folders.folder_id");
+
+ if (specification.getId() > -1) {
+ select.AND("file_id = ?", specification.getId());
+ }
+ if (specification.getFolderId() > -1) {
+ select.AND("folders.folder_id = ?", specification.getFolderId());
+ }
+ if (specification.getSubFolderId() > -1) {
+ select.AND("sub_folder_id = ?", specification.getSubFolderId());
+ }
+ if (StringUtils.isNotBlank(specification.getBarcode())) {
+ select.AND("barcode = ?", specification.getBarcode());
+ }
if (specification.getFilename() != null) {
- where.AND("LOWER(files.filename) = ?", specification.getFilename().trim().toLowerCase());
+ select.AND("LOWER(files.filename) = ?", specification.getFilename().trim().toLowerCase());
}
if (specification.getFileType() != null) {
- where.AND("LOWER(files.file_type) = ANY(?)",
- Arrays.stream(specification.getFileType()).map(String::toLowerCase).toArray(String[]::new), Types.ARRAY);
+ select.AND("LOWER(files.file_type) = ANY(?)",
+ Arrays.stream(specification.getFileType()).map(String::toLowerCase).toArray(String[]::new), CastType.ARRAY);
}
if (specification.getFileExtension() != null) {
- where.AND("LOWER(files.extension) = ANY(?)",
- Arrays.stream(specification.getFileExtension()).map(String::toLowerCase).toArray(String[]::new), Types.ARRAY);
+ select.AND("LOWER(files.extension) = ANY(?)",
+ Arrays.stream(specification.getFileExtension()).map(String::toLowerCase).toArray(String[]::new), CastType.ARRAY);
}
if (specification.getMatchesName() != null) {
String likeValue = specification.getMatchesName().trim()
@@ -129,23 +135,23 @@ private static DataResult query(FileSpecification specification, DataConstraints
.replace("%", "!%")
.replace("_", "!_")
.replace("[", "![");
- where.AND("LOWER(files.title) LIKE LOWER(?) ESCAPE '!'", "%" + likeValue + "%");
+ select.AND("LOWER(files.title) LIKE LOWER(?) ESCAPE '!'", "%" + likeValue + "%");
}
if (specification.getWithinLastDays() > 0) {
- where.AND("files.created > NOW() - INTERVAL '" + specification.getWithinLastDays() + " days'");
+ select.AND("files.created > NOW() - INTERVAL '" + specification.getWithinLastDays() + " days'");
}
if (specification.getInASubFolder() != DataConstants.UNDEFINED) {
if (specification.getInASubFolder() == DataConstants.TRUE) {
- where.AND("sub_folder_id IS NOT NULL");
+ select.AND("sub_folder_id IS NOT NULL");
} else {
- where.AND("sub_folder_id IS NULL");
+ select.AND("sub_folder_id IS NULL");
}
}
if (specification.getIsProcessed() != DataConstants.UNDEFINED) {
if (specification.getIsProcessed() == DataConstants.TRUE) {
- where.AND("processed IS NOT NULL");
+ select.AND("processed IS NOT NULL");
} else {
- where.AND("processed IS NULL");
+ select.AND("processed IS NULL");
}
}
@@ -153,58 +159,58 @@ private static DataResult query(FileSpecification specification, DataConstraints
// User must be in a user group with folder access
if (specification.getForUserId() != DataConstants.UNDEFINED) {
if (specification.getForUserId() == UserSession.GUEST_ID) {
- where.AND("folders.allows_guests = true");
+ select.AND("folders.allows_guests = true");
} else {
- // For logged out and logged in users
- where.AND(
- "(allows_guests = true " +
- "OR (has_allowed_groups = true " +
- "AND EXISTS (SELECT 1 FROM folder_groups WHERE folder_groups.folder_id = folders.folder_id AND view_all = true "
- +
- "AND EXISTS (SELECT 1 FROM user_groups WHERE user_groups.group_id = folder_groups.group_id AND user_id = ?))"
- +
- ")" +
- ")",
+ select.AND(
+ "(allows_guests = true OR (has_allowed_groups = true AND EXISTS (SELECT 1 FROM folder_groups WHERE folder_groups.folder_id = folders.folder_id AND view_all = true AND EXISTS (SELECT 1 FROM user_groups WHERE user_groups.group_id = folder_groups.group_id AND user_id = ?))))",
specification.getForUserId());
}
}
// For versionWebPath
if (specification.getVersionWebPath() != null) {
- where.AND(
+ select.AND(
"(web_path = ? OR EXISTS (SELECT 1 FROM file_versions WHERE file_versions.web_path = ? AND file_versions.file_id = ?))",
- new Object[] { specification.getVersionWebPath(), specification.getVersionWebPath(),
- specification.getId() });
+ specification.getVersionWebPath(), specification.getVersionWebPath(), specification.getId());
}
// Use the search engine
if (StringUtils.isNotBlank(specification.getSearchName())) {
- select.add("ts_rank_cd(tsv, websearch_to_tsquery('file_stem', ?)) AS rank",
- specification.getSearchName().trim());
- where.AND("tsv @@ websearch_to_tsquery('file_stem', ?)", specification.getSearchName().trim());
- // Override the order by for rank first
- orderBy.add("rank DESC, file_id");
+ select.SELECT("ts_rank_cd(tsv, websearch_to_tsquery('file_stem', ?)) AS rank", specification.getSearchName().trim());
+ select.AND("tsv @@ websearch_to_tsquery('file_stem', ?)", specification.getSearchName().trim());
+ select.ORDER_BY("rank DESC, file_id");
}
if (specification.getRegionTags() != null && specification.getRegionTags().length > 0) {
- where.AND("tags", specification.getRegionTags(), SqlWhere.OR_OPERATOR);
+ ConditionGroup condition = ConditionGroup.build("tags", specification.getRegionTags(), ConditionGroup.ANY);
+ if (condition != null) {
+ select.AND(condition.sql(), (Object[]) condition.values());
+ }
}
if (specification.getFilterTags() != null && specification.getFilterTags().length > 0) {
- where.AND("tags", specification.getFilterTags(), SqlWhere.AND_OPERATOR);
+ ConditionGroup filterCondition = ConditionGroup.build("tags", specification.getFilterTags(), ConditionGroup.ALL);
+ if (filterCondition != null) {
+ select.AND(filterCondition.sql(), (Object[]) filterCondition.values());
+ }
}
if (specification.getExcludeTags() != null && specification.getExcludeTags().length > 0) {
- where.AND("tags", specification.getExcludeTags(), SqlWhere.NOT_OR_OPERATOR);
+ // excluded legacy tag operators left as-is for now; repository still requires final compile pass
+ ConditionGroup excludeCondition = ConditionGroup.build("tags", specification.getExcludeTags(),
+ ConditionGroup.NOT_ANY);
+ if (excludeCondition != null) {
+ select.AND(excludeCondition.sql(), (Object[]) excludeCondition.values());
+ }
}
// Add modified date range filters
// Some imported files can have a null modified date, so fall back to created.
if (specification.getModifiedAfter() != null) {
- where.AND("COALESCE(files.modified, files.created) >= ?", specification.getModifiedAfter());
+ select.AND("COALESCE(files.modified, files.created) >= ?", specification.getModifiedAfter());
}
if (specification.getModifiedBefore() != null) {
- where.AND("COALESCE(files.modified, files.created) <= ?", specification.getModifiedBefore());
+ select.AND("COALESCE(files.modified, files.created) <= ?", specification.getModifiedBefore());
}
// Add modified by user filter
@@ -219,39 +225,45 @@ private static DataResult query(FileSpecification specification, DataConstraints
userIdsBoxed[i] = specification.getModifiedByUserIds()[i];
}
userCondition.append(")");
- where.AND(userCondition.toString(), (Object[]) userIdsBoxed);
+ select.AND(userCondition.toString(), (Object[]) userIdsBoxed);
}
}
- return DB.selectFrom(
- TABLE_NAME, select, joins, where, orderBy, constraints,
- rs -> buildRecord(rs, includeDocumentText));
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(rs -> buildRecord(rs, includeDocumentText));
}
public static FileItem findById(long id) {
if (id == -1) {
return null;
}
- return (FileItem) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("file_id = ?", id),
- FileItemRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("file_id = ?", id)
+ .returnRecord(FileItemRepository::buildRecord);
}
public static FileItem findByWebPathAndId(String versionWebPath, long id) {
if (StringUtils.isBlank(versionWebPath) || id == -1) {
return null;
}
- return (FileItem) DB.selectRecordFrom(TABLE_NAME, DB.WHERE("web_path = ?", versionWebPath).AND("file_id = ?", id),
- FileItemRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("web_path = ?", versionWebPath)
+ .AND("file_id = ?", id)
+ .returnRecord(FileItemRepository::buildRecord);
}
public static FileItem findByWebPath(String versionWebPath) {
if (StringUtils.isBlank(versionWebPath)) {
return null;
}
- return (FileItem) DB.selectRecordFrom(TABLE_NAME, DB.WHERE("web_path = ?", versionWebPath),
- FileItemRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("web_path = ?", versionWebPath)
+ .returnRecord(FileItemRepository::buildRecord);
}
public static List findAll() {
@@ -275,32 +287,36 @@ public static FileItem save(FileItem record) {
}
private static FileItem add(FileItem record) {
- SqlUtils insertValues = new SqlUtils()
- .add("folder_id", record.getFolderId())
- .addIfExists("sub_folder_id", record.getSubFolderId(), -1L)
- .addIfExists("category_id", record.getCategoryId(), -1L)
- .add("filename", StringUtils.trimToNull(record.getFilename()))
- .add("title", StringUtils.trimToNull(record.getTitle()))
- .add("barcode", StringUtils.trimToNull(record.getBarcode()))
- .add("version", StringUtils.trimToNull(record.getVersion()))
- .add("extension", StringUtils.trimToNull(record.getExtension()))
- .add("path", StringUtils.trimToNull(record.getFileServerPath()))
- .add("file_length", record.getFileLength())
- .add("file_type", record.getFileType())
- .add("mime_type", record.getMimeType())
- .add("file_hash", record.getFileHash())
- .add("web_path", StringUtils.trimToNull(record.getWebPath()))
- .add("width", record.getWidth(), -1)
- .add("height", record.getHeight(), -1)
- .add("summary", StringUtils.trimToNull(record.getSummary()))
- .add("created_by", record.getCreatedBy())
- .add("modified_by", record.getModifiedBy())
- .add("processed", record.getProcessed())
- .add("expiration_date", record.getExpirationDate())
- .add("privacy_type", record.getPrivacyType())
- .add("default_token", StringUtils.trimToNull(record.getDefaultToken()));
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("folder_id", record.getFolderId())
+ .FIELD("filename", StringUtils.trimToNull(record.getFilename()))
+ .FIELD("title", StringUtils.trimToNull(record.getTitle()))
+ .FIELD("barcode", StringUtils.trimToNull(record.getBarcode()))
+ .FIELD("version", StringUtils.trimToNull(record.getVersion()))
+ .FIELD("extension", StringUtils.trimToNull(record.getExtension()))
+ .FIELD("path", StringUtils.trimToNull(record.getFileServerPath()))
+ .FIELD("file_length", record.getFileLength())
+ .FIELD("file_type", record.getFileType())
+ .FIELD("mime_type", record.getMimeType())
+ .FIELD("file_hash", record.getFileHash())
+ .FIELD("web_path", StringUtils.trimToNull(record.getWebPath()))
+ .FIELD("width", record.getWidth() != -1 ? record.getWidth() : null)
+ .FIELD("height", record.getHeight() != -1 ? record.getHeight() : null)
+ .FIELD("summary", StringUtils.trimToNull(record.getSummary()))
+ .FIELD("created_by", record.getCreatedBy())
+ .FIELD("modified_by", record.getModifiedBy())
+ .FIELD("processed", record.getProcessed())
+ .FIELD("expiration_date", record.getExpirationDate())
+ .FIELD("privacy_type", record.getPrivacyType())
+ .FIELD("default_token", StringUtils.trimToNull(record.getDefaultToken()));
+ if (record.getSubFolderId() != -1) {
+ insert.FIELD("sub_folder_id", record.getSubFolderId());
+ }
+ if (record.getCategoryId() != -1) {
+ insert.FIELD("category_id", record.getCategoryId());
+ }
if (record.getTags() != null && record.getTags().length > 0) {
- insertValues.add(new SqlValue("tags", SqlValue.JSONB_TYPE, JsonCommand.toJsonArray(record.getTags())));
+ insert.FIELD("tags", JsonCommand.toJsonArray(record.getTags()), CastType.JSONB);
}
// Use a transaction
@@ -308,7 +324,7 @@ private static FileItem add(FileItem record) {
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
// In a transaction (use the existing connection)
- record.setId(DB.insertInto(connection, TABLE_NAME, insertValues, PRIMARY_KEY));
+ record.setId(insert.execute(connection));
// Create a version record
FileVersionRepository.add(connection, record);
// Update the file counts
@@ -331,35 +347,37 @@ private static FileItem update(FileItem record) {
// Update the counts in case the folder changed
FolderRepository.updateFileCountForFileId(connection, record.getId(), -1);
SubFolderRepository.updateFileCountForFileId(connection, record.getId(), -1);
- // Update the record
- SqlUtils updateValues = new SqlUtils()
- .add("folder_id", record.getFolderId())
- .add("sub_folder_id", record.getSubFolderId(), -1L)
- .add("category_id", record.getCategoryId(), -1L)
- .addIfExists("filename", StringUtils.trimToNull(record.getFilename()))
- .add("title", StringUtils.trimToNull(record.getTitle()))
- .add("barcode", StringUtils.trimToNull(record.getBarcode()))
- .add("version", StringUtils.trimToNull(record.getVersion()))
- .addIfExists("width", record.getWidth(), -1)
- .addIfExists("height", record.getHeight(), -1)
- .add("summary", StringUtils.trimToNull(record.getSummary()))
- .add("modified_by", record.getModifiedBy())
- .add("processed", record.getProcessed())
- .add("expiration_date", record.getExpirationDate())
- .add("privacy_type", record.getPrivacyType());
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("folder_id", record.getFolderId())
+ .SET("sub_folder_id", record.getSubFolderId() != -1 ? record.getSubFolderId() : null)
+ .SET("category_id", record.getCategoryId() != -1 ? record.getCategoryId() : null)
+ .SET("title", StringUtils.trimToNull(record.getTitle()))
+ .SET("barcode", StringUtils.trimToNull(record.getBarcode()))
+ .SET("version", StringUtils.trimToNull(record.getVersion()))
+ .SET("summary", StringUtils.trimToNull(record.getSummary()))
+ .SET("modified_by", record.getModifiedBy())
+ .SET("processed", record.getProcessed())
+ .SET("expiration_date", record.getExpirationDate())
+ .SET("privacy_type", record.getPrivacyType());
+ if (StringUtils.trimToNull(record.getFilename()) != null) {
+ update.SET("filename", StringUtils.trimToNull(record.getFilename()));
+ }
+ if (record.getWidth() != -1) {
+ update.SET("width", record.getWidth());
+ }
+ if (record.getHeight() != -1) {
+ update.SET("height", record.getHeight());
+ }
if (record.getTags() != null && record.getTags().length > 0) {
- updateValues.add(new SqlValue("tags", SqlValue.JSONB_TYPE, JsonCommand.toJsonArray(record.getTags())));
+ update.SET("tags", JsonCommand.toJsonArray(record.getTags()), CastType.JSONB);
} else if (record.getTags() != null) {
- updateValues.add(new SqlValue("tags", SqlValue.JSONB_TYPE, null));
+ update.SET("tags", (String) null, CastType.JSONB);
}
- // .add("default_token", StringUtils.trimToNull(record.getDefaultToken()));
- if (DB.update(connection, TABLE_NAME, updateValues, DB.WHERE("file_id = ?", record.getId()))) {
- // Update related records
+ update.WHERE("file_id = ?", record.getId());
+ if (update.execute(connection).booleanValue()) {
FileVersionRepository.update(connection, record);
- // Update the folder count
FolderRepository.updateFileCountForFileId(connection, record.getId(), 1);
SubFolderRepository.updateFileCountForFileId(connection, record.getId(), 1);
- // Finish transaction
transaction.commit();
return record;
}
@@ -377,45 +395,41 @@ public static FileItem saveVersion(FileItem record) {
// Update the counts in case the folder changed
FolderRepository.updateFileCountForFileId(connection, record.getId(), -1);
SubFolderRepository.updateFileCountForFileId(connection, record.getId(), -1);
- // Update the record, including the web_path for new version URL
- SqlUtils updateValues = new SqlUtils()
- .add("folder_id", record.getFolderId())
- .add("sub_folder_id", record.getSubFolderId(), -1L)
- .add("category_id", record.getCategoryId(), -1L)
- .add("filename", StringUtils.trimToNull(record.getFilename()))
- .add("title", StringUtils.trimToNull(record.getTitle()))
- .add("barcode", StringUtils.trimToNull(record.getBarcode()))
- .add("version", StringUtils.trimToNull(record.getVersion()))
- .add("extension", StringUtils.trimToNull(record.getExtension()))
- .add("path", StringUtils.trimToNull(record.getFileServerPath()))
- .add("web_path", StringUtils.trimToNull(record.getWebPath()))
- .add("file_length", record.getFileLength())
- .add("file_type", record.getFileType())
- .add("mime_type", record.getMimeType())
- .add("file_hash", record.getFileHash())
- .add("width", record.getWidth(), -1)
- .add("height", record.getHeight(), -1)
- .add("summary", StringUtils.trimToNull(record.getSummary()))
- .add("modified_by", record.getModifiedBy())
- .add("modified", new Timestamp(System.currentTimeMillis()))
- .add("processed", record.getProcessed())
- .add("expiration_date", record.getExpirationDate())
- .add("privacy_type", record.getPrivacyType())
- .add("default_token", StringUtils.trimToNull(record.getDefaultToken()));
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("folder_id", record.getFolderId())
+ .SET("sub_folder_id", record.getSubFolderId() != -1 ? record.getSubFolderId() : null)
+ .SET("category_id", record.getCategoryId() != -1 ? record.getCategoryId() : null)
+ .SET("filename", StringUtils.trimToNull(record.getFilename()))
+ .SET("title", StringUtils.trimToNull(record.getTitle()))
+ .SET("barcode", StringUtils.trimToNull(record.getBarcode()))
+ .SET("version", StringUtils.trimToNull(record.getVersion()))
+ .SET("extension", StringUtils.trimToNull(record.getExtension()))
+ .SET("path", StringUtils.trimToNull(record.getFileServerPath()))
+ .SET("web_path", StringUtils.trimToNull(record.getWebPath()))
+ .SET("file_length", record.getFileLength())
+ .SET("file_type", record.getFileType())
+ .SET("mime_type", record.getMimeType())
+ .SET("file_hash", record.getFileHash())
+ .SET("width", record.getWidth() != -1 ? record.getWidth() : null)
+ .SET("height", record.getHeight() != -1 ? record.getHeight() : null)
+ .SET("summary", StringUtils.trimToNull(record.getSummary()))
+ .SET("modified_by", record.getModifiedBy())
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .SET("processed", record.getProcessed())
+ .SET("expiration_date", record.getExpirationDate())
+ .SET("privacy_type", record.getPrivacyType())
+ .SET("default_token", StringUtils.trimToNull(record.getDefaultToken()));
if (record.getTags() != null && record.getTags().length > 0) {
- updateValues.add(new SqlValue("tags", SqlValue.JSONB_TYPE, JsonCommand.toJsonArray(record.getTags())));
+ update.SET("tags", JsonCommand.toJsonArray(record.getTags()), CastType.JSONB);
} else if (record.getTags() != null) {
- updateValues.add(new SqlValue("tags", SqlValue.JSONB_TYPE, null));
+ update.SET("tags", (String) null, CastType.JSONB);
}
- if (DB.update(connection, TABLE_NAME, updateValues, DB.WHERE("file_id = ?", record.getId()))) {
- // Update related records
+ update.WHERE("file_id = ?", record.getId());
+ if (update.execute(connection).booleanValue()) {
FileVersionRepository.update(connection, record);
- // Update the folder counts
FolderRepository.updateFileCountForFileId(connection, record.getId(), 1);
SubFolderRepository.updateFileCountForFileId(connection, record.getId(), 1);
- // Create a version record
FileVersionRepository.add(connection, record);
- // Finish transaction
transaction.commit();
return record;
}
@@ -428,10 +442,11 @@ public static FileItem saveVersion(FileItem record) {
public static boolean updateDocumentText(FileItem record, String documentText) {
try (Connection connection = DB.getConnection()) {
- SqlUtils updateValues = new SqlUtils()
- .add("document_text", documentText)
- .add("processed", new Timestamp(System.currentTimeMillis()));
- if (DB.update(connection, TABLE_NAME, updateValues, DB.WHERE("file_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("document_text", documentText)
+ .SET("processed", new Timestamp(System.currentTimeMillis()))
+ .WHERE("file_id = ?", record.getId());
+ if (update.execute(connection).booleanValue()) {
return true;
}
} catch (SQLException se) {
@@ -451,8 +466,7 @@ public static boolean remove(FileItem record) {
SubFolderRepository.updateFileCount(connection, record.getSubFolderId(), -1);
PageFileRepository.removeAll(connection, record);
// Delete the record
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("file_id = ?", record.getId()));
- // Finish transaction
+ DB.DELETE().FROM(TABLE_NAME).WHERE("file_id = ?", record.getId()).execute(connection);
transaction.commit();
return true;
} catch (SQLException se) {
@@ -463,12 +477,12 @@ public static boolean remove(FileItem record) {
public static void removeAll(Connection connection, Folder record) throws SQLException {
PageFileRepository.removeAll(connection, record);
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("folder_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("folder_id = ?", record.getId()).execute(connection);
}
public static int removeAll(Connection connection, SubFolder record) throws SQLException {
PageFileRepository.removeAll(connection, record);
- return DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("sub_folder_id = ?", record.getId()));
+ return DB.DELETE().FROM(TABLE_NAME).WHERE("sub_folder_id = ?", record.getId()).execute(connection).booleanValue() ? 1 : 0;
}
private static PreparedStatement createPreparedStatementForUpdateDownloadCount(Connection connection, FileItem record)
@@ -495,13 +509,13 @@ public static boolean incrementDownloadCount(FileItem record) {
}
public static long findTotalFileSize() {
- return DB.selectFunction("SUM(file_length)", TABLE_NAME, null);
+ return DB.SELECT("SUM(file_length)").FROM(TABLE_NAME).returnValue(Long.class);
}
private static FileItem buildRecord(ResultSet rs) {
return buildRecord(rs, false);
}
-
+
private static FileItem buildRecord(ResultSet rs, boolean includeDocumentText) {
try {
FileItem record = new FileItem();
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FileVersionRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FileVersionRepository.java
index e2afe28f4..588c77954 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FileVersionRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FileVersionRepository.java
@@ -26,15 +26,16 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.DB;
+import com.github.rajkowski.database.DataConstraints;
+import com.github.rajkowski.database.DataResult;
+import com.github.rajkowski.database.Insert;
+import com.github.rajkowski.database.Select;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.domain.model.cms.FileItem;
import com.simisinc.platform.domain.model.cms.FileVersion;
import com.simisinc.platform.domain.model.cms.Folder;
import com.simisinc.platform.domain.model.cms.SubFolder;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.DataConstraints;
-import com.simisinc.platform.infrastructure.database.DataResult;
-import com.simisinc.platform.infrastructure.database.SqlUtils;
-import com.simisinc.platform.infrastructure.database.SqlWhere;
/**
* Persists and retrieves file version objects
@@ -49,26 +50,36 @@ public class FileVersionRepository {
private static String TABLE_NAME = "file_versions";
private static String[] PRIMARY_KEY = new String[] { "version_id" };
- private static DataResult query(FileVersionSpecification specification, DataConstraints constraints) {
- SqlWhere where = null;
+ private static DataResult query(FileVersionSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("file_versions.*").FROM(TABLE_NAME).WHERE();
if (specification != null) {
- where = DB.WHERE()
- .andAddIfHasValue("version_id = ?", specification.getId(), -1)
- .andAddIfHasValue("file_id = ?", specification.getFileId(), -1)
- .andAddIfHasValue("folder_id = ?", specification.getFolderId(), -1)
- .andAddIfHasValue("sub_folder_id = ?", specification.getSubFolderId(), -1);
+ if (specification.getId() > -1) {
+ select.AND("version_id = ?", specification.getId());
+ }
+ if (specification.getFileId() > -1) {
+ select.AND("file_id = ?", specification.getFileId());
+ }
+ if (specification.getFolderId() > -1) {
+ select.AND("folder_id = ?", specification.getFolderId());
+ }
+ if (specification.getSubFolderId() > -1) {
+ select.AND("sub_folder_id = ?", specification.getSubFolderId());
+ }
+ }
+ if (constraints != null) {
+ select.WITH(constraints);
}
- return DB.selectAllFrom(TABLE_NAME, where, constraints, FileVersionRepository::buildRecord);
+ return select.returnDataResult(FileVersionRepository::buildRecord);
}
public static FileVersion findById(long id) {
if (id == -1) {
return null;
}
- return (FileVersion) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("version_id = ?", id),
- FileVersionRepository::buildRecord);
+ return DB.SELECT("file_versions.*")
+ .FROM(TABLE_NAME)
+ .WHERE("version_id = ?", id)
+ .returnRecord(FileVersionRepository::buildRecord);
}
public static List findAll(FileVersionSpecification specification, DataConstraints constraints) {
@@ -76,8 +87,7 @@ public static List findAll(FileVersionSpecification specification,
constraints = new DataConstraints();
}
constraints.setDefaultColumnToSortBy("created DESC");
- DataResult result = query(specification, constraints);
- return (List) result.getRecords();
+ return query(specification, constraints).getRecords();
}
public static FileVersion save(FileVersion record) {
@@ -88,51 +98,53 @@ public static FileVersion save(FileVersion record) {
}
public static FileItem add(Connection connection, FileItem record) throws SQLException {
- SqlUtils insertValues = new SqlUtils()
- .add("file_id", record.getId())
- .add("folder_id", record.getFolderId())
- .addIfExists("sub_folder_id", record.getSubFolderId(), -1L)
- .addIfExists("category_id", record.getCategoryId(), -1L)
- .add("filename", StringUtils.trimToNull(record.getFilename()))
- .add("title", StringUtils.trimToNull(record.getTitle()))
- .add("version", StringUtils.trimToNull(record.getVersion()))
- .add("extension", StringUtils.trimToNull(record.getExtension()))
- .add("path", StringUtils.trimToNull(record.getFileServerPath()))
- .add("web_path", StringUtils.trimToNull(record.getWebPath()))
- .add("file_length", record.getFileLength())
- .add("file_type", record.getFileType())
- .add("mime_type", record.getMimeType())
- .add("file_hash", record.getFileHash())
- .addIfExists("width", record.getWidth(), -1)
- .addIfExists("height", record.getHeight(), -1)
- .add("summary", StringUtils.trimToNull(record.getSummary()))
- .add("created_by", record.getCreatedBy());
- DB.insertInto(connection, TABLE_NAME, insertValues, PRIMARY_KEY);
- // Manage a few related tables
- // Finish the transaction
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("file_id", record.getId())
+ .FIELD("folder_id", record.getFolderId())
+ .FIELD("filename", StringUtils.trimToNull(record.getFilename()))
+ .FIELD("title", StringUtils.trimToNull(record.getTitle()))
+ .FIELD("version", StringUtils.trimToNull(record.getVersion()))
+ .FIELD("extension", StringUtils.trimToNull(record.getExtension()))
+ .FIELD("path", StringUtils.trimToNull(record.getFileServerPath()))
+ .FIELD("web_path", StringUtils.trimToNull(record.getWebPath()))
+ .FIELD("file_length", record.getFileLength())
+ .FIELD("file_type", record.getFileType())
+ .FIELD("mime_type", record.getMimeType())
+ .FIELD("file_hash", record.getFileHash())
+ .FIELD("summary", StringUtils.trimToNull(record.getSummary()))
+ .FIELD("created_by", record.getCreatedBy());
+ if (record.getSubFolderId() != -1) {
+ insert.FIELD("sub_folder_id", record.getSubFolderId());
+ }
+ if (record.getCategoryId() != -1) {
+ insert.FIELD("category_id", record.getCategoryId());
+ }
+ if (record.getWidth() != -1) {
+ insert.FIELD("width", record.getWidth());
+ }
+ if (record.getHeight() != -1) {
+ insert.FIELD("height", record.getHeight());
+ }
+ insert.execute(connection);
return record;
}
private static FileVersion update(FileVersion record) {
- SqlUtils updateValues = new SqlUtils()
- .add("folder_id", record.getFolderId())
- .add("sub_folder_id", record.getSubFolderId(), -1L)
- .add("category_id", record.getCategoryId(), -1L)
- // .add("filename", StringUtils.trimToNull(record.getFilename()))
- .add("title", StringUtils.trimToNull(record.getTitle()))
- .add("version", StringUtils.trimToNull(record.getVersion()))
- // .add("extension", StringUtils.trimToNull(record.getExtension()))
- // .add("path", StringUtils.trimToNull(record.getFileServerPath()))
- // .add("file_length", record.getFileLength())
- // .add("file_type", record.getFileType())
- // .add("mime_type", record.getMimeType())
- // .add("file_hash", record.getFileHash())
- .addIfExists("width", record.getWidth(), -1)
- .addIfExists("height", record.getHeight(), -1)
- .add("summary", StringUtils.trimToNull(record.getSummary()))
- // .add("created_by", record.getCreatedBy())
- .add("modified_by", record.getModifiedBy());
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("version_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("folder_id", record.getFolderId())
+ .SET("sub_folder_id", record.getSubFolderId() == -1L ? null : record.getSubFolderId())
+ .SET("category_id", record.getCategoryId() == -1L ? null : record.getCategoryId())
+ .SET("title", StringUtils.trimToNull(record.getTitle()))
+ .SET("version", StringUtils.trimToNull(record.getVersion()))
+ .SET("summary", StringUtils.trimToNull(record.getSummary()))
+ .SET("modified_by", record.getModifiedBy());
+ if (record.getWidth() != -1) {
+ update.SET("width", record.getWidth());
+ }
+ if (record.getHeight() != -1) {
+ update.SET("height", record.getHeight());
+ }
+ if (update.WHERE("version_id = ?", record.getId()).execute().booleanValue()) {
return record;
}
LOG.error("The update failed!");
@@ -140,11 +152,12 @@ private static FileVersion update(FileVersion record) {
}
public static FileItem update(Connection connection, FileItem record) throws SQLException {
- SqlUtils updateValues = new SqlUtils()
- .add("folder_id", record.getFolderId())
- .add("sub_folder_id", record.getSubFolderId(), -1L)
- .add("category_id", record.getCategoryId(), -1L);
- if (DB.update(connection, TABLE_NAME, updateValues, DB.WHERE("file_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("folder_id", record.getFolderId())
+ .SET("sub_folder_id", record.getSubFolderId() == -1L ? null : record.getSubFolderId())
+ .SET("category_id", record.getCategoryId() == -1L ? null : record.getCategoryId())
+ .WHERE("file_id = ?", record.getId());
+ if (update.execute(connection).booleanValue()) {
return record;
}
LOG.error("The update fileItem failed!");
@@ -152,23 +165,23 @@ public static FileItem update(Connection connection, FileItem record) throws SQL
}
public static void remove(FileVersion record) {
- DB.deleteFrom(TABLE_NAME, DB.WHERE("version_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("version_id = ?", record.getId()).execute();
}
public static void removeAll(Connection connection, Folder record) throws SQLException {
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("folder_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("folder_id = ?", record.getId()).execute(connection);
}
public static void removeAll(Connection connection, SubFolder record) throws SQLException {
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("sub_folder_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("sub_folder_id = ?", record.getId()).execute(connection);
}
public static void removeAll(Connection connection, FileItem record) throws SQLException {
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("file_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("file_id = ?", record.getId()).execute(connection);
}
public static long findTotalFileSize() {
- return DB.selectFunction("SUM(file_length)", TABLE_NAME, null);
+ return DB.SELECT("SUM(file_length) AS total_file_length").FROM(TABLE_NAME).returnValue(Long.class);
}
private static FileVersion buildRecord(ResultSet rs) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FolderCategoryRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FolderCategoryRepository.java
index 0bce44146..f567f18c7 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FolderCategoryRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FolderCategoryRepository.java
@@ -1,4 +1,5 @@
/*
+ * Copyright 2026 Matt Rajkowski (https://github.com/rajkowski)
* Copyright 2022 SimIS Inc. (https://www.simiscms.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -24,12 +25,11 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.DB;
+import com.github.rajkowski.database.DataConstraints;
+import com.github.rajkowski.database.DataResult;
import com.simisinc.platform.domain.model.cms.Folder;
import com.simisinc.platform.domain.model.cms.FolderCategory;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.DataConstraints;
-import com.simisinc.platform.infrastructure.database.DataResult;
-import com.simisinc.platform.infrastructure.database.SqlUtils;
/**
* Persists and retrieves folder category objects
@@ -48,45 +48,39 @@ public static FolderCategory findById(long id) {
if (id == -1) {
return null;
}
- return (FolderCategory) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("category_id = ?", id),
- FolderCategoryRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("category_id = ?", id)
+ .returnRecord(FolderCategoryRepository::buildRecord);
}
public static List findAllByFolderId(long folderId) {
if (folderId == -1) {
return null;
}
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- DB.WHERE("folder_id = ?", folderId),
- new DataConstraints().setDefaultColumnToSortBy("category_id").setUseCount(false),
- FolderCategoryRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ DataResult result = DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("folder_id = ?", folderId)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("category_id").setUseCount(false))
+ .returnDataResult(FolderCategoryRepository::buildRecord);
+ return result.getRecords();
}
public static List findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- null,
- new DataConstraints().setDefaultColumnToSortBy("category_id"),
- FolderCategoryRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ DataResult result = DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("category_id"))
+ .returnDataResult(FolderCategoryRepository::buildRecord);
+ return result.getRecords();
}
public static FolderCategory add(FolderCategory record) {
- SqlUtils insertValues = new SqlUtils()
- .add("folder_id", record.getFolderId())
- .add("name", record.getName())
- .add("enabled", record.getEnabled());
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ long id = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("folder_id", record.getFolderId())
+ .FIELD("name", record.getName())
+ .FIELD("enabled", record.getEnabled())
+ .execute();
+ record.setId(id);
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -99,12 +93,11 @@ public static void insertFolderCategoryList(Connection connection, Folder folder
return;
}
for (FolderCategory category : folder.getFolderCategoryList()) {
- SqlUtils insertValues = new SqlUtils();
- insertValues
- .add("folder_id", folder.getId())
- .add("name", category.getName())
- .add("enabled", category.getEnabled());
- DB.insertInto(connection, TABLE_NAME, insertValues, PRIMARY_KEY);
+ DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("folder_id", folder.getId())
+ .FIELD("name", category.getName())
+ .FIELD("enabled", category.getEnabled())
+ .execute(connection);
}
}
@@ -113,32 +106,28 @@ public static void updateFolderCategoryList(Connection connection, Folder folder
return;
}
for (FolderCategory category : folder.getFolderCategoryList()) {
- // Determine if inserting or updating
if (category.getId() == -1) {
- // New category
- SqlUtils insertValues = new SqlUtils();
- insertValues
- .add("folder_id", folder.getId())
- .add("name", category.getName())
- .add("enabled", category.getEnabled());
- DB.insertInto(connection, TABLE_NAME, insertValues, PRIMARY_KEY);
+ DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("folder_id", folder.getId())
+ .FIELD("name", category.getName())
+ .FIELD("enabled", category.getEnabled())
+ .execute(connection);
} else {
- // Update existing
- SqlUtils updateValues = new SqlUtils();
- updateValues
- .add("name", category.getName())
- .add("enabled", category.getEnabled());
- DB.update(connection, TABLE_NAME, updateValues, DB.WHERE("category_id = ?", category.getId()));
+ DB.UPDATE(TABLE_NAME)
+ .SET("name", category.getName())
+ .SET("enabled", category.getEnabled())
+ .WHERE("category_id = ?", category.getId())
+ .execute(connection);
}
}
}
public static void removeAll(Connection connection, Folder folder) throws SQLException {
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("folder_id = ?", folder.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("folder_id = ?", folder.getId()).execute(connection);
}
public static void remove(Connection connection, FolderCategory folderCategory) throws SQLException {
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("category_id = ?", folderCategory.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("category_id = ?", folderCategory.getId()).execute(connection);
}
private static FolderCategory buildRecord(ResultSet rs) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FolderGroupRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FolderGroupRepository.java
index ef785443d..eb4b827d5 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FolderGroupRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FolderGroupRepository.java
@@ -1,4 +1,5 @@
/*
+ * Copyright 2026 Matt Rajkowski (https://github.com/rajkowski)
* Copyright 2022 SimIS Inc. (https://www.simiscms.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -24,14 +25,13 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.DB;
+import com.github.rajkowski.database.DataConstraints;
+import com.github.rajkowski.database.DataResult;
import com.simisinc.platform.domain.model.Group;
import com.simisinc.platform.domain.model.cms.Folder;
import com.simisinc.platform.domain.model.cms.FolderGroup;
import com.simisinc.platform.domain.model.items.PrivacyType;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.DataConstraints;
-import com.simisinc.platform.infrastructure.database.DataResult;
-import com.simisinc.platform.infrastructure.database.SqlUtils;
/**
* Properties for querying objects from the repository
@@ -50,27 +50,20 @@ public static List findAllByFolderId(long folderId) {
if (folderId == -1) {
return null;
}
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- DB.WHERE("folder_id = ?", folderId),
- new DataConstraints().setDefaultColumnToSortBy("allowed_id").setUseCount(false),
- FolderGroupRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ DataResult result = DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("folder_id = ?", folderId)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("allowed_id").setUseCount(false))
+ .returnDataResult(FolderGroupRepository::buildRecord);
+ return result.getRecords();
}
public static List findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- null,
- new DataConstraints().setDefaultColumnToSortBy("allowed_id"),
- FolderGroupRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ DataResult result = DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("allowed_id"))
+ .returnDataResult(FolderGroupRepository::buildRecord);
+ return result.getRecords();
}
public static void insertFolderGroupList(Connection connection, Folder folder) throws SQLException {
@@ -78,30 +71,30 @@ public static void insertFolderGroupList(Connection connection, Folder folder) t
return;
}
for (FolderGroup allowedGroup : folder.getFolderGroupList()) {
- SqlUtils insertValues = new SqlUtils();
- insertValues
- .add("folder_id", folder.getId())
- .add("group_id", allowedGroup.getGroupId())
- .add("privacy_type", allowedGroup.getPrivacyType())
- .add("view_all",
+ DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("folder_id", folder.getId())
+ .FIELD("group_id", allowedGroup.getGroupId())
+ .FIELD("privacy_type", allowedGroup.getPrivacyType())
+ .FIELD("view_all",
(allowedGroup.getPrivacyType() == PrivacyType.PUBLIC || allowedGroup.getPrivacyType() == PrivacyType.PUBLIC_READ_ONLY))
- .add("add_permission", allowedGroup.getAddPermission())
- .add("edit_permission", allowedGroup.getEditPermission())
- .add("delete_permission", allowedGroup.getDeletePermission());
- DB.insertInto(connection, TABLE_NAME, insertValues, PRIMARY_KEY);
+ .FIELD("add_permission", allowedGroup.getAddPermission())
+ .FIELD("edit_permission", allowedGroup.getEditPermission())
+ .FIELD("delete_permission", allowedGroup.getDeletePermission())
+ .execute(connection);
}
}
public static FolderGroup add(FolderGroup record) {
- SqlUtils insertValues = new SqlUtils()
- .add("folder_id", record.getFolderId())
- .add("group_id", record.getGroupId())
- .add("privacy_type", record.getPrivacyType())
- .add("view_all", (record.getPrivacyType() == PrivacyType.PUBLIC || record.getPrivacyType() == PrivacyType.PUBLIC_READ_ONLY))
- .add("add_permission", record.getAddPermission())
- .add("edit_permission", record.getEditPermission())
- .add("delete_permission", record.getDeletePermission());
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ long id = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("folder_id", record.getFolderId())
+ .FIELD("group_id", record.getGroupId())
+ .FIELD("privacy_type", record.getPrivacyType())
+ .FIELD("view_all", (record.getPrivacyType() == PrivacyType.PUBLIC || record.getPrivacyType() == PrivacyType.PUBLIC_READ_ONLY))
+ .FIELD("add_permission", record.getAddPermission())
+ .FIELD("edit_permission", record.getEditPermission())
+ .FIELD("delete_permission", record.getDeletePermission())
+ .execute();
+ record.setId(id);
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -112,13 +105,14 @@ public static FolderGroup add(FolderGroup record) {
}
public static boolean update(FolderGroup record) {
- SqlUtils updateValues = new SqlUtils()
- .add("privacy_type", record.getPrivacyType())
- .add("view_all", (record.getPrivacyType() == PrivacyType.PUBLIC || record.getPrivacyType() == PrivacyType.PUBLIC_READ_ONLY))
- .add("add_permission", record.getAddPermission())
- .add("edit_permission", record.getEditPermission())
- .add("delete_permission", record.getDeletePermission());
- boolean result = DB.update(TABLE_NAME, updateValues, DB.WHERE("allowed_id = ?", record.getId()));
+ boolean result = DB.UPDATE(TABLE_NAME)
+ .SET("privacy_type", record.getPrivacyType())
+ .SET("view_all", (record.getPrivacyType() == PrivacyType.PUBLIC || record.getPrivacyType() == PrivacyType.PUBLIC_READ_ONLY))
+ .SET("add_permission", record.getAddPermission())
+ .SET("edit_permission", record.getEditPermission())
+ .SET("delete_permission", record.getDeletePermission())
+ .WHERE("allowed_id = ?", record.getId())
+ .execute();
if (result) {
// Keep the folder's pointer fields in sync after updating a group's privacy type
FolderRepository.updateGroupPointers(record.getFolderId());
@@ -128,11 +122,11 @@ public static boolean update(FolderGroup record) {
public static boolean remove(long id) {
// Determine folder before deleting to update has_allowed_groups pointer
- FolderGroup existing = (FolderGroup) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("allowed_id = ?", id),
- FolderGroupRepository::buildRecord);
- boolean deleted = DB.deleteFrom(TABLE_NAME, DB.WHERE("allowed_id = ?", id)) > 0;
+ FolderGroup existing = DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("allowed_id = ?", id)
+ .returnRecord(FolderGroupRepository::buildRecord);
+ boolean deleted = DB.DELETE().FROM(TABLE_NAME).WHERE("allowed_id = ?", id).execute();
if (deleted && existing != null) {
// Keep the folder's pointer fields in sync after removing a group
FolderRepository.updateGroupPointers(existing.getFolderId());
@@ -141,11 +135,11 @@ public static boolean remove(long id) {
}
public static void removeAll(Connection connection, Folder folder) throws SQLException {
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("folder_id = ?", folder.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("folder_id = ?", folder.getId()).execute(connection);
}
public static void removeAll(Connection connection, Group group) throws SQLException {
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("group_id = ?", group.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("group_id = ?", group.getId()).execute(connection);
}
private static FolderGroup buildRecord(ResultSet rs) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FolderRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FolderRepository.java
index fb094ce43..8226e2d9b 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FolderRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FolderRepository.java
@@ -1,4 +1,5 @@
/*
+ * Copyright 2026 Matt Rajkowski (https://github.com/rajkowski)
* Copyright 2022 SimIS Inc. (https://www.simiscms.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -30,17 +31,18 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.AutoRollback;
+import com.github.rajkowski.database.AutoStartTransaction;
+import com.github.rajkowski.database.DB;
+import com.github.rajkowski.database.DataConstraints;
+import com.github.rajkowski.database.DataResult;
+import com.github.rajkowski.database.Insert;
+import com.github.rajkowski.database.Select;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.domain.model.cms.Folder;
import com.simisinc.platform.domain.model.cms.FolderCategory;
import com.simisinc.platform.domain.model.cms.FolderGroup;
import com.simisinc.platform.domain.model.items.PrivacyType;
-import com.simisinc.platform.infrastructure.database.AutoRollback;
-import com.simisinc.platform.infrastructure.database.AutoStartTransaction;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.DataConstraints;
-import com.simisinc.platform.infrastructure.database.DataResult;
-import com.simisinc.platform.infrastructure.database.SqlUtils;
-import com.simisinc.platform.infrastructure.database.SqlWhere;
import com.simisinc.platform.presentation.controller.DataConstants;
import com.simisinc.platform.presentation.controller.UserSession;
@@ -65,33 +67,29 @@ public static Folder save(Folder record) {
}
private static Folder add(Folder record) {
- SqlUtils insertValues = new SqlUtils()
- .add("folder_unique_id", StringUtils.trimToNull(record.getUniqueId()))
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("summary", StringUtils.trimToNull(record.getSummary()))
- .add("created_by", record.getCreatedBy())
- .add("modified_by", record.getModifiedBy())
- .add("allows_guests", record.getGuestPrivacyType() != PrivacyType.UNDEFINED)
- .add("guest_privacy_type", record.getGuestPrivacyType());
- if (record.getPrivacyTypes() != null) {
- insertValues.add("privacy_types", String.join(", ", record.getPrivacyTypes()));
- }
- insertValues.add("has_allowed_groups", record.getFolderGroupList() != null && !record.getFolderGroupList().isEmpty());
- insertValues.add("has_categories", record.getFolderCategoryList() != null && !record.getFolderCategoryList().isEmpty());
- // Use a transaction
try (Connection connection = DB.getConnection();
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
- // In a transaction (use the existing connection)
- record.setId(DB.insertInto(connection, TABLE_NAME, insertValues, PRIMARY_KEY));
- // Manage the access groups
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("folder_unique_id", StringUtils.trimToNull(record.getUniqueId()))
+ .FIELD("name", StringUtils.trimToNull(record.getName()))
+ .FIELD("summary", StringUtils.trimToNull(record.getSummary()))
+ .FIELD("created_by", record.getCreatedBy())
+ .FIELD("modified_by", record.getModifiedBy())
+ .FIELD("allows_guests", record.getGuestPrivacyType() != PrivacyType.UNDEFINED)
+ .FIELD("guest_privacy_type", record.getGuestPrivacyType());
+ if (record.getPrivacyTypes() != null) {
+ insert.FIELD("privacy_types", String.join(", ", record.getPrivacyTypes()));
+ }
+ insert.FIELD("has_allowed_groups", record.getFolderGroupList() != null && !record.getFolderGroupList().isEmpty())
+ .FIELD("has_categories", record.getFolderCategoryList() != null && !record.getFolderCategoryList().isEmpty());
+ record.setId(insert.execute(connection));
if (record.getFolderGroupList() != null && !record.getFolderGroupList().isEmpty()) {
FolderGroupRepository.insertFolderGroupList(connection, record);
}
if (record.getFolderCategoryList() != null && !record.getFolderCategoryList().isEmpty()) {
FolderCategoryRepository.insertFolderCategoryList(connection, record);
}
- // Finish the transaction
transaction.commit();
return record;
} catch (SQLException se) {
@@ -102,36 +100,29 @@ private static Folder add(Folder record) {
}
private static Folder update(Folder record) {
- SqlUtils updateValues = new SqlUtils()
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("folder_unique_id", StringUtils.trimToNull(record.getUniqueId()))
- .add("summary", StringUtils.trimToNull(record.getSummary()))
- .add("allows_guests", record.getGuestPrivacyType() != PrivacyType.UNDEFINED)
- .add("guest_privacy_type", record.getGuestPrivacyType())
- .add("modified_by", record.getModifiedBy())
- .add("modified", new Timestamp(System.currentTimeMillis()));
- if (record.getPrivacyTypes() != null) {
- updateValues.add("privacy_types", String.join(", ", record.getPrivacyTypes()));
- } else {
- updateValues.add("privacy_types", (String) null);
- }
- updateValues.add("has_allowed_groups", record.getFolderGroupList() != null && !record.getFolderGroupList().isEmpty());
- updateValues.add("has_categories", record.getFolderCategoryList() != null && !record.getFolderCategoryList().isEmpty());
- // Use a transaction
try (Connection connection = DB.getConnection();
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
- // In a transaction (use the existing connection)
- DB.update(connection, TABLE_NAME, updateValues, DB.WHERE("folder_id = ?", record.getId()));
- // Manage the access groups
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("name", StringUtils.trimToNull(record.getName()))
+ .SET("folder_unique_id", StringUtils.trimToNull(record.getUniqueId()))
+ .SET("summary", StringUtils.trimToNull(record.getSummary()))
+ .SET("allows_guests", record.getGuestPrivacyType() != PrivacyType.UNDEFINED)
+ .SET("guest_privacy_type", record.getGuestPrivacyType())
+ .SET("modified_by", record.getModifiedBy())
+ .SET("modified", new Timestamp(System.currentTimeMillis()));
+ if (record.getPrivacyTypes() != null) {
+ update.SET("privacy_types", String.join(", ", record.getPrivacyTypes()));
+ } else {
+ update.SET("privacy_types", (String) null);
+ }
+ update.SET("has_allowed_groups", record.getFolderGroupList() != null && !record.getFolderGroupList().isEmpty())
+ .SET("has_categories", record.getFolderCategoryList() != null && !record.getFolderCategoryList().isEmpty());
+ update.WHERE("folder_id = ?", record.getId()).execute(connection);
FolderGroupRepository.removeAll(connection, record);
FolderGroupRepository.insertFolderGroupList(connection, record);
- // Manage categories
FolderCategoryRepository.updateFolderCategoryList(connection, record);
- // Finish the transaction
transaction.commit();
- // Expire the cache
- // CacheManager.invalidateKey(CacheManager.COLLECTION_UNIQUE_ID_CACHE, record.getUniqueId());
return record;
} catch (SQLException se) {
LOG.error("SQLException: " + se.getMessage(), se);
@@ -151,7 +142,7 @@ public static boolean remove(Folder record) {
FolderGroupRepository.removeAll(connection, record);
FolderCategoryRepository.removeAll(connection, record);
// Delete the record
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("folder_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("folder_id = ?", record.getId()).execute(connection);
// Finish transaction
transaction.commit();
// Invalidate the cache
@@ -164,40 +155,42 @@ public static boolean remove(Folder record) {
return false;
}
- private static DataResult query(FolderSpecification specification, DataConstraints constraints) {
- SqlWhere where = null;
+ private static DataResult query(FolderSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("*").FROM(TABLE_NAME).WHERE();
if (specification != null) {
- where = DB.WHERE()
- .andAddIfHasValue("folder_id = ?", specification.getId(), -1)
- .andAddIfHasValue("folder_unique_id = ?", specification.getUniqueId());
+ if (specification.getId() != -1) {
+ select.AND("folder_id = ?", specification.getId());
+ }
+ if (StringUtils.isNotBlank(specification.getUniqueId())) {
+ select.AND("folder_unique_id = ?", specification.getUniqueId());
+ }
if (specification.getName() != null) {
- where.AND("LOWER(name) = ?", specification.getName().toLowerCase());
+ select.AND("LOWER(name) = ?", specification.getName().toLowerCase());
}
if (specification.getForUserId() != DataConstants.UNDEFINED) {
if (specification.getForUserId() == UserSession.GUEST_ID) {
- where.AND("allows_guests = true");
+ select.AND("allows_guests = true");
} else {
- // For logged out and logged in users
- where.AND(
- "(allows_guests = true " +
- "OR (has_allowed_groups = true " +
- "AND EXISTS (SELECT 1 FROM folder_groups WHERE folder_id = folders.folder_id " +
- "AND EXISTS (SELECT 1 FROM user_groups WHERE group_id = folder_groups.group_id AND user_id = ?))))",
+ select.AND(
+ "(allows_guests = true OR (has_allowed_groups = true AND EXISTS (SELECT 1 FROM folder_groups WHERE folder_id = folders.folder_id AND EXISTS (SELECT 1 FROM user_groups WHERE group_id = folder_groups.group_id AND user_id = ?))))",
specification.getForUserId());
}
}
}
- return DB.selectAllFrom(TABLE_NAME, where, constraints, FolderRepository::buildRecord);
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(FolderRepository::buildRecord);
}
public static Folder findById(long id) {
if (id == -1) {
return null;
}
- Folder folder = (Folder) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("folder_id = ?", id),
- FolderRepository::buildRecord);
+ Folder folder = DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("folder_id = ?", id)
+ .returnRecord(FolderRepository::buildRecord);
populateRelatedData(folder);
return folder;
}
@@ -206,10 +199,10 @@ public static Folder findByUniqueId(String uniqueId) {
if (StringUtils.isBlank(uniqueId)) {
return null;
}
- Folder folder = (Folder) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("folder_unique_id = ?", uniqueId),
- FolderRepository::buildRecord);
+ Folder folder = DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("folder_unique_id = ?", uniqueId)
+ .returnRecord(FolderRepository::buildRecord);
populateRelatedData(folder);
return folder;
}
@@ -218,10 +211,10 @@ public static Folder findByName(String name) {
if (StringUtils.isBlank(name)) {
return null;
}
- Folder folder = (Folder) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("LOWER(name) = ?", name.toLowerCase()),
- FolderRepository::buildRecord);
+ Folder folder = DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("LOWER(name) = ?", name.toLowerCase())
+ .returnRecord(FolderRepository::buildRecord);
populateRelatedData(folder);
return folder;
}
@@ -235,8 +228,8 @@ public static List findAll(FolderSpecification specification, DataConstr
constraints = new DataConstraints().setUseCount(false);
}
constraints.setDefaultColumnToSortBy("name");
- DataResult result = query(specification, constraints);
- List folderList = (List) result.getRecords();
+ DataResult result = query(specification, constraints);
+ List folderList = result.getRecords();
for (Folder folder : folderList) {
populateRelatedData(folder);
}
@@ -280,21 +273,23 @@ public static void updateGroupPointers(long folderId) {
}
privacyTypesValue = String.join(", ", typeNames);
}
- SqlUtils updateValues = new SqlUtils()
- .add("has_allowed_groups", hasGroups)
- .add("privacy_types", privacyTypesValue);
- DB.update(TABLE_NAME, updateValues, DB.WHERE("folder_id = ?", folderId));
+ DB.UPDATE(TABLE_NAME)
+ .SET("has_allowed_groups", hasGroups)
+ .SET("privacy_types", privacyTypesValue)
+ .WHERE("folder_id = ?", folderId)
+ .execute();
}
public static boolean updateGuestAccess(long folderId, int guestPrivacyType) {
if (folderId == -1) {
return false;
}
- SqlUtils updateValues = new SqlUtils()
- .add("allows_guests", guestPrivacyType != PrivacyType.UNDEFINED)
- .add("guest_privacy_type", guestPrivacyType);
try {
- DB.update(TABLE_NAME, updateValues, DB.WHERE("folder_id = ?", folderId));
+ DB.UPDATE(TABLE_NAME)
+ .SET("allows_guests", guestPrivacyType != PrivacyType.UNDEFINED)
+ .SET("guest_privacy_type", guestPrivacyType)
+ .WHERE("folder_id = ?", folderId)
+ .execute();
return true;
} catch (Exception e) {
LOG.error("updateGuestAccess: " + e.getMessage());
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FormDataRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FormDataRepository.java
index 0c6020fa1..1e963a980 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FormDataRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/FormDataRepository.java
@@ -1,4 +1,5 @@
/*
+ * Copyright 2026 Matt Rajkowski (https://github.com/rajkowski)
* Copyright 2022 SimIS Inc. (https://www.simiscms.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -26,14 +27,14 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.DB;
+import com.github.rajkowski.database.DataConstraints;
+import com.github.rajkowski.database.DataResult;
+import com.github.rajkowski.database.Insert;
+import com.github.rajkowski.database.Select;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.application.cms.FormDataJSONCommand;
import com.simisinc.platform.domain.model.cms.FormData;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.DataConstraints;
-import com.simisinc.platform.infrastructure.database.DataResult;
-import com.simisinc.platform.infrastructure.database.SqlUtils;
-import com.simisinc.platform.infrastructure.database.SqlValue;
-import com.simisinc.platform.infrastructure.database.SqlWhere;
import com.simisinc.platform.presentation.controller.DataConstants;
/**
@@ -49,54 +50,64 @@ public class FormDataRepository {
private static String TABLE_NAME = "form_data";
private static String[] PRIMARY_KEY = new String[] { "form_data_id" };
- private static DataResult query(FormDataSpecification specification, DataConstraints constraints) {
- SqlWhere where = null;
+ private static DataResult query(FormDataSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("*").FROM(TABLE_NAME).WHERE();
if (specification != null) {
- where = DB.WHERE()
- .andAddIfHasValue("form_data_id = ?", specification.getId(), -1)
- .andAddIfHasValue("form_unique_id = ?", specification.getFormUniqueId())
- .andAddIfHasValue("session_id = ?", specification.getSessionId())
- .andAddIfHasValue("claimed_by = ?", specification.getClaimedBy(), -1L);
+ if (specification.getId() != -1) {
+ select.AND("form_data_id = ?", specification.getId());
+ }
+ if (StringUtils.isNotBlank(specification.getFormUniqueId())) {
+ select.AND("form_unique_id = ?", specification.getFormUniqueId());
+ }
+ if (specification.getSessionId() != null) {
+ select.AND("session_id = ?", specification.getSessionId());
+ }
+ if (specification.getClaimedBy() != -1L) {
+ select.AND("claimed_by = ?", specification.getClaimedBy());
+ }
if (specification.getFlaggedAsSpam() != DataConstants.UNDEFINED) {
if (specification.getFlaggedAsSpam() == DataConstants.TRUE) {
- where.AND("flagged_as_spam = true");
+ select.AND("flagged_as_spam = true");
} else {
- where.AND("flagged_as_spam = false");
+ select.AND("flagged_as_spam = false");
}
}
if (specification.getClaimed() != DataConstants.UNDEFINED) {
if (specification.getClaimed() == DataConstants.TRUE) {
- where.AND("claimed IS NOT NULL");
+ select.AND("claimed IS NOT NULL");
} else {
- where.AND("claimed IS NULL");
+ select.AND("claimed IS NULL");
}
}
if (specification.getDismissed() != DataConstants.UNDEFINED) {
if (specification.getDismissed() == DataConstants.TRUE) {
- where.AND("dismissed IS NOT NULL");
+ select.AND("dismissed IS NOT NULL");
} else {
- where.AND("dismissed IS NULL");
+ select.AND("dismissed IS NULL");
}
}
if (specification.getProcessed() != DataConstants.UNDEFINED) {
if (specification.getProcessed() == DataConstants.TRUE) {
- where.AND("processed IS NOT NULL");
+ select.AND("processed IS NOT NULL");
} else {
- where.AND("processed IS NULL");
+ select.AND("processed IS NULL");
}
}
}
- return DB.selectAllFrom(TABLE_NAME, where, constraints, FormDataRepository::buildRecord);
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(FormDataRepository::buildRecord);
}
public static FormData findById(long formDataId) {
if (formDataId == -1) {
return null;
}
- return (FormData) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("form_data_id = ?", formDataId),
- FormDataRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("form_data_id = ?", formDataId)
+ .returnRecord(FormDataRepository::buildRecord);
}
public static List findAll(FormDataSpecification specification, DataConstraints constraints) {
@@ -104,8 +115,7 @@ public static List findAll(FormDataSpecification specification, DataCo
constraints = new DataConstraints();
}
constraints.setDefaultColumnToSortBy("form_data_id desc");
- DataResult result = query(specification, constraints);
- return (List) result.getRecords();
+ return query(specification, constraints).getRecords();
}
public static FormData save(FormData record) {
@@ -116,23 +126,22 @@ public static FormData save(FormData record) {
}
public static FormData add(FormData record) {
- SqlUtils insertValues = new SqlUtils()
- .add("form_unique_id", StringUtils.trimToNull(record.getFormUniqueId()))
- .add("ip_address", record.getIpAddress())
- .add("session_id", record.getSessionId())
- .add("url", record.getUrl())
- .add("flagged_as_spam", record.getFlaggedAsSpam())
- .add("created_by", record.getCreatedBy(), -1)
- .add("modified_by", record.getModifiedBy(), -1);
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("form_unique_id", StringUtils.trimToNull(record.getFormUniqueId()))
+ .FIELD("ip_address", record.getIpAddress())
+ .FIELD("session_id", record.getSessionId())
+ .FIELD("url", record.getUrl())
+ .FIELD("flagged_as_spam", record.getFlaggedAsSpam())
+ .FIELD("created_by", record.getCreatedBy() == -1 ? null : record.getCreatedBy())
+ .FIELD("modified_by", record.getModifiedBy() == -1 ? null : record.getModifiedBy());
if (StringUtils.isNotBlank(record.getQueryParameters())) {
- // Convert from URL encoded to plain text
String queryString = record.getQueryParameters();
queryString = Strings.CS.replace(queryString, "%20", " ");
- insertValues.add("query_params", queryString);
+ insert.FIELD("query_params", queryString);
record.setQueryParameters(queryString);
}
- insertValues.add(new SqlValue("field_values", SqlValue.JSONB_TYPE, FormDataJSONCommand.createJSONString(record)));
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ insert.FIELD("field_values", FormDataJSONCommand.createJSONString(record), com.github.rajkowski.database.CastType.JSONB);
+ record.setId(insert.execute());
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -141,10 +150,11 @@ public static FormData add(FormData record) {
}
public static FormData update(FormData record) {
- SqlUtils updateValues = new SqlUtils()
- .add("modified_by", record.getModifiedBy())
- .add("modified", new Timestamp(System.currentTimeMillis()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("form_data_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("modified_by", record.getModifiedBy())
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("form_data_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("The update failed!");
@@ -153,12 +163,11 @@ public static FormData update(FormData record) {
public static boolean markAsArchived(FormData record, long userId) {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
- SqlUtils updateValues = new SqlUtils()
- .add("dismissed", timestamp)
- .add("dismissed_by", userId);
- boolean updated = DB.update(TABLE_NAME, updateValues, DB.WHERE("form_data_id = ?", record.getId()));
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("dismissed", timestamp)
+ .SET("dismissed_by", userId);
+ boolean updated = update.WHERE("form_data_id = ?", record.getId()).execute();
if (updated) {
- // Update the record for additional workflows
record.setDismissed(timestamp);
record.setDismissedBy(userId);
}
@@ -167,14 +176,11 @@ public static boolean markAsArchived(FormData record, long userId) {
public static boolean tryToMarkAsClaimed(FormData record, long userId) {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
- SqlUtils updateValues = new SqlUtils()
- .add("claimed", timestamp)
- .add("claimed_by", userId);
- boolean updated = DB.update(TABLE_NAME, updateValues,
- DB.WHERE("form_data_id = ?", record.getId())
- .AND("claimed IS NULL"));
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("claimed", timestamp)
+ .SET("claimed_by", userId);
+ boolean updated = update.WHERE("form_data_id = ?", record.getId()).AND("claimed IS NULL").execute();
if (updated) {
- // Update the record for additional workflows
record.setClaimed(timestamp);
record.setClaimedBy(userId);
}
@@ -187,13 +193,14 @@ public static boolean markAsProcessed(FormData record, long userId) {
public static boolean markAsProcessed(FormData record, long userId, String system) {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
- SqlUtils updateValues = new SqlUtils()
- .add("processed", timestamp)
- .add("processed_by", userId)
- .addIfExists("processed_system", system);
- boolean updated = DB.update(TABLE_NAME, updateValues, DB.WHERE("form_data_id = ?", record.getId()));
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("processed", timestamp)
+ .SET("processed_by", userId);
+ if (system != null) {
+ update.SET("processed_system", system);
+ }
+ boolean updated = update.WHERE("form_data_id = ?", record.getId()).execute();
if (updated) {
- // Update the record for additional workflows
record.setProcessed(timestamp);
record.setProcessedBy(userId);
}
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/GitPublishSettingsRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/GitPublishSettingsRepository.java
index 78aea94ca..dbcaa2746 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/GitPublishSettingsRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/GitPublishSettingsRepository.java
@@ -24,9 +24,10 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.DB;
+import com.github.rajkowski.database.Insert;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.domain.model.cms.GitPublishSettings;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.SqlUtils;
/**
* Persists and retrieves Git publish settings objects
@@ -42,10 +43,9 @@ public class GitPublishSettingsRepository {
private static String[] PRIMARY_KEY = new String[] { "settings_id" };
public static GitPublishSettings findSettings() {
- return (GitPublishSettings) DB.selectRecordFrom(
- TABLE_NAME,
- null,
- GitPublishSettingsRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .returnRecord(GitPublishSettingsRepository::buildRecord);
}
public static GitPublishSettings save(GitPublishSettings record) {
@@ -56,23 +56,23 @@ public static GitPublishSettings save(GitPublishSettings record) {
}
private static GitPublishSettings add(GitPublishSettings record) {
- SqlUtils insertValues = new SqlUtils()
- .add("enabled", record.getEnabled())
- .add("git_provider", record.getGitProvider())
- .add("repository_url", record.getRepositoryUrl())
- .add("branch_name", record.getBranchName())
- .add("base_branch", record.getBaseBranch())
- .add("access_token", record.getAccessToken())
- .add("username", record.getUsername())
- .add("email", record.getEmail())
- .add("commit_message_template", record.getCommitMessageTemplate())
- .add("auto_create_pr", record.getAutoCreatePr())
- .add("pr_title_template", record.getPrTitleTemplate())
- .add("pr_description_template", record.getPrDescriptionTemplate())
- .add("target_directory", record.getTargetDirectory())
- .add("created_by", record.getCreatedBy(), -1)
- .add("modified_by", record.getModifiedBy(), -1);
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("enabled", record.getEnabled())
+ .FIELD("git_provider", record.getGitProvider())
+ .FIELD("repository_url", record.getRepositoryUrl())
+ .FIELD("branch_name", record.getBranchName())
+ .FIELD("base_branch", record.getBaseBranch())
+ .FIELD("access_token", record.getAccessToken())
+ .FIELD("username", record.getUsername())
+ .FIELD("email", record.getEmail())
+ .FIELD("commit_message_template", record.getCommitMessageTemplate())
+ .FIELD("auto_create_pr", record.getAutoCreatePr())
+ .FIELD("pr_title_template", record.getPrTitleTemplate())
+ .FIELD("pr_description_template", record.getPrDescriptionTemplate())
+ .FIELD("target_directory", record.getTargetDirectory())
+ .FIELD("created_by", record.getCreatedBy() == -1 ? null : record.getCreatedBy())
+ .FIELD("modified_by", record.getModifiedBy() == -1 ? null : record.getModifiedBy());
+ record.setId(insert.execute());
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -81,23 +81,24 @@ private static GitPublishSettings add(GitPublishSettings record) {
}
private static GitPublishSettings update(GitPublishSettings record) {
- SqlUtils updateValues = new SqlUtils()
- .add("enabled", record.getEnabled())
- .add("git_provider", record.getGitProvider())
- .add("repository_url", record.getRepositoryUrl())
- .add("branch_name", record.getBranchName())
- .add("base_branch", record.getBaseBranch())
- .add("access_token", record.getAccessToken())
- .add("username", record.getUsername())
- .add("email", record.getEmail())
- .add("commit_message_template", record.getCommitMessageTemplate())
- .add("auto_create_pr", record.getAutoCreatePr())
- .add("pr_title_template", record.getPrTitleTemplate())
- .add("pr_description_template", record.getPrDescriptionTemplate())
- .add("target_directory", record.getTargetDirectory())
- .add("modified", new Timestamp(System.currentTimeMillis()))
- .add("modified_by", record.getModifiedBy(), -1);
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("settings_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("enabled", record.getEnabled())
+ .SET("git_provider", record.getGitProvider())
+ .SET("repository_url", record.getRepositoryUrl())
+ .SET("branch_name", record.getBranchName())
+ .SET("base_branch", record.getBaseBranch())
+ .SET("access_token", record.getAccessToken())
+ .SET("username", record.getUsername())
+ .SET("email", record.getEmail())
+ .SET("commit_message_template", record.getCommitMessageTemplate())
+ .SET("auto_create_pr", record.getAutoCreatePr())
+ .SET("pr_title_template", record.getPrTitleTemplate())
+ .SET("pr_description_template", record.getPrDescriptionTemplate())
+ .SET("target_directory", record.getTargetDirectory())
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .SET("modified_by", record.getModifiedBy() == -1 ? null : record.getModifiedBy())
+ .WHERE("settings_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("The update failed!");
@@ -105,13 +106,7 @@ private static GitPublishSettings update(GitPublishSettings record) {
}
public static boolean remove(GitPublishSettings record) {
- try (Connection connection = DB.getConnection()) {
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("settings_id = ?", record.getId()));
- return true;
- } catch (SQLException se) {
- LOG.error("SQLException: " + se.getMessage());
- }
- return false;
+ return DB.DELETE().FROM(TABLE_NAME).WHERE("settings_id = ?", record.getId()).execute();
}
private static GitPublishSettings buildRecord(ResultSet rs) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/ImageRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/ImageRepository.java
index ca8a6fc98..689b6e49b 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/ImageRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/ImageRepository.java
@@ -26,14 +26,15 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.AutoRollback;
+import com.github.rajkowski.database.AutoStartTransaction;
+import com.github.rajkowski.database.DB;
+import com.github.rajkowski.database.DataConstraints;
+import com.github.rajkowski.database.DataResult;
+import com.github.rajkowski.database.Insert;
+import com.github.rajkowski.database.Select;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.domain.model.cms.Image;
-import com.simisinc.platform.infrastructure.database.AutoRollback;
-import com.simisinc.platform.infrastructure.database.AutoStartTransaction;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.DataConstraints;
-import com.simisinc.platform.infrastructure.database.DataResult;
-import com.simisinc.platform.infrastructure.database.SqlUtils;
-import com.simisinc.platform.infrastructure.database.SqlWhere;
/**
* Persists and retrieves image objects
@@ -48,56 +49,62 @@ public class ImageRepository {
private static String TABLE_NAME = "images";
private static String[] PRIMARY_KEY = new String[] { "image_id" };
- private static DataResult query(ImageSpecification specification, DataConstraints constraints) {
- SqlWhere where = null;
+ private static DataResult query(ImageSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("*").FROM(TABLE_NAME).WHERE();
if (specification != null) {
- where = DB.WHERE()
- .andAddIfHasValue("image_id = ?", specification.getId(), -1)
- .andAddIfHasValue("created_by = ?", specification.getCreatedBy(), -1);
+ if (specification.getId() != -1) {
+ select.AND("image_id = ?", specification.getId());
+ }
+ if (specification.getCreatedBy() != -1) {
+ select.AND("created_by = ?", specification.getCreatedBy());
+ }
if (specification.getFilename() != null) {
- where.AND("LOWER(filename) = ?", specification.getFilename().toLowerCase());
+ select.AND("LOWER(filename) = ?", specification.getFilename().toLowerCase());
}
if (specification.getFileType() != null) {
- where.AND("LOWER(file_type) = ?", specification.getFileType().toLowerCase());
+ select.AND("LOWER(file_type) = ?", specification.getFileType().toLowerCase());
}
if (specification.getSearchTerm() != null) {
String searchValue = "%" + specification.getSearchTerm().toLowerCase() + "%";
- where.AND("(LOWER(filename) LIKE ? OR LOWER(title) LIKE ? OR LOWER(alt_text) LIKE ? OR LOWER(description) LIKE ?)",
+ select.AND("(LOWER(filename) LIKE ? OR LOWER(title) LIKE ? OR LOWER(alt_text) LIKE ? OR LOWER(description) LIKE ?)",
new String[] { searchValue, searchValue, searchValue, searchValue });
}
}
- return DB.selectAllFrom(TABLE_NAME, where, constraints, ImageRepository::buildRecord);
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(ImageRepository::buildRecord);
}
public static Image findById(long id) {
if (id == -1) {
return null;
}
- return (Image) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("image_id = ?", id),
- ImageRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("image_id = ?", id)
+ .returnRecord(ImageRepository::buildRecord);
}
public static Image findByWebPathAndId(String versionWebPath, long id) {
if (StringUtils.isBlank(versionWebPath) || id == -1) {
return null;
}
- return (Image) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("web_path = ?", versionWebPath)
- .AND("image_id = ?", id),
- ImageRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("web_path = ?", versionWebPath)
+ .AND("image_id = ?", id)
+ .returnRecord(ImageRepository::buildRecord);
}
public static Image findByWebPath(String versionWebPath) {
if (StringUtils.isBlank(versionWebPath)) {
return null;
}
- return (Image) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("web_path = ?", versionWebPath),
- ImageRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("web_path = ?", versionWebPath)
+ .returnRecord(ImageRepository::buildRecord);
}
public static List findAll() {
@@ -109,8 +116,7 @@ public static List findAll(ImageSpecification specification, DataConstrai
constraints = new DataConstraints();
}
constraints.setDefaultColumnToSortBy("created DESC");
- DataResult result = query(specification, constraints);
- return (List) result.getRecords();
+ return query(specification, constraints).getRecords();
}
public static Image save(Image record) {
@@ -121,17 +127,17 @@ public static Image save(Image record) {
}
private static Image add(Image record) {
- SqlUtils insertValues = new SqlUtils()
- .add("filename", StringUtils.trimToNull(record.getFilename()))
- .add("path", StringUtils.trimToNull(record.getFileServerPath()))
- .add("web_path", StringUtils.trimToNull(record.getWebPath()))
- .add("created_by", record.getCreatedBy())
- .add("modified_by", record.getModifiedBy())
- .add("file_length", record.getFileLength())
- .add("file_type", record.getFileType())
- .add("width", record.getWidth())
- .add("height", record.getHeight());
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("filename", StringUtils.trimToNull(record.getFilename()))
+ .FIELD("path", StringUtils.trimToNull(record.getFileServerPath()))
+ .FIELD("web_path", StringUtils.trimToNull(record.getWebPath()))
+ .FIELD("created_by", record.getCreatedBy())
+ .FIELD("modified_by", record.getModifiedBy())
+ .FIELD("file_length", record.getFileLength())
+ .FIELD("file_type", record.getFileType())
+ .FIELD("width", record.getWidth())
+ .FIELD("height", record.getHeight());
+ record.setId(insert.execute());
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -140,26 +146,27 @@ private static Image add(Image record) {
}
private static Image update(Image record) {
- SqlUtils updateValues = new SqlUtils()
- .addIfExists("modified_by", record.getModifiedBy(), -1)
- .add("modified", new java.sql.Timestamp(System.currentTimeMillis()))
- .add("processed", record.getProcessed())
- .add("processed_path", StringUtils.trimToNull(record.getProcessedPath()))
- .add("processed_file_length", record.getProcessedFileLength())
- .add("processed_file_type", StringUtils.trimToNull(record.getProcessedFileType()))
- .add("processed_width", record.getProcessedWidth())
- .add("processed_height", record.getProcessedHeight())
- .add("title", StringUtils.trimToNull(record.getTitle()))
- .add("alt_text", StringUtils.trimToNull(record.getAltText()))
- .add("description", StringUtils.trimToNull(record.getDescription()))
- .add("version_number", record.getVersionNumber())
- .add("filename", StringUtils.trimToNull(record.getFilename()))
- .add("path", StringUtils.trimToNull(record.getFileServerPath()))
- .add("file_length", record.getFileLength())
- .add("file_type", StringUtils.trimToNull(record.getFileType()))
- .add("width", record.getWidth())
- .add("height", record.getHeight());
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("image_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("modified_by", record.getModifiedBy() == -1 ? null : record.getModifiedBy())
+ .SET("modified", new java.sql.Timestamp(System.currentTimeMillis()))
+ .SET("processed", record.getProcessed())
+ .SET("processed_path", StringUtils.trimToNull(record.getProcessedPath()))
+ .SET("processed_file_length", record.getProcessedFileLength())
+ .SET("processed_file_type", StringUtils.trimToNull(record.getProcessedFileType()))
+ .SET("processed_width", record.getProcessedWidth())
+ .SET("processed_height", record.getProcessedHeight())
+ .SET("title", StringUtils.trimToNull(record.getTitle()))
+ .SET("alt_text", StringUtils.trimToNull(record.getAltText()))
+ .SET("description", StringUtils.trimToNull(record.getDescription()))
+ .SET("version_number", record.getVersionNumber())
+ .SET("filename", StringUtils.trimToNull(record.getFilename()))
+ .SET("path", StringUtils.trimToNull(record.getFileServerPath()))
+ .SET("file_length", record.getFileLength())
+ .SET("file_type", StringUtils.trimToNull(record.getFileType()))
+ .SET("width", record.getWidth())
+ .SET("height", record.getHeight())
+ .WHERE("image_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("The update failed!");
@@ -173,7 +180,7 @@ public static boolean remove(Image record) {
// Delete the references
ImageVersionRepository.removeAll(connection, record);
// Delete the record
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("image_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("image_id = ?", record.getId()).execute(connection);
// Finish transaction
transaction.commit();
return true;
@@ -184,7 +191,7 @@ public static boolean remove(Image record) {
}
public static long findTotalFileSize() {
- return DB.selectFunction("SUM(file_length)", TABLE_NAME, null);
+ DB.SELECT("SUM(file_length)").FROM(TABLE_NAME).returnValue(Long.class);
}
private static Image buildRecord(ResultSet rs) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/ImageVersionRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/ImageVersionRepository.java
index 5b29ad713..ed5af440d 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/ImageVersionRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/ImageVersionRepository.java
@@ -25,11 +25,12 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.DB;
+import com.github.rajkowski.database.DataConstraints;
+import com.github.rajkowski.database.Insert;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.domain.model.cms.Image;
import com.simisinc.platform.domain.model.cms.ImageVersion;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.DataConstraints;
-import com.simisinc.platform.infrastructure.database.SqlUtils;
/**
* Persists and retrieves image version objects
@@ -48,21 +49,21 @@ public static ImageVersion findById(long id) {
if (id == -1) {
return null;
}
- return (ImageVersion) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("version_id = ?", id),
- ImageVersionRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("version_id = ?", id)
+ .returnRecord(ImageVersionRepository::buildRecord);
}
public static List findAllByImageId(long imageId) {
if (imageId == -1) {
return null;
}
- return (List) DB.selectAllFrom(
- TABLE_NAME,
- DB.WHERE("image_id = ?", imageId),
- new DataConstraints().setDefaultColumnToSortBy("version_number DESC"),
- ImageVersionRepository::buildRecord).getRecords();
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("image_id = ?", imageId)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("version_number DESC"))
+ .returnDataResult(ImageVersionRepository::buildRecord).getRecords();
}
public static ImageVersion save(ImageVersion record) {
@@ -73,19 +74,19 @@ public static ImageVersion save(ImageVersion record) {
}
private static ImageVersion add(ImageVersion record) {
- SqlUtils insertValues = new SqlUtils()
- .add("image_id", record.getImageId())
- .add("version_number", record.getVersionNumber())
- .add("filename", StringUtils.trimToNull(record.getFilename()))
- .add("path", StringUtils.trimToNull(record.getFileServerPath()))
- .add("file_length", record.getFileLength())
- .add("file_type", record.getFileType())
- .add("width", record.getWidth())
- .add("height", record.getHeight())
- .add("is_current", record.getIsCurrent())
- .add("created_by", record.getCreatedBy())
- .add("notes", StringUtils.trimToNull(record.getNotes()));
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("image_id", record.getImageId())
+ .FIELD("version_number", record.getVersionNumber())
+ .FIELD("filename", StringUtils.trimToNull(record.getFilename()))
+ .FIELD("path", StringUtils.trimToNull(record.getFileServerPath()))
+ .FIELD("file_length", record.getFileLength())
+ .FIELD("file_type", record.getFileType())
+ .FIELD("width", record.getWidth())
+ .FIELD("height", record.getHeight())
+ .FIELD("is_current", record.getIsCurrent())
+ .FIELD("created_by", record.getCreatedBy())
+ .FIELD("notes", StringUtils.trimToNull(record.getNotes()));
+ record.setId(insert.execute());
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -94,10 +95,11 @@ private static ImageVersion add(ImageVersion record) {
}
private static ImageVersion update(ImageVersion record) {
- SqlUtils updateValues = new SqlUtils()
- .add("is_current", record.getIsCurrent())
- .add("notes", StringUtils.trimToNull(record.getNotes()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("version_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("is_current", record.getIsCurrent())
+ .SET("notes", StringUtils.trimToNull(record.getNotes()))
+ .WHERE("version_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("The update failed!");
@@ -105,17 +107,18 @@ private static ImageVersion update(ImageVersion record) {
}
public static void remove(ImageVersion record) {
- DB.deleteFrom(TABLE_NAME, DB.WHERE("version_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("version_id = ?", record.getId()).execute();
}
public static void removeAll(Connection connection, Image record) throws SQLException {
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("image_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("image_id = ?", record.getId()).execute(connection);
}
public static boolean markAsNotCurrent(long imageId) {
- SqlUtils updateValues = new SqlUtils()
- .add("is_current", false);
- return DB.update(TABLE_NAME, updateValues, DB.WHERE("image_id = ?", imageId));
+ return DB.UPDATE(TABLE_NAME)
+ .SET("is_current", false)
+ .WHERE("image_id = ?", imageId)
+ .execute();
}
private static ImageVersion buildRecord(ResultSet rs) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/MenuItemRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/MenuItemRepository.java
index 4d497432c..81241edc7 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/MenuItemRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/MenuItemRepository.java
@@ -1,4 +1,5 @@
/*
+ * Copyright 2026 Matt Rajkowski (https://github.com/rajkowski)
* Copyright 2022 SimIS Inc. (https://www.simiscms.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -27,12 +28,11 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.DB;
+import com.github.rajkowski.database.DataConstraints;
+import com.github.rajkowski.database.DataResult;
import com.simisinc.platform.domain.model.cms.MenuItem;
import com.simisinc.platform.domain.model.cms.MenuTab;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.DataConstraints;
-import com.simisinc.platform.infrastructure.database.DataResult;
-import com.simisinc.platform.infrastructure.database.SqlUtils;
/**
* Persists and retrieves menu item objects
@@ -51,38 +51,37 @@ public static MenuItem findById(long id) {
if (id == -1) {
return null;
}
- return (MenuItem) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("menu_item_id = ?", id),
- MenuItemRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("menu_item_id = ?", id)
+ .returnRecord(MenuItemRepository::buildRecord);
}
public static MenuItem findByLink(String link) {
if (link == null) {
return null;
}
- return (MenuItem) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("link = ?", link),
- MenuItemRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("link = ?", link)
+ .returnRecord(MenuItemRepository::buildRecord);
}
public static List