chibenwa commented on code in PR #1849:
URL: https://github.com/apache/james-project/pull/1849#discussion_r1423759559


##########
server/data/data-postgres/src/main/java/org/apache/james/sieve/postgres/PostgresSieveScriptDAO.java:
##########
@@ -39,20 +39,43 @@
 import org.apache.james.sieve.postgres.model.PostgresSieveScript;
 import org.apache.james.sieverepository.api.ScriptName;
 import org.jooq.Record;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
+import io.r2dbc.spi.Result;
 import reactor.core.publisher.Flux;
 import reactor.core.publisher.Mono;
 
 public class PostgresSieveScriptDAO {
+    private static final Logger LOGGER = 
LoggerFactory.getLogger(PostgresSieveScriptDAO.class);
+
+    public static void 
enforceMaximumOneActiveScriptPerUserConstraint(PostgresExecutor 
postgresExecutor) {
+        postgresExecutor.connection()
+            .flatMapMany(connection -> 
connection.createStatement(String.format("ALTER TABLE %s ADD CONSTRAINT 
maximum_one_active_script_per_user EXCLUDE (%s WITH =) WHERE (%s = TRUE);",
+                    TABLE_NAME.getName(), USERNAME.getName(), 
IS_ACTIVE.getName()))
+                .execute())
+            .flatMap(Result::getRowsUpdated)
+            .then()
+            .onErrorResume(e -> {
+                if (e.getMessage().contains("already exists")) {
+                    return Mono.empty();
+                }
+                LOGGER.error("Error while creating constraint for table {}", 
TABLE_NAME.getName(), e);
+                return Mono.error(e);
+            })
+            .block();
+    }
+
     private final PostgresExecutor postgresExecutor;
 
     @Inject
     public PostgresSieveScriptDAO(@Named(DEFAULT_INJECT) PostgresExecutor 
postgresExecutor) {
         this.postgresExecutor = postgresExecutor;
+        enforceMaximumOneActiveScriptPerUserConstraint(postgresExecutor);

Review Comment:
   Please find a way to do this at table creation



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to