diff --git a/checkstyle.xml b/checkstyle.xml
index 46e6005fe..25a53a4d4 100644
--- a/checkstyle.xml
+++ b/checkstyle.xml
@@ -1,33 +1,526 @@
-
+
+ "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
+ "https://checkstyle.org/dtds/configuration_1_3.dtd">
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/lib/build/db-1.0.9.jar b/lib/build/db-1.0.9.jar
new file mode 100644
index 000000000..2189909a8
Binary files /dev/null and b/lib/build/db-1.0.9.jar differ
diff --git a/lib/style/checkstyle-10.17.0-all.jar b/lib/style/checkstyle-14.1.0-all.jar
similarity index 58%
rename from lib/style/checkstyle-10.17.0-all.jar
rename to lib/style/checkstyle-14.1.0-all.jar
index cf0a416b5..6a48555e6 100644
Binary files a/lib/style/checkstyle-10.17.0-all.jar and b/lib/style/checkstyle-14.1.0-all.jar differ
diff --git a/lib/tests/h2-2.3.232.jar b/lib/tests/h2-2.3.232.jar
new file mode 100644
index 000000000..6c41966ee
Binary files /dev/null and b/lib/tests/h2-2.3.232.jar differ
diff --git a/pom.xml b/pom.xml
index eda198fb8..6dd26a2dd 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,5 +1,6 @@
-
+
4.0.0
com.github.rajkowski
cms-platform
@@ -123,6 +124,11 @@
commons-validator
1.10.1
+
+ com.github.rajkowski
+ db
+ 1.0.9
+
com.github.rajkowski
easy-flows-playbooks
@@ -362,6 +368,12 @@
9.0.120
provided
+
+ com.h2database
+ h2
+ 2.3.232
+ test
+
org.junit.jupiter
junit-jupiter
@@ -394,32 +406,43 @@
-
-
-
- org.apache.maven.plugins
- maven-checkstyle-plugin
- 3.6.0
-
- checkstyle.xml
- UTF-8
- true
- true
- false
-
-
-
- validate
- validate
-
- check
-
-
-
-
-
-
+
+
+ org.apache.maven.plugins
+ maven-checkstyle-plugin
+ 3.6.0
+
+ checkstyle.xml
+
+
+
+ com.puppycrawl.tools
+ checkstyle
+ 14.1.0
+
+
+
org.apache.maven.plugins
maven-release-plugin
@@ -476,7 +499,7 @@
-
+
@@ -490,7 +513,7 @@
-
+
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/application/json/JsonCommand.java b/src/main/java/com/simisinc/platform/application/json/JsonCommand.java
index 6d6da493d..85ea37949 100644
--- a/src/main/java/com/simisinc/platform/application/json/JsonCommand.java
+++ b/src/main/java/com/simisinc/platform/application/json/JsonCommand.java
@@ -179,8 +179,22 @@ public static String[] fromJsonArray(String json) {
return new String[0];
}
try {
+ String candidate = json.trim();
ObjectMapper mapper = new ObjectMapper();
- return mapper.readValue(json, String[].class);
+
+ // Some database drivers return a JSON array as a quoted string literal, such as
+ // "[\"updated\"]" instead of ["updated"]. Handle both forms safely.
+ if (candidate.startsWith("\"") && candidate.endsWith("\"")) {
+ String unwrapped = mapper.readValue(candidate, String.class);
+ if (StringUtils.isNotBlank(unwrapped)) {
+ candidate = unwrapped.trim();
+ }
+ }
+
+ if (StringUtils.isBlank(candidate)) {
+ return new String[0];
+ }
+ return mapper.readValue(candidate, String[].class);
} catch (Exception e) {
LOG.error("fromJson", e);
}
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/ConnectionPool.java b/src/main/java/com/simisinc/platform/infrastructure/database/ConnectionPool.java
index c4235acac..29d8aba1d 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/database/ConnectionPool.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/database/ConnectionPool.java
@@ -22,6 +22,11 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.DB;
+// import com.github.rajkowski.database.TenantRegistry;
+// import com.zeroio.platform.infrastructure.database.SitePropertyTenantDataSourceConfigurationStore;
+// import com.zeroio.platform.infrastructure.database.TenantDataSourceConfiguration;
+// import com.zeroio.platform.infrastructure.database.TenantDataSourceRegistrar;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
@@ -38,12 +43,17 @@ public class ConnectionPool {
private static HikariDataSource applicationDS;
private static HikariDataSource backgroundJobsDS;
private static HikariDataSource distributedMessagingDS;
+ // private static final TenantRegistry TENANT_REGISTRY = new TenantRegistry();
+ // private static TenantDataSourceRegistrar tenantDataSourceRegistrar;
private ConnectionPool() {
}
public static void init(Properties properties) {
applicationDS = initApplicationCP(properties);
+ DB.setDataSource(applicationDS);
+ // DB.setTenantRegistry(TENANT_REGISTRY);
+ // tenantDataSourceRegistrar = new TenantDataSourceRegistrar(new SitePropertyTenantDataSourceConfigurationStore());
LOG.info("Max pool size (applicationDS): " + applicationDS.getMaximumPoolSize());
backgroundJobsDS = initBackgroundJobsCP(properties);
LOG.info("Max pool size (backgroundJobsDS): " + backgroundJobsDS.getMaximumPoolSize());
@@ -54,6 +64,9 @@ public static void init(Properties properties) {
/** Configure the application's connection pool */
private static HikariDataSource initApplicationCP(Properties properties) {
HikariConfig config = new HikariConfig(mergePropertiesFromPrefix(properties, "application"));
+ if (!properties.containsKey("application.connectionTimeout")) {
+ config.setConnectionTimeout(5_000);
+ }
config.setMaxLifetime(600_000);
config.setPoolName("Web-Application-Pool");
return new HikariDataSource(config);
@@ -76,9 +89,23 @@ private static HikariDataSource initDistributedMessagingCP(Properties properties
}
public static void shutdown() {
- applicationDS.close();
- backgroundJobsDS.close();
- distributedMessagingDS.close();
+ // if (tenantDataSourceRegistrar != null) {
+ // tenantDataSourceRegistrar.shutdown();
+ // tenantDataSourceRegistrar = null;
+ // TENANT_REGISTRY.clear();
+ // }
+ if (applicationDS != null) {
+ applicationDS.close();
+ applicationDS = null;
+ }
+ if (backgroundJobsDS != null) {
+ backgroundJobsDS.close();
+ backgroundJobsDS = null;
+ }
+ if (distributedMessagingDS != null) {
+ distributedMessagingDS.close();
+ distributedMessagingDS = null;
+ }
}
/* Each pool is configured with the base dataSource properties and name specific properties */
@@ -109,6 +136,38 @@ public static javax.sql.DataSource getDistributedMessagingDataSource() {
return distributedMessagingDS;
}
+ // public static void registerTenantDataSource(String tenantId, javax.sql.DataSource dataSource) {
+ // TENANT_REGISTRY.register(tenantId, dataSource);
+ // }
+
+ // public static void unregisterTenantDataSource(String tenantId) {
+ // TENANT_REGISTRY.unregister(tenantId);
+ // }
+
+ // public static void registerConfiguredTenantDataSources() {
+ // if (tenantDataSourceRegistrar == null) {
+ // throw new IllegalStateException("ConnectionPool has not been initialized");
+ // }
+ // tenantDataSourceRegistrar.registerAllAtStartup();
+ // }
+
+ // public static void saveAndRegisterTenantDataSource(TenantDataSourceConfiguration configuration) {
+ // if (tenantDataSourceRegistrar == null) {
+ // throw new IllegalStateException("ConnectionPool has not been initialized");
+ // }
+ // tenantDataSourceRegistrar.saveAndRegister(configuration);
+ // }
+
+ // public static void retireIdleTenantDataSources() {
+ // if (tenantDataSourceRegistrar != null) {
+ // tenantDataSourceRegistrar.retireIdleDataSources();
+ // }
+ // }
+
+ // public static TenantRegistry getTenantRegistry() {
+ // return TENANT_REGISTRY;
+ // }
+
public static boolean isLive() {
// Use the background jobs connection pool to determine if the database is live
try (Connection connection = backgroundJobsDS.getConnection()) {
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/distributedlock/LockManager.java b/src/main/java/com/simisinc/platform/infrastructure/distributedlock/LockManager.java
index a497fd188..f53ea25f0 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/distributedlock/LockManager.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/distributedlock/LockManager.java
@@ -1,4 +1,5 @@
/*
+ * Copyright 2026 Matt Rajkowski (https://github.com/rajkowski)
* Copyright 2023 SimIS Inc. (https://www.simiscms.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -21,9 +22,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.SqlUtils;
-import com.simisinc.platform.infrastructure.database.SqlValue;
+import com.github.rajkowski.database.DB;
/**
* A distributed lock implementation
@@ -42,21 +41,19 @@ public static String lock(String name, Duration duration) {
String uuid = UUID.randomUUID().toString();
// INSERT or UPDATE
- SqlUtils insertValues = new SqlUtils()
- .add("name", name)
- .add(new SqlValue("locked_at", SqlValue.AS_IS, "CURRENT_TIMESTAMP"))
- .add(new SqlValue("lock_until", SqlValue.AS_IS,
- "CURRENT_TIMESTAMP - INTERVAL '10 SECONDS' + INTERVAL '" + duration.toString() + "'"))
- .add("uuid", uuid);
+ var insert = (DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("name", name)
+ .FIELD("locked_at = CURRENT_TIMESTAMP")
+ .FIELD("lock_until = CURRENT_TIMESTAMP - INTERVAL '10 SECONDS' + INTERVAL '" + duration.toString() + "'")
+ .FIELD("uuid", uuid)
+ .ON_CONFLICT("name")
+ .DO_UPDATE()
+ .SET("locked_at = EXCLUDED.locked_at")
+ .SET("lock_until = EXCLUDED.lock_until")
+ .SET("uuid = EXCLUDED.uuid")
+ .WHERE("distributed_lock.name = EXCLUDED.name AND CURRENT_TIMESTAMP >= distributed_lock.lock_until"));
- String onConflict = "ON CONFLICT (name) " +
- "DO UPDATE SET " +
- "locked_at = EXCLUDED.locked_at, " +
- "lock_until = EXCLUDED.lock_until, " +
- "uuid = EXCLUDED.uuid " +
- "WHERE distributed_lock.name = EXCLUDED.name AND CURRENT_TIMESTAMP >= distributed_lock.lock_until";
-
- if (DB.insertIntoWithConflict(TABLE_NAME, insertValues, onConflict)) {
+ if (insert.execute() > 0) {
LOG.debug("Lock succeeded: " + name);
return uuid;
}
@@ -64,14 +61,10 @@ public static String lock(String name, Duration duration) {
}
public static boolean unlock(String name, String uuid) {
- // Expire right away
- SqlUtils updateValues = new SqlUtils()
- .add(new SqlValue("lock_until", SqlValue.AS_IS, "CURRENT_TIMESTAMP"));
- if (DB.update(TABLE_NAME, updateValues,
- DB.WHERE("name = ?", name)
- .AND("uuid = ?", uuid))) {
- return true;
- }
- return false;
+ return DB.UPDATE(TABLE_NAME)
+ .SET("lock_until = CURRENT_TIMESTAMP")
+ .WHERE("name = ?", name)
+ .AND("uuid = ?", uuid)
+ .execute();
}
}
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/DatabaseVersionRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/DatabaseVersionRepository.java
index 0afa16f97..e3148e4fc 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/DatabaseVersionRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/DatabaseVersionRepository.java
@@ -24,11 +24,9 @@
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.simisinc.platform.domain.model.DatabaseVersion;
-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 database version objects
@@ -44,26 +42,26 @@ public class DatabaseVersionRepository {
private static String[] PRIMARY_KEY = new String[] { "version_id" };
public static long count() {
- return DB.selectCountFrom(TABLE_NAME);
+ return DB.SELECT("COUNT(*)")
+ .FROM(TABLE_NAME)
+ .returnCount();
}
public static DatabaseVersion findByVersion(String version) {
if (StringUtils.isBlank(version)) {
return null;
}
- return (DatabaseVersion) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("version = ?", version),
- DatabaseVersionRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("version = ?", version)
+ .returnRecord(DatabaseVersionRepository::buildRecord);
}
public static List findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- null,
- new DataConstraints().setDefaultColumnToSortBy(PRIMARY_KEY[0]),
- DatabaseVersionRepository::buildRecord);
- return (List) result.getRecords();
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy(PRIMARY_KEY[0]))
+ .returnDataResult(DatabaseVersionRepository::buildRecord).getRecords();
}
public static DatabaseVersion save(DatabaseVersion record) {
@@ -71,10 +69,11 @@ public static DatabaseVersion save(DatabaseVersion record) {
}
private static DatabaseVersion add(DatabaseVersion record) {
- SqlUtils insertValues = new SqlUtils()
- .add("file", StringUtils.trimToNull(record.getFile()))
- .add("version", StringUtils.trimToNull(record.getVersion()));
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ long insertedId = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("file", StringUtils.trimToNull(record.getFile()))
+ .FIELD("version", StringUtils.trimToNull(record.getVersion()))
+ .execute();
+ record.setId(insertedId);
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/GroupRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/GroupRepository.java
index 80a0016b5..952ee8d7f 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/GroupRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/GroupRepository.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.Insert;
+import com.github.rajkowski.database.Select;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.domain.model.Group;
import com.simisinc.platform.domain.model.User;
-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.persistence.login.UserGroupRepository;
/**
@@ -53,64 +54,58 @@ public static Group findById(long id) {
if (id == -1) {
return null;
}
- return (Group) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("group_id = ?", id),
- GroupRepository::buildRecord);
+ return DB.SELECT("groups.*")
+ .FROM(TABLE_NAME)
+ .WHERE("group_id = ?", id)
+ .returnRecord(GroupRepository::buildRecord);
}
public static Group findByUniqueId(String uniqueId) {
if (StringUtils.isBlank(uniqueId)) {
return null;
}
- return (Group) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("unique_id = ?", uniqueId),
- GroupRepository::buildRecord);
+ return DB.SELECT("groups.*")
+ .FROM(TABLE_NAME)
+ .WHERE("unique_id = ?", uniqueId)
+ .returnRecord(GroupRepository::buildRecord);
}
public static Group findByOAuthPath(String oAuthPath) {
if (StringUtils.isBlank(oAuthPath)) {
return null;
}
- return (Group) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("oauth_path = ?", oAuthPath),
- GroupRepository::buildRecord);
+ return DB.SELECT("groups.*")
+ .FROM(TABLE_NAME)
+ .WHERE("oauth_path = ?", oAuthPath)
+ .returnRecord(GroupRepository::buildRecord);
}
public static Group findByName(String name) {
if (StringUtils.isBlank(name)) {
return null;
}
- return (Group) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("LOWER(name) = ?", name.toLowerCase().trim()),
- GroupRepository::buildRecord);
+ return DB.SELECT("groups.*")
+ .FROM(TABLE_NAME)
+ .WHERE("LOWER(name) = ?", name.toLowerCase().trim())
+ .returnRecord(GroupRepository::buildRecord);
}
public static List findAllByUserId(long userId) {
if (userId == -1) {
return null;
}
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- DB.WHERE("EXISTS (SELECT 1 FROM user_groups WHERE group_id = groups.group_id AND user_id = ?)", userId),
- new DataConstraints().setDefaultColumnToSortBy("group_id").setUseCount(false),
- GroupRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ Select select = DB.SELECT("groups.*")
+ .FROM(TABLE_NAME)
+ .WHERE("EXISTS (SELECT 1 FROM user_groups WHERE group_id = groups.group_id AND user_id = ?)", userId)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("group_id").setUseCount(false));
+ return select.returnDataResult(GroupRepository::buildRecord).getRecords();
}
public static List findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- null,
- new DataConstraints().setDefaultColumnToSortBy("name"),
- GroupRepository::buildRecord);
- return (List) result.getRecords();
+ return DB.SELECT("groups.*")
+ .FROM(TABLE_NAME)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("name"))
+ .returnDataResult(GroupRepository::buildRecord).getRecords();
}
public static Group save(Group record) {
@@ -121,12 +116,14 @@ public static Group save(Group record) {
}
private static Group add(Group record) {
- SqlUtils insertValues = new SqlUtils()
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("unique_id", StringUtils.trimToNull(record.getUniqueId()))
- .add("description", StringUtils.trimToNull(record.getDescription()))
- .addIfExists("oauth_path", record.getOAuthPath());
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("name", StringUtils.trimToNull(record.getName()))
+ .FIELD("unique_id", StringUtils.trimToNull(record.getUniqueId()))
+ .FIELD("description", StringUtils.trimToNull(record.getDescription()));
+ if (StringUtils.isNotBlank(record.getOAuthPath())) {
+ insert.FIELD("oauth_path", record.getOAuthPath());
+ }
+ record.setId(insert.execute());
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -135,12 +132,17 @@ private static Group add(Group record) {
}
private static Group update(Group record) {
- SqlUtils updateValues = new SqlUtils()
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("unique_id", StringUtils.trimToNull(record.getUniqueId()))
- .add("description", StringUtils.trimToNull(record.getDescription()))
- .addIfExists("oauth_path", record.getOAuthPath());
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("group_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("name", StringUtils.trimToNull(record.getName()))
+ .SET("unique_id", StringUtils.trimToNull(record.getUniqueId()))
+ .SET("description", StringUtils.trimToNull(record.getDescription()));
+ if (StringUtils.isNotBlank(record.getOAuthPath())) {
+ update.SET("oauth_path", record.getOAuthPath());
+ } else {
+ update.SET("oauth_path", (String) null);
+ }
+ update.WHERE("group_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("The update failed!");
@@ -151,11 +153,8 @@ public static boolean remove(Group record) {
try (Connection connection = DB.getConnection();
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
- // Delete the references
UserGroupRepository.remove(connection, record);
- // Delete the record
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("group_id = ?", record.getId()));
- // Finish transaction
+ DB.DELETE().FROM(TABLE_NAME).WHERE("group_id = ?", record.getId()).execute(connection);
transaction.commit();
return true;
} catch (SQLException se) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/RoleRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/RoleRepository.java
index 893d41ed6..907e750c7 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/RoleRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/RoleRepository.java
@@ -24,10 +24,9 @@
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.simisinc.platform.domain.model.Role;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.DataConstraints;
-import com.simisinc.platform.infrastructure.database.DataResult;
/**
* Persists and retrieves role objects
@@ -45,57 +44,48 @@ public static Role findByCode(String code) {
if (StringUtils.isBlank(code)) {
return null;
}
- return (Role) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("code = ?", code),
- RoleRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("code = ?", code)
+ .returnRecord(RoleRepository::buildRecord);
}
public static Role findByOAuthPath(String oAuthPath) {
if (StringUtils.isBlank(oAuthPath)) {
return null;
}
- return (Role) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("oauth_path = ?", oAuthPath),
- RoleRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("oauth_path = ?", oAuthPath)
+ .returnRecord(RoleRepository::buildRecord);
}
public static Role findById(int id) {
if (id == -1) {
return null;
}
- return (Role) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("role_id = ?", id),
- RoleRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("role_id = ?", id)
+ .returnRecord(RoleRepository::buildRecord);
}
public static List findAllByUserId(long userId) {
if (userId == -1) {
return null;
}
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- DB.WHERE("EXISTS (SELECT 1 FROM user_roles WHERE role_id = lookup_role.role_id AND user_id = ?)", userId),
- new DataConstraints().setDefaultColumnToSortBy("role_id").setUseCount(false),
- RoleRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("EXISTS (SELECT 1 FROM user_roles WHERE role_id = lookup_role.role_id AND user_id = ?)", userId)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("role_id").setUseCount(false))
+ .returnDataResult(RoleRepository::buildRecord).getRecords();
}
public static List findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- null,
- new DataConstraints().setDefaultColumnToSortBy("level"),
- RoleRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("level"))
+ .returnDataResult(RoleRepository::buildRecord).getRecords();
}
/**
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/SessionRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/SessionRepository.java
index 3e3138b1f..25f4a3eb7 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/SessionRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/SessionRepository.java
@@ -30,15 +30,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.simisinc.platform.application.admin.LoadSitePropertyCommand;
import com.simisinc.platform.domain.model.Session;
import com.simisinc.platform.domain.model.Visitor;
import com.simisinc.platform.domain.model.dashboard.ActiveSessionData;
import com.simisinc.platform.domain.model.dashboard.StatisticsData;
-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.presentation.controller.UserSession;
/**
@@ -58,22 +56,17 @@ public static Session findBySessionId(long sessionId) {
if (sessionId == -1) {
return null;
}
- return (Session) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("session_id = ?", sessionId),
- SessionRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("session_id = ?", sessionId)
+ .returnRecord(SessionRepository::buildRecord);
}
public static List findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- null,
- new DataConstraints().setDefaultColumnToSortBy("id"),
- SessionRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("id"))
+ .returnDataResult(SessionRepository::buildRecord).getRecords();
}
public static List findDailyUniqueLocations(int daysToLimit) {
@@ -106,12 +99,12 @@ public static List findDailyUniqueLocations(int daysToLimit) {
}
public static long countDistinctSessions(Timestamp startDate, Timestamp endDate) {
- // Query the data, skip some things
- return DB.selectCountFrom(
- TABLE_NAME,
- DB.WHERE("created >= ?", startDate)
- .AND("created < ?", endDate)
- .AND("is_bot = ?", false));
+ return DB.SELECT().COUNT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("created >= ?", startDate)
+ .AND("created < ?", endDate)
+ .AND("is_bot = ?", false)
+ .returnCount();
}
public static long countSessionsToday() {
@@ -308,32 +301,31 @@ public static List findTopReferrals(int value, char intervalType
}
public static Session add(Session record) {
- // remove tailing slash on referer
String referer = record.getReferer();
if (referer != null && referer.length() > 1 && referer.endsWith("/")) {
referer = referer.substring(0, referer.length() - 1);
}
- // Insert the record
- SqlUtils insertValues = new SqlUtils()
- .add("session_id", record.getSessionId())
- .add("source", record.getSource())
- .add("ip_address", record.getIpAddress())
- .add("user_agent", StringUtils.abbreviate(record.getUserAgent(), 255))
- .add("referer", StringUtils.abbreviate(referer, 255))
- .add("continent", record.getContinent())
- .add("country_iso", record.getCountryIso())
- .add("country", record.getCountry())
- .add("city", record.getCity())
- .add("state_iso", record.getStateIso())
- .add("state", record.getState())
- .add("postal_code", record.getPostalCode())
- .add("timezone", record.getTimezone())
- .add("is_bot", record.getIsBot())
- .addIfExists("latitude", record.getLatitude(), 0)
- .addIfExists("longitude", record.getLongitude(), 0)
- .addIfExists("metro_code", record.getMetroCode(), -1)
- .addIfExists("app_id", record.getAppId(), -1L);
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ long id = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("session_id", record.getSessionId())
+ .FIELD("source", record.getSource())
+ .FIELD("ip_address", record.getIpAddress())
+ .FIELD("user_agent", StringUtils.abbreviate(record.getUserAgent(), 255))
+ .FIELD("referer", StringUtils.abbreviate(referer, 255))
+ .FIELD("continent", record.getContinent())
+ .FIELD("country_iso", record.getCountryIso())
+ .FIELD("country", record.getCountry())
+ .FIELD("city", record.getCity())
+ .FIELD("state_iso", record.getStateIso())
+ .FIELD("state", record.getState())
+ .FIELD("postal_code", record.getPostalCode())
+ .FIELD("timezone", record.getTimezone())
+ .FIELD("is_bot", record.getIsBot())
+ .FIELD_UNLESS_MATCHES("latitude", record.getLatitude(), 0)
+ .FIELD_UNLESS_MATCHES("longitude", record.getLongitude(), 0)
+ .FIELD_UNLESS_MATCHES("metro_code", record.getMetroCode(), -1)
+ .FIELD_UNLESS_MATCHES("app_id", record.getAppId(), -1L)
+ .execute();
+ record.setId(id);
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -345,19 +337,20 @@ public static void updateVisitorId(Connection connection, Visitor record) throws
if (record.getId() == -1 || record.getSessionId() == null) {
return;
}
- SqlUtils setValues = new SqlUtils().add("visitor_id", record.getId());
- DB.update(connection,
- TABLE_NAME,
- setValues,
- DB.WHERE("session_id = ?", record.getSessionId()));
+ DB.UPDATE(TABLE_NAME)
+ .SET("visitor_id", record.getId())
+ .WHERE("session_id = ?", record.getSessionId())
+ .execute(connection);
}
public static void updateVisitorId(UserSession userSession, Visitor visitor) {
if (userSession == null || userSession.getSessionId() == null || visitor == null || visitor.getId() == -1) {
return;
}
- SqlUtils setValues = new SqlUtils().add("visitor_id", visitor.getId());
- DB.update(TABLE_NAME, setValues, DB.WHERE("session_id = ?", userSession.getSessionId()));
+ DB.UPDATE(TABLE_NAME)
+ .SET("visitor_id", visitor.getId())
+ .WHERE("session_id = ?", userSession.getSessionId())
+ .execute();
}
/**
@@ -478,7 +471,8 @@ public static double findBounceRate(int daysToLimit) {
*/
public static List findDailyBounceRate(int daysToLimit) {
String SQL_QUERY = "WITH daily_session_counts AS ( " +
- " SELECT DATE_TRUNC('day', wph.hit_date)::VARCHAR(10) AS date_column, wph.session_id, COUNT(DISTINCT wph.hit_id) AS page_count " +
+ " SELECT DATE_TRUNC('day', wph.hit_date)::VARCHAR(10) AS date_column, wph.session_id, COUNT(DISTINCT wph.hit_id) AS page_count "
+ +
" FROM web_page_hits wph " +
" WHERE wph.hit_date > NOW() - INTERVAL '" + daysToLimit + " days' " +
" AND NOT EXISTS (SELECT 1 FROM sessions WHERE session_id = wph.session_id AND is_bot = TRUE) " +
@@ -496,10 +490,12 @@ public static List findDailyBounceRate(int daysToLimit) {
" GROUP BY date_column " +
"), " +
"date_series AS ( " +
- " SELECT generate_series(NOW() - INTERVAL '" + daysToLimit + " days', NOW(), INTERVAL '1 day')::date::VARCHAR(10) AS date_column " +
+ " SELECT generate_series(NOW() - INTERVAL '" + daysToLimit
+ + " days', NOW(), INTERVAL '1 day')::date::VARCHAR(10) AS date_column " +
") " +
"SELECT ds.date_column, " +
- " COALESCE(CASE WHEN dts.total_count > 0 THEN (dbs.bounce_count::float / dts.total_count) * 100 ELSE 0 END, 0) AS bounce_rate " +
+ " COALESCE(CASE WHEN dts.total_count > 0 THEN (dbs.bounce_count::float / dts.total_count) * 100 ELSE 0 END, 0) AS bounce_rate "
+ +
"FROM date_series ds " +
"LEFT JOIN daily_total_sessions dts ON ds.date_column = dts.date_column " +
"LEFT JOIN daily_bounce_sessions dbs ON ds.date_column = dbs.date_column " +
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/SitePropertyRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/SitePropertyRepository.java
index cbbd99420..3046b4b7c 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/SitePropertyRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/SitePropertyRepository.java
@@ -26,12 +26,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.simisinc.platform.application.admin.LoadSitePropertyCommand;
import com.simisinc.platform.domain.model.SiteProperty;
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;
/**
* Persists and retrieves site property objects
@@ -50,34 +49,25 @@ public static SiteProperty findByName(String name) {
if (StringUtils.isBlank(name)) {
return null;
}
- return (SiteProperty) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("property_name = ?", name),
- SitePropertyRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("property_name = ?", name)
+ .returnRecord(SitePropertyRepository::buildRecord);
}
public static List findAllByPrefix(String prefix) {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- DB.WHERE("property_name LIKE ?", prefix + ".%"),
- new DataConstraints().setDefaultColumnToSortBy("property_order, property_name").setUseCount(false),
- SitePropertyRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("property_name LIKE ?", prefix + ".%")
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("property_order, property_name").setUseCount(false))
+ .returnDataResult(SitePropertyRepository::buildRecord).getRecords();
}
public static List findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- null,
- new DataConstraints().setDefaultColumnToSortBy("property_id"),
- SitePropertyRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("property_id"))
+ .returnDataResult(SitePropertyRepository::buildRecord).getRecords();
}
private static PreparedStatement createPreparedStatementForUpdate(Connection connection, SiteProperty record) throws SQLException {
@@ -92,13 +82,12 @@ private static PreparedStatement createPreparedStatementForUpdate(Connection con
}
public static SiteProperty save(SiteProperty record) {
- try (Connection connection = DB.getConnection();
- PreparedStatement pst = createPreparedStatementForUpdate(connection, record)) {
- if (pst.executeUpdate() > 0) {
- return record;
- }
- } catch (SQLException se) {
- LOG.error("SQLException: " + se.getMessage());
+ boolean updated = DB.UPDATE(TABLE_NAME)
+ .SET("property_value", StringUtils.trimToEmpty(record.getValue()))
+ .WHERE("property_id = ?", record.getId())
+ .execute();
+ if (updated) {
+ return record;
}
return null;
}
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/UserProfileRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/UserProfileRepository.java
index fb1df721b..1478d48d1 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/UserProfileRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/UserProfileRepository.java
@@ -26,16 +26,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.CastType;
+import com.github.rajkowski.database.DB;
+import com.github.rajkowski.database.DataConstraints;
+import com.github.rajkowski.database.DataResult;
+import com.github.rajkowski.database.Select;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.application.CustomFieldListJSONCommand;
import com.simisinc.platform.application.cms.HtmlCommand;
import com.simisinc.platform.domain.model.UserProfile;
-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.SqlValue;
/**
* Persists and retrieves user profile objects
@@ -50,36 +51,32 @@ public class UserProfileRepository {
private static String TABLE_NAME = "users";
private static String[] PRIMARY_KEY = new String[] { "user_id" };
- private static DataResult query(UserSpecification specification, DataConstraints constraints) {
- SqlUtils select = new SqlUtils();
- SqlUtils orderBy = new SqlUtils();
- return DB.selectAllFrom(
- TABLE_NAME,
- select,
- DB.WHERE(),
- orderBy,
- constraints,
- UserProfileRepository::buildRecord);
+ private static DataResult query(UserSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("users.*").FROM(TABLE_NAME);
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(UserProfileRepository::buildRecord);
}
public static UserProfile findByUniqueId(String uniqueId) {
if (StringUtils.isBlank(uniqueId)) {
return null;
}
- return (UserProfile) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("unique_id = ?", uniqueId),
- UserProfileRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("unique_id = ?", uniqueId)
+ .returnRecord(UserProfileRepository::buildRecord);
}
public static UserProfile findByUserId(long userId) {
if (userId == -1) {
return null;
}
- return (UserProfile) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("user_id = ?", userId),
- UserProfileRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("user_id = ?", userId)
+ .returnRecord(UserProfileRepository::buildRecord);
}
public static List findAll(UserSpecification specification, DataConstraints constraints) {
@@ -87,8 +84,7 @@ public static List findAll(UserSpecification specification, DataCon
constraints = new DataConstraints();
}
constraints.setDefaultColumnToSortBy("first_name, last_name");
- DataResult result = query(specification, constraints);
- return (List) result.getRecords();
+ return query(specification, constraints).getRecords();
}
public static UserProfile save(UserProfile record) {
@@ -99,52 +95,45 @@ public static UserProfile save(UserProfile record) {
}
private static UserProfile update(UserProfile record) {
- SqlUtils updateValues = new SqlUtils()
- .add("unique_id", StringUtils.trimToNull(record.getUniqueId()))
- .add("first_name", StringUtils.trimToNull(record.getFirstName()))
- .add("last_name", StringUtils.trimToNull(record.getLastName()))
- .add("organization", StringUtils.trimToNull(record.getOrganization()))
- .add("nickname", StringUtils.trimToNull(record.getNickname()))
- .add("description", StringUtils.trimToNull(record.getDescription()))
- .add("description_text", HtmlCommand.text(StringUtils.trimToNull(record.getDescription())))
- .add("email", StringUtils.trimToNull(record.getEmail()))
- .add("title", StringUtils.trimToNull(record.getTitle()))
- .add("department", StringUtils.trimToNull(record.getDepartment()))
- .add("timezone", StringUtils.trimToNull(record.getTimeZone()))
- .add("city", StringUtils.trimToNull(record.getCity()))
- .add("state", StringUtils.trimToNull(record.getState()))
- .add("country", StringUtils.trimToNull(record.getCountry()))
- .add("postal_code", StringUtils.trimToNull(record.getPostalCode()))
- .add("image_url", StringUtils.trimToNull(record.getImageUrl()))
- .add("video_url", StringUtils.trimToNull(record.getVideoUrl()))
- .add("modified_by", record.getModifiedBy(), -1)
- .add("modified", new Timestamp(System.currentTimeMillis()));
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("unique_id", StringUtils.trimToNull(record.getUniqueId()))
+ .SET("first_name", StringUtils.trimToNull(record.getFirstName()))
+ .SET("last_name", StringUtils.trimToNull(record.getLastName()))
+ .SET("organization", StringUtils.trimToNull(record.getOrganization()))
+ .SET("nickname", StringUtils.trimToNull(record.getNickname()))
+ .SET("description", StringUtils.trimToNull(record.getDescription()))
+ .SET("description_text", HtmlCommand.text(StringUtils.trimToNull(record.getDescription())))
+ .SET("email", StringUtils.trimToNull(record.getEmail()))
+ .SET("title", StringUtils.trimToNull(record.getTitle()))
+ .SET("department", StringUtils.trimToNull(record.getDepartment()))
+ .SET("timezone", StringUtils.trimToNull(record.getTimeZone()))
+ .SET("city", StringUtils.trimToNull(record.getCity()))
+ .SET("state", StringUtils.trimToNull(record.getState()))
+ .SET("country", StringUtils.trimToNull(record.getCountry()))
+ .SET("postal_code", StringUtils.trimToNull(record.getPostalCode()))
+ .SET("image_url", StringUtils.trimToNull(record.getImageUrl()))
+ .SET("video_url", StringUtils.trimToNull(record.getVideoUrl()))
+ .SET("modified_by", record.getModifiedBy())
+ .SET("modified", new Timestamp(System.currentTimeMillis()));
if (record.hasGeoPoint()) {
- updateValues.add("latitude", record.getLatitude());
- updateValues.add("longitude", record.getLongitude());
- updateValues.addGeomPoint("geom", record.getLatitude(), record.getLongitude());
+ update.SET("latitude", record.getLatitude())
+ .SET("longitude", record.getLongitude())
+ .SET("geom", record.getLatitude(), record.getLongitude(), CastType.GEOM);
} else {
- updateValues.add("latitude", 0L, 0L);
- updateValues.add("longitude", 0L, 0L);
- updateValues.addGeomPoint("geom", 0, 0);
+ update.SET("latitude", (Double) null)
+ .SET("longitude", (Double) null)
+ .SET("geom", 0, 0, CastType.GEOM);
}
- // Handle custom fields
if (record.getCustomFieldList() != null && !record.getCustomFieldList().isEmpty()) {
- updateValues.add(
- new SqlValue("field_values", SqlValue.JSONB_TYPE, CustomFieldListJSONCommand.createJSONString(record.getCustomFieldList())));
+ update.SET("field_values", CustomFieldListJSONCommand.createJSONString(record.getCustomFieldList()), CastType.JSONB);
} else {
- updateValues.add(new SqlValue("field_values", SqlValue.JSONB_TYPE, null));
+ update.SET("field_values", (String) null, CastType.JSONB);
}
- // Use a transaction
+ update.WHERE("user_id = ?", record.getId());
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("user_id = ?", record.getId()));
- // Finish the transaction
+ update.execute(connection);
transaction.commit();
return record;
} catch (SQLException se) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/UserRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/UserRepository.java
index a3d0581d9..e429b3b61 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/UserRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/UserRepository.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");
@@ -29,16 +30,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.CastType;
+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.Role;
import com.simisinc.platform.domain.model.User;
import com.simisinc.platform.domain.model.dashboard.StatisticsData;
-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.infrastructure.persistence.ecommerce.OrderRepository;
import com.simisinc.platform.infrastructure.persistence.login.UserGroupRepository;
import com.simisinc.platform.infrastructure.persistence.login.UserLoginRepository;
@@ -59,95 +62,95 @@ public class UserRepository {
private static String TABLE_NAME = "users";
private static String[] PRIMARY_KEY = new String[] { "user_id" };
- private static DataResult query(UserSpecification specification, DataConstraints constraints) {
- SqlUtils select = new SqlUtils();
- SqlWhere where = DB.WHERE();
- SqlUtils orderBy = new SqlUtils();
+ private static DataResult query(UserSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("users.*").FROM(TABLE_NAME).WHERE();
if (specification != null) {
- where.andAddIfHasValue("user_id = ?", specification.getId(), -1);
+ if (specification.getId() > -1) {
+ select.AND("user_id = ?", specification.getId());
+ }
if (specification.getRoleId() > -1) {
- where.AND("EXISTS (SELECT 1 FROM user_roles WHERE user_id = users.user_id AND role_id = ?)", specification.getRoleId());
+ select.AND("EXISTS (SELECT 1 FROM user_roles WHERE user_id = users.user_id AND role_id = ?)", specification.getRoleId());
}
if (specification.getGroupId() > -1) {
- where.AND("EXISTS (SELECT 1 FROM user_groups WHERE user_id = users.user_id AND group_id = ?)", specification.getGroupId());
+ select.AND("EXISTS (SELECT 1 FROM user_groups WHERE user_id = users.user_id AND group_id = ?)", specification.getGroupId());
}
if (specification.getIsEnabled() != DataConstants.UNDEFINED) {
- where.AND("enabled = ?", specification.getIsEnabled() == DataConstants.TRUE);
+ select.AND("enabled = ?", specification.getIsEnabled() == DataConstants.TRUE);
}
if (specification.getIsVerified() != DataConstants.UNDEFINED) {
if (specification.getIsVerified() == DataConstants.TRUE) {
- where.AND("validated IS NOT NULL");
+ select.AND("validated IS NOT NULL");
} else {
- where.AND("validated IS NULL");
+ select.AND("validated IS NULL");
}
}
if (specification.getMatchesName() != null) {
if (specification.getMatchesName().contains("@")) {
- // Exact match on an email
- where.AND("LOWER(email) = LOWER(?)", specification.getMatchesName().trim());
+ select.AND("LOWER(email) = LOWER(?)", specification.getMatchesName().trim());
} else {
- // Like matching on a name
String likeValue = specification.getMatchesName().trim()
.replace("!", "!!")
.replace("%", "!%")
.replace("_", "!_")
.replace("[", "![");
- where.AND("LOWER(concat_ws(' ', first_name, last_name, nickname)) LIKE LOWER(?) ESCAPE '!'", "%" + likeValue + "%");
+ select.AND("LOWER(concat_ws(' ', first_name, last_name, nickname)) LIKE LOWER(?) ESCAPE '!'", "%" + likeValue + "%");
}
}
}
- return DB.selectAllFrom(
- TABLE_NAME, select, where, orderBy, constraints, UserRepository::buildRecord);
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(UserRepository::buildRecord);
}
public static User findByUniqueId(String uniqueId) {
if (StringUtils.isBlank(uniqueId)) {
return null;
}
- return (User) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("unique_id = ?", uniqueId),
- UserRepository::buildRecord);
+ return DB.SELECT("users.*")
+ .FROM(TABLE_NAME)
+ .WHERE("unique_id = ?", uniqueId)
+ .returnRecord(UserRepository::buildRecord);
}
public static User findByUsername(String username) {
if (StringUtils.isBlank(username)) {
return null;
}
- return (User) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("LOWER(username) = ?", username.toLowerCase()),
- UserRepository::buildRecord);
+ return DB.SELECT("users.*")
+ .FROM(TABLE_NAME)
+ .WHERE("LOWER(username) = ?", username.toLowerCase())
+ .returnRecord(UserRepository::buildRecord);
}
public static User findByUserId(long userId) {
if (userId == -1) {
return null;
}
- return (User) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("user_id = ?", userId),
- UserRepository::buildRecord);
+ return DB.SELECT("users.*")
+ .FROM(TABLE_NAME)
+ .WHERE("user_id = ?", userId)
+ .returnRecord(UserRepository::buildRecord);
}
public static User findByAccountToken(String token) {
if (StringUtils.isBlank(token)) {
return null;
}
- return (User) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("account_token = ?", token),
- UserRepository::buildRecord);
+ return DB.SELECT("users.*")
+ .FROM(TABLE_NAME)
+ .WHERE("account_token = ?", token)
+ .returnRecord(UserRepository::buildRecord);
}
public static User findByEmailAddress(String email) {
if (StringUtils.isBlank(email)) {
return null;
}
- return (User) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("LOWER(email) = ?", email.toLowerCase()),
- UserRepository::buildRecord);
+ return DB.SELECT("users.*")
+ .FROM(TABLE_NAME)
+ .WHERE("LOWER(email) = ?", email.toLowerCase())
+ .returnRecord(UserRepository::buildRecord);
}
public static List findAllByRole(Role role) {
@@ -266,42 +269,39 @@ public static User add(User record) {
if (record.getUsername() != null) {
record.setUsername(record.getUsername().trim().toLowerCase());
}
- SqlUtils insertValues = new SqlUtils()
- .add("unique_id", StringUtils.trimToNull(record.getUniqueId()))
- .add("first_name", StringUtils.trimToNull(record.getFirstName()))
- .add("last_name", StringUtils.trimToNull(record.getLastName()))
- .add("organization", StringUtils.trimToNull(record.getOrganization()))
- .add("nickname", StringUtils.trimToNull(record.getNickname()))
- .add("email", StringUtils.trimToNull(record.getEmail()))
- .add("username", StringUtils.trimToNull(record.getUsername()))
- .add("title", StringUtils.trimToNull(record.getTitle()))
- .add("department", StringUtils.trimToNull(record.getDepartment()))
- .add("timezone", StringUtils.trimToNull(record.getTimeZone()))
- .add("city", StringUtils.trimToNull(record.getCity()))
- .add("state", StringUtils.trimToNull(record.getState()))
- .add("country", StringUtils.trimToNull(record.getCountry()))
- .add("postal_code", StringUtils.trimToNull(record.getPostalCode()))
- .add("password", record.getPassword())
- .add("enabled", true)
- .add("account_token", record.getAccountToken())
- .addIfExists("created", record.getCreated())
- .add("created_by", record.getCreatedBy(), -1);
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("unique_id", StringUtils.trimToNull(record.getUniqueId()))
+ .FIELD("first_name", StringUtils.trimToNull(record.getFirstName()))
+ .FIELD("last_name", StringUtils.trimToNull(record.getLastName()))
+ .FIELD("organization", StringUtils.trimToNull(record.getOrganization()))
+ .FIELD("nickname", StringUtils.trimToNull(record.getNickname()))
+ .FIELD("email", StringUtils.trimToNull(record.getEmail()))
+ .FIELD("username", StringUtils.trimToNull(record.getUsername()))
+ .FIELD("title", StringUtils.trimToNull(record.getTitle()))
+ .FIELD("department", StringUtils.trimToNull(record.getDepartment()))
+ .FIELD("timezone", StringUtils.trimToNull(record.getTimeZone()))
+ .FIELD("city", StringUtils.trimToNull(record.getCity()))
+ .FIELD("state", StringUtils.trimToNull(record.getState()))
+ .FIELD("country", StringUtils.trimToNull(record.getCountry()))
+ .FIELD("postal_code", StringUtils.trimToNull(record.getPostalCode()))
+ .FIELD("password", record.getPassword())
+ .FIELD("enabled", true)
+ .FIELD("account_token", record.getAccountToken())
+ .FIELD("created_by", record.getCreatedBy() == -1 ? null : record.getCreatedBy());
+ if (record.getCreated() != null) {
+ insert.FIELD("created", record.getCreated());
+ }
if (record.hasGeoPoint()) {
- insertValues.add("latitude", record.getLatitude());
- insertValues.add("longitude", record.getLongitude());
- insertValues.addGeomPoint("geom", record.getLatitude(), record.getLongitude());
+ insert.FIELD("latitude", record.getLatitude())
+ .FIELD("longitude", record.getLongitude())
+ .FIELD("geom", record.getLatitude(), record.getLongitude(), CastType.GEOM);
}
- // 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
+ record.setId(insert.execute(connection));
UserGroupRepository.insertUserGroupList(connection, record);
- // Manage the roles
UserRoleRepository.insertUserRoleList(connection, record);
- // Finish the transaction
transaction.commit();
LOG.info("Inserted userId: " + record.getId() + " - " + record.getEmail());
return record;
@@ -319,47 +319,44 @@ private static User update(User record) {
if (record.getUsername() != null) {
record.setUsername(record.getUsername().trim().toLowerCase());
}
- SqlUtils updateValues = new SqlUtils()
- .add("unique_id", StringUtils.trimToNull(record.getUniqueId()))
- .add("first_name", StringUtils.trimToNull(record.getFirstName()))
- .add("last_name", StringUtils.trimToNull(record.getLastName()))
- .add("organization", StringUtils.trimToNull(record.getOrganization()))
- .add("nickname", StringUtils.trimToNull(record.getNickname()))
- .add("email", StringUtils.trimToNull(record.getEmail()))
- .add("username", StringUtils.trimToNull(record.getUsername()))
- .add("title", StringUtils.trimToNull(record.getTitle()))
- .add("department", StringUtils.trimToNull(record.getDepartment()))
- .add("timezone", StringUtils.trimToNull(record.getTimeZone()))
- .add("city", StringUtils.trimToNull(record.getCity()))
- .add("state", StringUtils.trimToNull(record.getState()))
- .add("country", StringUtils.trimToNull(record.getCountry()))
- .add("postal_code", StringUtils.trimToNull(record.getPostalCode()))
- .add("modified_by", record.getModifiedBy(), -1)
- .add("modified", new Timestamp(System.currentTimeMillis()));
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("unique_id", StringUtils.trimToNull(record.getUniqueId()))
+ .SET("first_name", StringUtils.trimToNull(record.getFirstName()))
+ .SET("last_name", StringUtils.trimToNull(record.getLastName()))
+ .SET("organization", StringUtils.trimToNull(record.getOrganization()))
+ .SET("nickname", StringUtils.trimToNull(record.getNickname()))
+ .SET("email", StringUtils.trimToNull(record.getEmail()))
+ .SET("username", StringUtils.trimToNull(record.getUsername()))
+ .SET("title", StringUtils.trimToNull(record.getTitle()))
+ .SET("department", StringUtils.trimToNull(record.getDepartment()))
+ .SET("timezone", StringUtils.trimToNull(record.getTimeZone()))
+ .SET("city", StringUtils.trimToNull(record.getCity()))
+ .SET("state", StringUtils.trimToNull(record.getState()))
+ .SET("country", StringUtils.trimToNull(record.getCountry()))
+ .SET("postal_code", StringUtils.trimToNull(record.getPostalCode()))
+ .SET("modified_by", record.getModifiedBy() == -1 ? null : record.getModifiedBy())
+ .SET("modified", new Timestamp(System.currentTimeMillis()));
if (record.hasGeoPoint()) {
- updateValues.add("latitude", record.getLatitude());
- updateValues.add("longitude", record.getLongitude());
- updateValues.addGeomPoint("geom", record.getLatitude(), record.getLongitude());
+ update.SET("latitude", record.getLatitude())
+ .SET("longitude", record.getLongitude())
+ .SET("geom", record.getLatitude(), record.getLongitude(), CastType.GEOM);
} else {
- updateValues.add("latitude", 0L, 0L);
- updateValues.add("longitude", 0L, 0L);
- updateValues.addGeomPoint("geom", 0, 0);
+ update.SET("latitude", (Double) null)
+ .SET("longitude", (Double) null)
+ .SET("geom", (String) null);
}
- // 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("user_id = ?", record.getId()));
- // Manage the access groups
- UserGroupRepository.removeAll(connection, record);
- UserGroupRepository.insertUserGroupList(connection, record);
- // Manage the roles
- UserRoleRepository.removeAll(connection, record);
- UserRoleRepository.insertUserRoleList(connection, record);
- // Finish the transaction
- transaction.commit();
- return record;
+ update.WHERE("user_id = ?", record.getId());
+ if (update.execute(connection) != null) {
+ UserGroupRepository.removeAll(connection, record);
+ UserGroupRepository.insertUserGroupList(connection, record);
+ UserRoleRepository.removeAll(connection, record);
+ UserRoleRepository.insertUserRoleList(connection, record);
+ transaction.commit();
+ return record;
+ }
} catch (SQLException se) {
LOG.error("SQLException: " + se.getMessage(), se);
}
@@ -368,12 +365,12 @@ private static User update(User record) {
public static User updateValidated(User record) {
Timestamp occurred = new Timestamp(System.currentTimeMillis());
- SqlUtils updateValues = new SqlUtils()
- .add("validated", occurred)
- .add("account_token", (String) null)
- .add("modified", occurred);
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("user_id = ?", record.getId()))) {
- // Updated related records
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("validated", occurred)
+ .SET("account_token", (String) null)
+ .SET("modified", occurred)
+ .WHERE("user_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
OrderRepository.updateUserOrders(record);
return record;
}
@@ -382,12 +379,12 @@ public static User updateValidated(User record) {
}
public static User updatePassword(User record) {
- SqlUtils updateValues = new SqlUtils()
- .add("password", record.getPassword())
- .add("account_token", (String) null)
- .add("modified", new Timestamp(System.currentTimeMillis()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("user_id = ?", record.getId()))) {
- // Invalidate user_tokens since there is a new password
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("password", record.getPassword())
+ .SET("account_token", (String) null)
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("user_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
UserTokenRepository.removeAll(record.getId());
return record;
}
@@ -397,10 +394,11 @@ public static User updatePassword(User record) {
public static User createAccountToken(User record) {
String newToken = UUID.randomUUID().toString();
- SqlUtils updateValues = new SqlUtils()
- .add("account_token", newToken)
- .add("modified", new Timestamp(System.currentTimeMillis()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("user_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("account_token", newToken)
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("user_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
record.setAccountToken(newToken);
return record;
}
@@ -409,10 +407,11 @@ public static User createAccountToken(User record) {
}
public static User suspendAccount(User record) {
- SqlUtils updateValues = new SqlUtils()
- .add("enabled", false)
- .add("modified", new Timestamp(System.currentTimeMillis()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("user_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("enabled", false)
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("user_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("suspendAccount failed!");
@@ -420,10 +419,11 @@ public static User suspendAccount(User record) {
}
public static User restoreAccount(User record) {
- SqlUtils updateValues = new SqlUtils()
- .add("enabled", true)
- .add("modified", new Timestamp(System.currentTimeMillis()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("user_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("enabled", true)
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("user_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("restoreAccount failed!");
@@ -435,16 +435,11 @@ public static boolean remove(User record) {
try (Connection connection = DB.getConnection();
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
- // Delete the references
- // @note the User is currently not cleaned up from all tables
- // until a business decision is made
UserGroupRepository.removeAll(connection, record);
UserRoleRepository.removeAll(connection, record);
UserTokenRepository.removeAll(connection, record);
UserLoginRepository.removeAll(connection, record);
- // Delete the record
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("user_id = ?", record.getId()));
- // Finish transaction
+ DB.DELETE().FROM(TABLE_NAME).WHERE("user_id = ?", record.getId()).execute(connection);
transaction.commit();
return true;
} catch (SQLException se) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/VisitorRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/VisitorRepository.java
index 292fe3660..7cc0cf578 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/VisitorRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/VisitorRepository.java
@@ -25,13 +25,12 @@
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.Insert;
import com.simisinc.platform.domain.model.Visitor;
-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 visitor objects
@@ -47,37 +46,33 @@ public class VisitorRepository {
private static String[] PRIMARY_KEY = new String[] { "visitor_id" };
public static List findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- null,
- new DataConstraints().setDefaultColumnToSortBy("visitor_id"),
- VisitorRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ return DB.SELECT("visitors.*")
+ .FROM(TABLE_NAME)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("visitor_id"))
+ .returnDataResult(VisitorRepository::buildRecord).getRecords();
}
public static Visitor findByToken(String visitorUniqueId) {
if (StringUtils.isBlank(visitorUniqueId)) {
return null;
}
- return (Visitor) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("token = ?", visitorUniqueId),
- VisitorRepository::buildRecord);
+ return DB.SELECT("visitors.*")
+ .FROM(TABLE_NAME)
+ .WHERE("token = ?", visitorUniqueId)
+ .returnRecord(VisitorRepository::buildRecord);
}
public static Visitor add(Visitor record) {
- SqlUtils insertValues = new SqlUtils()
- .add("token", record.getToken())
- .add("session_id", record.getSessionId());
+ Insert insert = DB.INSERT()
+ .INTO(TABLE_NAME)
+ .FIELD("token", record.getToken())
+ .FIELD("session_id", record.getSessionId());
// 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));
+ record.setId(insert.execute(connection));
// Manage the related session
SessionRepository.updateVisitorId(connection, record);
// Finish the transaction
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..c1f833201 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");
+ (Object[]) new Object[] { searchTerm });
+ select.SELECT("ts_rank_cd(tsv, websearch_to_tsquery('content_stem', ?)) AS rank", (Object[]) new Object[] { 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..dbbc0cc19 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", (Object[]) new Object[] { 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..7fd96c196 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);
+ (Object[]) new Object[] { specification.getSearchTerm().trim() });
+ select.SELECT("ts_rank_cd(tsv, websearch_to_tsquery('content_stem', ?)) AS rank", (Object[]) new Object[] { 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..a0a844564 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", (Object[]) new Object[] { 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..d77c6f9a5 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);
+ return 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 findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- null,
- new DataConstraints().setDefaultColumnToSortBy("menu_tab_id, item_order, menu_item_id"),
- MenuItemRepository::buildRecord);
- return (List) result.getRecords();
+ DataResult result = DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("menu_tab_id, item_order, menu_item_id"))
+ .returnDataResult(MenuItemRepository::buildRecord);
+ return result.getRecords();
}
public static List findAllByMenuTab(MenuTab menuTab) {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- DB.WHERE("menu_tab_id = ?", menuTab.getId()),
- new DataConstraints().setDefaultColumnToSortBy("item_order, menu_item_id").setUseCount(false),
- MenuItemRepository::buildRecord);
- return (List) result.getRecords();
+ DataResult result = DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("menu_tab_id = ?", menuTab.getId())
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("item_order, menu_item_id").setUseCount(false))
+ .returnDataResult(MenuItemRepository::buildRecord);
+ return result.getRecords();
}
private static PreparedStatement createPreparedStatementAllActiveByMenuTab(Connection connection, MenuTab menuTab)
@@ -122,18 +121,19 @@ public static MenuItem save(MenuItem record) {
}
public static MenuItem add(MenuItem record) {
- SqlUtils insertValues = new SqlUtils()
- .add("menu_tab_id", record.getMenuTabId())
- .add("item_order", record.getItemOrder())
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("link", StringUtils.trimToNull(record.getLink()))
- .add("page_title", StringUtils.trimToNull(record.getPageTitle()))
- .add("page_keywords", StringUtils.trimToNull(record.getPageKeywords()))
- .add("page_description", StringUtils.trimToNull(record.getPageDescription()))
- .add("draft", record.isDraft())
- .add("enabled", record.isEnabled())
- .add("comments", StringUtils.trimToNull(record.getComments()));
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ long id = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("menu_tab_id", record.getMenuTabId())
+ .FIELD("item_order", record.getItemOrder())
+ .FIELD("name", StringUtils.trimToNull(record.getName()))
+ .FIELD("link", StringUtils.trimToNull(record.getLink()))
+ .FIELD("page_title", StringUtils.trimToNull(record.getPageTitle()))
+ .FIELD("page_keywords", StringUtils.trimToNull(record.getPageKeywords()))
+ .FIELD("page_description", StringUtils.trimToNull(record.getPageDescription()))
+ .FIELD("draft", record.isDraft())
+ .FIELD("enabled", record.isEnabled())
+ .FIELD("comments", StringUtils.trimToNull(record.getComments()))
+ .execute();
+ record.setId(id);
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -142,18 +142,20 @@ public static MenuItem add(MenuItem record) {
}
public static MenuItem update(MenuItem record) {
- SqlUtils updateValues = new SqlUtils()
- .add("menu_tab_id", record.getMenuTabId())
- .add("item_order", record.getItemOrder())
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("link", StringUtils.trimToNull(record.getLink()))
- .add("page_title", StringUtils.trimToNull(record.getPageTitle()))
- .add("page_keywords", StringUtils.trimToNull(record.getPageKeywords()))
- .add("page_description", StringUtils.trimToNull(record.getPageDescription()))
- .add("draft", record.isDraft())
- .add("enabled", record.isEnabled())
- .add("comments", StringUtils.trimToNull(record.getComments()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("menu_item_id = ?", record.getId()))) {
+ boolean updated = DB.UPDATE(TABLE_NAME)
+ .SET("menu_tab_id", record.getMenuTabId())
+ .SET("item_order", record.getItemOrder())
+ .SET("name", StringUtils.trimToNull(record.getName()))
+ .SET("link", StringUtils.trimToNull(record.getLink()))
+ .SET("page_title", StringUtils.trimToNull(record.getPageTitle()))
+ .SET("page_keywords", StringUtils.trimToNull(record.getPageKeywords()))
+ .SET("page_description", StringUtils.trimToNull(record.getPageDescription()))
+ .SET("draft", record.isDraft())
+ .SET("enabled", record.isEnabled())
+ .SET("comments", StringUtils.trimToNull(record.getComments()))
+ .WHERE("menu_item_id = ?", record.getId())
+ .execute();
+ if (updated) {
return record;
}
LOG.error("The update failed!");
@@ -161,11 +163,11 @@ public static MenuItem update(MenuItem record) {
}
public static boolean remove(MenuItem record) {
- return (DB.deleteFrom(TABLE_NAME, DB.WHERE("menu_item_id = ?", record.getId())) > 0);
+ return DB.DELETE().FROM(TABLE_NAME).WHERE("menu_item_id = ?", record.getId()).execute();
}
public static void removeAll(Connection connection, MenuTab record) throws SQLException {
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("menu_tab_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("menu_tab_id = ?", record.getId()).execute(connection);
}
private static PreparedStatement createPreparedStatementNextTabOrder(Connection connection, MenuTab menuTab) throws SQLException {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/MenuTabRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/MenuTabRepository.java
index 2ef53c28f..3236e21ea 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/MenuTabRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/MenuTabRepository.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,13 +27,12 @@
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.simisinc.platform.domain.model.cms.MenuTab;
-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 menu tab objects
@@ -51,39 +51,38 @@ public static MenuTab findById(long id) {
if (id == -1) {
return null;
}
- return (MenuTab) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("menu_tab_id = ?", id),
- MenuTabRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("menu_tab_id = ?", id)
+ .returnRecord(MenuTabRepository::buildRecord);
}
public static MenuTab findByLink(String link) {
if (link == null) {
return null;
}
- return (MenuTab) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("link = ?", link),
- MenuTabRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("link = ?", link)
+ .returnRecord(MenuTabRepository::buildRecord);
}
public static List findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- null,
- new DataConstraints().setDefaultColumnToSortBy("tab_order, menu_tab_id"),
- MenuTabRepository::buildRecord);
- return (List) result.getRecords();
+ DataResult result = DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("tab_order, menu_tab_id"))
+ .returnDataResult(MenuTabRepository::buildRecord);
+ return result.getRecords();
}
public static List findAllActive() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- DB.WHERE("draft = ?", false)
- .AND("enabled = ?", true),
- new DataConstraints().setDefaultColumnToSortBy("tab_order").setUseCount(false),
- MenuTabRepository::buildRecord);
- return (List) result.getRecords();
+ DataResult result = DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("draft = ?", false)
+ .AND("enabled = ?", true)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("tab_order").setUseCount(false))
+ .returnDataResult(MenuTabRepository::buildRecord);
+ return result.getRecords();
}
public static MenuTab save(MenuTab record) {
@@ -94,18 +93,19 @@ public static MenuTab save(MenuTab record) {
}
private static MenuTab add(MenuTab record) {
- SqlUtils insertValues = new SqlUtils()
- .add("tab_order", record.getTabOrder())
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("link", StringUtils.trimToNull(record.getLink()))
- .add("icon", StringUtils.trimToNull(record.getIcon()))
- .add("page_title", StringUtils.trimToNull(record.getPageTitle()))
- .add("page_keywords", StringUtils.trimToNull(record.getPageKeywords()))
- .add("page_description", StringUtils.trimToNull(record.getPageDescription()))
- .add("draft", record.isDraft())
- .add("enabled", record.isEnabled())
- .add("comments", StringUtils.trimToNull(record.getComments()));
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ long id = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("tab_order", record.getTabOrder())
+ .FIELD("name", StringUtils.trimToNull(record.getName()))
+ .FIELD("link", StringUtils.trimToNull(record.getLink()))
+ .FIELD("icon", StringUtils.trimToNull(record.getIcon()))
+ .FIELD("page_title", StringUtils.trimToNull(record.getPageTitle()))
+ .FIELD("page_keywords", StringUtils.trimToNull(record.getPageKeywords()))
+ .FIELD("page_description", StringUtils.trimToNull(record.getPageDescription()))
+ .FIELD("draft", record.isDraft())
+ .FIELD("enabled", record.isEnabled())
+ .FIELD("comments", StringUtils.trimToNull(record.getComments()))
+ .execute();
+ record.setId(id);
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -114,18 +114,20 @@ private static MenuTab add(MenuTab record) {
}
private static MenuTab update(MenuTab record) {
- SqlUtils updateValues = new SqlUtils()
- .add("tab_order", record.getTabOrder())
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("link", StringUtils.trimToNull(record.getLink()))
- .add("icon", StringUtils.trimToNull(record.getIcon()))
- .add("page_title", StringUtils.trimToNull(record.getPageTitle()))
- .add("page_keywords", StringUtils.trimToNull(record.getPageKeywords()))
- .add("page_description", StringUtils.trimToNull(record.getPageDescription()))
- .add("draft", record.isDraft())
- .add("enabled", record.isEnabled())
- .add("comments", StringUtils.trimToNull(record.getComments()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("menu_tab_id = ?", record.getId()))) {
+ boolean updated = DB.UPDATE(TABLE_NAME)
+ .SET("tab_order", record.getTabOrder())
+ .SET("name", StringUtils.trimToNull(record.getName()))
+ .SET("link", StringUtils.trimToNull(record.getLink()))
+ .SET("icon", StringUtils.trimToNull(record.getIcon()))
+ .SET("page_title", StringUtils.trimToNull(record.getPageTitle()))
+ .SET("page_keywords", StringUtils.trimToNull(record.getPageKeywords()))
+ .SET("page_description", StringUtils.trimToNull(record.getPageDescription()))
+ .SET("draft", record.isDraft())
+ .SET("enabled", record.isEnabled())
+ .SET("comments", StringUtils.trimToNull(record.getComments()))
+ .WHERE("menu_tab_id = ?", record.getId())
+ .execute();
+ if (updated) {
return record;
}
LOG.error("The update failed!");
@@ -139,7 +141,7 @@ public static boolean remove(MenuTab record) {
// Delete the references
MenuItemRepository.removeAll(connection, record);
// Delete the record
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("menu_tab_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("menu_tab_id = ?", record.getId()).execute(connection);
// Finish transaction
transaction.commit();
return true;
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/StylesheetRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/StylesheetRepository.java
index 2b4766c58..5b2243290 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/StylesheetRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/StylesheetRepository.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,14 @@
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.simisinc.platform.application.cms.LoadStylesheetCommand;
import com.simisinc.platform.domain.model.cms.Stylesheet;
import com.simisinc.platform.infrastructure.cache.CacheManager;
-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 style sheet objects
@@ -53,29 +53,31 @@ public static Stylesheet findById(long id) {
if (id == -1) {
return null;
}
- return (Stylesheet) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("stylesheet_id = ?", id),
- StylesheetRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("stylesheet_id = ?", id)
+ .returnRecord(StylesheetRepository::buildRecord);
}
public static Stylesheet findByWebPageId(long webPageId) {
- return (Stylesheet) DB.selectRecordFrom(
- TABLE_NAME,
- (webPageId > 0 ? DB.WHERE("web_page_id = ?", webPageId) : DB.WHERE("web_page_id IS NULL")),
- StylesheetRepository::buildRecord);
+ if (webPageId > 0) {
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("web_page_id = ?", webPageId)
+ .returnRecord(StylesheetRepository::buildRecord);
+ }
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("web_page_id IS NULL")
+ .returnRecord(StylesheetRepository::buildRecord);
}
public static List findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- null,
- new DataConstraints().setDefaultColumnToSortBy("stylesheet_id"),
- StylesheetRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ DataResult result = DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("stylesheet_id"))
+ .returnDataResult(StylesheetRepository::buildRecord);
+ return result.getRecords();
}
public static Stylesheet save(Stylesheet record) {
@@ -92,11 +94,12 @@ public static Stylesheet save(Stylesheet record) {
private static Stylesheet add(Stylesheet record) {
Timestamp modified = new Timestamp(System.currentTimeMillis());
- SqlUtils insertValues = new SqlUtils()
- .add("web_page_id", record.getWebPageId(), -1)
- .add("css", StringUtils.trimToNull(record.getCss()))
- .add("modified", modified);
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ long id = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("web_page_id", record.getWebPageId() == -1 ? null : record.getWebPageId())
+ .FIELD("css", StringUtils.trimToNull(record.getCss()))
+ .FIELD("modified", modified)
+ .execute();
+ record.setId(id);
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -109,10 +112,12 @@ private static Stylesheet add(Stylesheet record) {
private static Stylesheet update(Stylesheet record) {
Timestamp modified = new Timestamp(System.currentTimeMillis());
- SqlUtils updateValues = new SqlUtils()
- .add("css", StringUtils.trimToNull(record.getCss()))
- .add("modified", modified);
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("stylesheet_id = ?", record.getId()))) {
+ boolean updated = DB.UPDATE(TABLE_NAME)
+ .SET("css", StringUtils.trimToNull(record.getCss()))
+ .SET("modified", modified)
+ .WHERE("stylesheet_id = ?", record.getId())
+ .execute();
+ if (updated) {
CacheManager.invalidateKey(CacheManager.STYLESHEET_WEB_PAGE_ID_CACHE, record.getWebPageId());
LoadStylesheetCommand.markStylesheetExists(record.getWebPageId(), true);
record.setModified(modified);
@@ -131,7 +136,7 @@ public static boolean remove(Stylesheet record) {
// CollectionRepository.updateItemCount(connection, record.getCollectionId(), -1);
// CategoryRepository.updateItemCount(connection, record.getCategoryId(), -1);
// Delete the record
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("stylesheet_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("stylesheet_id = ?", record.getId()).execute(connection);
// Finish transaction
transaction.commit();
CacheManager.invalidateKey(CacheManager.STYLESHEET_WEB_PAGE_ID_CACHE, record.getWebPageId());
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/SubFolderRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/SubFolderRepository.java
index 5c5c63de8..3cbb74a2a 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/SubFolderRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/SubFolderRepository.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");
@@ -25,16 +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.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.SqlWhere;
import com.simisinc.platform.presentation.controller.DataConstants;
import com.simisinc.platform.presentation.controller.UserSession;
@@ -51,62 +51,50 @@ public class SubFolderRepository {
private static String TABLE_NAME = "sub_folders";
private static String[] PRIMARY_KEY = new String[] { "sub_folder_id" };
- private static DataResult query(SubFolderSpecification specification, DataConstraints constraints) {
- SqlUtils select = new SqlUtils();
- SqlJoins joins = new SqlJoins();
- SqlWhere where = DB.WHERE();
- SqlUtils orderBy = new SqlUtils();
+ private static DataResult query(SubFolderSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("sub_folders.*").FROM(TABLE_NAME);
if (specification != null) {
-
- joins.add("LEFT JOIN folders ON (sub_folders.folder_id = folders.folder_id)");
-
- where
- .andAddIfHasValue("sub_folder_id = ?", specification.getId(), -1)
- .andAddIfHasValue("folders.folder_id = ?", specification.getFolderId(), -1);
-
- // For user id
- // User must be in a user group with folder access
+ select.LEFT_JOIN("folders").ON("sub_folders.folder_id = folders.folder_id");
+ if (specification.getId() != -1) {
+ select.AND("sub_folder_id = ?", specification.getId());
+ }
+ if (specification.getFolderId() != -1) {
+ select.AND("folders.folder_id = ?", specification.getFolderId());
+ }
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());
}
}
-
if (specification.getHasFiles() != DataConstants.UNDEFINED) {
if (specification.getHasFiles() == DataConstants.TRUE) {
- where.AND("sub_folders.file_count > 0");
+ select.AND("sub_folders.file_count > 0");
} else {
- where.AND("sub_folders.file_count = 0");
+ select.AND("sub_folders.file_count = 0");
}
}
-
if (specification.getYear() > 0) {
- where.AND("EXTRACT(YEAR FROM start_date) = ?", specification.getYear());
+ select.AND("EXTRACT(YEAR FROM start_date) = ?", specification.getYear());
}
-
}
- return DB.selectAllFrom(
- TABLE_NAME, select, joins, where, orderBy, constraints, SubFolderRepository::buildRecord);
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(SubFolderRepository::buildRecord);
}
public static SubFolder findById(long id) {
if (id == -1) {
return null;
}
- return (SubFolder) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("sub_folder_id = ?", id),
- SubFolderRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("sub_folder_id = ?", id)
+ .returnRecord(SubFolderRepository::buildRecord);
}
public static List findAll() {
@@ -118,18 +106,16 @@ public static List findAll(SubFolderSpecification specification, Data
constraints = new DataConstraints();
}
constraints.setDefaultColumnToSortBy("start_date DESC");
- DataResult result = query(specification, constraints);
- return (List) result.getRecords();
+ DataResult result = query(specification, constraints);
+ return result.getRecords();
}
public static List queryDistinctStartDateAsYearForFolder(Folder folder) {
- String SQL_FIELDS = "DISTINCT(EXTRACT(YEAR FROM start_date)) AS year";
- SqlUtils orderBy = new SqlUtils().add("year DESC");
- return DB.selectFunctionAsLongList(
- SQL_FIELDS,
- TABLE_NAME,
- DB.WHERE("folder_id = ?", folder.getId()),
- orderBy);
+ return DB.SELECT("DISTINCT(EXTRACT(YEAR FROM start_date)) AS year")
+ .FROM(TABLE_NAME)
+ .WHERE("folder_id = ?", folder.getId())
+ .ORDER_BY("year DESC")
+ .returnList(rs -> rs.getLong(1));
}
public static SubFolder save(SubFolder record) {
@@ -140,24 +126,21 @@ public static SubFolder save(SubFolder record) {
}
private static SubFolder add(SubFolder record) {
- SqlUtils insertValues = new SqlUtils()
- .add("folder_id", record.getFolderId())
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("summary", StringUtils.trimToNull(record.getSummary()))
- .add("created_by", record.getCreatedBy())
- .add("modified_by", record.getModifiedBy())
- .add("end_date", record.getEndDate());
- if (record.getStartDate() != null) {
- insertValues.add("start_date", record.getStartDate());
- }
-
// 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));
- // Finish the transaction
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("folder_id", record.getFolderId())
+ .FIELD("name", StringUtils.trimToNull(record.getName()))
+ .FIELD("summary", StringUtils.trimToNull(record.getSummary()))
+ .FIELD("created_by", record.getCreatedBy())
+ .FIELD("modified_by", record.getModifiedBy())
+ .FIELD("end_date", record.getEndDate());
+ if (record.getStartDate() != null) {
+ insert.FIELD("start_date", record.getStartDate());
+ }
+ record.setId(insert.execute(connection));
transaction.commit();
return record;
} catch (SQLException se) {
@@ -171,17 +154,15 @@ private static SubFolder update(SubFolder record) {
try (Connection connection = DB.getConnection();
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
- // Update the count in case the folder changed
FolderRepository.updateFileCountForFileId(connection, record.getId(), -1);
- // Update the record
- SqlUtils updateValues = new SqlUtils()
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("summary", StringUtils.trimToNull(record.getSummary()))
- .add("modified_by", record.getModifiedBy())
- .add("start_date", record.getStartDate())
- .add("end_date", record.getEndDate());
- if (DB.update(connection, TABLE_NAME, updateValues, DB.WHERE("sub_folder_id = ?", record.getId()))) {
- // Finish transaction
+ if (DB.UPDATE(TABLE_NAME)
+ .SET("name", StringUtils.trimToNull(record.getName()))
+ .SET("summary", StringUtils.trimToNull(record.getSummary()))
+ .SET("modified_by", record.getModifiedBy())
+ .SET("start_date", record.getStartDate())
+ .SET("end_date", record.getEndDate())
+ .WHERE("sub_folder_id = ?", record.getId())
+ .execute(connection)) {
transaction.commit();
return record;
}
@@ -202,7 +183,7 @@ public static boolean remove(SubFolder record) {
// Update the folder count
FolderRepository.updateFileCount(connection, record.getFolderId(), -deleteCount);
// Delete the record
- 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);
// Finish transaction
transaction.commit();
return true;
@@ -213,25 +194,23 @@ public static boolean remove(SubFolder record) {
}
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 boolean updateFileCount(Connection connection, long subFolderId, int value) throws SQLException {
// Update the totals
- SqlUtils update = new SqlUtils()
- .add("file_count = file_count + " + value);
- return DB.update(connection, TABLE_NAME, update, DB.WHERE("sub_folder_id = ?", subFolderId));
+ return DB.UPDATE(TABLE_NAME)
+ .SET("file_count = file_count + " + value)
+ .WHERE("sub_folder_id = ?", subFolderId)
+ .execute(connection);
}
public static boolean updateFileCountForFileId(Connection connection, long fileId, int value) throws SQLException {
// Update the totals
- SqlUtils update = new SqlUtils()
- .add("file_count = file_count + " + value);
- return DB.update(
- connection,
- TABLE_NAME,
- update,
- DB.WHERE("sub_folder_id IN (SELECT sub_folder_id FROM files WHERE file_id = ?)", fileId));
+ return DB.UPDATE(TABLE_NAME)
+ .SET("file_count = file_count + " + value)
+ .WHERE("sub_folder_id IN (SELECT sub_folder_id FROM files WHERE file_id = ?)", fileId)
+ .execute(connection);
}
private static SubFolder buildRecord(ResultSet rs) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/TableOfContentsRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/TableOfContentsRepository.java
index cb431790f..4490547b2 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/TableOfContentsRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/TableOfContentsRepository.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");
@@ -25,15 +26,16 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.CastType;
+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.TableOfContentsJSONCommand;
import com.simisinc.platform.domain.model.cms.TableOfContents;
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.SqlValue;
-import com.simisinc.platform.infrastructure.database.SqlWhere;
/**
* Persists and retrieves table of contents objects
@@ -48,24 +50,30 @@ public class TableOfContentsRepository {
private static String TABLE_NAME = "table_of_contents";
private static String[] PRIMARY_KEY = new String[] { "toc_id" };
- private static DataResult query(TableOfContentsSpecification specification, DataConstraints constraints) {
- SqlWhere where = null;
+ private static DataResult query(TableOfContentsSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("*").FROM(TABLE_NAME).WHERE();
if (specification != null) {
- where = DB.WHERE()
- .andAddIfHasValue("toc_id = ?", specification.getId(), -1)
- .andAddIfHasValue("toc_unique_id = ?", specification.getTocUniqueId());
+ if (specification.getId() != -1) {
+ select.AND("toc_id = ?", specification.getId());
+ }
+ if (StringUtils.isNotBlank(specification.getTocUniqueId())) {
+ select.AND("toc_unique_id = ?", specification.getTocUniqueId());
+ }
}
- return DB.selectAllFrom(TABLE_NAME, where, constraints, TableOfContentsRepository::buildRecord);
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(TableOfContentsRepository::buildRecord);
}
public static TableOfContents findByUniqueId(String tocUniqueId) {
if (StringUtils.isBlank(tocUniqueId)) {
return null;
}
- return (TableOfContents) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("toc_unique_id = ?", tocUniqueId),
- TableOfContentsRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("toc_unique_id = ?", tocUniqueId)
+ .returnRecord(TableOfContentsRepository::buildRecord);
}
public static List findAll(TableOfContentsSpecification specification, DataConstraints constraints) {
@@ -73,8 +81,8 @@ public static List findAll(TableOfContentsSpecification specifi
constraints = new DataConstraints();
}
constraints.setDefaultColumnToSortBy("toc_unique_id");
- DataResult result = query(specification, constraints);
- return (List) result.getRecords();
+ DataResult result = query(specification, constraints);
+ return result.getRecords();
}
public static TableOfContents save(TableOfContents record) {
@@ -85,13 +93,13 @@ public static TableOfContents save(TableOfContents record) {
}
public static TableOfContents add(TableOfContents record) {
- SqlUtils insertValues = new SqlUtils()
- .add("toc_unique_id", StringUtils.trimToNull(record.getTocUniqueId()))
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("created_by", record.getCreatedBy(), -1)
- .add("modified_by", record.getModifiedBy(), -1);
- insertValues.add(new SqlValue("entries", SqlValue.JSONB_TYPE, TableOfContentsJSONCommand.createJSONString(record)));
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("toc_unique_id", StringUtils.trimToNull(record.getTocUniqueId()))
+ .FIELD("name", StringUtils.trimToNull(record.getName()))
+ .FIELD("created_by", record.getCreatedBy() == -1 ? null : record.getCreatedBy())
+ .FIELD("modified_by", record.getModifiedBy() == -1 ? null : record.getModifiedBy())
+ .FIELD("entries", TableOfContentsJSONCommand.createJSONString(record), CastType.JSONB);
+ record.setId(insert.execute());
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -100,12 +108,12 @@ public static TableOfContents add(TableOfContents record) {
}
public static TableOfContents update(TableOfContents record) {
- SqlUtils updateValues = new SqlUtils()
- .add("modified_by", record.getModifiedBy())
- .add("modified", new Timestamp(System.currentTimeMillis()));
- updateValues.add(new SqlValue("entries", SqlValue.JSONB_TYPE, TableOfContentsJSONCommand.createJSONString(record)));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("toc_id = ?", record.getId()))) {
- // Expire the cache
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("modified_by", record.getModifiedBy())
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .SET("entries", TableOfContentsJSONCommand.createJSONString(record), CastType.JSONB)
+ .WHERE("toc_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
CacheManager.invalidateKey(CacheManager.TABLE_OF_CONTENTS_UNIQUE_ID_CACHE, record.getTocUniqueId());
return record;
}
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/ThemeRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/ThemeRepository.java
index 7b10e8815..0e4ec5c2f 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/ThemeRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/ThemeRepository.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");
@@ -25,15 +26,12 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.CastType;
+import com.github.rajkowski.database.DB;
+import com.github.rajkowski.database.DataConstraints;
import com.simisinc.platform.application.cms.ThemeJSONCommand;
import com.simisinc.platform.domain.model.SiteProperty;
import com.simisinc.platform.domain.model.cms.Theme;
-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;
/**
* Persists and retrieves theme objects
@@ -49,26 +47,25 @@ public class ThemeRepository {
private static String[] PRIMARY_KEY = new String[] { "theme_id" };
public static Theme findByName(String name) {
- return (Theme) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("LOWER(name) = ?", name.toLowerCase()),
- ThemeRepository::buildRecord);
+ return DB.SELECT("themes.*")
+ .FROM(TABLE_NAME)
+ .WHERE("LOWER(name) = ?", name.toLowerCase())
+ .returnRecord(ThemeRepository::buildRecord);
}
public static Theme findById(long id) {
- return (Theme) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("theme_id = ?", id),
- ThemeRepository::buildRecord);
+ return DB.SELECT("themes.*")
+ .FROM(TABLE_NAME)
+ .WHERE("theme_id = ?", id)
+ .returnRecord(ThemeRepository::buildRecord);
}
public static List findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- null,
- new DataConstraints().setDefaultColumnToSortBy("theme_id"),
- ThemeRepository::buildRecord);
- return (List) result.getRecords();
+ return DB.SELECT("themes.*")
+ .FROM(TABLE_NAME)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("theme_id"))
+ .returnDataResult(ThemeRepository::buildRecord)
+ .getRecords();
}
public static Theme save(Theme record) {
@@ -85,10 +82,10 @@ public static Theme save(List sitePropertyList, String name) {
}
public static Theme add(Theme record) {
- SqlUtils insertValues = new SqlUtils()
- .add("name", StringUtils.trimToNull(record.getName()));
- insertValues.add(new SqlValue("entries", SqlValue.JSONB_TYPE, ThemeJSONCommand.createJSONString(record)));
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ record.setId(DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("name", StringUtils.trimToNull(record.getName()))
+ .FIELD("entries", ThemeJSONCommand.createJSONString(record), CastType.JSONB)
+ .execute());
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -97,11 +94,12 @@ public static Theme add(Theme record) {
}
public static Theme update(Theme record) {
- SqlUtils updateValues = new SqlUtils()
- .add("name", record.getName())
- .add("modified", new Timestamp(System.currentTimeMillis()));
- updateValues.add(new SqlValue("entries", SqlValue.JSONB_TYPE, ThemeJSONCommand.createJSONString(record)));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("theme_id = ?", record.getId()))) {
+ if (DB.UPDATE(TABLE_NAME)
+ .SET("name", StringUtils.trimToNull(record.getName()))
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .SET("entries", ThemeJSONCommand.createJSONString(record), CastType.JSONB)
+ .WHERE("theme_id = ?", record.getId())
+ .execute()) {
return record;
}
LOG.error("The update failed!");
@@ -109,7 +107,7 @@ public static Theme update(Theme record) {
}
public static void remove(Theme record) {
- DB.deleteFrom(TABLE_NAME, DB.WHERE("theme_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("theme_id = ?", record.getId()).execute();
}
private static Theme buildRecord(ResultSet rs) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebContainerRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebContainerRepository.java
index 27c60e00f..90bfb0f0a 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebContainerRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebContainerRepository.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,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.simisinc.platform.domain.model.cms.WebContainer;
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;
/**
* Persists and retrieves web container objects
@@ -48,44 +47,38 @@ public static WebContainer findById(long id) {
if (id == -1) {
return null;
}
- return (WebContainer) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("container_id = ?", id),
- WebContainerRepository::buildRecord);
+ return DB.SELECT("web_containers.*")
+ .FROM(TABLE_NAME)
+ .WHERE("container_id = ?", id)
+ .returnRecord(WebContainerRepository::buildRecord);
}
public static WebContainer findByName(String name) {
if (StringUtils.isBlank(name)) {
return null;
}
- return (WebContainer) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("container_name = ?", name),
- WebContainerRepository::buildRecord);
+ return DB.SELECT("web_containers.*")
+ .FROM(TABLE_NAME)
+ .WHERE("container_name = ?", name)
+ .returnRecord(WebContainerRepository::buildRecord);
}
public static List findAllByPrefix(String prefix) {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- DB.WHERE("container_name LIKE ?", prefix + ".%"),
- new DataConstraints().setDefaultColumnToSortBy("container_name").setUseCount(false),
- WebContainerRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ DataConstraints constraints = new DataConstraints().setDefaultColumnToSortBy("container_name").setUseCount(false);
+ return DB.SELECT("web_containers.*")
+ .FROM(TABLE_NAME)
+ .WHERE("container_name LIKE ?", prefix + ".%")
+ .WITH(constraints)
+ .returnDataResult(WebContainerRepository::buildRecord)
+ .getRecords();
}
public static List findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- null,
- new DataConstraints().setDefaultColumnToSortBy("container_id"),
- WebContainerRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ return DB.SELECT("web_containers.*")
+ .FROM(TABLE_NAME)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("container_id"))
+ .returnDataResult(WebContainerRepository::buildRecord)
+ .getRecords();
}
public static WebContainer save(WebContainer record) {
@@ -96,14 +89,14 @@ public static WebContainer save(WebContainer record) {
}
private static WebContainer add(WebContainer record) {
- SqlUtils insertValues = new SqlUtils()
- .add("container_name", StringUtils.trimToNull(record.getName()))
- .add("label", StringUtils.trimToNull(record.getLabel()))
- .add("image_path", StringUtils.trimToNull(record.getImagePath()))
- .add("draft", record.getDraft())
- .add("container_xml", StringUtils.trimToNull(record.getContainerXml()))
- .add("draft_xml", StringUtils.trimToNull(record.getDraftXml()));
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ record.setId(DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("container_name", StringUtils.trimToNull(record.getName()))
+ .FIELD("label", StringUtils.trimToNull(record.getLabel()))
+ .FIELD("image_path", StringUtils.trimToNull(record.getImagePath()))
+ .FIELD("draft", record.getDraft())
+ .FIELD("container_xml", StringUtils.trimToNull(record.getContainerXml()))
+ .FIELD("draft_xml", StringUtils.trimToNull(record.getDraftXml()))
+ .execute());
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -112,14 +105,15 @@ private static WebContainer add(WebContainer record) {
}
private static WebContainer update(WebContainer record) {
- SqlUtils updateValues = new SqlUtils()
- .add("container_name", StringUtils.trimToNull(record.getName()))
- .add("label", StringUtils.trimToNull(record.getLabel()))
- .add("image_path", StringUtils.trimToNull(record.getImagePath()))
- .add("draft", record.getDraft())
- .add("container_xml", StringUtils.trimToNull(record.getContainerXml()))
- .add("draft_xml", StringUtils.trimToNull(record.getDraftXml()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("container_id = ?", record.getId()))) {
+ if (DB.UPDATE(TABLE_NAME)
+ .SET("container_name", StringUtils.trimToNull(record.getName()))
+ .SET("label", StringUtils.trimToNull(record.getLabel()))
+ .SET("image_path", StringUtils.trimToNull(record.getImagePath()))
+ .SET("draft", record.getDraft())
+ .SET("container_xml", StringUtils.trimToNull(record.getContainerXml()))
+ .SET("draft_xml", StringUtils.trimToNull(record.getDraftXml()))
+ .WHERE("container_id = ?", record.getId())
+ .execute()) {
// Invalidate the cache
if (record.getName().startsWith("header")) {
CacheManager.invalidateObjectCacheKey(CacheManager.WEBSITE_HEADER);
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebPageHierarchyRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebPageHierarchyRepository.java
index 088409cf7..7e1291a67 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebPageHierarchyRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebPageHierarchyRepository.java
@@ -28,10 +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.Insert;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.domain.model.cms.WebPage;
import com.simisinc.platform.domain.model.cms.WebPageHierarchy;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.SqlUtils;
/**
* Persists and retrieves web page hierarchy objects
@@ -65,10 +66,10 @@ public static WebPageHierarchy findByPageId(long pageId) {
if (pageId == -1) {
return null;
}
- return (WebPageHierarchy) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE(WHERE_WEB_PAGE_ID, pageId),
- WebPageHierarchyRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE(WHERE_WEB_PAGE_ID, pageId)
+ .returnRecord(WebPageHierarchyRepository::buildRecord);
}
/**
@@ -157,15 +158,15 @@ public static WebPageHierarchy save(Connection connection, WebPageHierarchy reco
* @return the inserted record
*/
private static WebPageHierarchy add(WebPageHierarchy record) {
- SqlUtils insertValues = new SqlUtils()
- .add(COL_WEB_PAGE_ID, record.getWebPageId())
- .add(COL_PARENT_PAGE_ID, record.getParentPageId() != null ? record.getParentPageId() : -1, -1)
- .add(COL_SORT_ORDER, record.getSortOrder())
- .add(COL_DEPTH, record.getDepth())
- .add(COL_PATH, StringUtils.trimToNull(record.getPath()))
- .add(COL_CREATED, record.getCreated() != null ? record.getCreated() : new Timestamp(System.currentTimeMillis()))
- .add(COL_MODIFIED, record.getModified() != null ? record.getModified() : new Timestamp(System.currentTimeMillis()));
- DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY);
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD(COL_WEB_PAGE_ID, record.getWebPageId())
+ .FIELD(COL_PARENT_PAGE_ID, record.getParentPageId() != null ? record.getParentPageId() : -1L)
+ .FIELD(COL_SORT_ORDER, record.getSortOrder())
+ .FIELD(COL_DEPTH, record.getDepth())
+ .FIELD(COL_PATH, StringUtils.trimToNull(record.getPath()))
+ .FIELD(COL_CREATED, record.getCreated() != null ? record.getCreated() : new Timestamp(System.currentTimeMillis()))
+ .FIELD(COL_MODIFIED, record.getModified() != null ? record.getModified() : new Timestamp(System.currentTimeMillis()));
+ insert.execute();
return record;
}
@@ -177,20 +178,15 @@ private static WebPageHierarchy add(WebPageHierarchy record) {
* @return the inserted record
*/
private static WebPageHierarchy add(Connection connection, WebPageHierarchy record) {
- SqlUtils insertValues = new SqlUtils()
- .add(COL_WEB_PAGE_ID, record.getWebPageId())
- .add(COL_PARENT_PAGE_ID, record.getParentPageId() != null ? record.getParentPageId() : -1, -1)
- .add(COL_SORT_ORDER, record.getSortOrder())
- .add(COL_DEPTH, record.getDepth())
- .add(COL_PATH, StringUtils.trimToNull(record.getPath()))
- .add(COL_CREATED, record.getCreated() != null ? record.getCreated() : new Timestamp(System.currentTimeMillis()))
- .add(COL_MODIFIED, record.getModified() != null ? record.getModified() : new Timestamp(System.currentTimeMillis()));
- try {
- DB.insertInto(connection, TABLE_NAME, insertValues, PRIMARY_KEY);
- } catch (SQLException se) {
- LOG.error(SQL_EXCEPTION + se.getMessage());
- return null;
- }
+ DB.INSERT().INTO(TABLE_NAME)
+ .FIELD(COL_WEB_PAGE_ID, record.getWebPageId())
+ .FIELD(COL_PARENT_PAGE_ID, record.getParentPageId() != null ? record.getParentPageId() : -1L)
+ .FIELD(COL_SORT_ORDER, record.getSortOrder())
+ .FIELD(COL_DEPTH, record.getDepth())
+ .FIELD(COL_PATH, StringUtils.trimToNull(record.getPath()))
+ .FIELD(COL_CREATED, record.getCreated() != null ? record.getCreated() : new Timestamp(System.currentTimeMillis()))
+ .FIELD(COL_MODIFIED, record.getModified() != null ? record.getModified() : new Timestamp(System.currentTimeMillis()))
+ .execute(connection);
return record;
}
@@ -201,13 +197,13 @@ private static WebPageHierarchy add(Connection connection, WebPageHierarchy reco
* @return the updated record or null if update failed
*/
private static WebPageHierarchy update(WebPageHierarchy record) {
- SqlUtils updateValues = new SqlUtils()
- .add(COL_PARENT_PAGE_ID, record.getParentPageId() != null ? record.getParentPageId() : -1, -1)
- .add(COL_SORT_ORDER, record.getSortOrder())
- .add(COL_DEPTH, record.getDepth())
- .add(COL_PATH, StringUtils.trimToNull(record.getPath()))
- .add(COL_MODIFIED, new Timestamp(System.currentTimeMillis()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE(WHERE_WEB_PAGE_ID, record.getWebPageId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET(COL_PARENT_PAGE_ID, record.getParentPageId() != null ? record.getParentPageId() : -1L)
+ .SET(COL_SORT_ORDER, record.getSortOrder())
+ .SET(COL_DEPTH, record.getDepth())
+ .SET(COL_PATH, StringUtils.trimToNull(record.getPath()))
+ .SET(COL_MODIFIED, new Timestamp(System.currentTimeMillis()));
+ if (update.WHERE(WHERE_WEB_PAGE_ID, record.getWebPageId()).execute()) {
return record;
}
LOG.error("The update failed!");
@@ -222,14 +218,14 @@ private static WebPageHierarchy update(WebPageHierarchy record) {
* @return the updated record or null if update failed
*/
private static WebPageHierarchy update(Connection connection, WebPageHierarchy record) {
- SqlUtils updateValues = new SqlUtils()
- .add(COL_PARENT_PAGE_ID, record.getParentPageId() != null ? record.getParentPageId() : -1, -1)
- .add(COL_SORT_ORDER, record.getSortOrder())
- .add(COL_DEPTH, record.getDepth())
- .add(COL_PATH, StringUtils.trimToNull(record.getPath()))
- .add(COL_MODIFIED, new Timestamp(System.currentTimeMillis()));
try {
- if (DB.update(connection, TABLE_NAME, updateValues, DB.WHERE(WHERE_WEB_PAGE_ID, record.getWebPageId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET(COL_PARENT_PAGE_ID, record.getParentPageId() != null ? record.getParentPageId() : -1L)
+ .SET(COL_SORT_ORDER, record.getSortOrder())
+ .SET(COL_DEPTH, record.getDepth())
+ .SET(COL_PATH, StringUtils.trimToNull(record.getPath()))
+ .SET(COL_MODIFIED, new Timestamp(System.currentTimeMillis()));
+ if (update.WHERE(WHERE_WEB_PAGE_ID, record.getWebPageId()).execute(connection)) {
return record;
}
} catch (SQLException se) {
@@ -348,7 +344,7 @@ public static boolean removeByPath(Connection connection, String path) {
return false;
}
try {
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("path LIKE ?", path + "%"));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("path LIKE ?", path + "%").execute(connection);
return true;
} catch (Exception e) {
LOG.error("Error removing by path: " + e.getMessage());
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebPageHitRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebPageHitRepository.java
index af0e2c916..a3670d4f4 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebPageHitRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebPageHitRepository.java
@@ -33,11 +33,11 @@
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.github.rajkowski.database.Select;
import com.simisinc.platform.domain.model.cms.WebPageHit;
import com.simisinc.platform.domain.model.dashboard.StatisticsData;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.SqlUtils;
-import com.simisinc.platform.infrastructure.database.SqlWhere;
import com.simisinc.platform.infrastructure.persistence.SessionRepository;
/**
@@ -58,17 +58,17 @@ public static WebPageHit save(WebPageHit record) {
}
private static WebPageHit add(WebPageHit record) {
- SqlUtils insertValues = new SqlUtils()
- .add("method", record.getMethod(), 6)
- .add("page_path", record.getPagePath(), 255)
- .add("web_page_id", record.getWebPageId(), -1)
- .add("ip_address", record.getIpAddress())
- .add("session_id", record.getSessionId())
- .add("is_logged_in", record.isLoggedIn());
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("method", StringUtils.truncate(record.getMethod(), 6))
+ .FIELD("page_path", StringUtils.truncate(record.getPagePath(), 255))
+ .FIELD("web_page_id", record.getWebPageId() == -1 ? null : record.getWebPageId())
+ .FIELD("ip_address", record.getIpAddress())
+ .FIELD("session_id", record.getSessionId())
+ .FIELD("is_logged_in", record.isLoggedIn());
if (record.getHitDate() != null) {
- insertValues.add("hit_date", record.getHitDate());
+ insert.FIELD("hit_date", record.getHitDate());
}
- 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;
@@ -102,35 +102,33 @@ public static void createSnapshot(Timestamp startDate, Timestamp endDate) {
String startDateValue = new SimpleDateFormat("yyyy-MM-dd").format(startDate);
// Query the data, skip some things
- SqlWhere where = DB.WHERE()
- .AND("hit_date >= ?", startDate)
+ Select select = DB.SELECT("COUNT(*)").FROM(TABLE_NAME)
+ .WHERE("hit_date >= ?", startDate)
.AND("hit_date < ?", endDate)
.AND("page_path NOT LIKE ?", "/admin%")
.AND("page_path NOT LIKE ?", "/assets%")
.AND("page_path NOT LIKE ?", "/json%")
.AND("page_path NOT LIKE ?", "%/*")
.AND("NOT EXISTS (SELECT 1 FROM sessions WHERE session_id = web_page_hits.session_id AND is_bot = TRUE)");
- long webPageHitCount = DB.selectCountFrom(TABLE_NAME, where);
+ long webPageHitCount = select.returnCount();
long uniqueSessionCount = SessionRepository.countDistinctSessions(startDate, endDate);
// INSERT or UPDATE
- SqlUtils insertValues = new SqlUtils()
- .add("snapshot_date", startDate)
- .add("date_value", startDateValue)
- .add("web_page_hits", webPageHitCount)
- .add("unique_sessions", uniqueSessionCount);
-
- String onConflict = "ON CONFLICT (date_value) " +
- "DO UPDATE SET " +
- "web_page_hits = EXCLUDED.web_page_hits, " +
- "unique_sessions = EXCLUDED.unique_sessions";
-
- DB.insertIntoWithConflict("web_page_hit_snapshots", insertValues, onConflict);
+ Insert insert = DB.INSERT().INTO("web_page_hit_snapshots")
+ .FIELD("snapshot_date", startDate)
+ .FIELD("date_value", startDateValue)
+ .FIELD("web_page_hits", webPageHitCount)
+ .FIELD("unique_sessions", uniqueSessionCount)
+ .ON_CONFLICT("date_value")
+ .DO_UPDATE()
+ .SET("web_page_hits = EXCLUDED.web_page_hits")
+ .SET("unique_sessions = EXCLUDED.unique_sessions");
+ insert.execute();
}
public static void deleteOldWebHits() {
- DB.deleteFrom(TABLE_NAME, DB.WHERE("hit_date < NOW() - INTERVAL '365 days'"));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("hit_date < NOW() - INTERVAL '365 days'").execute();
}
public static List findDailyWebHits(int daysToLimit) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebPageRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebPageRepository.java
index d777d41e6..363ca2873 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebPageRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebPageRepository.java
@@ -34,19 +34,21 @@
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.cms.TextCommand;
import com.simisinc.platform.application.cms.WebPageXmlLayoutCommand;
import com.simisinc.platform.application.json.JsonCommand;
import com.simisinc.platform.domain.model.cms.WebPage;
-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.zeroio.platform.infrastructure.persistence.cms.PageFileRepository;
import com.zeroio.platform.infrastructure.persistence.cms.WebPageVersionRepository;
@@ -66,103 +68,102 @@ public class WebPageRepository {
private static final int MAX_CONTENT_REFERENCE_NODES = 250;
private static final int MAX_INDIRECT_PAGES = 500;
- private static DataResult query(WebPageSpecification specification, DataConstraints constraints) {
- SqlUtils select = new SqlUtils();
- SqlJoins joins = new SqlJoins();
- SqlWhere where = null;
- SqlUtils orderBy = null;
-
+ private static DataResult query(WebPageSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("web_pages.*").FROM(TABLE_NAME).WHERE();
if (specification != null) {
-
- where = DB.WHERE()
- .andAddIfHasValue("LOWER(link) = ?", specification.getLink())
- .andAddIfDataConstantExists("enabled = ?", specification.getEnabled())
- .andAddIfDataConstantExists("draft = ?", specification.getDraft())
- .andAddIfDataConstantExists("searchable = ?", specification.getSearchable())
- .andAddIfDataConstantExists("show_in_sitemap = ?", specification.getInSitemap())
- .andAddIfDataConstantExists("has_redirect = ?", specification.getHasRedirect());
-
+ if (StringUtils.isNotBlank(specification.getLink())) {
+ select.AND("LOWER(link) = ?", specification.getLink().trim().toLowerCase());
+ }
+ if (specification.getEnabled() != DataConstants.UNDEFINED) {
+ select.AND("enabled = ?", specification.getEnabled() == DataConstants.TRUE);
+ }
+ if (specification.getDraft() != DataConstants.UNDEFINED) {
+ select.AND("draft = ?", specification.getDraft() == DataConstants.TRUE);
+ }
+ if (specification.getSearchable() != DataConstants.UNDEFINED) {
+ select.AND("searchable = ?", specification.getSearchable() == DataConstants.TRUE);
+ }
+ if (specification.getInSitemap() != DataConstants.UNDEFINED) {
+ select.AND("show_in_sitemap = ?", specification.getInSitemap() == DataConstants.TRUE);
+ }
+ if (specification.getHasRedirect() != DataConstants.UNDEFINED) {
+ select.AND("has_redirect = ?", specification.getHasRedirect() == DataConstants.TRUE);
+ }
if (specification.getRegionTags() != null && specification.getRegionTags().length > 0) {
- where.AND("web_pages.tags", specification.getRegionTags(), SqlWhere.OR_OPERATOR);
+ ConditionGroup condition = ConditionGroup.build("web_pages.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("web_pages.tags", specification.getFilterTags(), SqlWhere.AND_OPERATOR);
+ ConditionGroup filterCondition = ConditionGroup.build("web_pages.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("web_pages.tags", specification.getExcludeTags(), SqlWhere.NOT_OR_OPERATOR);
+ ConditionGroup excludeCondition = ConditionGroup.build("web_pages.tags", specification.getExcludeTags(),
+ ConditionGroup.NOT_ANY);
+ if (excludeCondition != null) {
+ select.AND(excludeCondition.sql(), (Object[]) excludeCondition.values());
+ }
}
-
- // Add modified date range filters
if (specification.getModifiedAfter() != null) {
- where.AND("web_pages.modified >= ?", specification.getModifiedAfter());
+ select.AND("web_pages.modified >= ?", specification.getModifiedAfter());
}
if (specification.getModifiedBefore() != null) {
- where.AND("web_pages.modified <= ?", specification.getModifiedBefore());
+ select.AND("web_pages.modified <= ?", specification.getModifiedBefore());
}
-
- // Add modified by user filter
if (specification.getModifiedByUserIds() != null && specification.getModifiedByUserIds().length > 0) {
+ long[] modifiedByUserIds = specification.getModifiedByUserIds();
StringBuilder userCondition = new StringBuilder("web_pages.modified_by IN (");
- Long[] userIdsBoxed = new Long[specification.getModifiedByUserIds().length];
- for (int i = 0; i < specification.getModifiedByUserIds().length; i++) {
+ Object[] values = new Object[modifiedByUserIds.length];
+ for (int i = 0; i < modifiedByUserIds.length; i++) {
if (i > 0) {
- userCondition.append(",");
+ userCondition.append(", ");
}
userCondition.append("?");
- userIdsBoxed[i] = specification.getModifiedByUserIds()[i];
+ values[i] = modifiedByUserIds[i];
}
userCondition.append(")");
- where.AND(userCondition.toString(), (Object[]) userIdsBoxed);
+ select.AND(userCondition.toString(), values);
}
-
if (StringUtils.isNotBlank(specification.getSearchTerm())) {
-
String term = specification.getSearchTerm().trim().toLowerCase();
-
- String quotedSearchTerm = "\"" + term + "\"";
- String searchTermSeparated = term.replaceAll("\\s+", " OR ");
- String searchToUse = quotedSearchTerm + " OR " + searchTermSeparated;
- String titleSearchPattern1 = term + "%";
- String titleSearchPattern2 = "%" + term + "%";
-
- select.add(
+ select.SELECT(
"ts_headline('english', page_text, websearch_to_tsquery('web_page_stem', ?), 'StartSel=${b}, StopSel=${/b}, MaxWords=40, MinWords=30, ShortWord=3, HighlightAll=FALSE, MaxFragments=2, FragmentDelimiter=\" ... \"') AS highlight",
- term);
- select.add(
+ (Object[]) new Object[] { term });
+ select.SELECT(
"(ts_rank_cd(web_pages.tsv, websearch_to_tsquery('web_page_stem', ?)) + CASE WHEN LOWER(web_pages.page_title) LIKE LOWER(?) THEN 200.0 ELSE 0.0 END + CASE WHEN LOWER(web_pages.page_title) LIKE LOWER(?) THEN 100.0 ELSE 0.0 END) AS rank",
- new String[] { searchToUse, titleSearchPattern1, titleSearchPattern2 });
-
- where.AND("web_pages.tsv @@ websearch_to_tsquery('web_page_stem', ?)", searchToUse);
-
- // Override the order by for rank first
- orderBy = new SqlUtils();
- orderBy.add("rank DESC, web_pages.modified DESC");
+ (Object[]) new Object[] { term, term + "%", "%" + term + "%" });
+ select.AND("web_pages.tsv @@ websearch_to_tsquery('web_page_stem', ?)", term);
+ select.ORDER_BY("rank DESC, web_pages.modified DESC");
}
}
-
- return DB.selectAllFrom(TABLE_NAME, select, joins, where, orderBy, constraints, WebPageRepository::buildRecord);
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(WebPageRepository::buildRecord);
}
public static WebPage findById(long id) {
if (id == -1) {
return null;
}
- return (WebPage) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("web_page_id = ?", id),
- WebPageRepository::buildRecord);
+ return DB.SELECT("web_pages.*")
+ .FROM(TABLE_NAME)
+ .WHERE("web_page_id = ?", id)
+ .returnRecord(WebPageRepository::buildRecord);
}
public static WebPage findByLink(String link) {
if (StringUtils.isBlank(link)) {
return null;
}
- return (WebPage) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("LOWER(link) = ?", link),
- WebPageRepository::buildRecord);
+ return DB.SELECT("web_pages.*")
+ .FROM(TABLE_NAME)
+ .WHERE("LOWER(link) = ?", link.trim().toLowerCase())
+ .returnRecord(WebPageRepository::buildRecord);
}
public static List findAll() {
@@ -174,8 +175,7 @@ public static List findAll(WebPageSpecification specification, DataCons
constraints = new DataConstraints();
}
constraints.setDefaultColumnToSortBy("link");
- DataResult result = query(specification, constraints);
- return (List) result.getRecords();
+ return query(specification, constraints).getRecords();
}
/**
@@ -183,28 +183,24 @@ public static List findAll(WebPageSpecification specification, DataCons
* @return List of unique tag strings, sorted alphabetically
*/
public static List findAllDistinctTags() {
- String SQL_QUERY = "SELECT DISTINCT tag FROM ( " +
- "SELECT jsonb_array_elements_text(tags) AS tag FROM web_pages WHERE tags IS NOT NULL AND enabled = true AND draft = false "
- +
- "UNION ALL " +
- "SELECT jsonb_array_elements_text(tags) AS tag FROM items WHERE tags IS NOT NULL " +
- ") AS all_tags " +
- "WHERE tag IS NOT NULL AND tag <> '' " +
- "ORDER BY tag";
- List tags = new ArrayList<>();
- try (Connection connection = DB.getConnection();
- PreparedStatement pst = connection.prepareStatement(SQL_QUERY);
- ResultSet rs = pst.executeQuery()) {
- while (rs.next()) {
- String tag = rs.getString("tag");
- if (StringUtils.isNotBlank(tag)) {
- tags.add(tag);
- }
- }
- } catch (SQLException se) {
- LOG.error("findAllDistinctTags", se);
- }
- return tags;
+ Select subquery = DB.SELECT("jsonb_array_elements_text(tags) AS tag")
+ .FROM("web_pages")
+ .WHERE("tags IS NOT NULL")
+ .AND("enabled = ?", true)
+ .AND("draft = ?", false)
+ .UNION_ALL(DB.SELECT("jsonb_array_elements_text(tags) AS tag")
+ .FROM("items")
+ .WHERE("tags IS NOT NULL"));
+
+ List tags = DB.SELECT("DISTINCT tag")
+ .FROM(subquery)
+ .AS("all_tags")
+ .WHERE("tag IS NOT NULL")
+ .AND("tag <> ?", "")
+ .ORDER_BY("tag")
+ .returnList(rs -> rs.getString("tag"));
+
+ return tags.stream().filter(StringUtils::isNotBlank).toList();
}
public static WebPage save(WebPage record) {
@@ -219,30 +215,32 @@ private static WebPage add(WebPage record) {
if (link != null) {
link = link.toLowerCase();
}
- SqlUtils insertValues = new SqlUtils()
- .add("link", link)
- .add("redirect_url", StringUtils.trimToNull(record.getRedirectUrl()))
- .add("page_title", StringUtils.trimToNull(record.getTitle()))
- .add("page_keywords", StringUtils.trimToNull(record.getKeywords()))
- .add("page_description", StringUtils.trimToNull(record.getDescription()))
- .add("draft", record.getDraft())
- .add("enabled", record.isEnabled())
- .add("searchable", record.isSearchable())
- .add("show_in_sitemap", record.getShowInSitemap())
- .add("created_by", record.getCreatedBy())
- .add("role_id_list", record.getRoleIdList())
- .add("page_xml", record.getPageXml())
- .add("draft_page_xml", StringUtils.trimToNull(record.getDraftPageXml()))
- .add("comments", record.getComments())
- .add("page_image_url", record.getImageUrl())
- .add("has_redirect", StringUtils.trimToNull(record.getRedirectUrl()) != null)
- .add("sitemap_priority", record.getSitemapPriority())
- .add("sitemap_changefreq", StringUtils.trimToNull(record.getSitemapChangeFrequency()));
+
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("link", link)
+ .FIELD("redirect_url", StringUtils.trimToNull(record.getRedirectUrl()))
+ .FIELD("page_title", StringUtils.trimToNull(record.getTitle()))
+ .FIELD("page_keywords", StringUtils.trimToNull(record.getKeywords()))
+ .FIELD("page_description", StringUtils.trimToNull(record.getDescription()))
+ .FIELD("draft", record.getDraft())
+ .FIELD("enabled", record.isEnabled())
+ .FIELD("searchable", record.isSearchable())
+ .FIELD("show_in_sitemap", record.getShowInSitemap())
+ .FIELD("created_by", record.getCreatedBy())
+ .FIELD("modified_by", record.getModifiedBy())
+ .FIELD("role_id_list", record.getRoleIdList())
+ .FIELD("page_xml", record.getPageXml())
+ .FIELD("draft_page_xml", StringUtils.trimToNull(record.getDraftPageXml()))
+ .FIELD("comments", record.getComments())
+ .FIELD("page_image_url", record.getImageUrl())
+ .FIELD("has_redirect", StringUtils.trimToNull(record.getRedirectUrl()) != null)
+ .FIELD("sitemap_priority", record.getSitemapPriority())
+ .FIELD("sitemap_changefreq", StringUtils.trimToNull(record.getSitemapChangeFrequency()));
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);
}
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
- if (record.getId() == -1) {
+ record.setId(insert.execute());
+ if (record.getId() == Insert.NO_GENERATED_KEY) {
LOG.error("An id was not set!");
return null;
}
@@ -256,34 +254,34 @@ private static WebPage update(WebPage record) {
}
// Before the update, retrieve the existing link for this page in case it changed
WebPage previousRecord = WebPageRepository.findById(record.getId());
- // Update the record
- SqlUtils updateValues = new SqlUtils()
- .add("link", link)
- .add("redirect_url", StringUtils.trimToNull(record.getRedirectUrl()))
- .add("page_title", StringUtils.trimToNull(record.getTitle()))
- .add("page_keywords", StringUtils.trimToNull(record.getKeywords()))
- .add("page_description", StringUtils.trimToNull(record.getDescription()))
- .add("draft", record.getDraft())
- .add("enabled", record.isEnabled())
- .add("searchable", record.isSearchable())
- .add("show_in_sitemap", record.getShowInSitemap())
- .add("modified", new Timestamp(System.currentTimeMillis()))
- .add("modified_by", record.getModifiedBy())
- .add("role_id_list", record.getRoleIdList())
- .add("page_xml", record.getPageXml())
- .add("draft_page_xml", StringUtils.trimToNull(record.getDraftPageXml()))
- .add("comments", record.getComments())
- .add("page_image_url", record.getImageUrl())
- .add("has_redirect", StringUtils.trimToNull(record.getRedirectUrl()) != null)
- .add("sitemap_priority", record.getSitemapPriority())
- .add("sitemap_changefreq", StringUtils.trimToNull(record.getSitemapChangeFrequency()));
+
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("link", link)
+ .SET("redirect_url", StringUtils.trimToNull(record.getRedirectUrl()))
+ .SET("page_title", StringUtils.trimToNull(record.getTitle()))
+ .SET("page_keywords", StringUtils.trimToNull(record.getKeywords()))
+ .SET("page_description", StringUtils.trimToNull(record.getDescription()))
+ .SET("draft", record.getDraft())
+ .SET("enabled", record.isEnabled())
+ .SET("searchable", record.isSearchable())
+ .SET("show_in_sitemap", record.getShowInSitemap())
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .SET("modified_by", record.getModifiedBy())
+ .SET("role_id_list", record.getRoleIdList())
+ .SET("page_xml", record.getPageXml())
+ .SET("draft_page_xml", StringUtils.trimToNull(record.getDraftPageXml()))
+ .SET("comments", record.getComments())
+ .SET("page_image_url", record.getImageUrl())
+ .SET("has_redirect", StringUtils.trimToNull(record.getRedirectUrl()) != null)
+ .SET("sitemap_priority", record.getSitemapPriority())
+ .SET("sitemap_changefreq", StringUtils.trimToNull(record.getSitemapChangeFrequency()));
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 {
- updateValues.add(new SqlValue("tags", SqlValue.JSONB_TYPE, null));
+ update.SET("tags", (String) null, CastType.JSONB);
}
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("web_page_id = ?", record.getId()))) {
- // Force the page(s) to re-cache
+ update.WHERE("web_page_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
if (previousRecord != null) {
WebPageXmlLayoutCommand.removeCustomPage(previousRecord.getLink());
}
@@ -298,12 +296,12 @@ public static void publish(WebPage record) {
if (record.getId() == -1) {
return;
}
- // Handle publishing and making sure there is content to publish
- if (DB.update(
- TABLE_NAME,
- "page_xml = draft_page_xml, draft_page_xml = null, draft = false",
- DB.WHERE("draft_page_xml IS NOT NULL AND web_page_id = ?", record.getId()))) {
- // Force the page to re-cache
+ if (DB.UPDATE(TABLE_NAME)
+ .SET("page_xml = draft_page_xml")
+ .SET("draft_page_xml = null")
+ .SET("draft = false")
+ .WHERE("draft_page_xml IS NOT NULL AND web_page_id = ?", record.getId())
+ .execute().booleanValue()) {
WebPageXmlLayoutCommand.removeCustomPage(record.getLink());
}
}
@@ -317,15 +315,14 @@ public static void markAsModifiedAndFindable(WebPage record, long userId) {
&& record.getModified().equals(record.getCreated());
long modified = System.currentTimeMillis();
- SqlUtils updateValues = new SqlUtils()
- .add("modified", new Timestamp(modified))
- .add("modified_by", userId);
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("modified", new Timestamp(modified))
+ .SET("modified_by", userId);
if (isFirstPublishAfterCreation) {
- updateValues
- .add("searchable", true)
- .add("show_in_sitemap", true);
+ update.SET("searchable", true)
+ .SET("show_in_sitemap", true);
}
- DB.update(TABLE_NAME, updateValues, DB.WHERE("web_page_id = ?", record.getId()));
+ update.WHERE("web_page_id = ?", record.getId()).execute();
// Now update the record for additional workflows
record.setModifiedBy(userId);
record.setModified(new Timestamp(modified));
@@ -340,11 +337,12 @@ public static boolean archivePage(WebPage record, long userId) {
return false;
}
// Explicitly set enabled to false (archived)
- SqlUtils updateValues = new SqlUtils()
- .add("enabled", false)
- .add("modified", new Timestamp(System.currentTimeMillis()))
- .add("modified_by", userId);
- boolean updated = DB.update(TABLE_NAME, updateValues, DB.WHERE("web_page_id = ?", record.getId()));
+ boolean updated = DB.UPDATE(TABLE_NAME)
+ .SET("enabled", false)
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .SET("modified_by", userId)
+ .WHERE("web_page_id = ?", record.getId())
+ .execute();
if (updated) {
record.setEnabled(false);
record.setModifiedBy(userId);
@@ -360,11 +358,12 @@ public static boolean unarchivePage(WebPage record, long userId) {
return false;
}
// Explicitly set enabled to true (unarchived)
- SqlUtils updateValues = new SqlUtils()
- .add("enabled", true)
- .add("modified", new Timestamp(System.currentTimeMillis()))
- .add("modified_by", userId);
- boolean updated = DB.update(TABLE_NAME, updateValues, DB.WHERE("web_page_id = ?", record.getId()));
+ boolean updated = DB.UPDATE(TABLE_NAME)
+ .SET("enabled", true)
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .SET("modified_by", userId)
+ .WHERE("web_page_id = ?", record.getId())
+ .execute();
if (updated) {
record.setEnabled(true);
record.setModifiedBy(userId);
@@ -378,9 +377,12 @@ public static void removeDraft(WebPage record) {
if (record == null || record.getId() == -1) {
return;
}
- String setValues = "draft_page_xml = null, draft = false";
- if (DB.update(TABLE_NAME, setValues, DB.WHERE("web_page_id = ?", record.getId()))) {
- // Force the page to re-cache
+ if (DB.UPDATE(TABLE_NAME)
+ .SET("draft_page_xml", (String) null)
+ .SET("draft", false)
+ .WHERE("web_page_id = ?", record.getId())
+ .execute()) {
+ // Forces the page to re-cache
WebPageXmlLayoutCommand.removeCustomPage(record.getLink());
}
}
@@ -397,7 +399,10 @@ public static boolean remove(WebPage record) {
WebPageHierarchyRepository.remove(connection, record);
WebPageVersionRepository.removeAll(connection, record);
// Delete the record
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("web_page_id = ?", record.getId()));
+ DB.DELETE()
+ .FROM(TABLE_NAME)
+ .WHERE("web_page_id = ?", record.getId())
+ .execute(connection);
// Finish transaction
transaction.commit();
// Force the page to re-cache
@@ -413,9 +418,10 @@ public static void updatePageText(long id, String generatedText) {
if (id == -1) {
return;
}
- SqlUtils updateValues = new SqlUtils()
- .add("page_text", generatedText);
- DB.update(TABLE_NAME, updateValues, DB.WHERE("web_page_id = ?", id));
+ DB.UPDATE(TABLE_NAME)
+ .SET("page_text", generatedText)
+ .WHERE("web_page_id = ?", id)
+ .execute();
}
private static WebPage buildRecord(ResultSet rs) {
@@ -460,14 +466,9 @@ public static List findByContentUniqueId(String contentUniqueId) {
return new ArrayList<>();
}
// Query for pages where pageXml contains the uniqueId reference
- SqlWhere where = DB.WHERE();
- where.AND("(page_xml LIKE ? OR draft_page_xml LIKE ?)",
- new String[] { "%" + contentUniqueId + "%", "%" + contentUniqueId + "%" });
- return (List) DB.selectAllFrom(
- TABLE_NAME,
- where,
- new DataConstraints(),
- WebPageRepository::buildRecord).getRecords();
+ return DB.SELECT().FROM(TABLE_NAME)
+ .WHERE("(page_xml LIKE ? OR draft_page_xml LIKE ?)", "%" + contentUniqueId + "%", "%" + contentUniqueId + "%")
+ .returnList(WebPageRepository::buildRecord);
}
public static List findIndirectlyAffectedPagesByContentUniqueId(String contentUniqueId) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebPageTemplateRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebPageTemplateRepository.java
index 4f150caac..2df319e16 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebPageTemplateRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebPageTemplateRepository.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,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.github.rajkowski.database.Insert;
+import com.github.rajkowski.database.Select;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.domain.model.cms.WebPageTemplate;
-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 web page template objects
@@ -44,32 +46,35 @@ public class WebPageTemplateRepository {
private static String TABLE_NAME = "web_page_templates";
private static String[] PRIMARY_KEY = new String[] { "template_id" };
- private static DataResult query(WebPageTemplateSpecification specification, DataConstraints constraints) {
- SqlWhere where = null;
- if (specification != null) {
- where = DB.WHERE().andAddIfHasValue("template_id = ?", specification.getId(), -1);
+ private static DataResult query(WebPageTemplateSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("*").FROM(TABLE_NAME);
+ if (specification != null && specification.getId() != -1) {
+ select.WHERE("template_id = ?", specification.getId());
}
- return DB.selectAllFrom(TABLE_NAME, where, constraints, WebPageTemplateRepository::buildRecord);
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(WebPageTemplateRepository::buildRecord);
}
public static WebPageTemplate findById(long id) {
if (id == -1) {
return null;
}
- return (WebPageTemplate) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("template_id = ?", id),
- WebPageTemplateRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("template_id = ?", id)
+ .returnRecord(WebPageTemplateRepository::buildRecord);
}
public static WebPageTemplate findByName(String name) {
if (StringUtils.isBlank(name)) {
return null;
}
- return (WebPageTemplate) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("name = ?", name),
- WebPageTemplateRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("name = ?", name)
+ .returnRecord(WebPageTemplateRepository::buildRecord);
}
public static List findAll() {
@@ -81,8 +86,7 @@ public static List findAll(WebPageTemplateSpecification specifi
constraints = new DataConstraints();
}
constraints.setDefaultColumnToSortBy("template_order, name");
- DataResult result = query(specification, constraints);
- return (List) result.getRecords();
+ return query(specification, constraints).getRecords();
}
public static WebPageTemplate save(WebPageTemplate record) {
@@ -93,15 +97,15 @@ public static WebPageTemplate save(WebPageTemplate record) {
}
private static WebPageTemplate add(WebPageTemplate record) {
- SqlUtils insertValues = new SqlUtils()
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("image_path", StringUtils.trimToNull(record.getImagePath()))
- .add("page_xml", StringUtils.trimToNull(record.getPageXml()))
- .add("template_order", record.getTemplateOrder())
- .add("description", StringUtils.trimToNull(record.getDescription()))
- .add("css", StringUtils.trimToNull(record.getCss()))
- .add("category", StringUtils.trimToNull(record.getCategory()));
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("name", StringUtils.trimToNull(record.getName()))
+ .FIELD("image_path", StringUtils.trimToNull(record.getImagePath()))
+ .FIELD("page_xml", StringUtils.trimToNull(record.getPageXml()))
+ .FIELD("template_order", record.getTemplateOrder())
+ .FIELD("description", StringUtils.trimToNull(record.getDescription()))
+ .FIELD("css", StringUtils.trimToNull(record.getCss()))
+ .FIELD("category", StringUtils.trimToNull(record.getCategory()));
+ record.setId(insert.execute());
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -110,15 +114,15 @@ private static WebPageTemplate add(WebPageTemplate record) {
}
private static WebPageTemplate update(WebPageTemplate record) {
- SqlUtils updateValues = new SqlUtils()
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("image_path", StringUtils.trimToNull(record.getImagePath()))
- .add("page_xml", StringUtils.trimToNull(record.getPageXml()))
- .add("template_order", record.getTemplateOrder())
- .add("description", StringUtils.trimToNull(record.getDescription()))
- .add("css", StringUtils.trimToNull(record.getCss()))
- .add("category", StringUtils.trimToNull(record.getCategory()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("template_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("name", StringUtils.trimToNull(record.getName()))
+ .SET("image_path", StringUtils.trimToNull(record.getImagePath()))
+ .SET("page_xml", StringUtils.trimToNull(record.getPageXml()))
+ .SET("template_order", record.getTemplateOrder())
+ .SET("description", StringUtils.trimToNull(record.getDescription()))
+ .SET("css", StringUtils.trimToNull(record.getCss()))
+ .SET("category", StringUtils.trimToNull(record.getCategory()));
+ if (update.WHERE("template_id = ?", record.getId()).execute()) {
return record;
}
LOG.error("The update failed!");
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebSearchRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebSearchRepository.java
index d07603772..37a499bb2 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebSearchRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WebSearchRepository.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,15 +17,15 @@
package com.simisinc.platform.infrastructure.persistence.cms;
-import com.simisinc.platform.infrastructure.database.DB;
-import com.simisinc.platform.infrastructure.database.SqlUtils;
-import com.simisinc.platform.domain.model.cms.WebSearch;
+import java.sql.Connection;
+import java.sql.SQLException;
+
+import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.SQLException;
+import com.github.rajkowski.database.DB;
+import com.simisinc.platform.domain.model.cms.WebSearch;
/**
* Persists and retrieves web search objects
@@ -37,20 +38,19 @@ public class WebSearchRepository {
private static Log LOG = LogFactory.getLog(WebSearchRepository.class);
private static String TABLE_NAME = "web_searches";
- private static String[] PRIMARY_KEY = new String[] { "search_id" };
public static WebSearch save(WebSearch record) {
return add(record);
}
private static WebSearch add(WebSearch record) {
- SqlUtils insertValues = new SqlUtils()
- .add("page_path", record.getPagePath(), 255)
- .add("query", record.getQuery(), 255)
- .add("ip_address", record.getIpAddress())
- .add("session_id", record.getSessionId())
- .add("is_logged_in", record.getIsLoggedIn());
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ record.setId(DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("page_path", StringUtils.truncate(record.getPagePath(), 255))
+ .FIELD("query", StringUtils.truncate(record.getQuery(), 255))
+ .FIELD("ip_address", record.getIpAddress())
+ .FIELD("session_id", record.getSessionId())
+ .FIELD("is_logged_in", record.getIsLoggedIn())
+ .execute());
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -59,22 +59,12 @@ private static WebSearch add(WebSearch record) {
}
public static boolean remove(WebSearch record) {
- try (Connection connection = DB.getConnection();
- PreparedStatement pst = createPreparedStatementForDelete(connection, record)) {
- pst.execute();
+ try (Connection connection = DB.getConnection()) {
+ return DB.DELETE().FROM(TABLE_NAME).WHERE("search_id = ?", record.getId()).execute(connection);
} catch (SQLException se) {
LOG.error("SQLException: " + se.getMessage());
}
LOG.error("The delete failed!");
return false;
}
-
- private static PreparedStatement createPreparedStatementForDelete(Connection connection, WebSearch record) throws SQLException {
- String SQL_QUERY = "DELETE FROM web_searches " +
- "WHERE search_id = ?";
- int i = 0;
- PreparedStatement pst = connection.prepareStatement(SQL_QUERY);
- pst.setLong(++i, record.getId());
- return pst;
- }
}
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WikiPageRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WikiPageRepository.java
index 0f6bd1e24..2f5b9161d 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WikiPageRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WikiPageRepository.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,14 @@
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.Select;
import com.simisinc.platform.domain.model.cms.Wiki;
import com.simisinc.platform.domain.model.cms.WikiPage;
-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 wiki page objects
@@ -49,47 +49,54 @@ public class WikiPageRepository {
private static String TABLE_NAME = "wiki_pages";
private static String[] PRIMARY_KEY = new String[] { "wiki_page_id" };
- private static SqlWhere createWhereStatement(WikiPageSpecification specification) {
- SqlWhere where = null;
+ private static Select createSelect(WikiPageSpecification specification) {
+ Select select = DB.SELECT("*").FROM(TABLE_NAME).WHERE();
if (specification != null) {
- where = DB.WHERE()
- .andAddIfHasValue("wiki_page_id = ?", specification.getId(), -1)
- .andAddIfHasValue("wiki_id = ?", specification.getWikiId(), -1)
- .andAddIfHasValue("page_unique_id = ?", specification.getUniqueId());
+ if (specification.getId() > -1) {
+ select.AND("wiki_page_id = ?", specification.getId());
+ }
+ if (specification.getWikiId() > -1) {
+ select.AND("wiki_id = ?", specification.getWikiId());
+ }
+ if (StringUtils.isNotBlank(specification.getUniqueId())) {
+ select.AND("page_unique_id = ?", specification.getUniqueId());
+ }
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());
}
}
- return where;
+ return select;
}
- private static DataResult query(WikiPageSpecification specification, DataConstraints constraints) {
- SqlWhere where = createWhereStatement(specification);
- return DB.selectAllFrom(TABLE_NAME, where, constraints, WikiPageRepository::buildRecord);
+ private static DataResult query(WikiPageSpecification specification, DataConstraints constraints) {
+ Select select = createSelect(specification);
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(WikiPageRepository::buildRecord);
}
public static WikiPage findByUniqueId(Long wikiId, String pageUniqueId) {
if (StringUtils.isBlank(pageUniqueId)) {
return null;
}
- return (WikiPage) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE()
- .AND("wiki_id = ?", wikiId)
- .AND("page_unique_id = ?", pageUniqueId.toLowerCase()),
- WikiPageRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("wiki_id = ?", wikiId)
+ .AND("page_unique_id = ?", pageUniqueId.toLowerCase())
+ .returnRecord(WikiPageRepository::buildRecord);
}
public static WikiPage findById(Long wikiPageId) {
if (wikiPageId == -1) {
return null;
}
- return (WikiPage) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("wiki_page_id = ?", wikiPageId),
- WikiPageRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("wiki_page_id = ?", wikiPageId)
+ .returnRecord(WikiPageRepository::buildRecord);
}
public static List findAll() {
@@ -106,8 +113,7 @@ public static List findAll(WikiPageSpecification specification, DataCo
}
public static long findCount(WikiPageSpecification specification) {
- SqlWhere where = createWhereStatement(specification);
- return DB.selectCountFrom(TABLE_NAME, where);
+ return createSelect(specification).returnCount();
}
public static WikiPage save(WikiPage record) {
@@ -117,27 +123,27 @@ public static WikiPage save(WikiPage record) {
return add(record);
}
- public static long addDefaultPage(Connection connection, Wiki wiki) throws SQLException {
- SqlUtils insertValues = new SqlUtils()
- .add("wiki_id", wiki.getId())
- .add("page_unique_id", "home")
- .add("title", "Home")
- .add("body", "Welcome to the " + wiki.getName() + " wiki!")
- .add("created_by", wiki.getCreatedBy())
- .add("modified_by", wiki.getModifiedBy());
- return DB.insertInto(connection, TABLE_NAME, insertValues, PRIMARY_KEY);
+ public static long addDefaultPage(Connection connection, Wiki wiki) {
+ return DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("wiki_id", wiki.getId())
+ .FIELD("page_unique_id", "home")
+ .FIELD("title", "Home")
+ .FIELD("body", "Welcome to the " + wiki.getName() + " wiki!")
+ .FIELD("created_by", wiki.getCreatedBy())
+ .FIELD("modified_by", wiki.getModifiedBy())
+ .execute(connection);
}
public static WikiPage add(WikiPage record) {
- SqlUtils insertValues = new SqlUtils()
- .add("wiki_id", record.getWikiId())
- .add("page_unique_id", StringUtils.trimToNull(record.getUniqueId()).toLowerCase())
- .add("title", StringUtils.trimToNull(record.getTitle()))
- .add("body", StringUtils.trimToNull(record.getBody()))
- .add("summary", StringUtils.trimToNull(record.getSummary()))
- .add("created_by", record.getCreatedBy())
- .add("modified_by", record.getModifiedBy());
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ record.setId(DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("wiki_id", record.getWikiId())
+ .FIELD("page_unique_id", StringUtils.trim(record.getUniqueId()).toLowerCase())
+ .FIELD("title", StringUtils.trimToNull(record.getTitle()))
+ .FIELD("body", StringUtils.trimToNull(record.getBody()))
+ .FIELD("summary", StringUtils.trimToNull(record.getSummary()))
+ .FIELD("created_by", record.getCreatedBy())
+ .FIELD("modified_by", record.getModifiedBy())
+ .execute());
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -146,16 +152,17 @@ public static WikiPage add(WikiPage record) {
}
public static WikiPage update(WikiPage record) {
- SqlUtils updateValues = new SqlUtils()
- .add("wiki_id", record.getWikiId())
- .add("page_unique_id", StringUtils.trimToNull(record.getUniqueId()).toLowerCase())
- .add("title", StringUtils.trimToNull(record.getTitle()))
- .add("body", StringUtils.trimToNull(record.getBody()))
- .add("summary", StringUtils.trimToNull(record.getSummary()))
- .add("modified_by", record.getModifiedBy())
- .add("modified", new Timestamp(System.currentTimeMillis()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("wiki_page_id = ?", record.getId()))) {
- // CacheManager.invalidateKey(CacheManager.CONTENT_UNIQUE_ID_CACHE, record.getUniqueId());
+ boolean updated = DB.UPDATE(TABLE_NAME)
+ .SET("wiki_id", record.getWikiId())
+ .SET("page_unique_id", StringUtils.trim(record.getUniqueId()).toLowerCase())
+ .SET("title", StringUtils.trimToNull(record.getTitle()))
+ .SET("body", StringUtils.trimToNull(record.getBody()))
+ .SET("summary", StringUtils.trimToNull(record.getSummary()))
+ .SET("modified_by", record.getModifiedBy())
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("wiki_page_id = ?", record.getId())
+ .execute();
+ if (updated) {
return record;
}
LOG.error("The update failed!");
@@ -166,13 +173,7 @@ public static boolean remove(WikiPage 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("wiki_page_id = ?", record.getId()));
- // Finish transaction
+ DB.DELETE().FROM(TABLE_NAME).WHERE("wiki_page_id = ?", record.getId()).execute(connection);
transaction.commit();
return true;
} catch (SQLException se) {
@@ -182,7 +183,7 @@ public static boolean remove(WikiPage record) {
}
public static void removeAll(Connection connection, Wiki wiki) throws SQLException {
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("wiki_id = ?", wiki.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("wiki_id = ?", wiki.getId()).execute(connection);
}
private static WikiPage buildRecord(ResultSet rs) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WikiRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WikiRepository.java
index 053aacd26..434d73f96 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WikiRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/cms/WikiRepository.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,13 @@
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.Select;
import com.simisinc.platform.domain.model.cms.Wiki;
-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 wiki objects
@@ -48,34 +48,40 @@ public class WikiRepository {
private static String TABLE_NAME = "wikis";
private static String[] PRIMARY_KEY = new String[] { "wiki_id" };
- private static DataResult query(WikiSpecification specification, DataConstraints constraints) {
- SqlWhere where = null;
+ private static DataResult query(WikiSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("*").FROM(TABLE_NAME).WHERE();
if (specification != null) {
- where = DB.WHERE()
- .andAddIfHasValue("wiki_id = ?", specification.getId(), -1)
- .andAddIfHasValue("wiki_unique_id = ?", specification.getUniqueId());
+ if (specification.getId() > -1) {
+ select.AND("wiki_id = ?", specification.getId());
+ }
+ if (StringUtils.isNotBlank(specification.getUniqueId())) {
+ select.AND("wiki_unique_id = ?", specification.getUniqueId());
+ }
+ }
+ if (constraints != null) {
+ select.WITH(constraints);
}
- return DB.selectAllFrom(TABLE_NAME, where, constraints, WikiRepository::buildRecord);
+ return select.returnDataResult(WikiRepository::buildRecord);
}
public static Wiki findById(long wikiId) {
if (wikiId == -1) {
return null;
}
- return (Wiki) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("wiki_id = ?", wikiId),
- WikiRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("wiki_id = ?", wikiId)
+ .returnRecord(WikiRepository::buildRecord);
}
public static Wiki findByUniqueId(String wikiUniqueId) {
if (StringUtils.isBlank(wikiUniqueId)) {
return null;
}
- return (Wiki) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("wiki_unique_id = ?", wikiUniqueId),
- WikiRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("wiki_unique_id = ?", wikiUniqueId)
+ .returnRecord(WikiRepository::buildRecord);
}
public static List findAll() {
@@ -87,8 +93,7 @@ public static List findAll(WikiSpecification specification, DataConstraint
constraints = new DataConstraints();
}
constraints.setDefaultColumnToSortBy("wiki_id");
- DataResult result = query(specification, constraints);
- return (List) result.getRecords();
+ return query(specification, constraints).getRecords();
}
public static Wiki save(Wiki record) {
@@ -99,29 +104,25 @@ public static Wiki save(Wiki record) {
}
public static Wiki add(Wiki record) {
- SqlUtils insertValues = new SqlUtils()
- .add("wiki_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())
- .add("starting_page", record.getStartingPage());
- // 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));
+ record.setId(DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("wiki_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())
+ .FIELD("starting_page", record.getStartingPage())
+ .execute(connection));
if (record.getStartingPage() == -1L) {
- // Create the default page
long wikiPageId = WikiPageRepository.addDefaultPage(connection, record);
- // @todo Create the first revision entry
- // Update the reference
- SqlUtils update = new SqlUtils().add("starting_page", wikiPageId);
- DB.update(connection, TABLE_NAME, update, DB.WHERE("wiki_id = ?", record.getId()));
+ DB.UPDATE(TABLE_NAME)
+ .SET("starting_page", wikiPageId)
+ .WHERE("wiki_id = ?", record.getId())
+ .execute(connection);
}
- // Finish the transaction
transaction.commit();
return record;
} catch (SQLException se) {
@@ -132,16 +133,17 @@ public static Wiki add(Wiki record) {
}
public static Wiki update(Wiki record) {
- SqlUtils updateValues = new SqlUtils()
- .add("wiki_unique_id", StringUtils.trimToNull(record.getUniqueId()))
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("description", StringUtils.trimToNull(record.getDescription()))
- .add("enabled", record.getEnabled())
- .add("starting_page", record.getStartingPage())
- .add("modified_by", record.getModifiedBy())
- .add("modified", new Timestamp(System.currentTimeMillis()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("wiki_id = ?", record.getId()))) {
- // CacheManager.invalidateKey(CacheManager.CONTENT_UNIQUE_ID_CACHE, record.getUniqueId());
+ boolean updated = DB.UPDATE(TABLE_NAME)
+ .SET("wiki_unique_id", StringUtils.trimToNull(record.getUniqueId()))
+ .SET("name", StringUtils.trimToNull(record.getName()))
+ .SET("description", StringUtils.trimToNull(record.getDescription()))
+ .SET("enabled", record.getEnabled())
+ .SET("starting_page", record.getStartingPage())
+ .SET("modified_by", record.getModifiedBy())
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("wiki_id = ?", record.getId())
+ .execute();
+ if (updated) {
return record;
}
LOG.error("The update failed!");
@@ -152,11 +154,8 @@ public static boolean remove(Wiki record) {
try (Connection connection = DB.getConnection();
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
- // Delete the references
WikiPageRepository.removeAll(connection, record);
- // Delete the record
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("wiki_id = ?", record.getId()));
- // Finish transaction
+ DB.DELETE().FROM(TABLE_NAME).WHERE("wiki_id = ?", record.getId()).execute(connection);
transaction.commit();
return true;
} catch (SQLException se) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/datasets/DatasetRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/datasets/DatasetRepository.java
index be111604b..84c5da349 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/datasets/DatasetRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/datasets/DatasetRepository.java
@@ -26,14 +26,13 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.CastType;
+import com.github.rajkowski.database.DB;
+import com.github.rajkowski.database.DataConstraints;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.application.CustomFieldListJSONCommand;
import com.simisinc.platform.application.datasets.DatasetColumnJSONCommand;
import com.simisinc.platform.domain.model.datasets.Dataset;
-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;
/**
* Persists and retrieves dataset objects
@@ -56,10 +55,10 @@ public static Dataset findById(long id) {
if (id == -1) {
return null;
}
- return (Dataset) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("dataset_id = ?", id),
- DatasetRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("dataset_id = ?", id)
+ .returnRecord(DatasetRepository::buildRecord);
}
public static Dataset findByName(String name) {
@@ -67,15 +66,15 @@ public static Dataset findByName(String name) {
return null;
}
String normalizedName = name.toLowerCase().trim();
- Dataset record = (Dataset) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("LOWER(name) = ?", normalizedName),
- DatasetRepository::buildRecord);
+ Dataset record = DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("LOWER(name) = ?", normalizedName)
+ .returnRecord(DatasetRepository::buildRecord);
if (record == null) {
- record = (Dataset) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("LOWER(name) = ?", normalizedName.replace("-", " ")),
- DatasetRepository::buildRecord);
+ record = DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("LOWER(name) = ?", normalizedName.replace("-", " "))
+ .returnRecord(DatasetRepository::buildRecord);
}
return record;
}
@@ -84,44 +83,41 @@ public static Dataset findByWebPath(String versionWebPath) {
if (StringUtils.isBlank(versionWebPath)) {
return null;
}
- return (Dataset) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("web_path = ?", versionWebPath),
- DatasetRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("web_path = ?", versionWebPath)
+ .returnRecord(DatasetRepository::buildRecord);
}
public static Dataset findByWebPathAndId(String versionWebPath, long id) {
if (StringUtils.isBlank(versionWebPath) || id == -1) {
return null;
}
- return (Dataset) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("web_path = ?", versionWebPath)
- .AND("dataset_id = ?", id),
- DatasetRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("web_path = ?", versionWebPath)
+ .AND("dataset_id = ?", id)
+ .returnRecord(DatasetRepository::buildRecord);
}
public static List findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- null,
- new DataConstraints().setDefaultColumnToSortBy("name"),
- DatasetRepository::buildRecord);
- return (List) result.getRecords();
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("name"))
+ .returnDataResult(DatasetRepository::buildRecord).getRecords();
}
public static List findAllScheduledForDownload() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- DB.WHERE("schedule_enabled = ?", true)
- .AND("schedule_frequency IS NOT NULL")
- .AND("source_url IS NOT NULL")
- .AND("CURRENT_TIMESTAMP > last_download + schedule_frequency")
- .AND("queue_date IS NULL OR CURRENT_TIMESTAMP > queue_date + queue_interval")
- .AND("queue_status = " + STATUS_READY),
- new DataConstraints().setDefaultColumnToSortBy("queue_status"),
- DatasetRepository::buildRecord);
- return (List) result.getRecords();
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("schedule_enabled = ?", true)
+ .AND("schedule_frequency IS NOT NULL")
+ .AND("source_url IS NOT NULL")
+ .AND("CURRENT_TIMESTAMP > last_download + schedule_frequency")
+ .AND("queue_date IS NULL OR CURRENT_TIMESTAMP > queue_date + queue_interval")
+ .AND("queue_status = ?", STATUS_READY)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("queue_status"))
+ .returnDataResult(DatasetRepository::buildRecord).getRecords();
}
public static Dataset save(Dataset record) {
@@ -132,30 +128,28 @@ public static Dataset save(Dataset record) {
}
public static Dataset add(Dataset record) {
- SqlUtils insertValues = new SqlUtils()
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("source_url", record.getSourceUrl())
- .add("source_info", record.getSourceInfo())
- .add("filename", StringUtils.trimToNull(record.getFilename()))
- .add("file_length", record.getFileLength())
- .add("file_type", record.getFileType())
- .add("file_hash", record.getFileHash())
- .add("web_path", StringUtils.trimToNull(record.getWebPath()))
- .add("path", StringUtils.trimToNull(record.getFileServerPath()))
- .add("last_download", record.getLastDownload())
- .add("records_path", record.getRecordsPath())
- .add("paging_url_path", record.getPagingUrlPath())
- .add("column_count", record.getColumnCount(), -1)
- .add("row_count", record.getRowCount())
- .add("collection_unique_id", record.getCollectionUniqueId())
- .add("category_id", record.getCategoryId())
- .add("created_by", record.getCreatedBy())
- .add("modified_by", record.getModifiedBy());
- insertValues.add(
- new SqlValue("column_config", SqlValue.JSONB_TYPE, DatasetColumnJSONCommand.createColumnJSONString(record)));
- insertValues.add(
- new SqlValue("request_config", SqlValue.JSONB_TYPE, StringUtils.trimToNull(record.getRequestConfig())));
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ record.setId(DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("name", StringUtils.trimToNull(record.getName()))
+ .FIELD("source_url", record.getSourceUrl())
+ .FIELD("source_info", record.getSourceInfo())
+ .FIELD("filename", StringUtils.trimToNull(record.getFilename()))
+ .FIELD("file_length", record.getFileLength())
+ .FIELD("file_type", record.getFileType())
+ .FIELD("file_hash", record.getFileHash())
+ .FIELD("web_path", StringUtils.trimToNull(record.getWebPath()))
+ .FIELD("path", StringUtils.trimToNull(record.getFileServerPath()))
+ .FIELD("last_download", record.getLastDownload())
+ .FIELD("records_path", record.getRecordsPath())
+ .FIELD("paging_url_path", record.getPagingUrlPath())
+ .FIELD("column_count", record.getColumnCount() == -1 ? null : record.getColumnCount())
+ .FIELD("row_count", record.getRowCount())
+ .FIELD("collection_unique_id", record.getCollectionUniqueId())
+ .FIELD("category_id", record.getCategoryId())
+ .FIELD("created_by", record.getCreatedBy())
+ .FIELD("modified_by", record.getModifiedBy())
+ .FIELD("column_config", DatasetColumnJSONCommand.createColumnJSONString(record), CastType.JSONB)
+ .FIELD("request_config", StringUtils.trimToNull(record.getRequestConfig()), CastType.JSONB)
+ .execute());
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -165,28 +159,26 @@ public static Dataset add(Dataset record) {
public static Dataset update(Dataset record) {
// Update
- SqlUtils updateValues = new SqlUtils()
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("source_url", record.getSourceUrl())
- .add("source_info", record.getSourceInfo())
- .add("filename", StringUtils.trimToNull(record.getFilename()))
- .add("file_length", record.getFileLength())
- .add("file_type", record.getFileType())
- .add("file_hash", record.getFileHash())
- .add("web_path", StringUtils.trimToNull(record.getWebPath()))
- .add("path", StringUtils.trimToNull(record.getFileServerPath()))
- .add("last_download", record.getLastDownload())
- .add("records_path", record.getRecordsPath())
- .add("paging_url_path", record.getPagingUrlPath())
- .add("column_count", record.getColumnCount(), -1)
- .add("row_count", record.getRowCount())
- .add("modified_by", record.getModifiedBy());
- updateValues.add(
- new SqlValue("column_config", SqlValue.JSONB_TYPE, DatasetColumnJSONCommand.createColumnJSONString(record)));
- updateValues.add(
- new SqlValue("request_config", SqlValue.JSONB_TYPE, StringUtils.trimToNull(record.getRequestConfig())));
- // Where
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("dataset_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("name", StringUtils.trimToNull(record.getName()))
+ .SET("source_url", record.getSourceUrl())
+ .SET("source_info", record.getSourceInfo())
+ .SET("filename", StringUtils.trimToNull(record.getFilename()))
+ .SET("file_length", record.getFileLength())
+ .SET("file_type", record.getFileType())
+ .SET("file_hash", record.getFileHash())
+ .SET("web_path", StringUtils.trimToNull(record.getWebPath()))
+ .SET("path", StringUtils.trimToNull(record.getFileServerPath()))
+ .SET("last_download", record.getLastDownload())
+ .SET("records_path", record.getRecordsPath())
+ .SET("paging_url_path", record.getPagingUrlPath())
+ .SET("column_count", record.getColumnCount() == -1 ? null : record.getColumnCount())
+ .SET("row_count", record.getRowCount())
+ .SET("modified_by", record.getModifiedBy())
+ .SET("column_config", DatasetColumnJSONCommand.createColumnJSONString(record), CastType.JSONB)
+ .SET("request_config", StringUtils.trimToNull(record.getRequestConfig()), CastType.JSONB)
+ .WHERE("dataset_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("The update failed!");
@@ -195,12 +187,12 @@ public static Dataset update(Dataset record) {
public static Dataset updateDetails(Dataset record) {
// Update
- SqlUtils updateValues = new SqlUtils()
- .add("name", record.getName())
- .add("source_info", record.getSourceInfo())
- .add("modified_by", record.getModifiedBy());
- // Where
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("dataset_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("name", record.getName())
+ .SET("source_info", record.getSourceInfo())
+ .SET("modified_by", record.getModifiedBy())
+ .WHERE("dataset_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("updateDetails failed!");
@@ -208,16 +200,14 @@ public static Dataset updateDetails(Dataset record) {
}
public static Dataset updateConfiguration(Dataset record) {
- // Update
- SqlUtils updateValues = new SqlUtils()
- .add("records_path", record.getRecordsPath())
- .add("paging_url_path", record.getPagingUrlPath())
- .add("column_count", record.getColumnCount(), -1)
- .add("row_count", record.getRowCount());
- updateValues.add(
- new SqlValue("column_config", SqlValue.JSONB_TYPE, DatasetColumnJSONCommand.createColumnJSONString(record)));
- // Where
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("dataset_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("records_path", record.getRecordsPath())
+ .SET("paging_url_path", record.getPagingUrlPath())
+ .SET("column_count", record.getColumnCount() == -1 ? null : record.getColumnCount())
+ .SET("row_count", record.getRowCount())
+ .SET("column_config", DatasetColumnJSONCommand.createColumnJSONString(record), CastType.JSONB)
+ .WHERE("dataset_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("updateConfiguration failed!");
@@ -225,14 +215,13 @@ public static Dataset updateConfiguration(Dataset record) {
}
public static Dataset updateMapping(Dataset record) {
- // Update
- SqlUtils updateValues = new SqlUtils()
- .add("collection_unique_id", StringUtils.trimToNull(record.getCollectionUniqueId()))
- .add("category_id", record.getCategoryId())
- .add("unique_column_name", record.getUniqueColumnName());
- updateValues.add(
- new SqlValue("column_config", SqlValue.JSONB_TYPE, DatasetColumnJSONCommand.createColumnJSONString(record)));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("dataset_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("collection_unique_id", StringUtils.trimToNull(record.getCollectionUniqueId()))
+ .SET("category_id", record.getCategoryId())
+ .SET("unique_column_name", record.getUniqueColumnName())
+ .SET("column_config", DatasetColumnJSONCommand.createColumnJSONString(record), CastType.JSONB)
+ .WHERE("dataset_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("updateMapping failed!");
@@ -240,14 +229,13 @@ public static Dataset updateMapping(Dataset record) {
}
public static Dataset updateScheduleAndSyncDetails(Dataset record) {
- // Update
- SqlUtils updateValues = new SqlUtils()
- .add("schedule_enabled", record.getScheduleEnabled())
- .add(new SqlValue("schedule_frequency", SqlValue.INTERVAL_TYPE, record.getScheduleFrequency()))
- .add("sync_enabled", record.getSyncEnabled())
- .add("sync_merge_type", record.getSyncMergeType());
- // Where
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("dataset_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("schedule_enabled", record.getScheduleEnabled())
+ .SET("schedule_frequency", record.getScheduleFrequency(), CastType.INTERVAL)
+ .SET("sync_enabled", record.getSyncEnabled())
+ .SET("sync_merge_type", record.getSyncMergeType())
+ .WHERE("dataset_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("updateScheduleAndSyncDetails failed!");
@@ -255,15 +243,15 @@ public static Dataset updateScheduleAndSyncDetails(Dataset record) {
}
public static Dataset updateCustomFields(Dataset record) {
- SqlUtils updateValues = new SqlUtils()
- .add("modified", new Timestamp(System.currentTimeMillis()));
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("modified", new Timestamp(System.currentTimeMillis()));
if (record.getCustomFieldList() != null && !record.getCustomFieldList().isEmpty()) {
- updateValues.add(new SqlValue("field_values", SqlValue.JSONB_TYPE,
- CustomFieldListJSONCommand.createJSONString(record.getCustomFieldList())));
+ update.SET("field_values", CustomFieldListJSONCommand.createJSONString(record.getCustomFieldList()), CastType.JSONB);
} else {
- updateValues.add(new SqlValue("field_values", SqlValue.JSONB_TYPE, null));
+ update.SET("field_values", (String) null, CastType.JSONB);
}
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("collection_id = ?", record.getId()))) {
+ update.WHERE("dataset_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("updateCustomFields failed!");
@@ -271,12 +259,11 @@ public static Dataset updateCustomFields(Dataset record) {
}
public static Dataset updateCollectionUniqueId(Dataset record) {
- // Update
- SqlUtils updateValues = new SqlUtils()
- .add("collection_unique_id", StringUtils.trimToNull(record.getCollectionUniqueId()))
- .add("category_id", record.getCategoryId());
- // Where
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("dataset_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("collection_unique_id", StringUtils.trimToNull(record.getCollectionUniqueId()))
+ .SET("category_id", record.getCategoryId())
+ .WHERE("dataset_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("updateCollectionUniqueId failed!");
@@ -284,10 +271,10 @@ public static Dataset updateCollectionUniqueId(Dataset record) {
}
public static Dataset updateRowsProcessed(Dataset record) {
- // Update
- SqlUtils updateValues = new SqlUtils()
- .add("rows_processed", record.getRowsProcessed());
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("dataset_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("rows_processed", record.getRowsProcessed())
+ .WHERE("dataset_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("updateRowsProcessed failed!");
@@ -299,28 +286,27 @@ public static Dataset updateRowsProcessed(Dataset record) {
* Status 0 = available, 1 = locked, 2 = red flag
*/
public static boolean markAsQueuedIfAllowed(Dataset record) {
- SqlUtils updateValues = new SqlUtils()
- .add("queue_status", STATUS_RUNNING)
- .add("queue_date = CURRENT_TIMESTAMP")
- .add("queue_attempts = queue_attempts + 1")
- .add("schedule_last_run = CURRENT_TIMESTAMP");
- return DB.update(TABLE_NAME, updateValues,
- DB.WHERE("dataset_id = ?", record.getId())
- .AND("queue_status = ?", STATUS_READY));
+ return DB.UPDATE(TABLE_NAME)
+ .SET("queue_status", STATUS_RUNNING)
+ .SET("queue_date = CURRENT_TIMESTAMP")
+ .SET("queue_attempts = queue_attempts + 1")
+ .SET("schedule_last_run = CURRENT_TIMESTAMP")
+ .WHERE("dataset_id = ?", record.getId())
+ .AND("queue_status = ?", STATUS_READY)
+ .execute();
}
public static boolean markAsUnqueued(Dataset record) {
- SqlUtils updateValues = new SqlUtils()
- .add("queue_status", STATUS_READY)
- .add("queue_date = NULL")
- .add("queue_message = NULL")
- .add("queue_attempts = 0")
- .add(new SqlValue("queue_interval", SqlValue.INTERVAL_TYPE, "PT5M"));
- return DB.update(TABLE_NAME, updateValues, DB.WHERE("dataset_id = ?", record.getId()));
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("queue_status", STATUS_READY)
+ .SET("queue_date = NULL")
+ .SET("queue_message = NULL")
+ .SET("queue_attempts = 0")
+ .SET("queue_interval", "PT5M", CastType.INTERVAL);
+ return update.WHERE("dataset_id = ?", record.getId()).execute();
}
public static boolean markToRetryDownload(Dataset record, String reason) {
- // Determine when to retry or finally fail
int queueStatus = STATUS_READY;
String retryInterval = "PT5M";
if (record.getQueueAttempts() < 5) {
@@ -334,20 +320,20 @@ public static boolean markToRetryDownload(Dataset record, String reason) {
} else {
queueStatus = STATUS_FAILED;
}
- SqlUtils updateValues = new SqlUtils()
- .add("queue_status", queueStatus)
- .add("queue_message", reason)
- .add(new SqlValue("queue_interval", SqlValue.INTERVAL_TYPE, retryInterval));
- return DB.update(TABLE_NAME, updateValues, DB.WHERE("dataset_id = ?", record.getId()));
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("queue_status", queueStatus)
+ .SET("queue_message", reason)
+ .SET("queue_interval", retryInterval, CastType.INTERVAL);
+ return update.WHERE("dataset_id = ?", record.getId()).execute();
}
public static boolean markLastDownload(Dataset record) {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
- SqlUtils updateValues = new SqlUtils()
- .add("last_download", timestamp);
- boolean updated = DB.update(TABLE_NAME, updateValues, DB.WHERE("dataset_id = ?", record.getId()));
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("last_download", timestamp)
+ .WHERE("dataset_id = ?", record.getId());
+ boolean updated = update.execute().booleanValue();
if (updated) {
- // Update the record for additional workflows
record.setLastDownload(timestamp);
}
return updated;
@@ -355,23 +341,23 @@ public static boolean markLastDownload(Dataset record) {
public static boolean markScheduleLastRun(Dataset record, int status, String message) {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
- SqlUtils updateValues = new SqlUtils()
- .add("schedule_last_run", timestamp);
- boolean updated = DB.update(TABLE_NAME, updateValues, DB.WHERE("dataset_id = ?", record.getId()));
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("schedule_last_run", timestamp)
+ .WHERE("dataset_id = ?", record.getId());
+ boolean updated = update.execute().booleanValue();
if (updated) {
- // Update the record for additional workflows
record.setScheduleLastRun(timestamp);
}
return updated;
}
public static boolean markAsProcessStarted(Dataset record) {
- SqlUtils updateValues = new SqlUtils()
- .add("process_status", STATUS_RUNNING)
- .add("process_message", (String) null);
- boolean updated = DB.update(TABLE_NAME, updateValues, DB.WHERE("dataset_id = ?", record.getId()));
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("process_status", STATUS_RUNNING)
+ .SET("process_message", (String) null)
+ .WHERE("dataset_id = ?", record.getId());
+ boolean updated = update.execute().booleanValue();
if (updated) {
- // Update the record for additional workflows
record.setProcessStatus(STATUS_RUNNING);
record.setProcessMessage(null);
}
@@ -380,14 +366,14 @@ public static boolean markAsProcessStarted(Dataset record) {
public static boolean markAsProcessFinished(Dataset record, String message) {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
- SqlUtils updateValues = new SqlUtils()
- .add("process_status = ?", STATUS_READY)
- .add("processed", timestamp)
- .add("process_message", message)
- .add("processed_ms", record.getTotalProcessTime());
- boolean updated = DB.update(TABLE_NAME, updateValues, DB.WHERE("dataset_id = ?", record.getId()));
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("process_status", STATUS_READY)
+ .SET("processed", timestamp)
+ .SET("process_message", message)
+ .SET("processed_ms", record.getTotalProcessTime())
+ .WHERE("dataset_id = ?", record.getId());
+ boolean updated = update.execute().booleanValue();
if (updated) {
- // Update the record for additional workflows
record.setProcessStatus(STATUS_READY);
record.setProcessMessage(message);
}
@@ -395,13 +381,13 @@ public static boolean markAsProcessFinished(Dataset record, String message) {
}
public static boolean resetSyncTimestamp(Dataset record, Timestamp timestamp) {
- SqlUtils updateValues = new SqlUtils()
- .add("sync_status", STATUS_RUNNING)
- .add("sync_date", timestamp)
- .add("sync_message", (String) null);
- boolean updated = DB.update(TABLE_NAME, updateValues, DB.WHERE("dataset_id = ?", record.getId()));
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("sync_status", STATUS_RUNNING)
+ .SET("sync_date", timestamp)
+ .SET("sync_message", (String) null)
+ .WHERE("dataset_id = ?", record.getId());
+ boolean updated = update.execute().booleanValue();
if (updated) {
- // Update the record for additional workflows
record.setSyncStatus(STATUS_RUNNING);
record.setSyncDate(timestamp);
record.setSyncMessage(null);
@@ -410,12 +396,12 @@ public static boolean resetSyncTimestamp(Dataset record, Timestamp timestamp) {
}
public static boolean saveSyncResult(Dataset record, String message) {
- SqlUtils updateValues = new SqlUtils()
- .add("sync_status", STATUS_READY)
- .add("sync_message", message);
- boolean updated = DB.update(TABLE_NAME, updateValues, DB.WHERE("dataset_id = ?", record.getId()));
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("sync_status", STATUS_READY)
+ .SET("sync_message", message)
+ .WHERE("dataset_id = ?", record.getId());
+ boolean updated = update.execute().booleanValue();
if (updated) {
- // Update the record for additional workflows
record.setSyncStatus(STATUS_READY);
record.setSyncMessage(message);
}
@@ -423,11 +409,11 @@ public static boolean saveSyncResult(Dataset record, String message) {
}
public static boolean remove(Dataset record) {
- return (DB.deleteFrom(TABLE_NAME, DB.WHERE("dataset_id = ?", record.getId())) > 0);
+ return DB.DELETE().FROM(TABLE_NAME).WHERE("dataset_id = ?", record.getId()).execute();
}
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 Dataset buildRecord(ResultSet rs) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/CartItemRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/CartItemRepository.java
index 4d35f114f..9648c5ce3 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/CartItemRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/CartItemRepository.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,14 @@
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.simisinc.platform.domain.model.ecommerce.Cart;
import com.simisinc.platform.domain.model.ecommerce.CartItem;
import com.simisinc.platform.domain.model.ecommerce.Product;
import com.simisinc.platform.domain.model.ecommerce.ProductSku;
-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 cart item objects
@@ -51,20 +50,19 @@ public class CartItemRepository {
private static String[] PRIMARY_KEY = new String[] { "item_id" };
public static List findValidItemsByCartId(long cartId) {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- DB.WHERE("is_removed = ?", false)
- .AND("cart_id = ?", cartId),
- new DataConstraints().setDefaultColumnToSortBy("item_id").setUseCount(false),
- CartItemRepository::buildRecord);
- return (List) result.getRecords();
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("is_removed = ?", false)
+ .AND("cart_id = ?", cartId)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("item_id").setUseCount(false))
+ .returnDataResult(CartItemRepository::buildRecord).getRecords();
}
public static CartItem findById(long itemId) {
- return (CartItem) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("item_id = ?", itemId),
- CartItemRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("item_id = ?", itemId)
+ .returnRecord(CartItemRepository::buildRecord);
}
public static void addProductToCart(Connection connection, Cart cart, Product product, ProductSku productSku, BigDecimal quantity)
@@ -72,25 +70,20 @@ public static void addProductToCart(Connection connection, Cart cart, Product pr
if (cart == null || productSku == null) {
throw new SQLException("Invalid request");
}
- SqlUtils insertValues = new SqlUtils();
- insertValues
- .add("cart_id", cart.getId())
- .add("product_id", productSku.getProductId())
- .add("sku_id", productSku.getId())
- .add("quantity", quantity)
- .add("each_amount", productSku.getPrice())
- .add("total_amount", productSku.getPrice().multiply(quantity))
- .add("product_name", product.getNameWithCaption())
- // .add("product_type", product.get)
- .add("product_sku", productSku.getSku())
- .add("product_barcode", productSku.getBarcode())
- .add("is_preorder", false)
- .add("is_backordered", false)
- .add("is_removed", false)
- // .add("created_by", )
- // .add("modified_by", )
- ;
- DB.insertInto(connection, TABLE_NAME, insertValues, PRIMARY_KEY);
+ DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("cart_id", cart.getId())
+ .FIELD("product_id", productSku.getProductId())
+ .FIELD("sku_id", productSku.getId())
+ .FIELD("quantity", quantity)
+ .FIELD("each_amount", productSku.getPrice())
+ .FIELD("total_amount", productSku.getPrice().multiply(quantity))
+ .FIELD("product_name", product.getNameWithCaption())
+ .FIELD("product_sku", productSku.getSku())
+ .FIELD("product_barcode", productSku.getBarcode())
+ .FIELD("is_preorder", false)
+ .FIELD("is_backordered", false)
+ .FIELD("is_removed", false)
+ .execute(connection);
}
public static void updateCartItemList(Connection connection, List cartItemList) throws SQLException {
@@ -98,13 +91,13 @@ public static void updateCartItemList(Connection connection, List cart
throw new SQLException("List is null");
}
for (CartItem cartItem : cartItemList) {
- SqlUtils setValues = new SqlUtils();
- setValues
- .add("quantity", cartItem.getQuantity())
- .add("each_amount", cartItem.getEachAmount())
- .add("total_amount", cartItem.getTotalAmount())
- .add("is_removed", cartItem.getRemoved());
- DB.update(connection, TABLE_NAME, setValues, DB.WHERE("item_id = ?", cartItem.getId()));
+ DB.UPDATE(TABLE_NAME)
+ .SET("quantity", cartItem.getQuantity())
+ .SET("each_amount", cartItem.getEachAmount())
+ .SET("total_amount", cartItem.getTotalAmount())
+ .SET("is_removed", cartItem.getRemoved())
+ .WHERE("item_id = ?", cartItem.getId())
+ .execute(connection);
}
}
@@ -115,21 +108,20 @@ public static boolean removeItemFromCart(Cart cart, CartItem cartItem) {
AutoRollback transaction = new AutoRollback(connection)) {
// In a transaction (use the existing connection)
{
- // Set as removed
- SqlUtils update = new SqlUtils()
- .add("is_removed", true)
- .add("modified", new Timestamp(System.currentTimeMillis()));
- DB.update(connection, TABLE_NAME, update, DB.WHERE("item_id = ?", cartItem.getId()));
- // DataSource.deleteFrom(connection, TABLE_NAME, where);
+ DB.UPDATE(TABLE_NAME)
+ .SET("is_removed", true)
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("item_id = ?", cartItem.getId())
+ .execute(connection);
}
{
- // Update the cart's total_items, total_qty, subtotal_amount, modified
- SqlUtils updateValues = new SqlUtils()
- .add("total_items = total_items - 1")
- .add("total_qty = total_qty - " + cartItem.getQuantity())
- .add("subtotal_amount = subtotal_amount - " + cartItem.getQuantity().multiply(cartItem.getEachAmount()))
- .add("modified", new Timestamp(System.currentTimeMillis()));
- DB.update(connection, "carts", updateValues, DB.WHERE("cart_id = ?", cartItem.getCartId()));
+ DB.UPDATE("carts")
+ .SET("total_items = total_items - 1")
+ .SET("total_qty = total_qty - " + cartItem.getQuantity())
+ .SET("subtotal_amount = subtotal_amount - " + cartItem.getQuantity().multiply(cartItem.getEachAmount()))
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("cart_id = ?", cartItem.getCartId())
+ .execute(connection);
}
// Finish the transaction
transaction.commit();
@@ -141,20 +133,20 @@ public static boolean removeItemFromCart(Cart cart, CartItem cartItem) {
}
public static void updateQuantityFree(CartItem cartItem) {
- SqlUtils setValues = new SqlUtils();
- setValues
- .add("quantity_free", cartItem.getQuantityFree());
- DB.update(TABLE_NAME, setValues, DB.WHERE("item_id = ?", cartItem.getId()));
+ DB.UPDATE(TABLE_NAME)
+ .SET("quantity_free", cartItem.getQuantityFree())
+ .WHERE("item_id = ?", cartItem.getId())
+ .execute();
}
public static void resetQuantityFree(Cart cart) {
if (cart == null) {
return;
}
- SqlUtils setValues = new SqlUtils();
- setValues
- .add("quantity_free", new BigDecimal(0));
- DB.update(TABLE_NAME, setValues, DB.WHERE("cart_id = ?", cart.getId()));
+ DB.UPDATE(TABLE_NAME)
+ .SET("quantity_free", new BigDecimal(0))
+ .WHERE("cart_id = ?", cart.getId())
+ .execute();
}
private static CartItem buildRecord(ResultSet rs) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/CartRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/CartRepository.java
index b50baac82..c45132237 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/CartRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/CartRepository.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,17 +28,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.simisinc.platform.domain.model.ecommerce.Cart;
import com.simisinc.platform.domain.model.ecommerce.CartItem;
import com.simisinc.platform.domain.model.ecommerce.Product;
import com.simisinc.platform.domain.model.ecommerce.ProductSku;
import com.simisinc.platform.domain.model.ecommerce.ShippingRate;
-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 cart objects
@@ -53,57 +52,52 @@ public class CartRepository {
private static String[] PRIMARY_KEY = new String[] { "cart_id" };
public static List findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- null,
- new DataConstraints().setDefaultColumnToSortBy("cart_id desc"),
- CartRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ DataConstraints constraints = new DataConstraints().setDefaultColumnToSortBy("cart_id desc");
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WITH(constraints)
+ .returnDataResult(CartRepository::buildRecord).getRecords();
}
public static Cart findById(long cartId) {
- return (Cart) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("cart_id = ?", cartId),
- CartRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("cart_id = ?", cartId)
+ .returnRecord(CartRepository::buildRecord);
}
public static Cart findValidCartByToken(String token) {
if (StringUtils.isBlank(token)) {
return null;
}
- return (Cart) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("cart_unique_id = ?", token)
- .AND("(expires IS NULL OR expires > ?)", new Timestamp(System.currentTimeMillis()))
- .AND("enabled = ?", true),
- CartRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("cart_unique_id = ?", token)
+ .AND("(expires IS NULL OR expires > ?)", new Timestamp(System.currentTimeMillis()))
+ .AND("enabled = ?", true)
+ .returnRecord(CartRepository::buildRecord);
}
public static Cart add(Cart record) {
- SqlUtils insertValues = new SqlUtils()
- .add("cart_unique_id", record.getToken())
- .addIfExists("visitor_id", record.getVisitorId(), -1)
- .addIfExists("session_id", record.getSessionId())
- .addIfExists("customer_id", record.getCustomerId(), -1)
- // .addIfExists("shipping_method", record.getShippingMethodId(), -1)
- .addIfExists("user_id", record.getUserId(), -1)
- .addIfExists("total_items", record.getTotalItems(), 0)
- .add("total_qty", record.getTotalQty())
- .addIfExists("currency", record.getCurrency())
- .add("subtotal_amount", record.getSubtotalAmount())
- .addIfExists("order_id", record.getOrderId(), -1)
- .addIfExists("order_date", record.getOrderDate())
- .addIfExists("expires", record.getExpires())
- .addIfExists("discount_amount", record.getDiscount())
- .addIfExists("promo_code", record.getPromoCode())
- .addIfExists("pricing_rule_1", record.getPricingRuleId(), -1)
- .addIfExists("created_by", record.getCreatedBy(), -1)
- .addIfExists("modified_by", record.getModifiedBy(), -1);
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ record.setId(DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("cart_unique_id", record.getToken())
+ .FIELD_UNLESS_MATCHES("visitor_id", record.getVisitorId(), -1)
+ .FIELD_UNLESS_NULL("session_id", record.getSessionId())
+ .FIELD_UNLESS_MATCHES("customer_id", record.getCustomerId(), -1)
+ .FIELD_UNLESS_MATCHES("user_id", record.getUserId(), -1)
+ .FIELD_UNLESS_MATCHES("total_items", record.getTotalItems(), 0)
+ .FIELD("total_qty", record.getTotalQty())
+ .FIELD_UNLESS_NULL("currency", record.getCurrency())
+ .FIELD("subtotal_amount", record.getSubtotalAmount())
+ .FIELD_UNLESS_MATCHES("order_id", record.getOrderId(), -1)
+ .FIELD_UNLESS_NULL("order_date", record.getOrderDate())
+ .FIELD_UNLESS_NULL("expires", record.getExpires())
+ .FIELD_UNLESS_NULL("discount_amount", record.getDiscount())
+ .FIELD_UNLESS_NULL("promo_code", record.getPromoCode())
+ .FIELD_UNLESS_MATCHES("pricing_rule_1", record.getPricingRuleId(), -1)
+ .FIELD_UNLESS_MATCHES("created_by", record.getCreatedBy(), -1)
+ .FIELD_UNLESS_MATCHES("modified_by", record.getModifiedBy(), -1)
+ .execute());
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -122,13 +116,13 @@ public static boolean addProductToCart(Cart cart, Product product, ProductSku pr
// In a transaction (use the existing connection)
CartItemRepository.addProductToCart(connection, cart, product, productSku, quantity);
// Update the totals
- SqlUtils update = new SqlUtils()
- .add("total_items = total_items + 1")
- .add("total_qty = total_qty + " + quantity)
- .add("subtotal_amount = subtotal_amount + " + productSku.getPrice().multiply(quantity))
- .add("modified", new Timestamp(System.currentTimeMillis()));
- DB.update(connection, TABLE_NAME, update, DB.WHERE("cart_id = ?", cart.getId()));
- // Finish the transaction
+ DB.UPDATE(TABLE_NAME)
+ .SET("total_items = total_items + 1")
+ .SET("total_qty = total_qty + " + quantity)
+ .SET("subtotal_amount = subtotal_amount + " + productSku.getPrice().multiply(quantity))
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("cart_id = ?", cart.getId())
+ .execute(connection);
transaction.commit();
return true;
} catch (SQLException se) {
@@ -147,14 +141,13 @@ public static boolean updateCart(Cart cart, List cartItemList) {
AutoRollback transaction = new AutoRollback(connection)) {
// In a transaction (use the existing connection)
CartItemRepository.updateCartItemList(connection, cartItemList);
- // Update the totals (and reset invalid items)
- SqlUtils update = new SqlUtils()
- .add("total_items", cart.getTotalItems())
- .add("total_qty", cart.getTotalQty())
- .add("subtotal_amount", cart.getSubtotalAmount())
- .add("modified", new Timestamp(System.currentTimeMillis()));
- DB.update(connection, TABLE_NAME, update, DB.WHERE("cart_id = ?", cart.getId()));
- // Finish the transaction
+ DB.UPDATE(TABLE_NAME)
+ .SET("total_items", cart.getTotalItems())
+ .SET("total_qty", cart.getTotalQty())
+ .SET("subtotal_amount", cart.getSubtotalAmount())
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("cart_id = ?", cart.getId())
+ .execute(connection);
transaction.commit();
return true;
} catch (SQLException se) {
@@ -171,14 +164,13 @@ public static boolean updateDiscount(Cart cart) {
try (Connection connection = DB.getConnection();
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
- // Update the rates and taxes
- SqlUtils update = new SqlUtils()
- .add("discount_amount", cart.getDiscount())
- .add("promo_code", cart.getPromoCode())
- .add("pricing_rule_1", cart.getPricingRuleId(), -1)
- .add("modified", new Timestamp(System.currentTimeMillis()));
- DB.update(connection, TABLE_NAME, update, DB.WHERE("cart_id = ?", cart.getId()));
- // Finish the transaction
+ DB.UPDATE(TABLE_NAME)
+ .SET("discount_amount", cart.getDiscount())
+ .SET("promo_code", cart.getPromoCode())
+ .SET_UNLESS_MATCHES("pricing_rule_1", cart.getPricingRuleId(), -1)
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("cart_id = ?", cart.getId())
+ .execute(connection);
transaction.commit();
return true;
} catch (SQLException se) {
@@ -200,19 +192,18 @@ public static boolean updateShippingRateAndTaxes(Cart cart) {
try (Connection connection = DB.getConnection();
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
- // Update the rates and taxes
- SqlUtils update = new SqlUtils()
- .add("shipping_method", shippingMethod, -1)
- .add("shipping_rate_id", cart.getShippingRateId(), -1)
- .add("handling_fee_amount", cart.getHandlingFee())
- .add("handling_fee_tax_amount", cart.getHandlingTax())
- .add("shipping_amount", cart.getShippingFee())
- .add("shipping_tax_amount", cart.getShippingTax())
- .add("tax_amount", cart.getTaxAmount())
- .add("tax_rate", cart.getTaxRate())
- .add("modified", new Timestamp(System.currentTimeMillis()));
- DB.update(connection, TABLE_NAME, update, DB.WHERE("cart_id = ?", cart.getId()));
- // Finish the transaction
+ DB.UPDATE(TABLE_NAME)
+ .SET("shipping_method", shippingMethod == -1 ? null : shippingMethod)
+ .SET("shipping_rate_id", cart.getShippingRateId() == -1 ? null : cart.getShippingRateId())
+ .SET("handling_fee_amount", cart.getHandlingFee())
+ .SET("handling_fee_tax_amount", cart.getHandlingTax())
+ .SET("shipping_amount", cart.getShippingFee())
+ .SET("shipping_tax_amount", cart.getShippingTax())
+ .SET("tax_amount", cart.getTaxAmount())
+ .SET("tax_rate", cart.getTaxRate())
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("cart_id = ?", cart.getId())
+ .execute(connection);
transaction.commit();
return true;
} catch (SQLException se) {
@@ -222,10 +213,11 @@ public static boolean updateShippingRateAndTaxes(Cart cart) {
}
public static Cart updateCustomer(Cart cart) {
- SqlUtils updateValues = new SqlUtils()
- .add("customer_id", cart.getCustomerId(), -1)
- .add("modified", new Timestamp(System.currentTimeMillis()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("cart_id = ?", cart.getId()))) {
+ if (DB.UPDATE(TABLE_NAME)
+ .SET("customer_id", cart.getCustomerId() == -1 ? null : cart.getCustomerId())
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("cart_id = ?", cart.getId())
+ .execute().booleanValue()) {
return cart;
}
LOG.error("updateCustomer failed!");
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/CustomerRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/CustomerRepository.java
index ee7f67dae..2c40cd3e6 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/CustomerRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/CustomerRepository.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,16 +28,17 @@
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.routines.checkdigit.CheckDigitException;
+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.ecommerce.SaveCustomerCommand;
import com.simisinc.platform.domain.model.ecommerce.Address;
import com.simisinc.platform.domain.model.ecommerce.Customer;
-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 customer objects
@@ -51,35 +53,37 @@ public class CustomerRepository {
private static String TABLE_NAME = "customers";
private static String[] PRIMARY_KEY = new String[] { "customer_id" };
- private static DataResult query(CustomerSpecification specification, DataConstraints constraints) {
- SqlWhere where = null;
+ private static DataResult query(CustomerSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("*").FROM(TABLE_NAME).WHERE();
if (specification != null) {
- where = DB.WHERE()
- .andAddIfHasValue("customer_id = ?", specification.getId(), -1)
- .andAddIfHasValue("LOWER(email) = ?",
- specification.getEmail() != null ? specification.getEmail().toLowerCase() : null);
+ if (specification.getId() > -1) {
+ select.AND("customer_id = ?", specification.getId());
+ }
+ if (StringUtils.isNotBlank(specification.getEmail())) {
+ select.AND("LOWER(email) = ?", specification.getEmail().toLowerCase());
+ }
if (StringUtils.isNotBlank(specification.getUniqueId())) {
- where
- .AND("(LOWER(customer_unique_id) = LOWER(?) OR LOWER(customer_unique_id) LIKE LOWER(?))",
- new String[] { specification.getUniqueId(), specification.getUniqueId() + "%" });
+ select.AND("(LOWER(customer_unique_id) = LOWER(?) OR LOWER(customer_unique_id) LIKE LOWER(?))",
+ specification.getUniqueId(), specification.getUniqueId() + "%");
}
if (StringUtils.isNotBlank(specification.getOrderNumber())) {
- where
- .AND("EXISTS (SELECT 1 FROM orders WHERE customers.customer_id = orders.customer_id AND LOWER(order_unique_id) = ?)",
- specification.getOrderNumber().toLowerCase());
+ select.AND("EXISTS (SELECT 1 FROM orders WHERE customers.customer_id = orders.customer_id AND LOWER(order_unique_id) = ?)",
+ specification.getOrderNumber().toLowerCase());
}
if (StringUtils.isNotBlank(specification.getPhoneNumber())) {
- where
- .AND("phone_number = ?", specification.getPhoneNumber());
+ select.AND("phone_number = ?", specification.getPhoneNumber());
}
if (StringUtils.isNotBlank(specification.getName())) {
- where
- .AND(
- "(LOWER(concat_ws(' ', first_name, last_name)) LIKE LOWER(?) ESCAPE '!' OR LOWER(concat_ws(' ', shipping_first_name, shipping_last_name)) LIKE LOWER(?) ESCAPE '!')",
- new String[] { "%" + specification.getName() + "%", "%" + specification.getName() + "%" });
+ select.AND(
+ "(LOWER(concat_ws(' ', first_name, last_name)) LIKE LOWER(?) ESCAPE '!' OR LOWER(concat_ws(' ', shipping_first_name, shipping_last_name)) LIKE LOWER(?) ESCAPE '!')",
+ "%" + specification.getName() + "%",
+ "%" + specification.getName() + "%");
}
}
- return DB.selectAllFrom(TABLE_NAME, where, constraints, CustomerRepository::buildRecord);
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(CustomerRepository::buildRecord);
}
public static List findAll(CustomerSpecification specification, DataConstraints constraints) {
@@ -92,10 +96,10 @@ public static List findAll(CustomerSpecification specification, DataCo
}
public static Customer findById(long customerId) {
- return (Customer) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("customer_id = ?", customerId),
- CustomerRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("customer_id = ?", customerId)
+ .returnRecord(CustomerRepository::buildRecord);
}
public static Customer save(Customer record) {
@@ -111,65 +115,73 @@ public static Customer add(Customer record) {
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
// In a transaction (use the existing connection)
- SqlUtils insertValues = new SqlUtils()
- .add("customer_unique_id", record.getUniqueId())
- .add("email", record.getEmail())
- .add("first_name", record.getFirstName())
- .add("last_name", record.getLastName())
- .add("organization", record.getOrganization())
- .add("barcode", record.getBarcode())
+
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("customer_unique_id", record.getUniqueId())
+ .FIELD("email", record.getEmail())
+ .FIELD("first_name", record.getFirstName())
+ .FIELD("last_name", record.getLastName())
+ .FIELD("organization", record.getOrganization())
+ .FIELD("barcode", record.getBarcode())
/*
- * .add("street_address", record.getStreet()) .add("address_line_2",
- * record.getAddressLine2()) .add("address_line_3", record.getAddressLine3())
- * .add("city", record.getCity()) .add("state", record.getState())
- * .add("country", record.getCountry()) .add("postal_code",
- * record.getPostalCode()) .add("county", record.getCounty())
+ * .FIELD("street_address", record.getStreet()) .FIELD("address_line_2",
+ * record.getAddressLine2()) .FIELD("address_line_3",
+ * record.getAddressLine3()) .FIELD("city", record.getCity())
+ * .FIELD("state", record.getState()) .FIELD("country",
+ * record.getCountry()) .FIELD("postal_code", record.getPostalCode())
+ * .FIELD("county", record.getCounty())
*/
- .add("phone_number", record.getPhoneNumber())
- .add("tax_id", record.getTaxId())
- .add("remote_customer_id", record.getRemoteCustomerId())
- .addIfExists("created_by", record.getCreatedBy(), -1)
- .addIfExists("modified_by", record.getModifiedBy(), -1);
+ .FIELD("phone_number", record.getPhoneNumber())
+ .FIELD("tax_id", record.getTaxId())
+ .FIELD("remote_customer_id", record.getRemoteCustomerId())
+ .FIELD_UNLESS_MATCHES("created_by", record.getCreatedBy(), -1)
+ .FIELD_UNLESS_MATCHES("modified_by", record.getModifiedBy(), -1);
if (record.getBillingAddress() != null) {
- insertValues.add("billing_first_name", record.getBillingAddress().getFirstName())
- .add("billing_last_name", record.getBillingAddress().getLastName())
- .add("billing_organization", record.getBillingAddress().getOrganization())
- .add("billing_street_address", record.getBillingAddress().getStreet())
- .add("billing_address_line_2", record.getBillingAddress().getAddressLine2())
- .add("billing_address_line_3", record.getBillingAddress().getAddressLine3())
- .add("billing_city", record.getBillingAddress().getCity())
- .add("billing_state", record.getBillingAddress().getState())
- .add("billing_country", record.getBillingAddress().getCountry())
- .add("billing_postal_code", record.getBillingAddress().getPostalCode())
- .add("billing_county", record.getBillingAddress().getCounty())
- .add("billing_phone_number", record.getBillingAddress().getPhoneNumber());
+ insert
+ .FIELD("billing_first_name", record.getBillingAddress().getFirstName())
+ .FIELD("billing_last_name", record.getBillingAddress().getLastName())
+ .FIELD("billing_organization", record.getBillingAddress().getOrganization())
+ .FIELD("billing_street_address", record.getBillingAddress().getStreet())
+ .FIELD("billing_address_line_2", record.getBillingAddress().getAddressLine2())
+ .FIELD("billing_address_line_3", record.getBillingAddress().getAddressLine3())
+ .FIELD("billing_city", record.getBillingAddress().getCity())
+ .FIELD("billing_state", record.getBillingAddress().getState())
+ .FIELD("billing_country", record.getBillingAddress().getCountry())
+ .FIELD("billing_postal_code", record.getBillingAddress().getPostalCode())
+ .FIELD("billing_county", record.getBillingAddress().getCounty())
+ .FIELD("billing_phone_number", record.getBillingAddress().getPhoneNumber());
}
if (record.getShippingAddress() != null) {
- insertValues.add("shipping_first_name", record.getShippingAddress().getFirstName())
- .add("shipping_last_name", record.getShippingAddress().getLastName())
- .add("shipping_organization", record.getShippingAddress().getOrganization())
- .add("shipping_street_address", record.getShippingAddress().getStreet())
- .add("shipping_address_line_2", record.getShippingAddress().getAddressLine2())
- .add("shipping_address_line_3", record.getShippingAddress().getAddressLine3())
- .add("shipping_city", record.getShippingAddress().getCity())
- .add("shipping_state", record.getShippingAddress().getState())
- .add("shipping_country", record.getShippingAddress().getCountry())
- .add("shipping_postal_code", record.getShippingAddress().getPostalCode())
- .add("shipping_county", record.getShippingAddress().getCounty())
- .add("shipping_phone_number", record.getShippingAddress().getPhoneNumber());
- }
- record.setId(DB.insertInto(connection, TABLE_NAME, insertValues, PRIMARY_KEY));
- {
- // Generate a new customer unique id
- LOG.debug("Updating customer unique id for id: " + record.getId());
- SqlUtils update = new SqlUtils().add("customer_unique_id", SaveCustomerCommand.generateUniqueId(record));
- DB.update(connection, TABLE_NAME, update, DB.WHERE("customer_id = ?", record.getId()));
+ insert
+ .FIELD("shipping_first_name", record.getShippingAddress().getFirstName())
+ .FIELD("shipping_last_name", record.getShippingAddress().getLastName())
+ .FIELD("shipping_organization", record.getShippingAddress().getOrganization())
+ .FIELD("shipping_street_address", record.getShippingAddress().getStreet())
+ .FIELD("shipping_address_line_2", record.getShippingAddress().getAddressLine2())
+ .FIELD("shipping_address_line_3", record.getShippingAddress().getAddressLine3())
+ .FIELD("shipping_city", record.getShippingAddress().getCity())
+ .FIELD("shipping_state", record.getShippingAddress().getState())
+ .FIELD("shipping_country", record.getShippingAddress().getCountry())
+ .FIELD("shipping_postal_code", record.getShippingAddress().getPostalCode())
+ .FIELD("shipping_county", record.getShippingAddress().getCounty())
+ .FIELD("shipping_phone_number", record.getShippingAddress().getPhoneNumber());
}
+ record.setId(insert.execute(connection));
+
+ // Generate a new customer unique id
+ LOG.debug("Updating customer unique id for id: " + record.getId());
+ DB.UPDATE(TABLE_NAME)
+ .SET("customer_unique_id", SaveCustomerCommand.generateUniqueId(record))
+ .WHERE("customer_id = ?", record.getId())
+ .execute(connection);
+
if (record.getCartId() > 0) {
- // Update the cart
+ // Update the cart with the customer id
LOG.debug("Updating cart " + record.getCartId() + " with the customer id");
- SqlUtils updateValues = new SqlUtils().add("customer_id", record.getId());
- DB.update(connection, "carts", updateValues, DB.WHERE("cart_id = ?", record.getCartId()));
+ DB.UPDATE("carts")
+ .SET("customer_id", record.getId())
+ .WHERE("cart_id = ?", record.getCartId())
+ .execute(connection);
}
// Finish the transaction
transaction.commit();
@@ -181,89 +193,95 @@ public static Customer add(Customer record) {
}
public static Customer update(Customer record) {
- SqlUtils updateValues = new SqlUtils()
- .add("email", record.getEmail())
- .add("first_name", record.getFirstName())
- .add("last_name", record.getLastName())
- .add("organization", record.getOrganization())
- .add("barcode", record.getBarcode())
+ if (record.getId() == -1) {
+ LOG.debug("Can't update customer -1");
+ return null;
+ }
+
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("email", record.getEmail())
+ .SET("first_name", record.getFirstName())
+ .SET("last_name", record.getLastName())
+ .SET("organization", record.getOrganization())
+ .SET("barcode", record.getBarcode())
/*
- * .add("street_address", record.getStreet()) .add("address_line_2",
- * record.getAddressLine2()) .add("address_line_3", record.getAddressLine3())
- * .add("city", record.getCity()) .add("state", record.getState())
- * .add("country", record.getCountry()) .add("postal_code",
- * record.getPostalCode()) .add("county", record.getCounty())
+ * .SET("street_address", record.getStreet()) .SET("address_line_2",
+ * record.getAddressLine2()) .SET("address_line_3",
+ * record.getAddressLine3()) .SET("city", record.getCity())
+ * .SET("state", record.getState()) .SET("country",
+ * record.getCountry()) .SET("postal_code", record.getPostalCode())
+ * .SET("county", record.getCounty())
*/
- .add("phone_number", record.getPhoneNumber())
- .add("tax_id", record.getTaxId())
- .add("remote_customer_id", record.getRemoteCustomerId())
- .addIfExists("modified_by", record.getModifiedBy(), -1)
- .add("modified", new Timestamp(System.currentTimeMillis()));
+ .SET("phone_number", record.getPhoneNumber())
+ .SET("tax_id", record.getTaxId())
+ .SET("remote_customer_id", record.getRemoteCustomerId())
+ .SET_UNLESS_MATCHES("modified_by", record.getModifiedBy(), -1)
+ .SET("modified", new Timestamp(System.currentTimeMillis()));
if (record.getBillingAddress() != null) {
LOG.debug("Updating the billing information...");
- updateValues
- .add("billing_first_name", record.getBillingAddress().getFirstName())
- .add("billing_last_name", record.getBillingAddress().getLastName())
- .add("billing_organization", record.getBillingAddress().getOrganization())
- .add("billing_street_address", record.getBillingAddress().getStreet())
- .add("billing_address_line_2", record.getBillingAddress().getAddressLine2())
- .add("billing_address_line_3", record.getBillingAddress().getAddressLine3())
- .add("billing_city", record.getBillingAddress().getCity())
- .add("billing_state", record.getBillingAddress().getState())
- .add("billing_country", record.getBillingAddress().getCountry())
- .add("billing_postal_code", record.getBillingAddress().getPostalCode())
- .add("billing_county", record.getBillingAddress().getCounty())
- .add("billing_phone_number", record.getBillingAddress().getPhoneNumber());
+ update
+ .SET("billing_first_name", record.getBillingAddress().getFirstName())
+ .SET("billing_last_name", record.getBillingAddress().getLastName())
+ .SET("billing_organization", record.getBillingAddress().getOrganization())
+ .SET("billing_street_address", record.getBillingAddress().getStreet())
+ .SET("billing_address_line_2", record.getBillingAddress().getAddressLine2())
+ .SET("billing_address_line_3", record.getBillingAddress().getAddressLine3())
+ .SET("billing_city", record.getBillingAddress().getCity())
+ .SET("billing_state", record.getBillingAddress().getState())
+ .SET("billing_country", record.getBillingAddress().getCountry())
+ .SET("billing_postal_code", record.getBillingAddress().getPostalCode())
+ .SET("billing_county", record.getBillingAddress().getCounty())
+ .SET("billing_phone_number", record.getBillingAddress().getPhoneNumber());
} else {
LOG.debug("Resetting the billing information...");
- updateValues
- .add("billing_first_name", (String) null)
- .add("billing_last_name", (String) null)
- .add("billing_organization", (String) null)
- .add("billing_street_address", (String) null)
- .add("billing_address_line_2", (String) null)
- .add("billing_address_line_3", (String) null)
- .add("billing_city", (String) null)
- .add("billing_state", (String) null)
- .add("billing_country", (String) null)
- .add("billing_postal_code", (String) null)
- .add("billing_county", (String) null)
- .add("billing_phone_number", (String) null);
+ update
+ .SET("billing_first_name", (String) null)
+ .SET("billing_last_name", (String) null)
+ .SET("billing_organization", (String) null)
+ .SET("billing_street_address", (String) null)
+ .SET("billing_address_line_2", (String) null)
+ .SET("billing_address_line_3", (String) null)
+ .SET("billing_city", (String) null)
+ .SET("billing_state", (String) null)
+ .SET("billing_country", (String) null)
+ .SET("billing_postal_code", (String) null)
+ .SET("billing_county", (String) null)
+ .SET("billing_phone_number", (String) null);
}
if (record.getShippingAddress() != null) {
LOG.debug("Updating the shipping information...");
- updateValues
- .add("shipping_first_name", record.getShippingAddress().getFirstName())
- .add("shipping_last_name", record.getShippingAddress().getLastName())
- .add("shipping_organization", record.getShippingAddress().getOrganization())
- .add("shipping_street_address", record.getShippingAddress().getStreet())
- .add("shipping_address_line_2", record.getShippingAddress().getAddressLine2())
- .add("shipping_address_line_3", record.getShippingAddress().getAddressLine3())
- .add("shipping_city", record.getShippingAddress().getCity())
- .add("shipping_state", record.getShippingAddress().getState())
- .add("shipping_country", record.getShippingAddress().getCountry())
- .add("shipping_postal_code", record.getShippingAddress().getPostalCode())
- .add("shipping_county", record.getShippingAddress().getCounty())
- .add("shipping_phone_number", record.getShippingAddress().getPhoneNumber());
+ update
+ .SET("shipping_first_name", record.getShippingAddress().getFirstName())
+ .SET("shipping_last_name", record.getShippingAddress().getLastName())
+ .SET("shipping_organization", record.getShippingAddress().getOrganization())
+ .SET("shipping_street_address", record.getShippingAddress().getStreet())
+ .SET("shipping_address_line_2", record.getShippingAddress().getAddressLine2())
+ .SET("shipping_address_line_3", record.getShippingAddress().getAddressLine3())
+ .SET("shipping_city", record.getShippingAddress().getCity())
+ .SET("shipping_state", record.getShippingAddress().getState())
+ .SET("shipping_country", record.getShippingAddress().getCountry())
+ .SET("shipping_postal_code", record.getShippingAddress().getPostalCode())
+ .SET("shipping_county", record.getShippingAddress().getCounty())
+ .SET("shipping_phone_number", record.getShippingAddress().getPhoneNumber());
} else {
LOG.debug("Resetting the shipping information...");
- updateValues
- .add("shipping_first_name", (String) null)
- .add("shipping_last_name", (String) null)
- .add("shipping_organization", (String) null)
- .add("shipping_street_address", (String) null)
- .add("shipping_address_line_2", (String) null)
- .add("shipping_address_line_3", (String) null)
- .add("shipping_city", (String) null)
- .add("shipping_state", (String) null)
- .add("shipping_country", (String) null)
- .add("shipping_postal_code", (String) null)
- .add("shipping_county", (String) null)
- .add("shipping_phone_number", (String) null);
+ update
+ .SET("shipping_first_name", (String) null)
+ .SET("shipping_last_name", (String) null)
+ .SET("shipping_organization", (String) null)
+ .SET("shipping_street_address", (String) null)
+ .SET("shipping_address_line_2", (String) null)
+ .SET("shipping_address_line_3", (String) null)
+ .SET("shipping_city", (String) null)
+ .SET("shipping_state", (String) null)
+ .SET("shipping_country", (String) null)
+ .SET("shipping_postal_code", (String) null)
+ .SET("shipping_county", (String) null)
+ .SET("shipping_phone_number", (String) null);
}
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("customer_id = ?", record.getId()))) {
- // CacheManager.invalidateKey(CacheManager.CONTENT_UNIQUE_ID_CACHE,
- // record.getUniqueId());
+ update
+ .WHERE("customer_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("The update failed!");
@@ -276,11 +294,12 @@ public static void updateContactInfo(Customer record) {
return;
}
LOG.debug("Updating the customer record");
- SqlUtils set = new SqlUtils()
- .add("first_name", record.getFirstName())
- .add("last_name", record.getLastName())
- .add("email", record.getEmail());
- DB.update(TABLE_NAME, set, DB.WHERE("customer_id = ?", record.getId()));
+ DB.UPDATE(TABLE_NAME)
+ .SET("first_name", record.getFirstName())
+ .SET("last_name", record.getLastName())
+ .SET("email", record.getEmail())
+ .WHERE("customer_id = ?", record.getId())
+ .execute();
}
private static Customer buildRecord(ResultSet rs) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/FulfillmentOptionRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/FulfillmentOptionRepository.java
index 6e8973b1f..2a0d2b9fc 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/FulfillmentOptionRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/FulfillmentOptionRepository.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,6 @@
package com.simisinc.platform.infrastructure.persistence.ecommerce;
-import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@@ -25,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.DataResult;
+import com.github.rajkowski.database.Insert;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.domain.model.ecommerce.FulfillmentOption;
-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.DataResult;
-import com.simisinc.platform.infrastructure.database.SqlUtils;
/**
* Persists and retrieves fulfillment option objects
@@ -46,49 +45,35 @@ public class FulfillmentOptionRepository {
private static String[] PRIMARY_KEY = new String[] { "fulfillment_id" };
public static List findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- DB.WHERE("enabled = ?", true),
- null,
- FulfillmentOptionRepository::buildRecord);
- List recordList = (List) result.getRecords();
- return recordList;
+ DataResult result = DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("enabled = ?", true)
+ .returnDataResult(FulfillmentOptionRepository::buildRecord);
+ return result.getRecords();
}
public static FulfillmentOption findById(long id) {
if (id == -1) {
return null;
}
- return (FulfillmentOption) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("fulfillment_id = ?", id),
- FulfillmentOptionRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("fulfillment_id = ?", id)
+ .returnRecord(FulfillmentOptionRepository::buildRecord);
}
public static FulfillmentOption findByCode(String code) {
if (StringUtils.isBlank(code)) {
return null;
}
- return (FulfillmentOption) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("code = ?", code),
- FulfillmentOptionRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("code = ?", code)
+ .returnRecord(FulfillmentOptionRepository::buildRecord);
}
public static boolean remove(FulfillmentOption record) {
- try (Connection connection = DB.getConnection();
- AutoStartTransaction a = new AutoStartTransaction(connection);
- AutoRollback transaction = new AutoRollback(connection)) {
- // Delete the record
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("fulfillment_id = ?", record.getId()));
- // Finish transaction
- transaction.commit();
- return true;
- } catch (SQLException se) {
- LOG.error("SQLException: " + se.getMessage());
- }
- LOG.error("The delete failed!");
- return false;
+ return DB.DELETE().FROM(TABLE_NAME).WHERE("fulfillment_id = ?", record.getId()).execute();
}
public static FulfillmentOption save(FulfillmentOption record) {
@@ -99,44 +84,29 @@ public static FulfillmentOption save(FulfillmentOption record) {
}
public static FulfillmentOption add(FulfillmentOption record) {
- SqlUtils insertValues = new SqlUtils()
- .add("code", StringUtils.trimToNull(record.getCode()))
- .add("title", StringUtils.trimToNull(record.getTitle()))
- .add("enabled", record.getEnabled())
- .add("overrides_others", record.getOverridesOthers());
- // 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));
- // Finish the transaction
- transaction.commit();
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("code", StringUtils.trimToNull(record.getCode()))
+ .FIELD("title", StringUtils.trimToNull(record.getTitle()))
+ .FIELD("enabled", record.getEnabled())
+ .FIELD("overrides_others", record.getOverridesOthers());
+ long generatedId = insert.execute();
+ if (insert.isSuccess()) {
+ record.setId(generatedId);
return record;
- } catch (SQLException se) {
- LOG.error("SQLException: " + se.getMessage());
}
LOG.error("An id was not set!");
return null;
}
public static FulfillmentOption update(FulfillmentOption record) {
- SqlUtils updateValues = new SqlUtils()
- .add("code", StringUtils.trimToNull(record.getCode()))
- .add("title", StringUtils.trimToNull(record.getTitle()))
- .add("enabled", record.getEnabled())
- .add("overrides_others", record.getOverridesOthers());
- // 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("fulfillment_id = ?", record.getId()));
- // Finish the transaction
- transaction.commit();
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("code", StringUtils.trimToNull(record.getCode()))
+ .SET("title", StringUtils.trimToNull(record.getTitle()))
+ .SET("enabled", record.getEnabled())
+ .SET("overrides_others", record.getOverridesOthers())
+ .WHERE("fulfillment_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
- } catch (SQLException se) {
- LOG.error("SQLException: " + se.getMessage(), se);
}
return null;
}
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/OrderItemRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/OrderItemRepository.java
index 8c53b7222..dad3cfc36 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/OrderItemRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/OrderItemRepository.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");
@@ -31,15 +32,13 @@
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.simisinc.platform.application.ecommerce.OrderStatusCommand;
import com.simisinc.platform.domain.model.ecommerce.Order;
import com.simisinc.platform.domain.model.ecommerce.OrderItem;
-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 order item objects
@@ -55,19 +54,18 @@ public class OrderItemRepository {
private static String[] PRIMARY_KEY = new String[] { "item_id" };
public static List findItemsByOrderId(long orderId) {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- DB.WHERE("order_id = ?", orderId),
- new DataConstraints().setDefaultColumnToSortBy("item_id").setUseCount(false),
- OrderItemRepository::buildRecord);
- return (List) result.getRecords();
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("order_id = ?", orderId)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("item_id").setUseCount(false))
+ .returnDataResult(OrderItemRepository::buildRecord).getRecords();
}
public static OrderItem findById(long itemId) {
- return (OrderItem) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("item_id = ?", itemId),
- OrderItemRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("item_id = ?", itemId)
+ .returnRecord(OrderItemRepository::buildRecord);
}
public static OrderItem add(OrderItem record) throws SQLException {
@@ -86,37 +84,37 @@ public static OrderItem add(OrderItem record) throws SQLException {
}
public static OrderItem add(Connection connection, OrderItem record) throws SQLException {
- SqlUtils insertValues = new SqlUtils()
- .add("order_id", record.getOrderId(), -1)
- .addIfExists("customer_id", record.getCustomerId(), -1)
- .addIfExists("product_id", record.getProductId(), -1)
- .addIfExists("sku_id", record.getSkuId(), -1)
- .addIfExists("quantity", record.getQuantity())
- .addIfExists("currency", record.getCurrency())
- .addIfExists("each_amount", record.getEachAmount())
- .addIfExists("total_amount", record.getTotalAmount())
- .addIfExists("product_name", record.getProductName())
- .addIfExists("product_type", record.getProductType())
- .addIfExists("product_sku", record.getProductSku())
- .add("is_preorder", record.getPreorder())
- .add("is_backordered", record.getBackordered())
- .add("paid", record.getPaid())
- .add("processed", record.getProcessed())
- .add("shipped", record.getShipped())
- .add("canceled", record.getCanceled())
- .add("refunded", record.getRefunded())
- .addIfExists("created", record.getCreated())
- .addIfExists("created_by", record.getCreatedBy(), -1)
- .addIfExists("modified_by", record.getModifiedBy(), -1)
- .addIfExists("product_barcode", record.getProductBarcode())
- .add("payment_date", record.getPaymentDate())
- .add("processing_date", record.getProcessingDate())
- .add("fulfillment_date", record.getFulfillmentDate())
- .add("shipped_date", record.getShippedDate())
- .add("canceled_date", record.getCanceledDate())
- .add("refunded_date", record.getRefundedDate())
- .add("status", record.getStatusId(), -1);
- record.setId(DB.insertInto(connection, TABLE_NAME, insertValues, PRIMARY_KEY));
+ record.setId(DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("order_id", record.getOrderId() == -1 ? null : record.getOrderId())
+ .FIELD_UNLESS_MATCHES("customer_id", record.getCustomerId(), -1)
+ .FIELD_UNLESS_MATCHES("product_id", record.getProductId(), -1)
+ .FIELD_UNLESS_MATCHES("sku_id", record.getSkuId(), -1)
+ .FIELD_UNLESS_NULL("quantity", record.getQuantity())
+ .FIELD_UNLESS_NULL("currency", record.getCurrency())
+ .FIELD_UNLESS_NULL("each_amount", record.getEachAmount())
+ .FIELD_UNLESS_NULL("total_amount", record.getTotalAmount())
+ .FIELD_UNLESS_NULL("product_name", record.getProductName())
+ .FIELD_UNLESS_NULL("product_type", record.getProductType())
+ .FIELD_UNLESS_NULL("product_sku", record.getProductSku())
+ .FIELD("is_preorder", record.getPreorder())
+ .FIELD("is_backordered", record.getBackordered())
+ .FIELD("paid", record.getPaid())
+ .FIELD("processed", record.getProcessed())
+ .FIELD("shipped", record.getShipped())
+ .FIELD("canceled", record.getCanceled())
+ .FIELD("refunded", record.getRefunded())
+ .FIELD("created", record.getCreated())
+ .FIELD("created_by", record.getCreatedBy() == -1 ? null : record.getCreatedBy())
+ .FIELD("modified_by", record.getModifiedBy() == -1 ? null : record.getModifiedBy())
+ .FIELD_UNLESS_NULL("product_barcode", record.getProductBarcode())
+ .FIELD("payment_date", record.getPaymentDate())
+ .FIELD("processing_date", record.getProcessingDate())
+ .FIELD("fulfillment_date", record.getFulfillmentDate())
+ .FIELD("shipped_date", record.getShippedDate())
+ .FIELD("canceled_date", record.getCanceledDate())
+ .FIELD("refunded_date", record.getRefundedDate())
+ .FIELD("status", record.getStatusId() == -1 ? null : record.getStatusId())
+ .execute(connection));
return record;
}
@@ -166,12 +164,13 @@ public static void markStatusAsPaid(Connection connection, OrderItem orderItem,
int statusId = OrderStatusCommand.retrieveStatusId(PAID);
Timestamp now = new Timestamp(System.currentTimeMillis());
// Update the order item status
- SqlUtils updateValues = new SqlUtils()
- .add("paid", true)
- .add("payment_date", paymentDate)
- .add("status", statusId)
- .add("modified", now);
- DB.update(connection, TABLE_NAME, updateValues, DB.WHERE("item_id = ?", orderItem.getId()));
+ DB.UPDATE(TABLE_NAME)
+ .SET("paid", true)
+ .SET("payment_date", paymentDate)
+ .SET("status", statusId)
+ .SET("modified", now)
+ .WHERE("item_id = ?", orderItem.getId())
+ .execute(connection);
// @todo Append to the order_history (PAID)
// Update the object
orderItem.setModified(now);
@@ -185,12 +184,13 @@ public static void markStatusAsPreparing(OrderItem orderItem) {
int statusId = OrderStatusCommand.retrieveStatusId(PREPARING);
Timestamp now = new Timestamp(System.currentTimeMillis());
// Update the order item status
- SqlUtils updateValues = new SqlUtils()
- .add("processed", true)
- .add("processing_date", now)
- .add("status", statusId)
- .add("modified", now);
- DB.update(TABLE_NAME, updateValues, DB.WHERE("item_id = ?", orderItem.getId()));
+ DB.UPDATE(TABLE_NAME)
+ .SET("processed", true)
+ .SET("processing_date", now)
+ .SET("status", statusId)
+ .SET("modified", now)
+ .WHERE("item_id = ?", orderItem.getId())
+ .execute();
// @todo Append to the order_history (PREPARING)
// Update the object
orderItem.setModified(now);
@@ -204,12 +204,13 @@ public static void markStatusAsShipped(OrderItem orderItem) {
int statusId = OrderStatusCommand.retrieveStatusId(SHIPPED);
Timestamp now = new Timestamp(System.currentTimeMillis());
// Update the order item status
- SqlUtils updateValues = new SqlUtils()
- .add("shipped", true)
- .add("shipped_date", now)
- .add("status", statusId)
- .add("modified", now);
- DB.update(TABLE_NAME, updateValues, DB.WHERE("item_id = ?", orderItem.getId()));
+ DB.UPDATE(TABLE_NAME)
+ .SET("shipped", true)
+ .SET("shipped_date", now)
+ .SET("status", statusId)
+ .SET("modified", now)
+ .WHERE("item_id = ?", orderItem.getId())
+ .execute();
// @todo Append to the order_history (SHIPPED)
// Update the object
orderItem.setModified(now);
@@ -223,12 +224,13 @@ public static void markStatusAsCanceled(Connection connection, Order order) thro
int statusId = OrderStatusCommand.retrieveStatusId(CANCELED);
Timestamp now = new Timestamp(System.currentTimeMillis());
// Update the order item status
- SqlUtils updateValues = new SqlUtils()
- .add("canceled", true)
- .add("canceled_date", now)
- .add("status", statusId)
- .add("modified", now);
- DB.update(connection, TABLE_NAME, updateValues, DB.WHERE("order_id = ?", order.getId()));
+ DB.UPDATE(TABLE_NAME)
+ .SET("canceled", true)
+ .SET("canceled_date", now)
+ .SET("status", statusId)
+ .SET("modified", now)
+ .WHERE("order_id = ?", order.getId())
+ .execute(connection);
}
public static void markStatusAsRefunded(Connection connection, Order order) throws SQLException {
@@ -236,11 +238,12 @@ public static void markStatusAsRefunded(Connection connection, Order order) thro
int statusId = OrderStatusCommand.retrieveStatusId(REFUNDED);
Timestamp now = new Timestamp(System.currentTimeMillis());
// Update the order item status
- SqlUtils updateValues = new SqlUtils()
- .add("refunded", true)
- .add("refunded_date", now)
- .add("status", statusId)
- .add("modified", now);
- DB.update(connection, TABLE_NAME, updateValues, DB.WHERE("order_id = ?", order.getId()));
+ DB.UPDATE(TABLE_NAME)
+ .SET("refunded", true)
+ .SET("refunded_date", now)
+ .SET("status", statusId)
+ .SET("modified", now)
+ .WHERE("order_id = ?", order.getId())
+ .execute(connection);
}
}
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/OrderRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/OrderRepository.java
index 4698e5e19..28f030b92 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/OrderRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/OrderRepository.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");
@@ -38,6 +39,14 @@
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.ecommerce.OrderItemCommand;
import com.simisinc.platform.application.ecommerce.OrderStatusCommand;
import com.simisinc.platform.domain.model.Session;
@@ -47,13 +56,6 @@
import com.simisinc.platform.domain.model.ecommerce.CartItem;
import com.simisinc.platform.domain.model.ecommerce.Order;
import com.simisinc.platform.domain.model.ecommerce.OrderItem;
-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;
/**
@@ -68,66 +70,74 @@ public class OrderRepository {
private static String TABLE_NAME = "orders";
private static String[] PRIMARY_KEY = new String[] { "order_id" };
- private static String STATUS_JOIN = "LEFT JOIN lookup_order_status los ON (orders.status = los.status_id)";
- private static DataResult query(OrderSpecification specification, DataConstraints constraints) {
- SqlWhere where = null;
+ private static DataResult query(OrderSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("*").FROM(TABLE_NAME).WHERE();
if (specification != null) {
- where = DB.WHERE()
- .andAddIfHasValue("order_id = ?", specification.getId(), -1)
- .andAddIfHasValue("customer_id = ?", specification.getCustomerId(), -1)
- .andAddIfHasValue("LOWER(email) = ?", specification.getEmail() != null ? specification.getEmail().toLowerCase() : null)
- .andAddIfHasValue("created_by = ?", specification.getCreatedBy(), -1);
+ if (specification.getId() != -1) {
+ select.AND("order_id = ?", specification.getId());
+ }
+ if (specification.getCustomerId() != -1) {
+ select.AND("customer_id = ?", specification.getCustomerId());
+ }
+ if (specification.getEmail() != null) {
+ select.AND("LOWER(email) = ?", specification.getEmail().toLowerCase());
+ }
+ if (specification.getCreatedBy() != -1) {
+ select.AND("created_by = ?", specification.getCreatedBy());
+ }
if (StringUtils.isNotBlank(specification.getUniqueId())) {
- where.AND("(LOWER(order_unique_id) = LOWER(?) OR LOWER(order_unique_id) LIKE LOWER(?))",
- new String[] { specification.getUniqueId(), specification.getUniqueId() + "%" });
+ select.AND("(LOWER(order_unique_id) = LOWER(?) OR LOWER(order_unique_id) LIKE LOWER(?))",
+ specification.getUniqueId(), specification.getUniqueId() + "%");
}
if (StringUtils.isNotBlank(specification.getCustomerNumber())) {
- where.AND(
+ select.AND(
"EXISTS (SELECT 1 FROM customers WHERE orders.customer_id = customers.customer_id AND LOWER(customer_unique_id) = ?)",
specification.getCustomerNumber().toLowerCase());
}
if (StringUtils.isNotBlank(specification.getPhoneNumber())) {
- where.AND("(billing_phone_number = ? OR shipping_phone_number = ?)",
- new String[] { specification.getPhoneNumber(), specification.getPhoneNumber() });
+ select.AND("(billing_phone_number = ? OR shipping_phone_number = ?)",
+ specification.getPhoneNumber(), specification.getPhoneNumber());
}
if (StringUtils.isNotBlank(specification.getName())) {
- where.AND(
+ select.AND(
"(LOWER(concat_ws(' ', first_name, last_name)) LIKE LOWER(?) ESCAPE '!' OR LOWER(concat_ws(' ', shipping_first_name, shipping_last_name)) LIKE LOWER(?) ESCAPE '!')",
- new String[] { "%" + specification.getName() + "%", "%" + specification.getName() + "%" });
+ "%" + specification.getName() + "%", "%" + specification.getName() + "%");
}
if (specification.getShowSandbox() != DataConstants.UNDEFINED) {
- where.AND("live_mode = ?", specification.getShowSandbox() == DataConstants.FALSE);
+ select.AND("live_mode = ?", specification.getShowSandbox() == DataConstants.FALSE);
}
if (specification.getShowIncompleteOrders() != DataConstants.UNDEFINED) {
- // Completed orders have paid = true
- where.AND("paid = ?", specification.getShowIncompleteOrders() == DataConstants.FALSE);
+ select.AND("paid = ?", specification.getShowIncompleteOrders() == DataConstants.FALSE);
}
if (specification.getShowCanceledOrders() != DataConstants.UNDEFINED) {
- where.AND("canceled = ?", specification.getShowCanceledOrders() == DataConstants.TRUE);
+ select.AND("canceled = ?", specification.getShowCanceledOrders() == DataConstants.TRUE);
}
if (specification.getShowProcessedOrders() != DataConstants.UNDEFINED) {
- where.AND("processed = ?", specification.getShowProcessedOrders() == DataConstants.TRUE);
+ select.AND("processed = ?", specification.getShowProcessedOrders() == DataConstants.TRUE);
}
if (specification.getShowShippedOrders() != DataConstants.UNDEFINED) {
- where.AND("shipped = ?", specification.getShowShippedOrders() == DataConstants.TRUE);
+ select.AND("shipped = ?", specification.getShowShippedOrders() == DataConstants.TRUE);
}
}
- return DB.selectAllFrom(TABLE_NAME, where, constraints, OrderRepository::buildRecord);
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(OrderRepository::buildRecord);
}
public static Order findById(long orderId) {
- return (Order) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("order_id = ?", orderId),
- OrderRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("order_id = ?", orderId)
+ .returnRecord(OrderRepository::buildRecord);
}
public static Order findByUniqueId(String orderUniqueId) {
- return (Order) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("order_unique_id = ?", orderUniqueId),
- OrderRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("order_unique_id = ?", orderUniqueId)
+ .returnRecord(OrderRepository::buildRecord);
}
public static List findAll(OrderSpecification specification, DataConstraints constraints) {
@@ -135,8 +145,7 @@ public static List findAll(OrderSpecification specification, DataConstrai
constraints = new DataConstraints();
}
constraints.setDefaultColumnToSortBy("order_id desc");
- DataResult result = query(specification, constraints);
- return (List) result.getRecords();
+ return query(specification, constraints).getRecords();
}
public static List findDailyUniqueLocations(int daysToLimit) {
@@ -359,111 +368,112 @@ public static Order add(Order record, List cartItemList) {
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
// In a transaction (use the existing connection)
- SqlUtils insertValues = new SqlUtils()
- .add("order_unique_id", record.getUniqueId())
- .addIfExists("customer_id", record.getCustomerId(), -1)
- .add("email", record.getEmail())
- .add("first_name", record.getFirstName())
- .add("last_name", record.getLastName())
- .add("customer_note", record.getCustomerNote())
- .add("barcode", record.getBarcode())
- .add("remote_order_id", record.getRemoteOrderId())
- .add("shipping_method", record.getShippingMethodId(), -1)
- .add("shipping_rate_id", record.getShippingRateId(), -1)
- .add("total_items", record.getTotalItems())
- .addIfExists("currency", record.getCurrency())
- .add("subtotal_amount", record.getSubtotalAmount())
- .addIfExists("discount_amount", record.getDiscountAmount())
- .add("promo_code", record.getPromoCode())
- .add("pricing_rule_1", record.getPricingRuleId(), -1)
- .addIfExists("fee_amount", record.getHandlingFee())
- .addIfExists("fee_tax_amount", record.getHandlingFeeTaxAmount())
- .addIfExists("shipping_amount", record.getShippingFee())
- .addIfExists("shipping_tax_amount", record.getShippingTaxAmount())
- .addIfExists("tax_amount", record.getTaxAmount())
- .addIfExists("tax_rate", record.getTaxRate())
- .addIfExists("total_amount", record.getTotalAmount())
- .addIfExists("total_paid", record.getTotalPaid())
- .addIfExists("total_pending", record.getTotalPending())
- .addIfExists("total_refunded", record.getTotalRefunded())
- .add("status", record.getStatusId(), -1)
- .add("has_preorder", record.getHasPreOrder())
- .add("has_backorder", record.getHasBackOrder())
- .add("paid", record.getPaid())
- .add("processed", record.getProcessed())
- .add("shipped", record.getShipped())
- .add("canceled", record.getCanceled())
- .add("refunded", record.getRefunded())
- .add("tax_id", record.getTaxId())
- .add("cart_id", record.getCartId())
- .add("payment_processor", record.getPaymentProcessor())
- .add("payment_token", record.getPaymentToken())
- .add("payment_type", record.getPaymentType())
- .add("payment_brand", record.getPaymentBrand())
- .add("payment_last4", record.getPaymentLast4())
- .add("payment_fingerprint", record.getPaymentFingerprint())
- .add("payment_country", record.getPaymentCountry())
- .add("charge_token", record.getChargeToken())
- .add("ip_address", record.getIpAddress())
- .add("session_id", record.getSessionId())
- .add("country_iso", record.getCountryIso())
- .add("country", record.getCountry())
- .add("city", record.getCity())
- .add("state_iso", record.getStateIso())
- .add("state", record.getState())
- .add("latitude", record.getLatitude(), 0)
- .add("longitude", record.getLongitude(), 0)
- .add("payment_date", record.getPaymentDate())
- .add("processing_date", record.getProcessingDate())
- .add("fulfillment_date", record.getFulfillmentDate())
- .add("shipped_date", record.getShippedDate())
- .add("canceled_date", record.getCanceledDate())
- .add("refunded_date", record.getRefundedDate())
- .addIfExists("tracking_numbers", record.getTrackingNumbers())
- .addIfExists("square_order_id", record.getSquareOrderId())
- .addIfExists("created_by", record.getCreatedBy(), -1)
- .addIfExists("modified_by", record.getModifiedBy(), -1);
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("order_unique_id", record.getUniqueId())
+ .FIELD_UNLESS_MATCHES("customer_id", record.getCustomerId(), -1)
+ .FIELD("email", record.getEmail())
+ .FIELD("first_name", record.getFirstName())
+ .FIELD("last_name", record.getLastName())
+ .FIELD("customer_note", record.getCustomerNote())
+ .FIELD("barcode", record.getBarcode())
+ .FIELD("remote_order_id", record.getRemoteOrderId())
+ .FIELD("shipping_method", record.getShippingMethodId() == -1 ? null : record.getShippingMethodId())
+ .FIELD("shipping_rate_id", record.getShippingRateId() == -1 ? null : record.getShippingRateId())
+ .FIELD("total_items", record.getTotalItems())
+ .FIELD_UNLESS_NULL("currency", record.getCurrency())
+ .FIELD("subtotal_amount", record.getSubtotalAmount())
+ .FIELD_UNLESS_NULL("discount_amount", record.getDiscountAmount())
+ .FIELD("promo_code", record.getPromoCode())
+ .FIELD("pricing_rule_1", record.getPricingRuleId() == -1 ? null : record.getPricingRuleId())
+ .FIELD_UNLESS_NULL("fee_amount", record.getHandlingFee())
+ .FIELD_UNLESS_NULL("fee_tax_amount", record.getHandlingFeeTaxAmount())
+ .FIELD_UNLESS_NULL("shipping_amount", record.getShippingFee())
+ .FIELD_UNLESS_NULL("shipping_tax_amount", record.getShippingTaxAmount())
+ .FIELD_UNLESS_NULL("tax_amount", record.getTaxAmount())
+ .FIELD_UNLESS_NULL("tax_rate", record.getTaxRate())
+ .FIELD_UNLESS_NULL("total_amount", record.getTotalAmount())
+ .FIELD_UNLESS_NULL("total_paid", record.getTotalPaid())
+ .FIELD_UNLESS_NULL("total_pending", record.getTotalPending())
+ .FIELD_UNLESS_NULL("total_refunded", record.getTotalRefunded())
+ .FIELD("status", record.getStatusId() == -1 ? null : record.getStatusId())
+ .FIELD("has_preorder", record.getHasPreOrder())
+ .FIELD("has_backorder", record.getHasBackOrder())
+ .FIELD("paid", record.getPaid())
+ .FIELD("processed", record.getProcessed())
+ .FIELD("shipped", record.getShipped())
+ .FIELD("canceled", record.getCanceled())
+ .FIELD("refunded", record.getRefunded())
+ .FIELD("tax_id", record.getTaxId())
+ .FIELD("cart_id", record.getCartId())
+ .FIELD("payment_processor", record.getPaymentProcessor())
+ .FIELD("payment_token", record.getPaymentToken())
+ .FIELD("payment_type", record.getPaymentType())
+ .FIELD("payment_brand", record.getPaymentBrand())
+ .FIELD("payment_last4", record.getPaymentLast4())
+ .FIELD("payment_fingerprint", record.getPaymentFingerprint())
+ .FIELD("payment_country", record.getPaymentCountry())
+ .FIELD("charge_token", record.getChargeToken())
+ .FIELD("ip_address", record.getIpAddress())
+ .FIELD("session_id", record.getSessionId())
+ .FIELD("country_iso", record.getCountryIso())
+ .FIELD("country", record.getCountry())
+ .FIELD("city", record.getCity())
+ .FIELD("state_iso", record.getStateIso())
+ .FIELD("state", record.getState())
+ .FIELD("latitude", record.getLatitude())
+ .FIELD("longitude", record.getLongitude())
+ .FIELD("payment_date", record.getPaymentDate())
+ .FIELD("processing_date", record.getProcessingDate())
+ .FIELD("fulfillment_date", record.getFulfillmentDate())
+ .FIELD("shipped_date", record.getShippedDate())
+ .FIELD("canceled_date", record.getCanceledDate())
+ .FIELD("refunded_date", record.getRefundedDate())
+ .FIELD_UNLESS_NULL("tracking_numbers", record.getTrackingNumbers())
+ .FIELD_UNLESS_NULL("square_order_id", record.getSquareOrderId())
+ .FIELD_UNLESS_MATCHES("created_by", record.getCreatedBy(), -1)
+ .FIELD_UNLESS_MATCHES("modified_by", record.getModifiedBy(), -1);
if (record.getBillingAddress() != null) {
- insertValues
- .add("billing_first_name", record.getBillingAddress().getFirstName())
- .add("billing_last_name", record.getBillingAddress().getLastName())
- .add("billing_organization", record.getBillingAddress().getOrganization())
- .add("billing_street_address", record.getBillingAddress().getStreet())
- .add("billing_address_line_2", record.getBillingAddress().getAddressLine2())
- .add("billing_address_line_3", record.getBillingAddress().getAddressLine3())
- .add("billing_city", record.getBillingAddress().getCity())
- .add("billing_state", record.getBillingAddress().getState())
- .add("billing_country", record.getBillingAddress().getCountry())
- .add("billing_postal_code", record.getBillingAddress().getPostalCode())
- .add("billing_county", record.getBillingAddress().getCounty())
- .add("billing_phone_number", record.getBillingAddress().getPhoneNumber())
- .addIfExists("billing_latitude", record.getBillingAddress().getLatitude(), 0)
- .addIfExists("billing_longitude", record.getBillingAddress().getLongitude(), 0);
+ insert
+ .FIELD("billing_first_name", record.getBillingAddress().getFirstName())
+ .FIELD("billing_last_name", record.getBillingAddress().getLastName())
+ .FIELD("billing_organization", record.getBillingAddress().getOrganization())
+ .FIELD("billing_street_address", record.getBillingAddress().getStreet())
+ .FIELD("billing_address_line_2", record.getBillingAddress().getAddressLine2())
+ .FIELD("billing_address_line_3", record.getBillingAddress().getAddressLine3())
+ .FIELD("billing_city", record.getBillingAddress().getCity())
+ .FIELD("billing_state", record.getBillingAddress().getState())
+ .FIELD("billing_country", record.getBillingAddress().getCountry())
+ .FIELD("billing_postal_code", record.getBillingAddress().getPostalCode())
+ .FIELD("billing_county", record.getBillingAddress().getCounty())
+ .FIELD("billing_phone_number", record.getBillingAddress().getPhoneNumber())
+ .FIELD_UNLESS_MATCHES("billing_latitude", record.getBillingAddress().getLatitude(), 0)
+ .FIELD_UNLESS_MATCHES("billing_longitude", record.getBillingAddress().getLongitude(), 0);
}
if (record.getShippingAddress() != null) {
- insertValues
- .add("shipping_first_name", record.getShippingAddress().getFirstName())
- .add("shipping_last_name", record.getShippingAddress().getLastName())
- .add("shipping_organization", record.getShippingAddress().getOrganization())
- .add("shipping_street_address", record.getShippingAddress().getStreet())
- .add("shipping_address_line_2", record.getShippingAddress().getAddressLine2())
- .add("shipping_address_line_3", record.getShippingAddress().getAddressLine3())
- .add("shipping_city", record.getShippingAddress().getCity())
- .add("shipping_state", record.getShippingAddress().getState())
- .add("shipping_country", record.getShippingAddress().getCountry())
- .add("shipping_postal_code", record.getShippingAddress().getPostalCode())
- .add("shipping_county", record.getShippingAddress().getCounty())
- .add("shipping_phone_number", record.getShippingAddress().getPhoneNumber())
- .addIfExists("shipping_latitude", record.getShippingAddress().getLatitude(), 0)
- .addIfExists("shipping_longitude", record.getShippingAddress().getLongitude(), 0);
+ insert
+ .FIELD("shipping_first_name", record.getShippingAddress().getFirstName())
+ .FIELD("shipping_last_name", record.getShippingAddress().getLastName())
+ .FIELD("shipping_organization", record.getShippingAddress().getOrganization())
+ .FIELD("shipping_street_address", record.getShippingAddress().getStreet())
+ .FIELD("shipping_address_line_2", record.getShippingAddress().getAddressLine2())
+ .FIELD("shipping_address_line_3", record.getShippingAddress().getAddressLine3())
+ .FIELD("shipping_city", record.getShippingAddress().getCity())
+ .FIELD("shipping_state", record.getShippingAddress().getState())
+ .FIELD("shipping_country", record.getShippingAddress().getCountry())
+ .FIELD("shipping_postal_code", record.getShippingAddress().getPostalCode())
+ .FIELD("shipping_county", record.getShippingAddress().getCounty())
+ .FIELD("shipping_phone_number", record.getShippingAddress().getPhoneNumber())
+ .FIELD_UNLESS_MATCHES("shipping_latitude", record.getShippingAddress().getLatitude(), 0)
+ .FIELD_UNLESS_MATCHES("shipping_longitude", record.getShippingAddress().getLongitude(), 0);
}
- record.setId(DB.insertInto(connection, TABLE_NAME, insertValues, PRIMARY_KEY));
+ record.setId(insert.execute(connection));
// Update the cart's link
if (record.getCartId() > 0) {
- SqlUtils update = new SqlUtils()
- .add("order_id", record.getId())
- .add("order_date", new Timestamp(System.currentTimeMillis()));
- DB.update(connection, "carts", update, DB.WHERE("cart_id = ?", record.getCartId()));
+ DB.UPDATE("carts")
+ .SET("order_id", record.getId())
+ .SET("order_date", new Timestamp(System.currentTimeMillis()))
+ .WHERE("cart_id = ?", record.getCartId())
+ .execute(connection);
}
// Make a copy of the cart items
if (cartItemList != null && !cartItemList.isEmpty()) {
@@ -487,116 +497,122 @@ public static Order update(Order record) {
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
// In a transaction (use the existing connection)
- SqlUtils updateValues = new SqlUtils()
- .addIfExists("customer_id", record.getCustomerId(), -1)
- .add("email", record.getEmail())
- .add("first_name", record.getFirstName())
- .add("last_name", record.getLastName())
- .add("barcode", record.getBarcode())
- .add("remote_order_id", record.getRemoteOrderId())
- .addIfExists("square_order_id", record.getSquareOrderId())
- .addWhen("live_mode", record.getLive(), true)
- .addWhen("paid", record.getPaid(), true)
- .addIfExists("total_paid", record.getTotalPaid())
- .addWhen("processed", record.getProcessed(), true)
- .addWhen("shipped", record.getShipped(), true)
- .addWhen("canceled", record.getCanceled(), true)
- .addWhen("refunded", record.getRefunded(), true)
- .addIfExists("status", record.getStatusId(), -1)
- .addIfExists("payment_processor", record.getPaymentProcessor())
- .addIfExists("payment_token", record.getPaymentToken())
- .addIfExists("payment_type", record.getPaymentType())
- .addIfExists("payment_brand", record.getPaymentBrand())
- .addIfExists("payment_last4", record.getPaymentLast4())
- .addIfExists("payment_fingerprint", record.getPaymentFingerprint())
- .addIfExists("payment_country", record.getPaymentCountry())
- .addIfExists("payment_date", record.getPaymentDate())
- .add("charge_token", record.getChargeToken())
- .add("ip_address", record.getIpAddress())
- .addIfExists("session_id", record.getSessionId())
- .add("country_iso", record.getCountryIso())
- .add("country", record.getCountry())
- .add("city", record.getCity())
- .add("state_iso", record.getStateIso())
- .add("state", record.getState())
- .add("latitude", record.getLatitude(), 0)
- .add("longitude", record.getLongitude(), 0)
- .addIfExists("modified_by", record.getModifiedBy(), -1)
- .add("modified", new Timestamp(System.currentTimeMillis()));
+ Update update = DB.UPDATE(TABLE_NAME);
+ update
+ .SET_UNLESS_MATCHES("customer_id", record.getCustomerId(), -1)
+ .SET("email", record.getEmail())
+ .SET("first_name", record.getFirstName())
+ .SET("last_name", record.getLastName())
+ .SET("barcode", record.getBarcode())
+ .SET("remote_order_id", record.getRemoteOrderId())
+ .SET_UNLESS_NULL("square_order_id", record.getSquareOrderId())
+ .SET_WHEN_MATCHES("live_mode", record.getLive(), true)
+ .SET_WHEN_MATCHES("paid", record.getPaid(), true)
+ .SET_UNLESS_NULL("total_paid", record.getTotalPaid())
+ .SET_WHEN_MATCHES("processed", record.getProcessed(), true)
+ .SET_WHEN_MATCHES("shipped", record.getShipped(), true)
+ .SET_WHEN_MATCHES("canceled", record.getCanceled(), true)
+ .SET_WHEN_MATCHES("refunded", record.getRefunded(), true)
+ .SET_UNLESS_MATCHES("status", record.getStatusId(), -1)
+ .SET_UNLESS_NULL("payment_processor", record.getPaymentProcessor())
+ .SET_UNLESS_NULL("payment_token", record.getPaymentToken())
+ .SET_UNLESS_NULL("payment_type", record.getPaymentType())
+ .SET_UNLESS_NULL("payment_brand", record.getPaymentBrand())
+ .SET_UNLESS_NULL("payment_last4", record.getPaymentLast4())
+ .SET_UNLESS_NULL("payment_fingerprint", record.getPaymentFingerprint())
+ .SET_UNLESS_NULL("payment_country", record.getPaymentCountry())
+ .SET_UNLESS_NULL("payment_date", record.getPaymentDate())
+ .SET("charge_token", record.getChargeToken())
+ .SET("ip_address", record.getIpAddress())
+ .SET_UNLESS_NULL("session_id", record.getSessionId())
+ .SET("country_iso", record.getCountryIso())
+ .SET("country", record.getCountry())
+ .SET("city", record.getCity())
+ .SET("state_iso", record.getStateIso())
+ .SET("state", record.getState())
+ .SET("latitude", record.getLatitude() != 0 ? record.getLatitude() : null)
+ .SET("longitude", record.getLongitude() != 0 ? record.getLongitude() : null)
+ .SET_UNLESS_MATCHES("modified_by", record.getModifiedBy(), -1)
+ .SET("modified", new Timestamp(System.currentTimeMillis()));
if (record.getBillingAddress() != null) {
- updateValues
- .add("billing_first_name", record.getBillingAddress().getFirstName())
- .add("billing_last_name", record.getBillingAddress().getLastName())
- .add("billing_organization", record.getBillingAddress().getOrganization())
- .add("billing_street_address", record.getBillingAddress().getStreet())
- .add("billing_address_line_2", record.getBillingAddress().getAddressLine2())
- .add("billing_address_line_3", record.getBillingAddress().getAddressLine3())
- .add("billing_city", record.getBillingAddress().getCity())
- .add("billing_state", record.getBillingAddress().getState())
- .add("billing_country", record.getBillingAddress().getCountry())
- .add("billing_postal_code", record.getBillingAddress().getPostalCode())
- .add("billing_county", record.getBillingAddress().getCounty())
- .add("billing_phone_number", record.getBillingAddress().getPhoneNumber())
- .add("billing_latitude", record.getBillingAddress().getLatitude(), 0)
- .add("billing_longitude", record.getBillingAddress().getLongitude(), 0);
+ update
+ .SET("billing_first_name", record.getBillingAddress().getFirstName())
+ .SET("billing_last_name", record.getBillingAddress().getLastName())
+ .SET("billing_organization", record.getBillingAddress().getOrganization())
+ .SET("billing_street_address", record.getBillingAddress().getStreet())
+ .SET("billing_address_line_2", record.getBillingAddress().getAddressLine2())
+ .SET("billing_address_line_3", record.getBillingAddress().getAddressLine3())
+ .SET("billing_city", record.getBillingAddress().getCity())
+ .SET("billing_state", record.getBillingAddress().getState())
+ .SET("billing_country", record.getBillingAddress().getCountry())
+ .SET("billing_postal_code", record.getBillingAddress().getPostalCode())
+ .SET("billing_county", record.getBillingAddress().getCounty())
+ .SET("billing_phone_number", record.getBillingAddress().getPhoneNumber())
+ .SET("billing_latitude", record.getBillingAddress().getLatitude() != 0 ? record.getBillingAddress().getLatitude() : null)
+ .SET("billing_longitude",
+ record.getBillingAddress().getLongitude() != 0 ? record.getBillingAddress().getLongitude() : null);
} else {
- updateValues
- .add("billing_first_name", (String) null)
- .add("billing_last_name", (String) null)
- .add("billing_organization", (String) null)
- .add("billing_street_address", (String) null)
- .add("billing_address_line_2", (String) null)
- .add("billing_address_line_3", (String) null)
- .add("billing_city", (String) null)
- .add("billing_state", (String) null)
- .add("billing_country", (String) null)
- .add("billing_postal_code", (String) null)
- .add("billing_county", (String) null)
- .add("billing_phone_number", (String) null)
- .add("billing_latitude", 0d, 0d)
- .add("billing_longitude", 0d, 0d);
+ update
+ .SET("billing_first_name", (String) null)
+ .SET("billing_last_name", (String) null)
+ .SET("billing_organization", (String) null)
+ .SET("billing_street_address", (String) null)
+ .SET("billing_address_line_2", (String) null)
+ .SET("billing_address_line_3", (String) null)
+ .SET("billing_city", (String) null)
+ .SET("billing_state", (String) null)
+ .SET("billing_country", (String) null)
+ .SET("billing_postal_code", (String) null)
+ .SET("billing_county", (String) null)
+ .SET("billing_phone_number", (String) null)
+ .SET("billing_latitude", (BigDecimal) null)
+ .SET("billing_longitude", (BigDecimal) null);
}
if (record.getShippingAddress() != null) {
- updateValues
- .add("shipping_first_name", record.getShippingAddress().getFirstName())
- .add("shipping_last_name", record.getShippingAddress().getLastName())
- .add("shipping_organization", record.getShippingAddress().getOrganization())
- .add("shipping_street_address", record.getShippingAddress().getStreet())
- .add("shipping_address_line_2", record.getShippingAddress().getAddressLine2())
- .add("shipping_address_line_3", record.getShippingAddress().getAddressLine3())
- .add("shipping_city", record.getShippingAddress().getCity())
- .add("shipping_state", record.getShippingAddress().getState())
- .add("shipping_country", record.getShippingAddress().getCountry())
- .add("shipping_postal_code", record.getShippingAddress().getPostalCode())
- .add("shipping_county", record.getShippingAddress().getCounty())
- .add("shipping_phone_number", record.getShippingAddress().getPhoneNumber())
- .add("shipping_latitude", record.getShippingAddress().getLatitude(), 0)
- .add("shipping_longitude", record.getShippingAddress().getLongitude(), 0);
+ update
+ .SET("shipping_first_name", record.getShippingAddress().getFirstName())
+ .SET("shipping_last_name", record.getShippingAddress().getLastName())
+ .SET("shipping_organization", record.getShippingAddress().getOrganization())
+ .SET("shipping_street_address", record.getShippingAddress().getStreet())
+ .SET("shipping_address_line_2", record.getShippingAddress().getAddressLine2())
+ .SET("shipping_address_line_3", record.getShippingAddress().getAddressLine3())
+ .SET("shipping_city", record.getShippingAddress().getCity())
+ .SET("shipping_state", record.getShippingAddress().getState())
+ .SET("shipping_country", record.getShippingAddress().getCountry())
+ .SET("shipping_postal_code", record.getShippingAddress().getPostalCode())
+ .SET("shipping_county", record.getShippingAddress().getCounty())
+ .SET("shipping_phone_number", record.getShippingAddress().getPhoneNumber())
+ .SET("shipping_latitude",
+ record.getShippingAddress().getLatitude() != 0 ? record.getShippingAddress().getLatitude() : null)
+ .SET("shipping_longitude",
+ record.getShippingAddress().getLongitude() != 0 ? record.getShippingAddress().getLongitude() : null);
} else {
- updateValues
- .add("shipping_first_name", (String) null)
- .add("shipping_last_name", (String) null)
- .add("shipping_organization", (String) null)
- .add("shipping_street_address", (String) null)
- .add("shipping_address_line_2", (String) null)
- .add("shipping_address_line_3", (String) null)
- .add("shipping_city", (String) null)
- .add("shipping_state", (String) null)
- .add("shipping_country", (String) null)
- .add("shipping_postal_code", (String) null)
- .add("shipping_county", (String) null)
- .add("shipping_phone_number", (String) null)
- .add("shipping_latitude", 0d, 0d)
- .add("shipping_longitude", 0d, 0d);
+ update
+ .SET("shipping_first_name", (String) null)
+ .SET("shipping_last_name", (String) null)
+ .SET("shipping_organization", (String) null)
+ .SET("shipping_street_address", (String) null)
+ .SET("shipping_address_line_2", (String) null)
+ .SET("shipping_address_line_3", (String) null)
+ .SET("shipping_city", (String) null)
+ .SET("shipping_state", (String) null)
+ .SET("shipping_country", (String) null)
+ .SET("shipping_postal_code", (String) null)
+ .SET("shipping_county", (String) null)
+ .SET("shipping_phone_number", (String) null)
+ .SET("shipping_latitude", (BigDecimal) null)
+ .SET("shipping_longitude", (BigDecimal) null);
}
- if (DB.update(connection, TABLE_NAME, updateValues, DB.WHERE("order_id = ?", record.getId()))) {
+ update.WHERE("order_id = ?", record.getId());
+ if (update.execute(connection).booleanValue()) {
// The order was successfully charged, disable the cart
if (record.getPaid()) {
// Update the cart reference so it cannot be reused
- SqlUtils cartUpdate = new SqlUtils()
- .add("enabled", false)
- .add("order_date", new Timestamp(System.currentTimeMillis()));
- DB.update(connection, "carts", cartUpdate, DB.WHERE("cart_id = ?", record.getCartId()));
+ DB.UPDATE("carts")
+ .SET("enabled", false)
+ .SET("order_date", new Timestamp(System.currentTimeMillis()))
+ .WHERE("cart_id = ?", record.getCartId())
+ .execute(connection);
// @todo Append to the order_history (PAID)
@@ -740,12 +756,13 @@ public static void markStatusAsPreparing(Order order) {
int statusId = OrderStatusCommand.retrieveStatusId(PREPARING);
Timestamp now = new Timestamp(System.currentTimeMillis());
// Update the order status
- SqlUtils updateValues = new SqlUtils()
- .add("processed", true)
- .add("processing_date", now)
- .add("status", statusId)
- .add("modified", now);
- DB.update(TABLE_NAME, updateValues, DB.WHERE("order_id = ?", order.getId()));
+ DB.UPDATE(TABLE_NAME)
+ .SET("processed", true)
+ .SET("processing_date", now)
+ .SET("status", statusId)
+ .SET("modified", now)
+ .WHERE("order_id = ?", order.getId())
+ .execute();
// @todo Append to the order_history (PREPARING)
// Update the object
order.setModified(now);
@@ -759,10 +776,11 @@ public static void markStatusAsPartiallyPrepared(Order order) {
int statusId = OrderStatusCommand.retrieveStatusId(PARTIALLY_PREPARED);
Timestamp now = new Timestamp(System.currentTimeMillis());
// Update the order status
- SqlUtils updateValues = new SqlUtils()
- .add("status", statusId)
- .add("modified", now);
- DB.update(TABLE_NAME, updateValues, DB.WHERE("order_id = ?", order.getId()));
+ DB.UPDATE(TABLE_NAME)
+ .SET("status", statusId)
+ .SET("modified", now)
+ .WHERE("order_id = ?", order.getId())
+ .execute();
// @todo Append to the order_history (PARTIALLY_PREPARED)
// Update the object
order.setModified(now);
@@ -779,12 +797,13 @@ public static void markStatusAsCanceled(Order order) {
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
// Update the order status
- SqlUtils updateValues = new SqlUtils()
- .add("canceled", true)
- .add("canceled_date", now)
- .add("status", statusId)
- .add("modified", now);
- DB.update(connection, TABLE_NAME, updateValues, DB.WHERE("order_id = ?", order.getId()));
+ DB.UPDATE(TABLE_NAME)
+ .SET("canceled", true)
+ .SET("canceled_date", now)
+ .SET("status", statusId)
+ .SET("modified", now)
+ .WHERE("order_id = ?", order.getId())
+ .execute(connection);
// Mark the order items as canceled too
OrderItemRepository.markStatusAsCanceled(connection, order);
// @todo Append to the order_history (CANCELED)
@@ -809,13 +828,14 @@ public static void markStatusAsRefunded(Order order, BigDecimal amountRefunded)
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
// Update the order status
- SqlUtils updateValues = new SqlUtils()
- .add("refunded", true)
- .add("refunded_date", now)
- .add("total_refunded = total_refunded + ?", amountRefunded)
- .add("status", statusId)
- .add("modified", new Timestamp(System.currentTimeMillis()));
- DB.update(connection, TABLE_NAME, updateValues, DB.WHERE("order_id = ?", order.getId()));
+ DB.UPDATE(TABLE_NAME)
+ .SET("refunded", true)
+ .SET("refunded_date", now)
+ .SET("total_refunded = total_refunded + ?", amountRefunded)
+ .SET("status", statusId)
+ .SET("modified", now)
+ .WHERE("order_id = ?", order.getId())
+ .execute(connection);
// Mark the order items as refunded too
OrderItemRepository.markStatusAsRefunded(connection, order);
// @todo Append to the order_history (REFUNDED)
@@ -837,12 +857,12 @@ public static void markStatusAsPartiallyShipped(Order order) {
int statusId = OrderStatusCommand.retrieveStatusId(PARTIALLY_SHIPPED);
Timestamp now = new Timestamp(System.currentTimeMillis());
// Update the order status
- SqlUtils updateValues = new SqlUtils()
- .add("status", statusId)
- // .add("shipped", true)
- .add("shipped_date", now)
- .add("modified", now);
- DB.update(TABLE_NAME, updateValues, DB.WHERE("order_id = ?", order.getId()));
+ DB.UPDATE(TABLE_NAME)
+ .SET("status", statusId)
+ .SET("shipped_date", now)
+ .SET("modified", now)
+ .WHERE("order_id = ?", order.getId())
+ .execute();
// @todo Append to the order_history (PARTIALLY_SHIPPED)
// Update the object
order.setModified(now);
@@ -859,12 +879,13 @@ public static void markStatusAsShipped(Order order) {
order.setShippedDate(now);
}
// Update the order status
- SqlUtils updateValues = new SqlUtils()
- .add("status", statusId)
- .add("shipped", true)
- .add("shipped_date", order.getShippedDate())
- .add("modified", now);
- DB.update(TABLE_NAME, updateValues, DB.WHERE("order_id = ?", order.getId()));
+ DB.UPDATE(TABLE_NAME)
+ .SET("status", statusId)
+ .SET("shipped", true)
+ .SET("shipped_date", order.getShippedDate())
+ .SET("modified", now)
+ .WHERE("order_id = ?", order.getId())
+ .execute();
// @todo Append to the order_history (SHIPPED)
// Update the object
order.setModified(now);
@@ -879,52 +900,51 @@ public static void updateUserOrders(User user) {
return;
}
// Update unlinked orders
- SqlUtils updateValues = new SqlUtils()
- .add("created_by", user.getId());
- SqlWhere where = DB.WHERE()
- .AND("created_by IS NULL")
- .AND("LOWER(email) = LOWER(?)", user.getEmail());
- DB.update(TABLE_NAME, updateValues, where);
+ DB.UPDATE(TABLE_NAME)
+ .SET("created_by", user.getId())
+ .WHERE("created_by IS NULL")
+ .AND("LOWER(email) = LOWER(?)", user.getEmail())
+ .execute();
// @todo Append to the order_history (USER ASSOCIATED)
}
public static void export(DataConstraints constraints, File file) {
- // show paid orders, and only refunded ones that have shipped
- // Use the specification to filter results
if (constraints == null) {
constraints = new DataConstraints();
}
constraints.setDefaultColumnToSortBy("order_id");
- DB.exportToCsvAllFrom(TABLE_NAME,
- DB.SELECT(
- "order_unique_id AS \"Order Number\"",
- "live_mode AS \"Live Mode\"",
- "payment_date AS \"Date Ordered\"",
- "processing_date AS \"Date Processed\"",
- "shipped_date AS \"Date Shipped\"",
- "los.title AS \"Status\"",
- "concat_ws(' ', shipping_first_name, shipping_last_name) AS \"Customer Name\"",
- "shipping_city AS \"City\"",
- "shipping_state AS \"State\"",
- "shipping_country AS \"Country\"",
- "shipping_postal_code AS \"Postal Code\"",
- "currency AS \"Currency\"",
- "subtotal_amount AS \"Subtotal\"",
- "-discount_amount AS \"Discount\"",
- "shipping_amount AS \"Shipping\"",
- "subtotal_amount + shipping_amount + fee_amount - discount_amount AS \"Sales Total\"",
- "tax_amount AS \"Sales Tax\"",
- "tax_rate AS \"Sales Tax Rate\"",
- "total_amount AS \"Total\"",
- "-total_refunded AS \"Refunded\"",
- "promo_code AS \"Promo Code\"",
- "payment_processor AS \"Processor\""),
- DB.JOIN(STATUS_JOIN),
- DB.WHERE("live_mode = ?", true)
- .AND("paid = ?", true)
- .AND("canceled = ?", false)
- .AND("(refunded = false OR (refunded = true and shipped = true))"),
- null, constraints, file);
+ Select select = DB.SELECT(
+ "order_unique_id AS \"Order Number\"",
+ "live_mode AS \"Live Mode\"",
+ "payment_date AS \"Date Ordered\"",
+ "processing_date AS \"Date Processed\"",
+ "shipped_date AS \"Date Shipped\"",
+ "los.title AS \"Status\"",
+ "concat_ws(' ', shipping_first_name, shipping_last_name) AS \"Customer Name\"",
+ "shipping_city AS \"City\"",
+ "shipping_state AS \"State\"",
+ "shipping_country AS \"Country\"",
+ "shipping_postal_code AS \"Postal Code\"",
+ "currency AS \"Currency\"",
+ "subtotal_amount AS \"Subtotal\"",
+ "-discount_amount AS \"Discount\"",
+ "shipping_amount AS \"Shipping\"",
+ "subtotal_amount + shipping_amount + fee_amount - discount_amount AS \"Sales Total\"",
+ "tax_amount AS \"Sales Tax\"",
+ "tax_rate AS \"Sales Tax Rate\"",
+ "total_amount AS \"Total\"",
+ "-total_refunded AS \"Refunded\"",
+ "promo_code AS \"Promo Code\"",
+ "payment_processor AS \"Processor\"")
+ .FROM(TABLE_NAME)
+ .LEFT_JOIN("lookup_order_status los")
+ .ON("orders.status = los.status_id")
+ .WHERE("live_mode = ?", true)
+ .AND("paid = ?", true)
+ .AND("canceled = ?", false)
+ .AND("(refunded = false OR (refunded = true and shipped = true))")
+ .WITH(constraints);
+ writeCsvExport(select, file);
}
public static void exportForTaxJar(DataConstraints constraints, File file) {
@@ -934,38 +954,70 @@ public static void exportForTaxJar(DataConstraints constraints, File file) {
constraints = new DataConstraints();
}
constraints.setDefaultColumnToSortBy("order_id");
- DB.exportToCsvAllFrom(TABLE_NAME,
- DB.SELECT(
- "'web' AS provider", // web/Square/etc.
- "charge_token AS \"order_id\"",
- "'Order' AS transaction_type", // Order or Refund
- "'' AS transaction_reference_id", // for Refunds
- "payment_date AS \"completed_at\"",
- "concat_ws(' ', shipping_first_name, shipping_last_name) AS \"customer_name\"",
- "'' AS shiptostreet",
- "shipping_city AS \"shiptocity\"",
- "shipping_state AS \"shiptostate\"",
- "shipping_postal_code AS \"shiptozip\"",
- "shipping_country AS \"Country\"",
- "'' AS shiptocountrycode",
- "'' AS from_street",
- "'' AS from_city",
- "'' AS from_state",
- "'' AS from_zip",
- "'' AS from_country",
- "shipping_amount AS \"shipping_amount\"",
- "fee_amount AS \"handling_amount\"",
- "discount_amount AS \"discount_amount\"",
- // without tax; subtotal + shipping + handling - discount
- "subtotal_amount + shipping_amount + fee_amount - discount_amount AS \"total_sale\"",
- "tax_amount AS \"sales_tax\"",
- "total_amount AS \"Total\"",
- "-total_refunded AS \"Refunded\""),
- DB.JOIN(STATUS_JOIN),
- DB.WHERE("live_mode = ?", true)
- .AND("paid = ?", true)
- .AND("canceled = ?", false)
- .AND("(refunded = false OR (refunded = true and shipped = true))"),
- null, constraints, file);
+ Select select = DB.SELECT(
+ "'web' AS provider",
+ "charge_token AS \"order_id\"",
+ "'Order' AS transaction_type",
+ "'' AS transaction_reference_id",
+ "payment_date AS \"completed_at\"",
+ "concat_ws(' ', shipping_first_name, shipping_last_name) AS \"customer_name\"",
+ "'' AS shiptostreet",
+ "shipping_city AS \"shiptocity\"",
+ "shipping_state AS \"shiptostate\"",
+ "shipping_postal_code AS \"shiptozip\"",
+ "shipping_country AS \"Country\"",
+ "'' AS shiptocountrycode",
+ "'' AS from_street",
+ "'' AS from_city",
+ "'' AS from_state",
+ "'' AS from_zip",
+ "'' AS from_country",
+ "shipping_amount AS \"shipping_amount\"",
+ "fee_amount AS \"handling_amount\"",
+ "discount_amount AS \"discount_amount\"",
+ // without tax; subtotal + shipping + handling - discount
+ "subtotal_amount + shipping_amount + fee_amount - discount_amount AS \"total_sale\"",
+ "tax_amount AS \"sales_tax\"",
+ "total_amount AS \"Total\"",
+ "-total_refunded AS \"Refunded\"")
+ .FROM(TABLE_NAME)
+ .LEFT_JOIN("lookup_order_status los")
+ .ON("orders.status = los.status_id")
+ .WHERE("live_mode = ?", true)
+ .AND("paid = ?", true)
+ .AND("canceled = ?", false)
+ .AND("(refunded = false OR (refunded = true and shipped = true))")
+ .WITH(constraints);
+ writeCsvExport(select, file);
+ }
+
+ // @todo move this to a utility class
+
+ private static void writeCsvExport(Select select, File file) {
+ if (select == null || file == null) {
+ return;
+ }
+ try (Connection connection = DB.getConnection();
+ java.sql.PreparedStatement statement = connection.prepareStatement(select.getSql())) {
+ int index = 0;
+ for (Object value : select.getParameters()) {
+ statement.setObject(++index, value);
+ }
+ try (java.sql.ResultSet rs = statement.executeQuery();
+ java.io.BufferedWriter writer = new java.io.BufferedWriter(new java.io.FileWriter(file))) {
+ writer.write(
+ "Order Number,Live Mode,Date Ordered,Date Processed,Date Shipped,Status,Customer Name,City,State,Country,Postal Code,Currency,Subtotal,Discount,Shipping,Sales Total,Sales Tax,Sales Tax Rate,Total,Refunded,Promo Code,Processor\n");
+ while (rs.next()) {
+ writer.write(rs.getString(1) + "," + rs.getString(2) + "," + rs.getString(3) + "," + rs.getString(4) + "," + rs.getString(5)
+ + "," + rs.getString(6) + "," + rs.getString(7) + "," + rs.getString(8) + "," + rs.getString(9) + "," + rs.getString(10)
+ + "," + rs.getString(11) + "," + rs.getString(12) + "," + rs.getString(13) + "," + rs.getString(14) + ","
+ + rs.getString(15) + "," + rs.getString(16) + "," + rs.getString(17) + "," + rs.getString(18) + "," + rs.getString(19)
+ + "," + rs.getString(20) + "," + rs.getString(21) + "," + rs.getString(22) + "\n");
+ }
+ writer.flush();
+ }
+ } catch (Exception e) {
+ LOG.error("Order export failed", e);
+ }
}
}
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/PricingRuleRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/PricingRuleRepository.java
index 196d49538..a5150a250 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/PricingRuleRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/PricingRuleRepository.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");
@@ -31,14 +32,13 @@
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.Select;
import com.simisinc.platform.domain.model.ecommerce.PricingRule;
-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;
/**
@@ -54,32 +54,33 @@ public class PricingRuleRepository {
private static String TABLE_NAME = "pricing_rules";
private static String[] PRIMARY_KEY = new String[] { "rule_id" };
- private static DataResult query(PricingRuleSpecification specification, DataConstraints constraints) {
- SqlWhere where = null;
+ private static DataResult query(PricingRuleSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("*").FROM(TABLE_NAME).WHERE();
if (specification != null) {
- where = DB.WHERE();
if (StringUtils.isNotBlank(specification.getCountryCode())) {
- where.AND("valid_country_code IS NULL OR valid_country_code = ?", specification.getCountryCode());
+ select.AND("valid_country_code IS NULL OR valid_country_code = ?", specification.getCountryCode());
}
if (StringUtils.isNotBlank(specification.getPromoCode())) {
- where.AND("upper(promo_code) = ?", specification.getPromoCode().toUpperCase());
+ select.AND("upper(promo_code) = ?", specification.getPromoCode().toUpperCase());
}
if (specification.getEnabled() != DataConstants.UNDEFINED) {
- where.AND("enabled = ?", specification.getEnabled() == DataConstants.TRUE);
+ select.AND("enabled = ?", specification.getEnabled() == DataConstants.TRUE);
}
if (specification.getIsValidToday() == DataConstants.TRUE) {
- where.AND("(from_date IS NULL OR from_date <= CURRENT_TIMESTAMP)");
- where.AND("(to_date IS NULL OR to_date > CURRENT_TIMESTAMP)");
+ select.AND("(from_date IS NULL OR from_date <= CURRENT_TIMESTAMP)");
+ select.AND("(to_date IS NULL OR to_date > CURRENT_TIMESTAMP)");
}
if (specification.getHasPromoCode() != DataConstants.UNDEFINED) {
- where.AND("promo_code IS NULL OR promo_code = ''");
+ select.AND("promo_code IS NULL OR promo_code = ''");
}
if (StringUtils.isNotBlank(specification.getIncludesSku())) {
- // @todo use a JSON field type to improve accuracy
- where.AND("LOWER(valid_skus) LIKE LOWER(?) ESCAPE '!'", "%" + specification.getIncludesSku().toLowerCase() + "%");
+ select.AND("LOWER(valid_skus) LIKE LOWER(?) ESCAPE '!'", "%" + specification.getIncludesSku().toLowerCase() + "%");
}
}
- return DB.selectAllFrom(TABLE_NAME, where, constraints, PricingRuleRepository::buildRecord);
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(PricingRuleRepository::buildRecord);
}
public static List findAll(PricingRuleSpecification specification, DataConstraints constraints) {
@@ -87,8 +88,7 @@ public static List findAll(PricingRuleSpecification specification,
constraints = new DataConstraints();
}
constraints.setDefaultColumnToSortBy("to_date desc, created");
- DataResult result = query(specification, constraints);
- return (List) result.getRecords();
+ return query(specification, constraints).getRecords();
}
public static List findAllRulesByValidSku(String sku) {
@@ -96,9 +96,7 @@ public static List findAllRulesByValidSku(String sku) {
specification.setEnabled(true);
specification.setHasPromoCode(false);
specification.setIncludesSku(sku);
- DataResult result = query(specification, null);
- List recordList = (List) result.getRecords();
- // The query is currently not precise, so fish out the matches
+ List recordList = query(specification, null).getRecords();
List pricingRuleList = new ArrayList<>();
for (PricingRule record : recordList) {
List validSkuList = Stream.of(record.getValidSkus().toUpperCase().split(Pattern.quote(",")))
@@ -112,10 +110,10 @@ public static List findAllRulesByValidSku(String sku) {
}
public static PricingRule findById(long ruleId) {
- return (PricingRule) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("rule_id = ?", ruleId),
- PricingRuleRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("rule_id = ?", ruleId)
+ .returnRecord(PricingRuleRepository::buildRecord);
}
public static PricingRule save(PricingRule record) {
@@ -126,40 +124,37 @@ public static PricingRule save(PricingRule record) {
}
public static PricingRule add(PricingRule record) {
- // 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)
- SqlUtils insertValues = new SqlUtils()
- .add("name", record.getName())
- .add("description", record.getDescription())
- .add("error_message", record.getErrorMessage())
- .add("from_date", record.getFromDate())
- .add("to_date", record.getToDate())
- .add("promo_code", record.getPromoCode())
- .add("uses_per_code", record.getUsesPerCode())
- .add("uses_per_customer", record.getUsesPerCustomer())
- .add("times_used", record.getTimesUsed())
- .add("created_by", record.getCreatedBy())
- .add("modified_by", record.getModifiedBy())
- .add("enabled", record.getEnabled())
- .add("minimum_subtotal", record.getMinimumSubtotal())
- .add("minimum_order_qty", record.getMinimumOrderQuantity())
- .add("maximum_order_qty", record.getMaximumOrderQuantity())
- .add("item_limit", record.getItemLimit())
- .add("valid_skus", record.getValidSkus())
- .add("invalid_skus", record.getInvalidSkus())
- .add("subtotal_percent", record.getSubtotalPercent())
- .add("subtract_amount", record.getSubtractAmount())
- .add("buy_x_items", record.getBuyXItems())
- .add("get_y_free", record.getGetYItemsFree())
- .add("free_shipping", record.getFreeShipping())
- .add("free_product_sku", record.getFreeProductSku())
- .add("free_shipping_code", record.getFreeShippingCode())
- .add("valid_country_code", record.getCountryCode());
- record.setId(DB.insertInto(connection, TABLE_NAME, insertValues, PRIMARY_KEY));
- // Finish the transaction
+ record.setId(DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("name", record.getName())
+ .FIELD("description", record.getDescription())
+ .FIELD("error_message", record.getErrorMessage())
+ .FIELD("from_date", record.getFromDate())
+ .FIELD("to_date", record.getToDate())
+ .FIELD("promo_code", record.getPromoCode())
+ .FIELD("uses_per_code", record.getUsesPerCode())
+ .FIELD("uses_per_customer", record.getUsesPerCustomer())
+ .FIELD("times_used", record.getTimesUsed())
+ .FIELD("created_by", record.getCreatedBy())
+ .FIELD("modified_by", record.getModifiedBy())
+ .FIELD("enabled", record.getEnabled())
+ .FIELD("minimum_subtotal", record.getMinimumSubtotal())
+ .FIELD("minimum_order_qty", record.getMinimumOrderQuantity())
+ .FIELD("maximum_order_qty", record.getMaximumOrderQuantity())
+ .FIELD("item_limit", record.getItemLimit())
+ .FIELD("valid_skus", record.getValidSkus())
+ .FIELD("invalid_skus", record.getInvalidSkus())
+ .FIELD("subtotal_percent", record.getSubtotalPercent())
+ .FIELD("subtract_amount", record.getSubtractAmount())
+ .FIELD("buy_x_items", record.getBuyXItems())
+ .FIELD("get_y_free", record.getGetYItemsFree())
+ .FIELD("free_shipping", record.getFreeShipping())
+ .FIELD("free_product_sku", record.getFreeProductSku())
+ .FIELD("free_shipping_code", record.getFreeShippingCode())
+ .FIELD("valid_country_code", record.getCountryCode())
+ .execute(connection));
transaction.commit();
return record;
} catch (SQLException se) {
@@ -169,35 +164,35 @@ public static PricingRule add(PricingRule record) {
}
public static PricingRule update(PricingRule record) {
- SqlUtils updateValues = new SqlUtils()
- .add("name", record.getName())
- .add("description", record.getDescription())
- .add("error_message", record.getErrorMessage())
- .add("from_date", record.getFromDate())
- .add("to_date", record.getToDate())
- .add("promo_code", record.getPromoCode())
- .add("uses_per_code", record.getUsesPerCode())
- .add("uses_per_customer", record.getUsesPerCustomer())
- // .add("times_used", record.getTimesUsed())
- .add("enabled", record.getEnabled())
- .add("minimum_subtotal", record.getMinimumSubtotal())
- .add("minimum_order_qty", record.getMinimumOrderQuantity())
- .add("maximum_order_qty", record.getMaximumOrderQuantity())
- .add("item_limit", record.getItemLimit())
- .add("valid_skus", record.getValidSkus())
- .add("invalid_skus", record.getInvalidSkus())
- .add("subtotal_percent", record.getSubtotalPercent())
- .add("subtract_amount", record.getSubtractAmount())
- .add("buy_x_items", record.getBuyXItems())
- .add("get_y_free", record.getGetYItemsFree())
- .add("free_shipping", record.getFreeShipping())
- .add("free_product_sku", record.getFreeProductSku())
- .add("free_shipping_code", record.getFreeShippingCode())
- .add("valid_country_code", record.getCountryCode())
- .add("modified_by", record.getModifiedBy(), -1)
- .add("modified", new Timestamp(System.currentTimeMillis()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("rule_id = ?", record.getId()))) {
- // CacheManager.invalidateKey(CacheManager.CONTENT_UNIQUE_ID_CACHE, record.getUniqueId());
+ boolean updated = DB.UPDATE(TABLE_NAME)
+ .SET("name", record.getName())
+ .SET("description", record.getDescription())
+ .SET("error_message", record.getErrorMessage())
+ .SET("from_date", record.getFromDate())
+ .SET("to_date", record.getToDate())
+ .SET("promo_code", record.getPromoCode())
+ .SET("uses_per_code", record.getUsesPerCode())
+ .SET("uses_per_customer", record.getUsesPerCustomer())
+ .SET("enabled", record.getEnabled())
+ .SET("minimum_subtotal", record.getMinimumSubtotal())
+ .SET("minimum_order_qty", record.getMinimumOrderQuantity())
+ .SET("maximum_order_qty", record.getMaximumOrderQuantity())
+ .SET("item_limit", record.getItemLimit())
+ .SET("valid_skus", record.getValidSkus())
+ .SET("invalid_skus", record.getInvalidSkus())
+ .SET("subtotal_percent", record.getSubtotalPercent())
+ .SET("subtract_amount", record.getSubtractAmount())
+ .SET("buy_x_items", record.getBuyXItems())
+ .SET("get_y_free", record.getGetYItemsFree())
+ .SET("free_shipping", record.getFreeShipping())
+ .SET("free_product_sku", record.getFreeProductSku())
+ .SET("free_shipping_code", record.getFreeShippingCode())
+ .SET("valid_country_code", record.getCountryCode())
+ .SET("modified_by", record.getModifiedBy() == -1 ? null : record.getModifiedBy())
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("rule_id = ?", record.getId())
+ .execute();
+ if (updated) {
return record;
}
LOG.error("The update failed!");
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ProductCategoryRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ProductCategoryRepository.java
index 9b8a4fd4d..dc836b81e 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ProductCategoryRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ProductCategoryRepository.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,13 +27,13 @@
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.Insert;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.domain.model.ecommerce.ProductCategory;
-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 product category objects
@@ -48,35 +49,30 @@ public class ProductCategoryRepository {
private static String[] PRIMARY_KEY = new String[] { "category_id" };
public static List findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- null,
- new DataConstraints().setDefaultColumnToSortBy("display_order, name").setUseCount(false),
- ProductCategoryRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("display_order, name").setUseCount(false))
+ .returnDataResult(ProductCategoryRepository::buildRecord).getRecords();
}
public static ProductCategory findById(long categoryId) {
if (categoryId == -1) {
return null;
}
- return (ProductCategory) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("category_id = ?", categoryId),
- ProductCategoryRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("category_id = ?", categoryId)
+ .returnRecord(ProductCategoryRepository::buildRecord);
}
public static ProductCategory findByUniqueId(String uniqueId) {
if (StringUtils.isBlank(uniqueId)) {
return null;
}
- return (ProductCategory) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("UPPER(category_unique_id) = ?", uniqueId.toUpperCase()),
- ProductCategoryRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("UPPER(category_unique_id) = ?", uniqueId.toUpperCase())
+ .returnRecord(ProductCategoryRepository::buildRecord);
}
public static ProductCategory save(ProductCategory record) {
@@ -87,23 +83,20 @@ public static ProductCategory save(ProductCategory record) {
}
public static ProductCategory add(ProductCategory record) {
- // 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)
- SqlUtils insertValues = new SqlUtils()
- .add("category_unique_id", record.getUniqueId())
- .add("name", record.getName())
- .add("description", record.getDescription())
- .add("created_by", record.getCreatedBy(), -1)
- .add("modified_by", record.getModifiedBy(), -1)
- .add("enabled", record.getEnabled());
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("category_unique_id", record.getUniqueId())
+ .FIELD("name", record.getName())
+ .FIELD("description", record.getDescription())
+ .FIELD("created_by", record.getCreatedBy() == -1 ? null : record.getCreatedBy())
+ .FIELD("modified_by", record.getModifiedBy() == -1 ? null : record.getModifiedBy())
+ .FIELD("enabled", record.getEnabled());
if (record.getDisplayOrder() > 0) {
- insertValues.add("display_order", record.getDisplayOrder());
+ insert.FIELD("display_order", record.getDisplayOrder());
}
- record.setId(DB.insertInto(connection, TABLE_NAME, insertValues, PRIMARY_KEY));
- // Finish the transaction
+ record.setId(insert.execute(connection));
transaction.commit();
return record;
} catch (SQLException se) {
@@ -113,18 +106,18 @@ public static ProductCategory add(ProductCategory record) {
}
public static ProductCategory update(ProductCategory record) {
- SqlUtils updateValues = new SqlUtils()
- .add("category_unique_id", record.getUniqueId())
- .add("name", record.getName())
- .add("description", record.getDescription())
- .add("enabled", record.getEnabled())
- .add("modified_by", record.getModifiedBy(), -1)
- .add("modified", new Timestamp(System.currentTimeMillis()));
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("category_unique_id", record.getUniqueId())
+ .SET("name", record.getName())
+ .SET("description", record.getDescription())
+ .SET("enabled", record.getEnabled())
+ .SET("modified_by", record.getModifiedBy() == -1 ? null : record.getModifiedBy())
+ .SET("modified", new Timestamp(System.currentTimeMillis()));
if (record.getDisplayOrder() > 0) {
- updateValues.add("display_order", record.getDisplayOrder());
+ update.SET("display_order", record.getDisplayOrder());
}
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("category_id = ?", record.getId()))) {
- // CacheManager.invalidateKey(CacheManager.CONTENT_UNIQUE_ID_CACHE, record.getUniqueId());
+ update.WHERE("category_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("The update failed!");
@@ -132,7 +125,7 @@ public static ProductCategory update(ProductCategory record) {
}
public static boolean remove(ProductCategory record) {
- return DB.deleteFrom(TABLE_NAME, DB.WHERE("category_id = ?", record.getId())) > 0;
+ return DB.DELETE().FROM(TABLE_NAME).WHERE("category_id = ?", record.getId()).execute();
}
private static ProductCategory buildRecord(ResultSet rs) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ProductRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ProductRepository.java
index 0d21629d1..baeb56804 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ProductRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ProductRepository.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,23 +21,25 @@
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
+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.github.rajkowski.database.AutoRollback;
+import com.github.rajkowski.database.AutoStartTransaction;
+import com.github.rajkowski.database.CastType;
+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.ecommerce.ProductJSONCommand;
import com.simisinc.platform.domain.model.ecommerce.Product;
import com.simisinc.platform.domain.model.ecommerce.ProductSku;
-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.SqlValue;
-import com.simisinc.platform.infrastructure.database.SqlWhere;
import com.simisinc.platform.presentation.controller.DataConstants;
/**
@@ -52,38 +55,40 @@ public class ProductRepository {
private static String TABLE_NAME = "products";
private static String[] PRIMARY_KEY = new String[] { "product_id" };
- private static DataResult query(ProductSpecification specification, DataConstraints constraints) {
- SqlWhere where = null;
+ private static DataResult query(ProductSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("products.*").FROM(TABLE_NAME).WHERE();
if (specification != null) {
- where = DB.WHERE()
- .andAddIfHasValue("products.product_id = ?", specification.getId(), -1)
- .andAddIfHasValue("products.product_unique_id = ?", specification.getProductUniqueId());
+ if (specification.getId() > -1) {
+ select.AND("products.product_id = ?", specification.getId());
+ }
+ if (StringUtils.isNotBlank(specification.getProductUniqueId())) {
+ select.AND("products.product_unique_id = ?", specification.getProductUniqueId());
+ }
if (specification.getWithProductUniqueIdList() != null && !specification.getWithProductUniqueIdList().isEmpty()) {
- StringBuilder sb = new StringBuilder();
+ StringBuilder placeholders = new StringBuilder();
+ List values = new ArrayList<>();
for (int i = 0; i < specification.getWithProductUniqueIdList().size(); i++) {
if (i > 0) {
- sb.append(",");
+ placeholders.append(", ");
}
- sb.append("?");
+ placeholders.append("?");
+ values.add(specification.getWithProductUniqueIdList().get(i));
}
- if (sb.length() > 0) {
- where.AND("products.product_unique_id IN (" + sb.toString() + ")",
- specification.getWithProductUniqueIdList().toArray(new String[0]));
+ if (!placeholders.isEmpty()) {
+ select.AND("products.product_unique_id IN (" + placeholders + ")", values.toArray());
}
}
if (specification.getIsForSale() != DataConstants.UNDEFINED) {
if (specification.getIsForSale() == DataConstants.TRUE) {
- where.AND("products.enabled = true");
- // @todo add the dates
- // today >= activeDate
- // today < deactivateOnDate
- // has a product_sku with at least 1 visible sku.getEnabled()
- where.AND("EXISTS (SELECT 1 FROM product_skus WHERE product_id = products.product_id AND enabled = "
- + (specification.getIsForSale() == DataConstants.TRUE ? "true" : "false") + ")");
+ select.AND("products.enabled = true");
+ select.AND("EXISTS (SELECT 1 FROM product_skus WHERE product_id = products.product_id AND enabled = ?)", true);
}
}
}
- return DB.selectAllFrom(TABLE_NAME, null, where, constraints, ProductRepository::buildRecord);
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(ProductRepository::buildRecord);
}
public static List findAll() {
@@ -111,10 +116,10 @@ public static Product findById(long id, boolean includeRelatedData) {
if (id == -1) {
return null;
}
- Product product = (Product) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("product_id = ?", id),
- ProductRepository::buildRecord);
+ Product product = DB.SELECT("products.*")
+ .FROM(TABLE_NAME)
+ .WHERE("product_id = ?", id)
+ .returnRecord(ProductRepository::buildRecord);
if (includeRelatedData) {
populateRelatedData(product);
}
@@ -125,10 +130,10 @@ public static Product findByName(String name) {
if (StringUtils.isBlank(name)) {
return null;
}
- Product product = (Product) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("LOWER(name) = ?", name.toLowerCase()),
- ProductRepository::buildRecord);
+ Product product = DB.SELECT("products.*")
+ .FROM(TABLE_NAME)
+ .WHERE("LOWER(name) = ?", name.toLowerCase())
+ .returnRecord(ProductRepository::buildRecord);
populateRelatedData(product);
return product;
}
@@ -137,10 +142,10 @@ public static Product findByUniqueId(String uniqueId) {
if (StringUtils.isBlank(uniqueId)) {
return null;
}
- Product product = (Product) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("product_unique_id = ?", uniqueId),
- ProductRepository::buildRecord);
+ Product product = DB.SELECT("products.*")
+ .FROM(TABLE_NAME)
+ .WHERE("product_unique_id = ?", uniqueId)
+ .returnRecord(ProductRepository::buildRecord);
populateRelatedData(product);
return product;
}
@@ -149,10 +154,10 @@ public static Product findBySku(String sku) {
if (StringUtils.isBlank(sku)) {
return null;
}
- Product product = (Product) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("EXISTS (SELECT 1 FROM product_skus WHERE product_id = products.product_id AND sku = ?)", sku.toUpperCase().trim()),
- ProductRepository::buildRecord);
+ Product product = DB.SELECT("products.*")
+ .FROM(TABLE_NAME)
+ .WHERE("EXISTS (SELECT 1 FROM product_skus WHERE product_id = products.product_id AND sku = ?)", sku.toUpperCase().trim())
+ .returnRecord(ProductRepository::buildRecord);
populateRelatedData(product);
return product;
}
@@ -174,7 +179,7 @@ public static boolean remove(Product record) {
// Delete the references
ProductSkuRepository.removeAll(connection, record);
// Delete the record
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("product_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("product_id = ?", record.getId()).execute(connection);
// Finish transaction
transaction.commit();
return true;
@@ -193,42 +198,41 @@ public static Product save(Product record) {
}
public static Product add(Product record) {
- SqlUtils insertValues = new SqlUtils()
- .add("product_unique_id", StringUtils.trimToNull(record.getUniqueId()))
- .add("product_order", record.getOrder())
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("description", StringUtils.trimToNull(record.getDescription()))
- .add("caption", StringUtils.trimToNull(record.getCaption()))
- .add("is_good", record.getIsGood())
- .add("is_service", record.getIsService())
- .add("is_virtual", record.getIsVirtual())
- .add("is_download", record.getIsDownload())
- .add("fulfillment_id", record.getFulfillmentId(), -1)
- .add("taxable", record.getTaxable())
- .add("tax_code", StringUtils.trimToNull(record.getTaxCode()))
- .add("active_date", record.getActiveDate())
- .add("deactivate_on", record.getDeactivateOnDate())
- .add("available_date", record.getAvailableDate())
- .add("shippable", record.getShippable())
- .add("package_height", record.getPackageHeight())
- .add("package_length", record.getPackageLength())
- .add("package_width", record.getPackageWidth())
- .add("package_weight_lbs", record.getPackageWeightPounds())
- .add("package_weight_ozs", record.getPackageWeightOunces())
- .add("image_url", StringUtils.trimToNull(record.getImageUrl()))
- .add("product_url", StringUtils.trimToNull(record.getProductUrl()))
- .add("exclude_us_states", StringUtils.trimToNull(record.getExcludeUsStates()))
- .add("created_by", record.getCreatedBy(), -1)
- .add("modified_by", record.getModifiedBy(), -1)
- // .add("enabled", record.getEnabled());
- .add("enabled", true);
- insertValues.add(new SqlValue("sku_attributes", SqlValue.JSONB_TYPE, ProductJSONCommand.createJSONString(record)));
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("product_unique_id", StringUtils.trimToNull(record.getUniqueId()))
+ .FIELD("product_order", record.getOrder())
+ .FIELD("name", StringUtils.trimToNull(record.getName()))
+ .FIELD("description", StringUtils.trimToNull(record.getDescription()))
+ .FIELD("caption", StringUtils.trimToNull(record.getCaption()))
+ .FIELD("is_good", record.getIsGood())
+ .FIELD("is_service", record.getIsService())
+ .FIELD("is_virtual", record.getIsVirtual())
+ .FIELD("is_download", record.getIsDownload())
+ .FIELD("fulfillment_id", record.getFulfillmentId() != -1 ? record.getFulfillmentId() : null)
+ .FIELD("taxable", record.getTaxable())
+ .FIELD("tax_code", StringUtils.trimToNull(record.getTaxCode()))
+ .FIELD("active_date", record.getActiveDate())
+ .FIELD("deactivate_on", record.getDeactivateOnDate())
+ .FIELD("available_date", record.getAvailableDate())
+ .FIELD("shippable", record.getShippable())
+ .FIELD("package_height", record.getPackageHeight())
+ .FIELD("package_length", record.getPackageLength())
+ .FIELD("package_width", record.getPackageWidth())
+ .FIELD("package_weight_lbs", record.getPackageWeightPounds())
+ .FIELD("package_weight_ozs", record.getPackageWeightOunces())
+ .FIELD("image_url", StringUtils.trimToNull(record.getImageUrl()))
+ .FIELD("product_url", StringUtils.trimToNull(record.getProductUrl()))
+ .FIELD("exclude_us_states", StringUtils.trimToNull(record.getExcludeUsStates()))
+ .FIELD("created_by", record.getCreatedBy() != -1 ? record.getCreatedBy() : null)
+ .FIELD("modified_by", record.getModifiedBy() != -1 ? record.getModifiedBy() : null)
+ .FIELD("enabled", true)
+ .FIELD("sku_attributes", ProductJSONCommand.createJSONString(record), CastType.JSONB);
// 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));
+ record.setId(insert.execute(connection));
// Manage the Product SKUs
ProductSkuRepository.saveProductSKUList(connection, record);
// Finish the transaction
@@ -242,40 +246,40 @@ public static Product add(Product record) {
}
public static Product update(Product record) {
- SqlUtils updateValues = new SqlUtils()
- .add("product_unique_id", StringUtils.trimToNull(record.getUniqueId()))
- .add("product_order", record.getOrder())
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("description", StringUtils.trimToNull(record.getDescription()))
- .add("caption", StringUtils.trimToNull(record.getCaption()))
- .add("is_good", record.getIsGood())
- .add("is_service", record.getIsService())
- .add("is_virtual", record.getIsVirtual())
- .add("is_download", record.getIsDownload())
- .add("fulfillment_id", record.getFulfillmentId(), -1)
- .add("taxable", record.getTaxable())
- .add("tax_code", StringUtils.trimToNull(record.getTaxCode()))
- .add("active_date", record.getActiveDate())
- .add("deactivate_on", record.getDeactivateOnDate())
- .add("available_date", record.getAvailableDate())
- .add("shippable", record.getShippable())
- .add("package_height", record.getPackageHeight())
- .add("package_length", record.getPackageLength())
- .add("package_width", record.getPackageWidth())
- .add("package_weight_lbs", record.getPackageWeightPounds())
- .add("package_weight_ozs", record.getPackageWeightOunces())
- .add("image_url", StringUtils.trimToNull(record.getImageUrl()))
- .add("product_url", StringUtils.trimToNull(record.getProductUrl()))
- .add("exclude_us_states", StringUtils.trimToNull(record.getExcludeUsStates()))
- .add("modified_by", record.getModifiedBy())
- .add("modified", new Timestamp(System.currentTimeMillis()));
- updateValues.add(new SqlValue("sku_attributes", SqlValue.JSONB_TYPE, ProductJSONCommand.createJSONString(record)));
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("product_unique_id", StringUtils.trimToNull(record.getUniqueId()))
+ .SET("product_order", record.getOrder())
+ .SET("name", StringUtils.trimToNull(record.getName()))
+ .SET("description", StringUtils.trimToNull(record.getDescription()))
+ .SET("caption", StringUtils.trimToNull(record.getCaption()))
+ .SET("is_good", record.getIsGood())
+ .SET("is_service", record.getIsService())
+ .SET("is_virtual", record.getIsVirtual())
+ .SET("is_download", record.getIsDownload())
+ .SET("fulfillment_id", record.getFulfillmentId() != -1 ? record.getFulfillmentId() : null)
+ .SET("taxable", record.getTaxable())
+ .SET("tax_code", StringUtils.trimToNull(record.getTaxCode()))
+ .SET("active_date", record.getActiveDate())
+ .SET("deactivate_on", record.getDeactivateOnDate())
+ .SET("available_date", record.getAvailableDate())
+ .SET("shippable", record.getShippable())
+ .SET("package_height", record.getPackageHeight())
+ .SET("package_length", record.getPackageLength())
+ .SET("package_width", record.getPackageWidth())
+ .SET("package_weight_lbs", record.getPackageWeightPounds())
+ .SET("package_weight_ozs", record.getPackageWeightOunces())
+ .SET("image_url", StringUtils.trimToNull(record.getImageUrl()))
+ .SET("product_url", StringUtils.trimToNull(record.getProductUrl()))
+ .SET("exclude_us_states", StringUtils.trimToNull(record.getExcludeUsStates()))
+ .SET("modified_by", record.getModifiedBy())
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .SET("sku_attributes", ProductJSONCommand.createJSONString(record), CastType.JSONB);
// 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("product_id = ?", record.getId()));
+ update.WHERE("product_id = ?", record.getId()).execute(connection);
// Manage the Product SKUs
ProductSkuRepository.saveProductSKUList(connection, record);
// Finish the transaction
@@ -288,10 +292,11 @@ public static Product update(Product record) {
}
public static boolean updateSquareCatalogIdForProductId(long productId, String squareCatalogId) {
- SqlUtils updateValues = new SqlUtils()
- .add("square_catalog_id", squareCatalogId)
- .add("modified", new Timestamp(System.currentTimeMillis()));
- DB.update(TABLE_NAME, updateValues, DB.WHERE("product_id = ?", productId));
+ DB.UPDATE(TABLE_NAME)
+ .SET("square_catalog_id", squareCatalogId)
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("product_id = ?", productId)
+ .execute();
return true;
}
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ProductSkuRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ProductSkuRepository.java
index d907aa7f7..d23e13f79 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ProductSkuRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ProductSkuRepository.java
@@ -30,6 +30,13 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import com.github.rajkowski.database.CastType;
+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.DateCommand;
import com.simisinc.platform.application.ecommerce.ProductInventoryCommand;
import com.simisinc.platform.application.ecommerce.ProductSkuJSONCommand;
@@ -37,12 +44,6 @@
import com.simisinc.platform.domain.model.ecommerce.Product;
import com.simisinc.platform.domain.model.ecommerce.ProductSku;
import com.simisinc.platform.domain.model.ecommerce.ProductSkuAttribute;
-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;
/**
@@ -58,27 +59,34 @@ public class ProductSkuRepository {
private static String TABLE_NAME = "product_skus";
private static String ADDITIONAL_SELECT = "products.active_date AS product_active_date," +
"products.deactivate_on AS product_deactivate_on";
- private static String JOIN = "LEFT JOIN products ON (product_skus.product_id = products.product_id)";
private static String[] PRIMARY_KEY = new String[] { "sku_id" };
- private static DataResult query(ProductSkuSpecification specification, DataConstraints constraints) {
- SqlUtils select = new SqlUtils().add(ADDITIONAL_SELECT);
- SqlWhere where = null;
+ private static DataResult query(ProductSkuSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("product_skus.*", ADDITIONAL_SELECT)
+ .FROM(TABLE_NAME)
+ .LEFT_JOIN("products")
+ .ON("product_skus.product_id = products.product_id")
+ .WHERE();
if (specification != null) {
- where = DB.WHERE()
- .andAddIfHasValue("sku_id = ?", specification.getId(), -1)
- .andAddIfHasValue("sku = ?", specification.getSku())
- .andAddIfHasValue("product_skus.product_id = ?", specification.getProductId(), -1)
- .andAddIfHasValue("products.product_unique_id = ?", specification.getProductUniqueId());
+ if (specification.getId() > -1) {
+ select.WHERE("sku_id = ?", specification.getId());
+ }
+ if (StringUtils.isNotBlank(specification.getSku())) {
+ select.AND("sku = ?", specification.getSku());
+ }
+ if (specification.getProductId() > -1) {
+ select.AND("product_skus.product_id = ?", specification.getProductId());
+ }
+ if (StringUtils.isNotBlank(specification.getProductUniqueId())) {
+ select.AND("products.product_unique_id = ?", specification.getProductUniqueId());
+ }
if (specification.getIsNotId() != -1) {
- where.AND("sku_id <> ?", specification.getIsNotId());
+ select.AND("sku_id <> ?", specification.getIsNotId());
}
if (specification.getShowOnline() != DataConstants.UNDEFINED) {
- where.AND("product_skus.enabled = " + (specification.getShowOnline() == DataConstants.TRUE ? "true" : "false"));
+ select.AND("product_skus.enabled = ?", specification.getShowOnline() == DataConstants.TRUE);
}
if (specification.getWithProductSkuAttributeList() != null && !specification.getWithProductSkuAttributeList().isEmpty()) {
- // SELECT * FROM product_skus WHERE attributes @> '[{"name":"attribute0", "value":"0.5 oz"}]' AND attributes @> '[{"name":"attribute1", "value":"Jasmine"}]';
- // SELECT * FROM product_skus WHERE attributes @> '[{"name":"attribute0", "value":"1.7 oz"}, {"name":"attribute1", "value":"Jasmine"}]';
StringBuilder sb = new StringBuilder();
int count = 0;
for (ProductSkuAttribute skuAttribute : specification.getWithProductSkuAttributeList()) {
@@ -93,19 +101,15 @@ private static DataResult query(ProductSkuSpecification specification, DataConst
.append("\"");
sb.append("}");
}
- if (sb.length() > 0) {
- where.AND("attributes @> ?::jsonb", "[" + sb.toString() + "]");
+ if (!sb.isEmpty()) {
+ select.AND("attributes @> ?::jsonb", "[" + sb + "]");
}
}
}
- return DB.selectAllFrom(
- TABLE_NAME,
- select,
- DB.JOIN(JOIN),
- where,
- null,
- constraints,
- ProductSkuRepository::buildRecord);
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(ProductSkuRepository::buildRecord);
}
public static List findAll(ProductSkuSpecification specification, DataConstraints constraints) {
@@ -113,38 +117,32 @@ public static List findAll(ProductSkuSpecification specification, Da
constraints = new DataConstraints();
}
constraints.setDefaultColumnToSortBy("sku_order, sku");
- DataResult result = query(specification, constraints);
- return (List) result.getRecords();
+ return query(specification, constraints).getRecords();
}
public static ProductSku findById(long id) {
if (id == -1) {
return null;
}
- SqlUtils select = new SqlUtils().add(ADDITIONAL_SELECT);
- return (ProductSku) DB.selectRecordFrom(
- TABLE_NAME,
- select,
- DB.JOIN(JOIN),
- DB.WHERE("sku_id = ?", id),
- ProductSkuRepository::buildRecord);
+ return DB.SELECT("product_skus.*", ADDITIONAL_SELECT)
+ .FROM(TABLE_NAME)
+ .LEFT_JOIN("products")
+ .ON("product_skus.product_id = products.product_id")
+ .WHERE("sku_id = ?", id)
+ .returnRecord(ProductSkuRepository::buildRecord);
}
public static List findAllByProductId(long productId) {
if (productId == -1) {
return null;
}
- SqlUtils select = new SqlUtils().add(ADDITIONAL_SELECT);
-
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- select,
- DB.JOIN(JOIN),
- DB.WHERE("product_skus.product_id = ?", productId),
- null,
- new DataConstraints().setDefaultColumnToSortBy("sku_id").setUseCount(false),
- ProductSkuRepository::buildRecord);
- return (List) result.getRecords();
+ return DB.SELECT("product_skus.*", ADDITIONAL_SELECT)
+ .FROM(TABLE_NAME)
+ .LEFT_JOIN("products")
+ .ON("product_skus.product_id = products.product_id")
+ .WHERE("product_skus.product_id = ?", productId)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("sku_id").setUseCount(false))
+ .returnDataResult(ProductSkuRepository::buildRecord).getRecords();
}
public static void saveProductSKUList(Connection connection, Product product) throws SQLException {
@@ -169,11 +167,11 @@ public static void saveProductSKUList(Connection connection, Product product) th
}
public static void remove(ProductSku record) {
- DB.deleteFrom(TABLE_NAME, DB.WHERE("sku_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("sku_id = ?", record.getId()).execute();
}
public static void removeAll(Connection connection, Product product) throws SQLException {
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("product_id = ?", product.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("product_id = ?", product.getId()).execute(connection);
}
public static ProductSku save(Connection connection, ProductSku record) throws SQLException {
@@ -184,33 +182,33 @@ public static ProductSku save(Connection connection, ProductSku record) throws S
}
public static ProductSku add(Connection connection, ProductSku record) throws SQLException {
- SqlUtils insertValues = new SqlUtils()
- .add("product_id", record.getProductId())
- .add("sku", StringUtils.trimToNull(record.getSku()))
- .add("currency", record.getCurrency())
- .add("price", record.getPrice())
- .add("strike_price", record.getStrikePrice())
- .add("cost_of_good", record.getCostOfGood())
- .add("barcode", record.getBarcode())
- .add("active_date", record.getActiveDate())
- .add("deactivate_on", record.getDeactivateOnDate())
- .add("available_date", record.getAvailableDate())
- .add("inventory_qty", record.getInventoryQty())
- .add("inventory_qty_low", record.getInventoryLow())
- .add("inventory_qty_incoming", record.getInventoryIncoming())
- .add("minimum_purchase_qty", record.getMinimumPurchaseQty())
- .add("maximum_purchase_qty", record.getMaximumPurchaseQty())
- .add("allow_backorders", record.getAllowBackorders())
- .add("package_height", record.getPackageHeight())
- .add("package_length", record.getPackageLength())
- .add("package_width", record.getPackageWidth())
- .add("package_weight_lbs", record.getPackageWeightPounds())
- .add("package_weight_ozs", record.getPackageWeightOunces())
- .add("enabled", record.getEnabled())
- .add("created_by", record.getCreatedBy(), -1)
- .add("modified_by", record.getModifiedBy(), -1);
- insertValues.add(new SqlValue("attributes", SqlValue.JSONB_TYPE, ProductSkuJSONCommand.createJSONString(record)));
- record.setId(DB.insertInto(connection, TABLE_NAME, insertValues, PRIMARY_KEY));
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("product_id", record.getProductId())
+ .FIELD("sku", StringUtils.trimToNull(record.getSku()))
+ .FIELD("currency", record.getCurrency())
+ .FIELD("price", record.getPrice())
+ .FIELD("strike_price", record.getStrikePrice())
+ .FIELD("cost_of_good", record.getCostOfGood())
+ .FIELD("barcode", record.getBarcode())
+ .FIELD("active_date", record.getActiveDate())
+ .FIELD("deactivate_on", record.getDeactivateOnDate())
+ .FIELD("available_date", record.getAvailableDate())
+ .FIELD("inventory_qty", record.getInventoryQty())
+ .FIELD("inventory_qty_low", record.getInventoryLow())
+ .FIELD("inventory_qty_incoming", record.getInventoryIncoming())
+ .FIELD("minimum_purchase_qty", record.getMinimumPurchaseQty())
+ .FIELD("maximum_purchase_qty", record.getMaximumPurchaseQty())
+ .FIELD("allow_backorders", record.getAllowBackorders())
+ .FIELD("package_height", record.getPackageHeight())
+ .FIELD("package_length", record.getPackageLength())
+ .FIELD("package_width", record.getPackageWidth())
+ .FIELD("package_weight_lbs", record.getPackageWeightPounds())
+ .FIELD("package_weight_ozs", record.getPackageWeightOunces())
+ .FIELD("enabled", record.getEnabled())
+ .FIELD("created_by", record.getCreatedBy() != -1 ? record.getCreatedBy() : null)
+ .FIELD("modified_by", record.getModifiedBy() != -1 ? record.getModifiedBy() : null)
+ .FIELD("attributes", ProductSkuJSONCommand.createJSONString(record), CastType.JSONB);
+ record.setId(insert.execute(connection));
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -219,30 +217,30 @@ public static ProductSku add(Connection connection, ProductSku record) throws SQ
}
public static ProductSku update(Connection connection, ProductSku record) throws SQLException {
- SqlUtils updateValues = new SqlUtils()
- .add("sku", StringUtils.trimToNull(record.getSku()))
- .add("currency", record.getCurrency())
- .add("price", record.getPrice())
- .add("strike_price", record.getStrikePrice())
- .add("cost_of_good", record.getCostOfGood())
- .add("barcode", record.getBarcode())
- .add("active_date", record.getActiveDate())
- .add("deactivate_on", record.getDeactivateOnDate())
- .add("available_date", record.getAvailableDate())
- .add("inventory_qty_low", record.getInventoryLow())
- .add("inventory_qty_incoming", record.getInventoryIncoming())
- .add("minimum_purchase_qty", record.getMinimumPurchaseQty())
- .add("maximum_purchase_qty", record.getMaximumPurchaseQty())
- .add("allow_backorders", record.getAllowBackorders())
- .add("package_height", record.getPackageHeight())
- .add("package_length", record.getPackageLength())
- .add("package_width", record.getPackageWidth())
- .add("package_weight_lbs", record.getPackageWeightPounds())
- .add("package_weight_ozs", record.getPackageWeightOunces())
- .add("enabled", record.getEnabled())
- .add("modified_by", record.getModifiedBy())
- .add("modified", new Timestamp(System.currentTimeMillis()));
- updateValues.add(new SqlValue("attributes", SqlValue.JSONB_TYPE, ProductSkuJSONCommand.createJSONString(record)));
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("sku", StringUtils.trimToNull(record.getSku()))
+ .SET("currency", record.getCurrency())
+ .SET("price", record.getPrice())
+ .SET("strike_price", record.getStrikePrice())
+ .SET("cost_of_good", record.getCostOfGood())
+ .SET("barcode", record.getBarcode())
+ .SET("active_date", record.getActiveDate())
+ .SET("deactivate_on", record.getDeactivateOnDate())
+ .SET("available_date", record.getAvailableDate())
+ .SET("inventory_qty_low", record.getInventoryLow())
+ .SET("inventory_qty_incoming", record.getInventoryIncoming())
+ .SET("minimum_purchase_qty", record.getMinimumPurchaseQty())
+ .SET("maximum_purchase_qty", record.getMaximumPurchaseQty())
+ .SET("allow_backorders", record.getAllowBackorders())
+ .SET("package_height", record.getPackageHeight())
+ .SET("package_length", record.getPackageLength())
+ .SET("package_width", record.getPackageWidth())
+ .SET("package_weight_lbs", record.getPackageWeightPounds())
+ .SET("package_weight_ozs", record.getPackageWeightOunces())
+ .SET("enabled", record.getEnabled())
+ .SET("modified_by", record.getModifiedBy())
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .SET("attributes", ProductSkuJSONCommand.createJSONString(record), CastType.JSONB);
// Determine if Qty State is being used
if (record.getInventoryQtyState() > -1) {
// The update will use an offset, not a setter for the inventory in case an order
@@ -251,9 +249,9 @@ public static ProductSku update(Connection connection, ProductSku record) throws
updateInventoryCount(connection, record.getId(), difference);
} else {
// state is not being used, so set the value
- updateValues.add("inventory_qty", record.getInventoryQty(), 0);
+ update.SET("inventory_qty", record.getInventoryQty() == 0 ? null : record.getInventoryQty());
}
- if (DB.update(connection, TABLE_NAME, updateValues, DB.WHERE("sku_id = ?", record.getId()))) {
+ if (update.WHERE("sku_id = ?", record.getId()).execute(connection).booleanValue()) {
return record;
}
LOG.error("The update failed!");
@@ -283,10 +281,11 @@ public static boolean updateInventoryCount(Connection connection, long productSk
}
public static boolean updateSquareVariationIdForProductSkuId(long productSkuId, String squareVariationId) {
- SqlUtils updateValues = new SqlUtils()
- .add("square_variation_id", squareVariationId)
- .add("modified", new Timestamp(System.currentTimeMillis()));
- DB.update(TABLE_NAME, updateValues, DB.WHERE("sku_id = ?", productSkuId));
+ DB.UPDATE(TABLE_NAME)
+ .SET("square_variation_id", squareVariationId)
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("sku_id = ?", productSkuId)
+ .execute();
return true;
}
@@ -356,27 +355,43 @@ private static ProductSku 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("sku");
- DB.exportToCsvAllFrom(
- TABLE_NAME,
- DB.SELECT(
- "sku AS \"SKU\"",
- "products.name AS \"Name\"",
- "products.caption AS \"Caption\"",
- "TRIM(concat_ws(' ', products.name, products.caption)) AS \"ItemName\"",
- "price AS \"Value\"",
- "(SELECT JSONB_AGG(t -> 'value') FROM JSONB_ARRAY_ELEMENTS(attributes) AS x(t) WHERE t ->> 'value' <> '') AS \"Attributes\"",
- "products.description AS \"Description\"",
- // "short_description AS \"ShortDescription\"",
- "barcode AS \"UPC\"",
- "product_skus.enabled AS \"Enabled\""),
- DB.JOIN(JOIN),
- DB.WHERE(),
- null,
- constraints, file);
+ Select select = DB.SELECT(
+ "sku AS \"SKU\"",
+ "products.name AS \"Name\"",
+ "products.caption AS \"Caption\"",
+ "TRIM(concat_ws(' ', products.name, products.caption)) AS \"ItemName\"",
+ "price AS \"Value\"",
+ "(SELECT JSONB_AGG(t -> 'value') FROM JSONB_ARRAY_ELEMENTS(attributes) AS x(t) WHERE t ->> 'value' <> '') AS \"Attributes\"",
+ "products.description AS \"Description\"",
+ "barcode AS \"UPC\"",
+ "product_skus.enabled AS \"Enabled\"")
+ .FROM(TABLE_NAME)
+ .JOIN("products")
+ .ON("product_skus.product_id = products.product_id")
+ .WITH(constraints);
+ writeCsvExport(select, file);
+ }
+
+ private static void writeCsvExport(Select select, File file) {
+ if (select == null || file == null) {
+ return;
+ }
+ try (Connection connection = DB.getConnection();
+ java.sql.PreparedStatement statement = connection.prepareStatement(select.getSql());
+ java.sql.ResultSet rs = statement.executeQuery()) {
+ java.io.BufferedWriter writer = new java.io.BufferedWriter(new java.io.FileWriter(file));
+ writer.write("SKU,Name,Caption,ItemName,Value,Attributes,Description,UPC,Enabled\n");
+ while (rs.next()) {
+ writer.write(rs.getString(1) + "," + rs.getString(2) + "," + rs.getString(3) + "," + rs.getString(4) + "," + rs.getString(5)
+ + "," + rs.getString(6) + "," + rs.getString(7) + "," + rs.getString(8) + "," + rs.getString(9) + "\n");
+ }
+ writer.flush();
+ } catch (SQLException | java.io.IOException se) {
+ LOG.error("Export SQLException", se);
+ }
}
}
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/SalesTaxNexusAddressRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/SalesTaxNexusAddressRepository.java
index 6fada0fa0..cba54bfb9 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/SalesTaxNexusAddressRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/SalesTaxNexusAddressRepository.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");
@@ -25,13 +26,12 @@
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.Update;
import com.simisinc.platform.domain.model.ecommerce.SalesTaxNexusAddress;
-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 sales tax nexus address objects
@@ -47,22 +47,17 @@ public class SalesTaxNexusAddressRepository {
private static String[] PRIMARY_KEY = new String[] { "address_id" };
public static List findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- null,
- new DataConstraints().setDefaultColumnToSortBy("address_id"),
- SalesTaxNexusAddressRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("address_id"))
+ .returnDataResult(SalesTaxNexusAddressRepository::buildRecord).getRecords();
}
public static SalesTaxNexusAddress findById(long addressId) {
- return (SalesTaxNexusAddress) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("address_id = ?", addressId),
- SalesTaxNexusAddressRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("address_id = ?", addressId)
+ .returnRecord(SalesTaxNexusAddressRepository::buildRecord);
}
public static SalesTaxNexusAddress save(SalesTaxNexusAddress record) {
@@ -76,9 +71,7 @@ public static boolean remove(SalesTaxNexusAddress record) {
try (Connection connection = DB.getConnection();
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
- // Delete the record
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("address_id = ?", record.getId()));
- // Finish transaction
+ DB.DELETE().FROM(TABLE_NAME).WHERE("address_id = ?", record.getId()).execute(connection);
transaction.commit();
return true;
} catch (SQLException se) {
@@ -93,20 +86,19 @@ public static SalesTaxNexusAddress add(SalesTaxNexusAddress record) {
try (Connection connection = DB.getConnection();
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
- // In a transaction (use the existing connection)
- SqlUtils insertValues = new SqlUtils()
- .add("street_address", record.getStreet())
- .add("address_line_2", record.getAddressLine2())
- .add("city", record.getCity())
- .add("state", record.getState())
- .add("country", record.getCountry())
- .add("postal_code", record.getPostalCode())
- .add("latitude", record.getLatitude())
- .add("longitude", record.getLongitude())
- .add("created_by", record.getCreatedBy())
- .add("modified_by", record.getModifiedBy());
- record.setId(DB.insertInto(connection, TABLE_NAME, insertValues, PRIMARY_KEY));
- // Finish the transaction
+ long generatedId = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("street_address", record.getStreet())
+ .FIELD("address_line_2", record.getAddressLine2())
+ .FIELD("city", record.getCity())
+ .FIELD("state", record.getState())
+ .FIELD("country", record.getCountry())
+ .FIELD("postal_code", record.getPostalCode())
+ .FIELD("latitude", record.getLatitude())
+ .FIELD("longitude", record.getLongitude())
+ .FIELD("created_by", record.getCreatedBy())
+ .FIELD("modified_by", record.getModifiedBy())
+ .execute(connection);
+ record.setId(generatedId);
transaction.commit();
return record;
} catch (SQLException se) {
@@ -116,19 +108,19 @@ public static SalesTaxNexusAddress add(SalesTaxNexusAddress record) {
}
public static SalesTaxNexusAddress update(SalesTaxNexusAddress record) {
- SqlUtils updateValues = new SqlUtils()
- .add("street_address", record.getStreet())
- .add("address_line_2", record.getAddressLine2())
- .add("city", record.getCity())
- .add("state", record.getState())
- .add("country", record.getCountry())
- .add("postal_code", record.getPostalCode())
- .add("latitude", record.getLatitude())
- .add("longitude", record.getLongitude())
- .add("modified_by", record.getModifiedBy())
- .add("modified", new Timestamp(System.currentTimeMillis()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("address_id = ?", record.getId()))) {
- // CacheManager.invalidateKey(CacheManager.CONTENT_UNIQUE_ID_CACHE, record.getUniqueId());
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("street_address", record.getStreet())
+ .SET("address_line_2", record.getAddressLine2())
+ .SET("city", record.getCity())
+ .SET("state", record.getState())
+ .SET("country", record.getCountry())
+ .SET("postal_code", record.getPostalCode())
+ .SET("latitude", record.getLatitude())
+ .SET("longitude", record.getLongitude())
+ .SET("modified_by", record.getModifiedBy())
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("address_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("The update failed!");
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ShippingCarrierRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ShippingCarrierRepository.java
index 4bcb41ebf..1f0f2470a 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ShippingCarrierRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ShippingCarrierRepository.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");
@@ -25,13 +26,13 @@
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.Insert;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.domain.model.ecommerce.ShippingCarrier;
-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 shipping carrier objects
@@ -47,35 +48,30 @@ public class ShippingCarrierRepository {
private static String[] PRIMARY_KEY = new String[] { "carrier_id" };
public static List findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- null,
- new DataConstraints().setDefaultColumnToSortBy("level"),
- ShippingCarrierRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("level"))
+ .returnDataResult(ShippingCarrierRepository::buildRecord).getRecords();
}
public static ShippingCarrier findById(long carrierId) {
if (carrierId == -1) {
return null;
}
- return (ShippingCarrier) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("carrier_id = ?", carrierId),
- ShippingCarrierRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("carrier_id = ?", carrierId)
+ .returnRecord(ShippingCarrierRepository::buildRecord);
}
public static ShippingCarrier findByCode(String code) {
if (StringUtils.isBlank(code)) {
return null;
}
- return (ShippingCarrier) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("UPPER(code) = ?", code.toUpperCase()),
- ShippingCarrierRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("UPPER(code) = ?", code.toUpperCase())
+ .returnRecord(ShippingCarrierRepository::buildRecord);
}
public static ShippingCarrier save(ShippingCarrier record) {
@@ -90,16 +86,12 @@ public static ShippingCarrier add(ShippingCarrier record) {
try (Connection connection = DB.getConnection();
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
- // In a transaction (use the existing connection)
- SqlUtils insertValues = new SqlUtils()
- .add("level", record.getLevel())
- .add("code", record.getCode())
- .add("title", record.getTitle())
- .add("enabled", record.getEnabled());
- // .addIfExists("created_by", record.getCreatedBy(), -1)
- // .addIfExists("modified_by", record.getModifiedBy(), -1);
- record.setId(DB.insertInto(connection, TABLE_NAME, insertValues, PRIMARY_KEY));
- // Finish the transaction
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("level", record.getLevel())
+ .FIELD("code", record.getCode())
+ .FIELD("title", record.getTitle())
+ .FIELD("enabled", record.getEnabled());
+ record.setId(insert.execute(connection));
transaction.commit();
return record;
} catch (SQLException se) {
@@ -109,15 +101,13 @@ public static ShippingCarrier add(ShippingCarrier record) {
}
public static ShippingCarrier update(ShippingCarrier record) {
- SqlUtils updateValues = new SqlUtils()
- .add("level", record.getLevel())
- .add("code", record.getCode())
- .add("title", record.getTitle())
- .add("enabled", record.getEnabled());
- // .add("modified_by", record.getModifiedBy(), -1)
- // .add("modified", new Timestamp(System.currentTimeMillis()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("carrier_id = ?", record.getId()))) {
- // CacheManager.invalidateKey(CacheManager.CONTENT_UNIQUE_ID_CACHE, record.getUniqueId());
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("level", record.getLevel())
+ .SET("code", record.getCode())
+ .SET("title", record.getTitle())
+ .SET("enabled", record.getEnabled())
+ .WHERE("carrier_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("The update failed!");
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ShippingCountryRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ShippingCountryRepository.java
index 32a5698a7..1bcad8494 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ShippingCountryRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ShippingCountryRepository.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,13 +25,13 @@
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.Insert;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.domain.model.ecommerce.ShippingCountry;
-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 shipping country objects
@@ -46,30 +47,25 @@ public class ShippingCountryRepository {
private static String[] PRIMARY_KEY = new String[] { "country_id" };
public static List findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- null,
- new DataConstraints().setDefaultColumnToSortBy("level"),
- ShippingCountryRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("level"))
+ .returnDataResult(ShippingCountryRepository::buildRecord).getRecords();
}
public static ShippingCountry findById(long countryId) {
- return (ShippingCountry) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("country_id = ?", countryId),
- ShippingCountryRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("country_id = ?", countryId)
+ .returnRecord(ShippingCountryRepository::buildRecord);
}
public static ShippingCountry findByEnabledCountry(String name) {
- return (ShippingCountry) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("LOWER(title) = ?", name.toLowerCase())
- .AND("enabled = ?", true),
- ShippingCountryRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("LOWER(title) = ?", name.toLowerCase())
+ .AND("enabled = ?", true)
+ .returnRecord(ShippingCountryRepository::buildRecord);
}
public static ShippingCountry save(ShippingCountry record) {
@@ -84,16 +80,12 @@ public static ShippingCountry add(ShippingCountry record) {
try (Connection connection = DB.getConnection();
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
- // In a transaction (use the existing connection)
- SqlUtils insertValues = new SqlUtils()
- .add("level", record.getLevel())
- .add("code", record.getCode())
- .add("title", record.getTitle())
- .add("enabled", record.getEnabled());
- // .addIfExists("created_by", record.getCreatedBy(), -1)
- // .addIfExists("modified_by", record.getModifiedBy(), -1);
- record.setId(DB.insertInto(connection, TABLE_NAME, insertValues, PRIMARY_KEY));
- // Finish the transaction
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("level", record.getLevel())
+ .FIELD("code", record.getCode())
+ .FIELD("title", record.getTitle())
+ .FIELD("enabled", record.getEnabled());
+ record.setId(insert.execute(connection));
transaction.commit();
return record;
} catch (SQLException se) {
@@ -103,15 +95,13 @@ public static ShippingCountry add(ShippingCountry record) {
}
public static ShippingCountry update(ShippingCountry record) {
- SqlUtils updateValues = new SqlUtils()
- .add("level", record.getLevel())
- .add("code", record.getCode())
- .add("title", record.getTitle())
- .add("enabled", record.getEnabled());
- // .add("modified_by", record.getModifiedBy(), -1)
- // .add("modified", new Timestamp(System.currentTimeMillis()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("country_id = ?", record.getId()))) {
- // CacheManager.invalidateKey(CacheManager.CONTENT_UNIQUE_ID_CACHE, record.getUniqueId());
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("level", record.getLevel())
+ .SET("code", record.getCode())
+ .SET("title", record.getTitle())
+ .SET("enabled", record.getEnabled())
+ .WHERE("country_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("The update failed!");
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ShippingMethodRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ShippingMethodRepository.java
index dd920f05a..e1e90e80a 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ShippingMethodRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ShippingMethodRepository.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,13 +25,13 @@
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.Insert;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.domain.model.ecommerce.ShippingMethod;
-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 shipping method objects
@@ -46,22 +47,17 @@ public class ShippingMethodRepository {
private static String[] PRIMARY_KEY = new String[] { "method_id" };
public static List findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- null,
- new DataConstraints().setDefaultColumnToSortBy("level"),
- ShippingMethodRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("level"))
+ .returnDataResult(ShippingMethodRepository::buildRecord).getRecords();
}
public static ShippingMethod findById(long methodId) {
- return (ShippingMethod) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("method_id = ?", methodId),
- ShippingMethodRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("method_id = ?", methodId)
+ .returnRecord(ShippingMethodRepository::buildRecord);
}
public static ShippingMethod save(ShippingMethod record) {
@@ -76,16 +72,12 @@ public static ShippingMethod add(ShippingMethod record) {
try (Connection connection = DB.getConnection();
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
- // In a transaction (use the existing connection)
- SqlUtils insertValues = new SqlUtils()
- .add("level", record.getLevel())
- .add("code", record.getCode())
- .add("title", record.getTitle())
- .add("enabled", record.getEnabled());
- // .addIfExists("created_by", record.getCreatedBy(), -1)
- // .addIfExists("modified_by", record.getModifiedBy(), -1);
- record.setId(DB.insertInto(connection, TABLE_NAME, insertValues, PRIMARY_KEY));
- // Finish the transaction
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("level", record.getLevel())
+ .FIELD("code", record.getCode())
+ .FIELD("title", record.getTitle())
+ .FIELD("enabled", record.getEnabled());
+ record.setId(insert.execute(connection));
transaction.commit();
return record;
} catch (SQLException se) {
@@ -95,15 +87,13 @@ public static ShippingMethod add(ShippingMethod record) {
}
public static ShippingMethod update(ShippingMethod record) {
- SqlUtils updateValues = new SqlUtils()
- .add("level", record.getLevel())
- .add("code", record.getCode())
- .add("title", record.getTitle())
- .add("enabled", record.getEnabled());
- // .add("modified_by", record.getModifiedBy(), -1)
- // .add("modified", new Timestamp(System.currentTimeMillis()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("method_id = ?", record.getId()))) {
- // CacheManager.invalidateKey(CacheManager.CONTENT_UNIQUE_ID_CACHE, record.getUniqueId());
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("level", record.getLevel())
+ .SET("code", record.getCode())
+ .SET("title", record.getTitle())
+ .SET("enabled", record.getEnabled())
+ .WHERE("method_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("The update failed!");
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ShippingRateRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ShippingRateRepository.java
index e05d31b5c..aae2602ab 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ShippingRateRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/ShippingRateRepository.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");
@@ -25,15 +26,13 @@
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.Select;
import com.simisinc.platform.domain.model.ecommerce.ShippingRate;
-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.SqlWhere;
/**
* Persists and retrieves shipping rate objects
@@ -50,53 +49,46 @@ public class ShippingRateRepository {
private static String JOIN = "LEFT JOIN lookup_shipping_method ON (shipping_rates.shipping_method = lookup_shipping_method.method_id)";
private static String[] PRIMARY_KEY = new String[] { "rate_id" };
- private static DataResult query(ShippingRateSpecification specification, DataConstraints constraints) {
- SqlUtils select = new SqlUtils().add(ADDITIONAL_SELECT);
- SqlJoins joins = new SqlJoins().add(JOIN);
- SqlWhere where = DB.WHERE();
- // Use the specification to find the best matching rate for the given address
+ private static DataResult query(ShippingRateSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("shipping_rates.*", ADDITIONAL_SELECT).FROM(TABLE_NAME).WHERE();
+ select.LEFT_JOIN("lookup_shipping_method")
+ .ON("shipping_rates.shipping_method = lookup_shipping_method.method_id");
+
if (specification != null) {
if (StringUtils.isNotBlank(specification.getCountryCode())) {
- where.AND("country_code = ?", specification.getCountryCode());
+ select.AND("country_code = ?", specification.getCountryCode());
}
if (StringUtils.isNotBlank(specification.getRegion()) && StringUtils.isNotBlank(specification.getPostalCode())) {
String region = specification.getRegion();
String postalCode = specification.getPostalCode();
if ("*".equals(region) && "*".equals(postalCode)) {
- // Non-specific, fall-back
- where.AND("postal_code = '*'");
- where.AND("region = '*'");
+ select.AND("postal_code = '*'");
+ select.AND("region = '*'");
} else {
- // Location specific and non-specific
- if ("US".equals(specification.getCountryCode())) {
- if (postalCode.length() > 5) {
- postalCode = postalCode.substring(0, 5);
- }
+ if ("US".equals(specification.getCountryCode()) && postalCode.length() > 5) {
+ postalCode = postalCode.substring(0, 5);
}
- // Determine the region setting
if (specification.getSpecificRegionOnly()) {
- // Look for a specific region (like Alaska, Hawaii)
- where.AND("(postal_code = ? OR (postal_code = '*' AND region = ?))", new String[] { postalCode, region });
+ select.AND("(postal_code = ? OR (postal_code = '*' AND region = ?))", postalCode, region);
} else {
- // Use any generic region
- where.AND("(postal_code = ? OR (postal_code = '*' AND region = ?) OR (postal_code = '*' AND region = '*'))",
- new String[] { postalCode, region });
+ select.AND("(postal_code = ? OR (postal_code = '*' AND region = ?) OR (postal_code = '*' AND region = '*'))",
+ postalCode, region);
}
}
}
if (specification.getOrderSubtotal() != null) {
- where.AND("min_subtotal <= ?", specification.getOrderSubtotal());
+ select.AND("min_subtotal <= ?", specification.getOrderSubtotal());
}
if (specification.getPackageTotalWeightOz() >= 0) {
- where.AND("min_weight_oz <= ?", specification.getPackageTotalWeightOz());
+ select.AND("min_weight_oz <= ?", specification.getPackageTotalWeightOz());
}
if (specification.getEnabledOnly()) {
- where.AND("lookup_shipping_method.enabled = ?", true);
+ select.AND("lookup_shipping_method.enabled = ?", true);
}
constraints.setDefaultColumnToSortBy("postal_code, region, shipping_method, shipping_fee");
}
- return DB.selectAllFrom(TABLE_NAME, select, joins, where, null, constraints, ShippingRateRepository::buildRecord);
+ return select.WITH(constraints).returnDataResult(ShippingRateRepository::buildRecord);
}
public static List findAll(ShippingRateSpecification specification, DataConstraints constraints) {
@@ -104,19 +96,16 @@ public static List findAll(ShippingRateSpecification specification
constraints = new DataConstraints();
}
constraints.setDefaultColumnToSortBy("country_code, region, postal_code, shipping_method, shipping_fee");
- DataResult result = query(specification, constraints);
- return (List) result.getRecords();
+ return query(specification, constraints).getRecords();
}
public static ShippingRate findById(long shippingRateId) {
- SqlUtils select = new SqlUtils().add(ADDITIONAL_SELECT);
- SqlJoins joins = new SqlJoins().add(JOIN);
- return (ShippingRate) DB.selectRecordFrom(
- TABLE_NAME,
- select,
- joins,
- DB.WHERE("rate_id = ?", shippingRateId),
- ShippingRateRepository::buildRecord);
+ return DB.SELECT("shipping_rates.*", ADDITIONAL_SELECT)
+ .FROM(TABLE_NAME)
+ .LEFT_JOIN("lookup_shipping_method")
+ .ON("shipping_rates.shipping_method = lookup_shipping_method.method_id")
+ .WHERE("rate_id = ?", shippingRateId)
+ .returnRecord(ShippingRateRepository::buildRecord);
}
public static ShippingRate save(ShippingRate record) {
@@ -127,27 +116,23 @@ public static ShippingRate save(ShippingRate record) {
}
public static ShippingRate add(ShippingRate record) {
- // 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)
- SqlUtils insertValues = new SqlUtils()
- .add("country_code", record.getCountryCode())
- .add("region", record.getRegion())
- .add("postal_code", record.getPostalCode())
- .add("min_subtotal", record.getMinSubTotal())
- .add("min_weight_oz", record.getMinWeightOz())
- .add("shipping_fee", record.getShippingFee())
- .add("handling_fee", record.getHandlingFee())
- .add("shipping_code", record.getShippingCode())
- .add("shipping_method", record.getShippingMethodId())
- .add("display_text", record.getDisplayText())
- .add("exclude_skus", record.getExcludeSkus());
- // .addIfExists("created_by", record.getCreatedBy(), -1)
- // .addIfExists("modified_by", record.getModifiedBy(), -1);
- record.setId(DB.insertInto(connection, TABLE_NAME, insertValues, PRIMARY_KEY));
- // Finish the transaction
+ long generatedId = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("country_code", record.getCountryCode())
+ .FIELD("region", record.getRegion())
+ .FIELD("postal_code", record.getPostalCode())
+ .FIELD("min_subtotal", record.getMinSubTotal())
+ .FIELD("min_weight_oz", record.getMinWeightOz())
+ .FIELD("shipping_fee", record.getShippingFee())
+ .FIELD("handling_fee", record.getHandlingFee())
+ .FIELD("shipping_code", record.getShippingCode())
+ .FIELD("shipping_method", record.getShippingMethodId())
+ .FIELD("display_text", record.getDisplayText())
+ .FIELD("exclude_skus", record.getExcludeSkus())
+ .execute(connection);
+ record.setId(generatedId);
transaction.commit();
return record;
} catch (SQLException se) {
@@ -157,22 +142,21 @@ public static ShippingRate add(ShippingRate record) {
}
public static ShippingRate update(ShippingRate record) {
- SqlUtils updateValues = new SqlUtils()
- .add("country_code", record.getCountryCode())
- .add("region", record.getRegion())
- .add("postal_code", record.getPostalCode())
- .add("min_subtotal", record.getMinSubTotal())
- .add("min_weight_oz", record.getMinWeightOz())
- .add("shipping_fee", record.getShippingFee())
- .add("handling_fee", record.getHandlingFee())
- .add("shipping_code", record.getShippingCode())
- .add("shipping_method", record.getShippingMethodId())
- .add("display_text", record.getDisplayText())
- .add("exclude_skus", record.getExcludeSkus());
- // .add("modified_by", record.getModifiedBy(), -1)
- // .add("modified", new Timestamp(System.currentTimeMillis()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("rate_id = ?", record.getId()))) {
- // CacheManager.invalidateKey(CacheManager.CONTENT_UNIQUE_ID_CACHE, record.getUniqueId());
+ boolean updated = DB.UPDATE(TABLE_NAME)
+ .SET("country_code", record.getCountryCode())
+ .SET("region", record.getRegion())
+ .SET("postal_code", record.getPostalCode())
+ .SET("min_subtotal", record.getMinSubTotal())
+ .SET("min_weight_oz", record.getMinWeightOz())
+ .SET("shipping_fee", record.getShippingFee())
+ .SET("handling_fee", record.getHandlingFee())
+ .SET("shipping_code", record.getShippingCode())
+ .SET("shipping_method", record.getShippingMethodId())
+ .SET("display_text", record.getDisplayText())
+ .SET("exclude_skus", record.getExcludeSkus())
+ .WHERE("rate_id = ?", record.getId())
+ .execute();
+ if (updated) {
return record;
}
LOG.error("The update failed!");
@@ -180,7 +164,7 @@ public static ShippingRate update(ShippingRate record) {
}
public static boolean remove(ShippingRate record) {
- return DB.deleteFrom(TABLE_NAME, DB.WHERE("rate_id = ?", record.getId())) > 0;
+ return DB.DELETE().FROM(TABLE_NAME).WHERE("rate_id = ?", record.getId()).execute();
}
private static ShippingRate buildRecord(ResultSet rs) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/TrackingNumberRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/TrackingNumberRepository.java
index 81ca95d2b..28f5dbe42 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/TrackingNumberRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/TrackingNumberRepository.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");
@@ -25,13 +26,13 @@
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.Insert;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.domain.model.ecommerce.TrackingNumber;
-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 tracking number objects
@@ -47,25 +48,26 @@ public class TrackingNumberRepository {
private static String[] PRIMARY_KEY = new String[] { "tracking_id" };
public static TrackingNumber findById(long trackingId) {
- return (TrackingNumber) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("tracking_id = ?", trackingId),
- TrackingNumberRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("tracking_id = ?", trackingId)
+ .returnRecord(TrackingNumberRepository::buildRecord);
}
public static List findAllForOrderId(long orderId) {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- DB.WHERE("order_id = ?", orderId),
- new DataConstraints().setDefaultColumnToSortBy("created").setUseCount(false),
- TrackingNumberRepository::buildRecord);
- return (List) result.getRecords();
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("order_id = ?", orderId)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("created").setUseCount(false))
+ .returnDataResult(TrackingNumberRepository::buildRecord).getRecords();
}
public static boolean exists(TrackingNumber record) {
- return DB.selectCountFrom(TABLE_NAME,
- DB.WHERE("order_id = ?", record.getOrderId())
- .AND("tracking_number = ?", StringUtils.trimToNull(record.getTrackingNumber()))) > 0;
+ return DB.SELECT().COUNT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("order_id = ?", record.getOrderId())
+ .AND("tracking_number = ?", StringUtils.trimToNull(record.getTrackingNumber()))
+ .returnCount() > 0;
}
public static TrackingNumber save(TrackingNumber record) {
@@ -81,20 +83,17 @@ private static TrackingNumber add(TrackingNumber record) {
try (Connection connection = DB.getConnection();
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
- // Add the record
- SqlUtils insertValues = new SqlUtils()
- .add("order_id", record.getOrderId())
- .add("tracking_number", StringUtils.trimToNull(record.getTrackingNumber()))
- .addIfExists("shipping_carrier", record.getShippingCarrierId(), -1)
- .addIfExists("created_by", record.getCreatedBy(), -1)
- .addIfExists("ship_date", record.getShipDate())
- .addIfExists("delivery_date", record.getDeliveryDate())
- .add("cart_item_id_list", StringUtils.trimToNull(record.getCartItemIdList()))
- .add("order_item_id_list", StringUtils.trimToNull(record.getOrderItemIdList()));
- record.setId(DB.insertInto(connection, TABLE_NAME, insertValues, PRIMARY_KEY));
- // Maintain an updated field in the order table
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("order_id", record.getOrderId())
+ .FIELD("tracking_number", StringUtils.trimToNull(record.getTrackingNumber()))
+ .FIELD_UNLESS_MATCHES("shipping_carrier", record.getShippingCarrierId(), -1)
+ .FIELD_UNLESS_MATCHES("created_by", record.getCreatedBy(), -1)
+ .FIELD_UNLESS_NULL("ship_date", record.getShipDate())
+ .FIELD_UNLESS_NULL("delivery_date", record.getDeliveryDate())
+ .FIELD("cart_item_id_list", StringUtils.trimToNull(record.getCartItemIdList()))
+ .FIELD("order_item_id_list", StringUtils.trimToNull(record.getOrderItemIdList()));
+ record.setId(insert.execute(connection));
updateOrderField(connection, record);
- // Finish the transaction
transaction.commit();
return record;
} catch (SQLException se) {
@@ -109,18 +108,16 @@ private static TrackingNumber update(TrackingNumber record) {
try (Connection connection = DB.getConnection();
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
- // Update the record
- SqlUtils updateValues = new SqlUtils()
- .add("tracking_number", StringUtils.trimToNull(record.getTrackingNumber()))
- .addIfExists("shipping_carrier", record.getShippingCarrierId(), -1)
- .addIfExists("ship_date", record.getShipDate())
- .addIfExists("delivery_date", record.getDeliveryDate())
- .add("cart_item_id_list", StringUtils.trimToNull(record.getCartItemIdList()))
- .add("order_item_id_list", StringUtils.trimToNull(record.getOrderItemIdList()));
- if (DB.update(connection, TABLE_NAME, updateValues, DB.WHERE("tracking_id = ?", record.getId()))) {
- // Maintain an updated field in the order table
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("tracking_number", StringUtils.trimToNull(record.getTrackingNumber()))
+ .SET_UNLESS_MATCHES("shipping_carrier", record.getShippingCarrierId(), -1)
+ .SET_UNLESS_NULL("ship_date", record.getShipDate())
+ .SET_UNLESS_NULL("delivery_date", record.getDeliveryDate())
+ .SET("cart_item_id_list", StringUtils.trimToNull(record.getCartItemIdList()))
+ .SET("order_item_id_list", StringUtils.trimToNull(record.getOrderItemIdList()))
+ .WHERE("tracking_id = ?", record.getId());
+ if (update.execute(connection).booleanValue()) {
updateOrderField(connection, record);
- // Finish the transaction
transaction.commit();
return record;
}
@@ -132,15 +129,13 @@ private static TrackingNumber update(TrackingNumber record) {
/** Update the order field */
private static void updateOrderField(Connection connection, TrackingNumber record) throws SQLException {
- SqlUtils update = new SqlUtils()
- .add("tracking_numbers = sub_q.agg_value " +
- "FROM " +
- "(" +
- "SELECT string_agg(tracking_number, ',') AS agg_value " +
- "FROM order_tracking_numbers AS tn " +
- "WHERE tn.order_id = ?" +
- ") AS sub_q", record.getOrderId());
- DB.update(connection, "orders", update, DB.WHERE("orders.order_id = ?", record.getOrderId()));
+ DB.UPDATE("orders")
+ .SET(
+ "tracking_numbers = sub_q.agg_value FROM (SELECT string_agg(tracking_number, ',') AS agg_value " +
+ "FROM order_tracking_numbers AS tn WHERE tn.order_id = ?) AS sub_q",
+ record.getOrderId())
+ .WHERE("orders.order_id = ?", record.getOrderId())
+ .execute(connection);
}
private static TrackingNumber buildRecord(ResultSet rs) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/USSalesTaxRatesRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/USSalesTaxRatesRepository.java
index bd0a3e9d7..fa70c0a43 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/USSalesTaxRatesRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/ecommerce/USSalesTaxRatesRepository.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.github.rajkowski.database.Select;
import com.simisinc.platform.domain.model.ecommerce.USSalesTaxRate;
-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 US sales tax rates objects
@@ -43,24 +43,24 @@ public class USSalesTaxRatesRepository {
private static String TABLE_NAME = "us_sales_tax_rates";
- private static DataResult query(USSalesTaxRatesSpecification specification, DataConstraints constraints) {
- SqlUtils select = new SqlUtils();
- SqlWhere where = DB.WHERE();
- SqlUtils orderBy = new SqlUtils();
+ private static DataResult query(USSalesTaxRatesSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("*").FROM(TABLE_NAME).WHERE();
if (specification != null) {
if (specification.getStateAbbreviation() != null) {
- where.AND("state = ?", specification.getStateAbbreviation().toUpperCase());
+ select.AND("state = ?", specification.getStateAbbreviation().toUpperCase());
}
if (specification.getZipCode() != null) {
String zipCode = specification.getZipCode();
if (zipCode.length() > 5) {
zipCode = zipCode.substring(0, 5);
}
- where.AND("zip_code = ?", zipCode);
+ select.AND("zip_code = ?", zipCode);
}
}
- return DB.selectAllFrom(
- TABLE_NAME, select, where, orderBy, constraints, USSalesTaxRatesRepository::buildRecord);
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(USSalesTaxRatesRepository::buildRecord);
}
public static List findAll(USSalesTaxRatesSpecification specification, DataConstraints constraints) {
@@ -82,21 +82,21 @@ public static USSalesTaxRate findByStateZipCode(String state, String zipCode) {
if (zipCode.length() > 5) {
zipCode = zipCode.substring(0, 5);
}
- return (USSalesTaxRate) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("state = ?", state.toUpperCase())
- .AND("zip_code = ?", zipCode),
- USSalesTaxRatesRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("state = ?", state.toUpperCase())
+ .AND("zip_code = ?", zipCode)
+ .returnRecord(USSalesTaxRatesRepository::buildRecord);
}
public static USSalesTaxRate findByState(String state) {
if (StringUtils.isBlank(state)) {
return null;
}
- return (USSalesTaxRate) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("state = ?", state.toUpperCase()),
- USSalesTaxRatesRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("state = ?", state.toUpperCase())
+ .returnRecord(USSalesTaxRatesRepository::buildRecord);
}
private static USSalesTaxRate buildRecord(ResultSet rs) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/items/ActivityRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/items/ActivityRepository.java
index 2af8b3089..21392ee3c 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/items/ActivityRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/items/ActivityRepository.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.domain.model.items.Activity;
import com.simisinc.platform.domain.model.items.Collection;
import com.simisinc.platform.domain.model.items.Item;
-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 activity objects
@@ -58,20 +60,17 @@ public static Activity save(Activity record) {
}
private static Activity add(Activity record) {
- SqlUtils insertValues = new SqlUtils()
- .add("item_id", record.getItemId())
- .add("collection_id", record.getCollectionId())
- .add("activity_type", record.getActivityType())
- .add("message_text", StringUtils.trimToNull(record.getMessageText()))
- .add("created_by", record.getCreatedBy())
- .add("modified_by", record.getModifiedBy());
- // Use a transaction for related data
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));
- // Finish the transaction
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("item_id", record.getItemId())
+ .FIELD("collection_id", record.getCollectionId())
+ .FIELD("activity_type", record.getActivityType())
+ .FIELD("message_text", StringUtils.trimToNull(record.getMessageText()))
+ .FIELD("created_by", record.getCreatedBy())
+ .FIELD("modified_by", record.getModifiedBy());
+ record.setId(insert.execute(connection));
transaction.commit();
return record;
} catch (SQLException se) {
@@ -82,11 +81,12 @@ private static Activity add(Activity record) {
}
private static Activity update(Activity record) {
- SqlUtils updateValues = new SqlUtils()
- .add("message_text", StringUtils.trimToNull(record.getMessageText()))
- .add("modified_by", record.getModifiedBy())
- .add("modified", new Timestamp(System.currentTimeMillis()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("activity_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("message_text", StringUtils.trimToNull(record.getMessageText()))
+ .SET("modified_by", record.getModifiedBy())
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("activity_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("The update failed!");
@@ -97,10 +97,7 @@ public static boolean remove(Activity record) {
try (Connection connection = DB.getConnection();
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
- // Delete the references
- // Delete the record
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("activity_id = ?", record.getId()));
- // Finish transaction
+ DB.DELETE().FROM(TABLE_NAME).WHERE("activity_id = ?", record.getId()).execute(connection);
transaction.commit();
return true;
} catch (SQLException se) {
@@ -110,44 +107,49 @@ public static boolean remove(Activity record) {
}
public static void removeAll(Connection connection, Item record) throws SQLException {
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("item_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("item_id = ?", record.getId()).execute(connection);
}
public static void removeAll(Connection connection, Collection record) throws SQLException {
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("collection_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("collection_id = ?", record.getId()).execute(connection);
}
private static DataResult query(ActivitySpecification specification, DataConstraints constraints) {
- SqlUtils select = new SqlUtils();
- SqlWhere where = DB.WHERE();
- SqlUtils orderBy = new SqlUtils();
+ Select select = DB.SELECT("*").FROM(TABLE_NAME).WHERE();
if (specification != null) {
- where
- .andAddIfHasValue("item_id = ?", specification.getItemId(), -1)
- .andAddIfHasValue("collection_id = ?", specification.getCollectionId(), -1)
- .andAddIfHasValue("created_by = ?", specification.getCreatedBy(), -1);
+ if (specification.getItemId() != -1) {
+ select.AND("item_id = ?", specification.getItemId());
+ }
+ if (specification.getCollectionId() != -1) {
+ select.AND("collection_id = ?", specification.getCollectionId());
+ }
+ if (specification.getCreatedBy() != -1) {
+ select.AND("created_by = ?", specification.getCreatedBy());
+ }
if (specification.getActivityType() != null) {
- where.AND("upper(activity_type) = ?", specification.getActivityType().trim().toUpperCase());
+ select.AND("upper(activity_type) = ?", specification.getActivityType().trim().toUpperCase());
}
if (specification.getMinTimestamp() > 0) {
- where.AND("created >= ?", new Timestamp(specification.getMinTimestamp()));
+ select.AND("created >= ?", new Timestamp(specification.getMinTimestamp()));
}
if (specification.getMaxTimestamp() > 0) {
- where.AND("created <= ?", new Timestamp(specification.getMaxTimestamp()));
+ select.AND("created <= ?", new Timestamp(specification.getMaxTimestamp()));
}
}
- return DB.selectAllFrom(
- TABLE_NAME, select, where, orderBy, constraints, ActivityRepository::buildRecord);
+ if (constraints != null) {
+ select.WITH(constraints);
+ }
+ return select.returnDataResult(ActivityRepository::buildRecord);
}
public static Activity findById(long id) {
if (id == -1) {
return null;
}
- return (Activity) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("activity_id = ?", id),
- ActivityRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("activity_id = ?", id)
+ .returnRecord(ActivityRepository::buildRecord);
}
public static List findAll(ActivitySpecification specification, DataConstraints constraints) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CategoryRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CategoryRepository.java
index e5374e436..a07928aec 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CategoryRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CategoryRepository.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,15 +28,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.items.Category;
import com.simisinc.platform.domain.model.items.Collection;
-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 category objects
@@ -54,21 +56,21 @@ public static Category findById(long id) {
if (id == -1) {
return null;
}
- return (Category) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("category_id = ?", id),
- CategoryRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("category_id = ?", id)
+ .returnRecord(CategoryRepository::buildRecord);
}
public static Category findByUniqueIdWithinCollection(String uniqueId, long collectionId) {
if (StringUtils.isBlank(uniqueId)) {
return null;
}
- return (Category) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("collection_id = ?", collectionId)
- .AND("unique_id = ?", uniqueId),
- CategoryRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("collection_id = ?", collectionId)
+ .AND("unique_id = ?", uniqueId)
+ .returnRecord(CategoryRepository::buildRecord);
}
public static Category findByNameWithinCollection(String name, long collectionId) {
@@ -78,23 +80,23 @@ public static Category findByNameWithinCollection(String name, long collectionId
if (StringUtils.isBlank(name)) {
return null;
}
- return (Category) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("collection_id = ?", collectionId)
- .AND("LOWER(name) = ?", name.trim().toLowerCase()),
- CategoryRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("collection_id = ?", collectionId)
+ .AND("LOWER(name) = ?", name.trim().toLowerCase())
+ .returnRecord(CategoryRepository::buildRecord);
}
public static List findAllByItemId(long itemId) {
if (itemId == -1) {
return null;
}
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- DB.WHERE("EXISTS (SELECT 1 FROM item_categories WHERE category_id = categories.category_id AND item_id = ?)", itemId),
- new DataConstraints().setDefaultColumnToSortBy("name").setUseCount(false),
- CategoryRepository::buildRecord);
- return (List) result.getRecords();
+ DataResult result = DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("EXISTS (SELECT 1 FROM item_categories WHERE category_id = categories.category_id AND item_id = ?)", itemId)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("name").setUseCount(false))
+ .returnDataResult(CategoryRepository::buildRecord);
+ return result.getRecords();
}
public static List findAllByCollectionId(long collectionId) {
@@ -105,27 +107,25 @@ public static List findAllByCollectionId(long collectionId, boolean ba
if (collectionId == -1) {
return null;
}
- SqlWhere where = DB.WHERE("collection_id = ?", collectionId);
+ Select select = DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("collection_id = ?", collectionId);
if (basedOnItems) {
- where.AND("item_count > 0");
- // where.add("EXISTS (SELECT 1 FROM items WHERE category_id = items.category_id AND collection_id = ?)", collectionId);
- }
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- where,
- new DataConstraints().setDefaultColumnToSortBy("name").setUseCount(false),
- CategoryRepository::buildRecord);
- return (List) result.getRecords();
+ select.AND("item_count > 0");
+ }
+ DataResult result = select
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("name").setUseCount(false))
+ .returnDataResult(CategoryRepository::buildRecord);
+ return result.getRecords();
}
public static List findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- null,
- new DataConstraints().setDefaultColumnToSortBy("name"),
- CategoryRepository::buildRecord);
+ DataResult result = DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("name"))
+ .returnDataResult(CategoryRepository::buildRecord);
if (result.hasRecords()) {
- return (List) result.getRecords();
+ return result.getRecords();
}
return null;
}
@@ -146,7 +146,7 @@ public static boolean remove(Category record) {
// Update pointers
CollectionRepository.updateCategoryCount(connection, record.getCollectionId(), -1);
// Delete the record
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("category_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("category_id = ?", record.getId()).execute(connection);
// Finish transaction
transaction.commit();
return true;
@@ -157,25 +157,29 @@ public static boolean remove(Category record) {
}
public static void removeAll(Connection connection, Collection record) throws SQLException {
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("collection_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("collection_id = ?", record.getId()).execute(connection);
}
private static Category insert(Category record) {
- SqlUtils insertValues = new SqlUtils()
- .add("collection_id", record.getCollectionId())
- .add("unique_id", StringUtils.trimToNull(record.getUniqueId()))
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("description", StringUtils.trimToNull(record.getDescription()))
- .add("created_by", record.getCreatedBy())
- .add("icon", StringUtils.trimToNull(record.getIcon()))
- .addIfExists("header_text_color", record.getHeaderTextColor())
- .addIfExists("header_bg_color", record.getHeaderBgColor())
- .add("item_url_text", StringUtils.trimToNull(record.getItemUrlText()));
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("collection_id", record.getCollectionId())
+ .FIELD("unique_id", StringUtils.trimToNull(record.getUniqueId()))
+ .FIELD("name", StringUtils.trimToNull(record.getName()))
+ .FIELD("description", StringUtils.trimToNull(record.getDescription()))
+ .FIELD("created_by", record.getCreatedBy())
+ .FIELD("icon", StringUtils.trimToNull(record.getIcon()));
+ if (record.getHeaderTextColor() != null) {
+ insert.FIELD("header_text_color", record.getHeaderTextColor());
+ }
+ if (record.getHeaderBgColor() != null) {
+ insert.FIELD("header_bg_color", record.getHeaderBgColor());
+ }
+ insert.FIELD("item_url_text", StringUtils.trimToNull(record.getItemUrlText()));
try (Connection connection = DB.getConnection();
AutoStartTransaction a = new AutoStartTransaction(connection);
AutoRollback transaction = new AutoRollback(connection)) {
// Insert the record
- record.setId(DB.insertInto(connection, TABLE_NAME, insertValues, PRIMARY_KEY));
+ record.setId(insert.execute(connection));
// Update the pointer
CollectionRepository.updateCategoryCount(connection, record.getCollectionId(), 1);
// Finish transaction
@@ -188,16 +192,17 @@ private static Category insert(Category record) {
}
private static Category update(Category record) {
- SqlUtils updateValues = new SqlUtils()
- .add("unique_id", StringUtils.trimToNull(record.getUniqueId()))
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("description", StringUtils.trimToNull(record.getDescription()))
- .add("icon", StringUtils.trimToNull(record.getIcon()))
- .add("header_text_color", StringUtils.trimToNull(record.getHeaderTextColor()))
- .add("header_bg_color", StringUtils.trimToNull(record.getHeaderBgColor()))
- .add("item_url_text", StringUtils.trimToNull(record.getItemUrlText()))
- .add("modified", new Timestamp(System.currentTimeMillis()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("category_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("unique_id", StringUtils.trimToNull(record.getUniqueId()))
+ .SET("name", StringUtils.trimToNull(record.getName()))
+ .SET("description", StringUtils.trimToNull(record.getDescription()))
+ .SET("icon", StringUtils.trimToNull(record.getIcon()))
+ .SET("header_text_color", StringUtils.trimToNull(record.getHeaderTextColor()))
+ .SET("header_bg_color", StringUtils.trimToNull(record.getHeaderBgColor()))
+ .SET("item_url_text", StringUtils.trimToNull(record.getItemUrlText()))
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("category_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("The update failed!");
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CollectionGroupRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CollectionGroupRepository.java
index 6a2711b42..55b543d96 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CollectionGroupRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CollectionGroupRepository.java
@@ -24,14 +24,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.Insert;
import com.simisinc.platform.domain.model.Group;
import com.simisinc.platform.domain.model.items.Collection;
import com.simisinc.platform.domain.model.items.CollectionGroup;
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;
/**
* Persists and retrieves collection group objects
@@ -50,39 +49,30 @@ public static List findAllByCollectionId(long collectionId) {
if (collectionId == -1) {
return null;
}
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- DB.WHERE("collection_id = ?", collectionId),
- new DataConstraints().setDefaultColumnToSortBy("allowed_id").setUseCount(false),
- CollectionGroupRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("collection_id = ?", collectionId)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("allowed_id").setUseCount(false))
+ .returnDataResult(CollectionGroupRepository::buildRecord).getRecords();
}
public static List findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- null,
- new DataConstraints().setDefaultColumnToSortBy("allowed_id"),
- CollectionGroupRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("allowed_id"))
+ .returnDataResult(CollectionGroupRepository::buildRecord).getRecords();
}
public static CollectionGroup add(CollectionGroup record) {
- SqlUtils insertValues = new SqlUtils()
- .add("collection_id", record.getCollectionId())
- .add("group_id", record.getGroupId())
- .add("privacy_type", record.getPrivacyType())
- .add("view_all", record.getPrivacyType() != PrivacyType.PRIVATE)
- .add("add_permission", record.getAddPermission())
- .add("edit_permission", record.getEditPermission())
- .add("delete_permission", record.getDeletePermission());
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("collection_id", record.getCollectionId())
+ .FIELD("group_id", record.getGroupId())
+ .FIELD("privacy_type", record.getPrivacyType())
+ .FIELD("view_all", record.getPrivacyType() != PrivacyType.PRIVATE)
+ .FIELD("add_permission", record.getAddPermission())
+ .FIELD("edit_permission", record.getEditPermission())
+ .FIELD("delete_permission", record.getDeletePermission());
+ record.setId(insert.execute());
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -95,25 +85,24 @@ public static void insertCollectionGroupList(Connection connection, Collection c
return;
}
for (CollectionGroup allowedGroup : collection.getCollectionGroupList()) {
- SqlUtils insertValues = new SqlUtils();
- insertValues
- .add("collection_id", collection.getId())
- .add("group_id", allowedGroup.getGroupId())
- .add("privacy_type", allowedGroup.getPrivacyType())
- .add("view_all", allowedGroup.getPrivacyType() != PrivacyType.PRIVATE)
- .add("add_permission", allowedGroup.getAddPermission())
- .add("edit_permission", allowedGroup.getEditPermission())
- .add("delete_permission", allowedGroup.getDeletePermission());
- DB.insertInto(connection, TABLE_NAME, insertValues, PRIMARY_KEY);
+ DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("collection_id", collection.getId())
+ .FIELD("group_id", allowedGroup.getGroupId())
+ .FIELD("privacy_type", allowedGroup.getPrivacyType())
+ .FIELD("view_all", allowedGroup.getPrivacyType() != PrivacyType.PRIVATE)
+ .FIELD("add_permission", allowedGroup.getAddPermission())
+ .FIELD("edit_permission", allowedGroup.getEditPermission())
+ .FIELD("delete_permission", allowedGroup.getDeletePermission())
+ .execute(connection);
}
}
public static void removeAll(Connection connection, Collection collection) throws SQLException {
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("collection_id = ?", collection.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("collection_id = ?", collection.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 CollectionGroup buildRecord(ResultSet rs) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CollectionRelationshipRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CollectionRelationshipRepository.java
index a22ca3a8b..88dd5a7d5 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CollectionRelationshipRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CollectionRelationshipRepository.java
@@ -24,12 +24,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.items.Collection;
import com.simisinc.platform.domain.model.items.CollectionRelationship;
-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 collection relationship objects
@@ -48,59 +48,46 @@ public static List findAllParentsByCollectionId(long col
if (collectionId == -1) {
return null;
}
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- DB.WHERE("related_collection_id = ?", collectionId)
- .AND("collection_id != related_collection_id"),
- new DataConstraints().setDefaultColumnToSortBy("relationship_id"),
- CollectionRelationshipRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("related_collection_id = ?", collectionId)
+ .AND("collection_id != related_collection_id")
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("relationship_id"))
+ .returnDataResult(CollectionRelationshipRepository::buildRecord).getRecords();
}
public static List findAllSelfByCollectionId(long collectionId) {
if (collectionId == -1) {
return null;
}
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- DB.WHERE("collection_id = ?", collectionId)
- .AND("related_collection_id = ?", collectionId),
- new DataConstraints().setDefaultColumnToSortBy("relationship_id"),
- CollectionRelationshipRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("collection_id = ?", collectionId)
+ .AND("related_collection_id = ?", collectionId)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("relationship_id"))
+ .returnDataResult(CollectionRelationshipRepository::buildRecord).getRecords();
}
public static List findAllChildrenByCollectionId(long collectionId) {
if (collectionId == -1) {
return null;
}
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- DB.WHERE("collection_id = ?", collectionId)
- .AND("collection_id != related_collection_id"),
- new DataConstraints().setDefaultColumnToSortBy("relationship_id"),
- CollectionRelationshipRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("collection_id = ?", collectionId)
+ .AND("collection_id != related_collection_id")
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("relationship_id"))
+ .returnDataResult(CollectionRelationshipRepository::buildRecord).getRecords();
}
public static CollectionRelationship findById(long relationshipId) {
if (relationshipId == -1) {
return null;
}
- CollectionRelationship relationship = (CollectionRelationship) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("relationship_id = ?", relationshipId),
- CollectionRelationshipRepository::buildRecord);
- return relationship;
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("relationship_id = ?", relationshipId)
+ .returnRecord(CollectionRelationshipRepository::buildRecord);
}
public static CollectionRelationship save(CollectionRelationship record) {
@@ -111,13 +98,13 @@ public static CollectionRelationship save(CollectionRelationship record) {
}
public static CollectionRelationship add(CollectionRelationship record) {
- SqlUtils insertValues = new SqlUtils()
- .add("collection_id", record.getCollectionId())
- .add("related_collection_id", record.getRelatedCollectionId())
- .add("is_active", record.getIsActive())
- .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("collection_id", record.getCollectionId())
+ .FIELD("related_collection_id", record.getRelatedCollectionId())
+ .FIELD("is_active", record.getIsActive())
+ .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;
@@ -126,10 +113,11 @@ public static CollectionRelationship add(CollectionRelationship record) {
}
private static CollectionRelationship update(CollectionRelationship record) {
- SqlUtils updateValues = new SqlUtils()
- .add("is_active", record.getIsActive())
- .add("modified_by", record.getModifiedBy());
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("relationship_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("is_active", record.getIsActive())
+ .SET("modified_by", record.getModifiedBy())
+ .WHERE("relationship_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("The update failed!");
@@ -137,16 +125,16 @@ private static CollectionRelationship update(CollectionRelationship record) {
}
public static void remove(CollectionRelationship collectionRelationship) {
- DB.deleteFrom(TABLE_NAME, DB.WHERE("relationship_id = ?", collectionRelationship.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("relationship_id = ?", collectionRelationship.getId()).execute();
}
public static void remove(Connection connection, CollectionRelationship collectionRelationship) throws SQLException {
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("relationship_id = ?", collectionRelationship.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("relationship_id = ?", collectionRelationship.getId()).execute(connection);
}
public static void removeAll(Connection connection, Collection collection) throws SQLException {
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("collection_id = ?", collection.getId()));
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("related_collection_id = ?", collection.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("collection_id = ?", collection.getId()).execute(connection);
+ DB.DELETE().FROM(TABLE_NAME).WHERE("related_collection_id = ?", collection.getId()).execute(connection);
}
private static CollectionRelationship buildRecord(ResultSet rs) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CollectionRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CollectionRepository.java
index af81f9578..b2e05f3d2 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CollectionRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CollectionRepository.java
@@ -27,6 +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.CastType;
+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.CollectionTableColumnsJSONCommand;
import com.simisinc.platform.application.CustomFieldListJSONCommand;
import com.simisinc.platform.application.items.LoadCollectionCommand;
@@ -34,14 +43,6 @@
import com.simisinc.platform.domain.model.items.CollectionGroup;
import com.simisinc.platform.domain.model.items.PrivacyType;
import com.simisinc.platform.infrastructure.cache.CacheManager;
-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.SqlValue;
-import com.simisinc.platform.infrastructure.database.SqlWhere;
import com.simisinc.platform.presentation.controller.DataConstants;
import com.simisinc.platform.presentation.controller.UserSession;
@@ -66,27 +67,25 @@ public static Collection save(Collection record) {
}
private static Collection add(Collection record) {
- SqlUtils insertValues = new SqlUtils()
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("unique_id", StringUtils.trimToNull(record.getUniqueId()))
- .add("description", StringUtils.trimToNull(record.getDescription()))
- .add("created_by", record.getCreatedBy())
- .add("allows_guests", PrivacyType.isPublic(record.getGuestPrivacyType()))
- .add("guest_privacy_type", record.getGuestPrivacyType())
- .add("has_allowed_groups",
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("name", StringUtils.trimToNull(record.getName()))
+ .FIELD("unique_id", StringUtils.trimToNull(record.getUniqueId()))
+ .FIELD("description", StringUtils.trimToNull(record.getDescription()))
+ .FIELD("created_by", record.getCreatedBy())
+ .FIELD("allows_guests", PrivacyType.isPublic(record.getGuestPrivacyType()))
+ .FIELD("guest_privacy_type", record.getGuestPrivacyType())
+ .FIELD("has_allowed_groups",
record.getCollectionGroupList() != null && !record.getCollectionGroupList().isEmpty())
- .add("listings_link", StringUtils.trimToNull(record.getListingsLink()))
- .add("icon", StringUtils.trimToNull(record.getIcon()))
- .add("show_listings_link", record.getShowListingsLink())
- .add("show_search", record.getShowSearch())
- .add("item_url_text", StringUtils.trimToNull(record.getItemUrlText()));
+ .FIELD("listings_link", StringUtils.trimToNull(record.getListingsLink()))
+ .FIELD("icon", StringUtils.trimToNull(record.getIcon()))
+ .FIELD("show_listings_link", record.getShowListingsLink())
+ .FIELD("show_search", record.getShowSearch())
+ .FIELD("item_url_text", StringUtils.trimToNull(record.getItemUrlText()));
- // 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));
+ record.setId(insert.execute(connection));
// Manage the access groups
if (record.getCollectionGroupList() != null && !record.getCollectionGroupList().isEmpty()) {
CollectionGroupRepository.insertCollectionGroupList(connection, record);
@@ -102,26 +101,25 @@ private static Collection add(Collection record) {
}
private static Collection update(Collection record) {
- SqlUtils updateValues = new SqlUtils()
- .add("name", StringUtils.trimToNull(record.getName()))
- .add("unique_id", StringUtils.trimToNull(record.getUniqueId()))
- .add("description", StringUtils.trimToNull(record.getDescription()))
- .add("allows_guests", PrivacyType.isPublic(record.getGuestPrivacyType()))
- .add("guest_privacy_type", record.getGuestPrivacyType())
- .add("has_allowed_groups",
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("name", StringUtils.trimToNull(record.getName()))
+ .SET("unique_id", StringUtils.trimToNull(record.getUniqueId()))
+ .SET("description", StringUtils.trimToNull(record.getDescription()))
+ .SET("allows_guests", PrivacyType.isPublic(record.getGuestPrivacyType()))
+ .SET("guest_privacy_type", record.getGuestPrivacyType())
+ .SET("has_allowed_groups",
record.getCollectionGroupList() != null && !record.getCollectionGroupList().isEmpty())
- .add("listings_link", StringUtils.trimToNull(record.getListingsLink()))
- .add("icon", StringUtils.trimToNull(record.getIcon()))
- .add("show_listings_link", record.getShowListingsLink())
- .add("show_search", record.getShowSearch())
- .add("item_url_text", StringUtils.trimToNull(record.getItemUrlText()))
- .add("modified", new Timestamp(System.currentTimeMillis()));
- // Use a transaction
+ .SET("listings_link", StringUtils.trimToNull(record.getListingsLink()))
+ .SET("icon", StringUtils.trimToNull(record.getIcon()))
+ .SET("show_listings_link", record.getShowListingsLink())
+ .SET("show_search", record.getShowSearch())
+ .SET("item_url_text", StringUtils.trimToNull(record.getItemUrlText()))
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("collection_id = ?", record.getId());
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("collection_id = ?", record.getId()));
+ update.execute(connection);
// Manage the access groups
CollectionGroupRepository.removeAll(connection, record);
CollectionGroupRepository.insertCollectionGroupList(connection, record);
@@ -137,15 +135,15 @@ private static Collection update(Collection record) {
}
public static Collection updateCustomFields(Collection record) {
- SqlUtils updateValues = new SqlUtils()
- .add("modified", new Timestamp(System.currentTimeMillis()));
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("modified", new Timestamp(System.currentTimeMillis()));
if (record.getCustomFieldList() != null && !record.getCustomFieldList().isEmpty()) {
- updateValues.add(new SqlValue("field_values", SqlValue.JSONB_TYPE,
- CustomFieldListJSONCommand.createJSONString(record.getCustomFieldList())));
+ update.SET("field_values", CustomFieldListJSONCommand.createJSONString(record.getCustomFieldList()), CastType.JSONB);
} else {
- updateValues.add(new SqlValue("field_values", SqlValue.JSONB_TYPE, null));
+ update.SET("field_values", (String) null, CastType.JSONB);
}
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("collection_id = ?", record.getId()))) {
+ update.WHERE("collection_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
// Expire the cache
CacheManager.invalidateKey(CacheManager.COLLECTION_UNIQUE_ID_CACHE, record.getUniqueId());
return record;
@@ -155,15 +153,15 @@ public static Collection updateCustomFields(Collection record) {
}
public static Collection updateTableColumns(Collection record) {
- SqlUtils updateValues = new SqlUtils()
- .add("modified", new Timestamp(System.currentTimeMillis()));
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("modified", new Timestamp(System.currentTimeMillis()));
if (record.getTableColumnsList() != null && !record.getTableColumnsList().isEmpty()) {
- updateValues.add(new SqlValue("table_columns", SqlValue.JSONB_TYPE,
- CollectionTableColumnsJSONCommand.createJSONString(record.getTableColumnsList())));
+ update.SET("table_columns", CollectionTableColumnsJSONCommand.createJSONString(record.getTableColumnsList()), CastType.JSONB);
} else {
- updateValues.add(new SqlValue("table_columns", SqlValue.JSONB_TYPE, null));
+ update.SET("table_columns", (String) null, CastType.JSONB);
}
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("collection_id = ?", record.getId()))) {
+ update.WHERE("collection_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
// Expire the cache
CacheManager.invalidateKey(CacheManager.COLLECTION_UNIQUE_ID_CACHE, record.getUniqueId());
return record;
@@ -173,20 +171,21 @@ public static Collection updateTableColumns(Collection record) {
}
public static Collection updateTheme(Collection record) {
- SqlUtils updateValues = new SqlUtils()
- .add("header_text_color", record.getHeaderTextColor())
- .add("header_bg_color", record.getHeaderBgColor())
- .add("menu_text_color", record.getMenuTextColor())
- .add("menu_bg_color", record.getMenuBgColor())
- .add("menu_border_color", record.getMenuBorderColor())
- .add("menu_active_text_color", record.getMenuActiveTextColor())
- .add("menu_active_bg_color", record.getMenuActiveBgColor())
- .add("menu_active_border_color", record.getMenuActiveBorderColor())
- .add("menu_hover_text_color", record.getMenuHoverTextColor())
- .add("menu_hover_bg_color", record.getMenuHoverBgColor())
- .add("menu_hover_border_color", record.getMenuHoverBorderColor())
- .add("modified", new Timestamp(System.currentTimeMillis()));
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("collection_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("header_text_color", record.getHeaderTextColor())
+ .SET("header_bg_color", record.getHeaderBgColor())
+ .SET("menu_text_color", record.getMenuTextColor())
+ .SET("menu_bg_color", record.getMenuBgColor())
+ .SET("menu_border_color", record.getMenuBorderColor())
+ .SET("menu_active_text_color", record.getMenuActiveTextColor())
+ .SET("menu_active_bg_color", record.getMenuActiveBgColor())
+ .SET("menu_active_border_color", record.getMenuActiveBorderColor())
+ .SET("menu_hover_text_color", record.getMenuHoverTextColor())
+ .SET("menu_hover_bg_color", record.getMenuHoverBgColor())
+ .SET("menu_hover_border_color", record.getMenuHoverBorderColor())
+ .SET("modified", new Timestamp(System.currentTimeMillis()))
+ .WHERE("collection_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
// Expire the cache
CacheManager.invalidateKey(CacheManager.COLLECTION_UNIQUE_ID_CACHE, record.getUniqueId());
return record;
@@ -211,7 +210,7 @@ public static boolean remove(Collection record) {
CategoryRepository.removeAll(connection, record);
CollectionRelationshipRepository.removeAll(connection, record);
// Delete the record
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("collection_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("collection_id = ?", record.getId()).execute(connection);
// Finish transaction
transaction.commit();
// Invalidate the cache
@@ -224,21 +223,23 @@ public static boolean remove(Collection record) {
return false;
}
- private static DataResult query(CollectionSpecification specification, DataConstraints constraints) {
- SqlWhere where = null;
+ private static DataResult query(CollectionSpecification specification, DataConstraints constraints) {
+ Select select = DB.SELECT("*").FROM(TABLE_NAME).WHERE();
if (specification != null) {
- where = DB.WHERE()
- .andAddIfHasValue("collection_id = ?", specification.getId(), -1)
- .andAddIfHasValue("unique_id = ?", specification.getUniqueId());
+ if (specification.getId() != -1) {
+ select.AND("collection_id = ?", specification.getId());
+ }
+ if (StringUtils.isNotBlank(specification.getUniqueId())) {
+ select.AND("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(
+ select.AND(
"(allows_guests = true " +
"OR (has_allowed_groups = true " +
"AND EXISTS (SELECT 1 FROM collection_groups WHERE collection_id = collections.collection_id " +
@@ -247,17 +248,17 @@ private static DataResult query(CollectionSpecification specification, DataConst
}
}
}
- return DB.selectAllFrom(TABLE_NAME, where, constraints, CollectionRepository::buildRecord);
+ return select.WITH(constraints).returnDataResult(CollectionRepository::buildRecord);
}
public static Collection findById(long id) {
if (id == -1) {
return null;
}
- Collection collection = (Collection) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("collection_id = ?", id),
- CollectionRepository::buildRecord);
+ Collection collection = DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("collection_id = ?", id)
+ .returnRecord(CollectionRepository::buildRecord);
populateRelatedData(collection);
return collection;
}
@@ -266,10 +267,10 @@ public static Collection findByUniqueId(String uniqueId) {
if (StringUtils.isBlank(uniqueId)) {
return null;
}
- Collection collection = (Collection) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("unique_id = ?", uniqueId),
- CollectionRepository::buildRecord);
+ Collection collection = DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("unique_id = ?", uniqueId)
+ .returnRecord(CollectionRepository::buildRecord);
populateRelatedData(collection);
return collection;
}
@@ -278,10 +279,10 @@ public static Collection findByName(String name) {
if (StringUtils.isBlank(name)) {
return null;
}
- Collection collection = (Collection) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("LOWER(name) = ?", name.toLowerCase()),
- CollectionRepository::buildRecord);
+ Collection collection = DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("LOWER(name) = ?", name.toLowerCase())
+ .returnRecord(CollectionRepository::buildRecord);
populateRelatedData(collection);
return collection;
}
@@ -295,8 +296,7 @@ public static List findAll(CollectionSpecification specification, Da
constraints = new DataConstraints().setUseCount(false);
}
constraints.setDefaultColumnToSortBy("name");
- DataResult result = query(specification, constraints);
- List collectionList = (List) result.getRecords();
+ List collectionList = query(specification, constraints).getRecords();
for (Collection collection : collectionList) {
populateRelatedData(collection);
}
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CollectionRoleRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CollectionRoleRepository.java
index 619c55d2b..671ddae33 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CollectionRoleRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CollectionRoleRepository.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");
@@ -25,13 +26,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.Insert;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.domain.model.items.Collection;
import com.simisinc.platform.domain.model.items.CollectionRole;
import com.simisinc.platform.domain.model.items.Member;
-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 collection role objects
@@ -50,60 +51,50 @@ public static CollectionRole findById(long id) {
if (id == -1) {
return null;
}
- return (CollectionRole) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("role_id = ?", id),
- CollectionRoleRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("role_id = ?", id)
+ .returnRecord(CollectionRoleRepository::buildRecord);
}
public static CollectionRole findByCode(String code) {
if (StringUtils.isBlank(code)) {
return null;
}
- return (CollectionRole) DB.selectRecordFrom(
- TABLE_NAME,
- DB.WHERE("code = ?", code),
- CollectionRoleRepository::buildRecord);
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("code = ?", code)
+ .returnRecord(CollectionRoleRepository::buildRecord);
}
public static List findAllAvailableForCollectionId(long collectionId) {
if (collectionId == -1) {
return null;
}
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- DB.WHERE("collection_id IS NULL OR collection_id = ?", collectionId),
- new DataConstraints().setDefaultColumnToSortBy("level,role_id").setUseCount(false),
- CollectionRoleRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("collection_id IS NULL OR collection_id = ?", collectionId)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("level,role_id").setUseCount(false))
+ .returnDataResult(CollectionRoleRepository::buildRecord).getRecords();
}
public static List findAllByMember(Member member) {
if (member.getItemId() == -1 || member.getUserId() == -1) {
return null;
}
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- DB.WHERE("EXISTS (SELECT 1 FROM member_roles WHERE role_id = lookup_collection_role.role_id AND item_id = ? AND user_id = ?)",
- new Long[] { member.getItemId(), member.getUserId() }),
- new DataConstraints().setDefaultColumnToSortBy("role_id").setUseCount(false),
- CollectionRoleRepository::buildRecord);
- if (result.hasRecords()) {
- return (List) result.getRecords();
- }
- return null;
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WHERE("EXISTS (SELECT 1 FROM member_roles WHERE role_id = lookup_collection_role.role_id AND item_id = ? AND user_id = ?)",
+ member.getItemId(), member.getUserId())
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("role_id").setUseCount(false))
+ .returnDataResult(CollectionRoleRepository::buildRecord).getRecords();
}
public static List findAll() {
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- null,
- new DataConstraints().setDefaultColumnToSortBy("title"),
- CollectionRoleRepository::buildRecord);
- return (List) result.getRecords();
+ return DB.SELECT("*")
+ .FROM(TABLE_NAME)
+ .WITH(new DataConstraints().setDefaultColumnToSortBy("title"))
+ .returnDataResult(CollectionRoleRepository::buildRecord).getRecords();
}
public static CollectionRole save(CollectionRole record) {
@@ -114,12 +105,14 @@ public static CollectionRole save(CollectionRole record) {
}
private static CollectionRole add(CollectionRole record) {
- SqlUtils insertValues = new SqlUtils()
- .add("code", StringUtils.trimToNull(record.getCode()))
- .addIfExists("collection_id", record.getCollectionId(), -1)
- .add("title", StringUtils.trimToNull(record.getTitle()))
- .add("archived", record.getArchived());
- record.setId(DB.insertInto(TABLE_NAME, insertValues, PRIMARY_KEY));
+ Insert insert = DB.INSERT().INTO(TABLE_NAME)
+ .FIELD("code", StringUtils.trimToNull(record.getCode()));
+ if (record.getCollectionId() > -1) {
+ insert.FIELD("collection_id", record.getCollectionId());
+ }
+ insert.FIELD("title", StringUtils.trimToNull(record.getTitle()))
+ .FIELD("archived", record.getArchived());
+ record.setId(insert.execute());
if (record.getId() == -1) {
LOG.error("An id was not set!");
return null;
@@ -128,11 +121,12 @@ private static CollectionRole add(CollectionRole record) {
}
private static CollectionRole update(CollectionRole record) {
- SqlUtils updateValues = new SqlUtils()
- .add("code", StringUtils.trimToNull(record.getCode()))
- .add("title", StringUtils.trimToNull(record.getTitle()))
- .add("archived", record.getArchived());
- if (DB.update(TABLE_NAME, updateValues, DB.WHERE("role_id = ?", record.getId()))) {
+ Update update = DB.UPDATE(TABLE_NAME)
+ .SET("code", StringUtils.trimToNull(record.getCode()))
+ .SET("title", StringUtils.trimToNull(record.getTitle()))
+ .SET("archived", record.getArchived())
+ .WHERE("role_id = ?", record.getId());
+ if (update.execute().booleanValue()) {
return record;
}
LOG.error("The update failed!");
@@ -140,15 +134,15 @@ private static CollectionRole update(CollectionRole record) {
}
public static void remove(CollectionRole record) {
- DB.deleteFrom(TABLE_NAME, DB.WHERE("role_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("role_id = ?", record.getId()).execute();
}
public static void remove(Collection record) {
- DB.deleteFrom(TABLE_NAME, DB.WHERE("collection_id = ?", record.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("collection_id = ?", record.getId()).execute();
}
public static void removeAll(Connection connection, Collection collection) throws SQLException {
- DB.deleteFrom(connection, TABLE_NAME, DB.WHERE("collection_id = ?", collection.getId()));
+ DB.DELETE().FROM(TABLE_NAME).WHERE("collection_id = ?", collection.getId()).execute(connection);
}
private static CollectionRole buildRecord(ResultSet rs) {
diff --git a/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CollectionTabRepository.java b/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CollectionTabRepository.java
index cb094c6fc..0e6a2b644 100644
--- a/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CollectionTabRepository.java
+++ b/src/main/java/com/simisinc/platform/infrastructure/persistence/items/CollectionTabRepository.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");
@@ -19,24 +20,23 @@
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
-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.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.Insert;
+import com.github.rajkowski.database.Update;
import com.simisinc.platform.domain.model.items.Collection;
import com.simisinc.platform.domain.model.items.CollectionTab;
-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 colleciton tab objects
+ * Persists and retrieves collection tab objects
*
* @author matt rajkowski
* @created 4/13/21 12:00 PM
@@ -52,15 +52,11 @@ public static List findAllByCollectionId(long collectionId) {
if (collectionId == -1) {
return null;
}
- DataResult result = DB.selectAllFrom(
- TABLE_NAME,
- DB.WHERE("collection_id = ?", collectionId),
- new DataConstraints().setDefaultColumnToSortBy("tab_order,name").setUseCount(false),
- CollectionTabRepository::buildRecord);
- if (result.hasRecords()) {
- return (List