From 4306370495059446300fb9b0bb0a2dbaacdf55bb Mon Sep 17 00:00:00 2001
From: "S.Listl" <S.Listl@SLISTL.aditosoftware.local>
Date: Tue, 29 Oct 2019 14:16:35 +0100
Subject: [PATCH] SqlBuilder usages added

---
 .../entityfields/new_tasks/valueProcess.js    |  16 ++-
 .../opennewtasks/onActionProcess.js           |  13 +-
 .../turnover_forecast/valueProcess.js         |   4 +-
 .../recordcontainers/jdito/contentProcess.js  |   7 +-
 .../bulkmail_id/displayValueProcess.js        |   2 -
 .../entityfields/sorting/valueProcess.js      |   9 +-
 .../entityfields/contact_id/onValueChange.js  |  18 +--
 .../countactivity/valueProcess.js             |  12 +-
 .../turnovercurrentyear/valueProcess.js       |  17 +--
 .../turnoverlastyear/valueProcess.js          |  18 +--
 .../excludedproducts_param/valueProcess.js    |  13 +-
 .../recordcontainers/jdito/contentProcess.js  |   8 +-
 .../entityfields/productcode/onValidation.js  |  16 +--
 .../filteredattributes_param/valueProcess.js  |   2 +-
 .../recordcontainers/jdito/contentProcess.js  |  12 +-
 .../entityfields/totaltime/valueProcess.js    |   6 +-
 process/Campaign_lib/process.js               | 121 +++++++++---------
 process/Date_lib/process.js                   |   8 ++
 process/Loghistory_lib/process.js             |   4 +-
 process/Neon_lib/process.js                   |   3 +-
 process/ObjectRelation_lib/process.js         |  95 +++++---------
 process/Product_lib/process.js                |   8 +-
 process/Sql_lib/process.js                    |  14 ++
 process/StandardObject_lib/process.js         |  41 +++---
 24 files changed, 243 insertions(+), 224 deletions(-)

diff --git a/entity/Analyses_entity/entityfields/new_tasks/valueProcess.js b/entity/Analyses_entity/entityfields/new_tasks/valueProcess.js
index 8aa5325599c..510afae5b2c 100644
--- a/entity/Analyses_entity/entityfields/new_tasks/valueProcess.js
+++ b/entity/Analyses_entity/entityfields/new_tasks/valueProcess.js
@@ -1,9 +1,13 @@
 import("Employee_lib");
 import("system.db");
 import("system.result");
-
-var opentask = db.cell("select count(TASKID) "
-             + " from TASK "
-             + " where STATUS = 'NEW' and EDITOR_CONTACT_ID = '" + EmployeeUtils.getCurrentContactId() + "'");                             
-                                  
-result.string(opentask);
\ No newline at end of file
+import("Sql_lib");
+import("KeywordRegistry_basic");
+                     
+var opentask = newSelect("count(TASKID)")
+    .from("TASK")
+    .where("TASK.STATUS", $KeywordRegistry.taskStatus$new())
+    .and("TASK.EDITOR_CONTACT_ID", EmployeeUtils.getCurrentContactId())
+    .cell();
+    
+result.string(opentask || 0);
\ No newline at end of file
diff --git a/entity/Analyses_entity/entityfields/opennewtasks/onActionProcess.js b/entity/Analyses_entity/entityfields/opennewtasks/onActionProcess.js
index 696d1e7e7cf..696815d5aed 100644
--- a/entity/Analyses_entity/entityfields/opennewtasks/onActionProcess.js
+++ b/entity/Analyses_entity/entityfields/opennewtasks/onActionProcess.js
@@ -1,9 +1,12 @@
+import("KeywordRegistry_basic");
+import("Sql_lib");
 import("Employee_lib");
-import("system.db");
 import("system.neon");
 
-var taskIds = db.table("select TASKID  "
-             + " from TASK "
-             + " where STATUS = 'NEW' and EDITOR_CONTACT_ID = '" + EmployeeUtils.getCurrentContactId() + "'", "Data_alias");
-
+var taskIds = newSelect("TASKID")
+    .from("TASK")
+    .where("TASK.STATUS", $KeywordRegistry.taskStatus$new())
+    .and("TASK.EDITOR_CONTACT_ID", EmployeeUtils.getCurrentContactId())
+    .arrayColumn();
+    
 neon.openContext("Task", "TaskFilter_view", taskIds, neon.OPERATINGSTATE_SEARCH, null);
\ No newline at end of file
diff --git a/entity/Analyses_entity/entityfields/turnover_forecast/valueProcess.js b/entity/Analyses_entity/entityfields/turnover_forecast/valueProcess.js
index 72d7b1588dc..1ac6f93dde0 100644
--- a/entity/Analyses_entity/entityfields/turnover_forecast/valueProcess.js
+++ b/entity/Analyses_entity/entityfields/turnover_forecast/valueProcess.js
@@ -8,7 +8,7 @@ import("system.SQLTYPES")
 
 var forecast = newSelect("sum(VOLUME)")
                 .from("FORECAST")
-                .where("FORECAST.DATE_START", datetime.toDate(vars.get("$sys.date"), "yyyy"), "year(#) = ?", SQLTYPES.INTEGER)
+                .where("FORECAST.DATE_START", DateUtils.getCurrentYear(), SqlBuilder.YEAR_EQUALS(), SQLTYPES.INTEGER)
                 .cell();
                                   
-result.string(forecast);
\ No newline at end of file
+result.string(forecast || 0);
\ No newline at end of file
diff --git a/entity/Attribute_entity/recordcontainers/jdito/contentProcess.js b/entity/Attribute_entity/recordcontainers/jdito/contentProcess.js
index a7b6c13eace..fbe2e30a6b8 100644
--- a/entity/Attribute_entity/recordcontainers/jdito/contentProcess.js
+++ b/entity/Attribute_entity/recordcontainers/jdito/contentProcess.js
@@ -122,11 +122,6 @@ if (fetchUsages) //this query is only necessary in Attribute, not in AttributeRe
     }
 }
 
-
-var sqlSelect = "select AB_ATTRIBUTEID, ATTRIBUTE_PARENT_ID, ATTRIBUTE_NAME, ATTRIBUTE_ACTIVE, DROPDOWNDEFINITION, DROPDOWNFILTER, SORTING, ATTRIBUTE_TYPE, " 
-    + KeywordUtils.getResolvedTitleSqlPart($KeywordRegistry.attributeType(), "ATTRIBUTE_TYPE") //3
-    + ", '', '', '' from AB_ATTRIBUTE"; 
-
 var attributes = newSelect("AB_ATTRIBUTEID, ATTRIBUTE_PARENT_ID, ATTRIBUTE_NAME, ATTRIBUTE_ACTIVE, DROPDOWNDEFINITION, DROPDOWNFILTER, SORTING, ATTRIBUTE_TYPE, " 
                             + KeywordUtils.getResolvedTitleSqlPart($KeywordRegistry.attributeType(), "ATTRIBUTE_TYPE") //3
                             + ", '', '', ''")
@@ -136,7 +131,7 @@ var attributes = newSelect("AB_ATTRIBUTEID, ATTRIBUTE_PARENT_ID, ATTRIBUTE_NAME,
                     .table();
 
 //TODO: attribute name caching like keywords
-var allNames = db.table("select AB_ATTRIBUTEID, ATTRIBUTE_PARENT_ID, ATTRIBUTE_NAME from AB_ATTRIBUTE");
+var allNames = newSelect("AB_ATTRIBUTEID, ATTRIBUTE_PARENT_ID, ATTRIBUTE_NAME").from("AB_ATTRIBUTE").table();
 var attrNameData = {};
 for (let i = 0, l = allNames.length; i < l; i++)
 {
diff --git a/entity/BulkMailAddRecipients_entity/entityfields/bulkmail_id/displayValueProcess.js b/entity/BulkMailAddRecipients_entity/entityfields/bulkmail_id/displayValueProcess.js
index 908c3e0ae7e..b3e0f9ffb75 100644
--- a/entity/BulkMailAddRecipients_entity/entityfields/bulkmail_id/displayValueProcess.js
+++ b/entity/BulkMailAddRecipients_entity/entityfields/bulkmail_id/displayValueProcess.js
@@ -1,13 +1,11 @@
 import("system.vars");
 import("Sql_lib");
-import("system.db");
 import("system.result");
 
 if (vars.get("$this.value"))
     result.string(newSelect("NAME")
                     .from("BULKMAIL")
                     .where("BULKMAIL.BULKMAILID", "$this.value")
-                    .buildSql("select NAME from BULKMAIL")
                     .cell());
 else
     result.string("");
\ No newline at end of file
diff --git a/entity/CampaignStep_entity/entityfields/sorting/valueProcess.js b/entity/CampaignStep_entity/entityfields/sorting/valueProcess.js
index 6c154f155ae..14299877ed4 100644
--- a/entity/CampaignStep_entity/entityfields/sorting/valueProcess.js
+++ b/entity/CampaignStep_entity/entityfields/sorting/valueProcess.js
@@ -1,4 +1,4 @@
-import("system.db");
+import("Sql_lib");
 import("system.neon");
 import("system.vars");
 import("system.util");
@@ -7,8 +7,9 @@ import("system.result");
 if(vars.get("$sys.recordstate") == neon.OPERATINGSTATE_NEW)
 {
     var campaignId = vars.get("$field.CAMPAIGN_ID");
-    var latestSortingQuery = "select COUNT(CAMPAIGNSTEPID) from CAMPAIGNSTEP " + 
-        "where CAMPAIGN_ID = '" + campaignId + "'";
-    var stepCount = db.cell(latestSortingQuery);
+    var stepCount = newSelect("count(CAMPAIGNSTEPID)")
+        .from("CAMPAINGSTEP")
+        .where("CAMPAIGNSTEP.CAMPAIGN_ID", campaignId)
+        .cell();
     result.string(parseInt(stepCount) + 1);
 }
\ No newline at end of file
diff --git a/entity/Order_entity/entityfields/contact_id/onValueChange.js b/entity/Order_entity/entityfields/contact_id/onValueChange.js
index a65930ffa61..d0c5b9a5c46 100644
--- a/entity/Order_entity/entityfields/contact_id/onValueChange.js
+++ b/entity/Order_entity/entityfields/contact_id/onValueChange.js
@@ -1,15 +1,17 @@
+import("Sql_lib");
 import("system.neon");
 import("system.vars");
-import("system.db");
 import("Util_lib");
 import("Entity_lib");
 
 var contactid = vars.get("local.value");
-if(contactid != "")
-{
-    var relData = db.array(db.ROW, "select ISOLANGUAGE from CONTACT where CONTACTID = '" + contactid + "'");
-    
-    if(relData[0] != "")   
-        vars.set("$field.ISOLANGUAGE", relData[0]);
-}
+
+var relData = newSelect("ISOLANGUAGE")
+    .from("CONTACT")
+    .whereIfSet("CONTACT.CONTACTID", contactid)
+    .cell(true);
+
+if(relData)   
+    vars.set("$field.ISOLANGUAGE", relData[0]);
+
 neon.setFieldValue("$field.OBJECT_ROWID", null)
\ No newline at end of file
diff --git a/entity/Organisation_entity/entityfields/countactivity/valueProcess.js b/entity/Organisation_entity/entityfields/countactivity/valueProcess.js
index d3606bbab63..08f56eefb94 100644
--- a/entity/Organisation_entity/entityfields/countactivity/valueProcess.js
+++ b/entity/Organisation_entity/entityfields/countactivity/valueProcess.js
@@ -1,7 +1,13 @@
+import("Context_lib");
+import("Sql_lib");
 import("system.result");
 import("system.vars");
-import("system.db");
-var amount = db.cell("select count(ACTIVITYID) from ACTIVITY join ACTIVITYLINK on ACTIVITYLINK.ACTIVITY_ID = ACTIVITY.ACTIVITYID \n\
-                      where ACTIVITYLINK.OBJECT_ROWID = '" + vars.get("$field.CONTACTID") + "' and ACTIVITYLINK.OBJECT_TYPE = 'Organisation'");
 
+var amount = newSelect("count(ACTIVITYID)")
+    .from("ACTIVITY")
+    .join("ACTIVITYLINK", "ACTIVITYLINK.ACTIVITY_ID = ACTIVITY.ACTIVITYID")
+    .where("ACTIVITYLINK.OBJECT_ROWID", "$field.CONTACTID")
+    .and("ACTIVITYLINK.OBJECT_TYPE", ContextUtils.getCurrentContextId())
+    .cell(null, "0");
+    
 result.string(amount);
\ No newline at end of file
diff --git a/entity/Organisation_entity/entityfields/turnovercurrentyear/valueProcess.js b/entity/Organisation_entity/entityfields/turnovercurrentyear/valueProcess.js
index 1f8ee1ceff0..f1418b16404 100644
--- a/entity/Organisation_entity/entityfields/turnovercurrentyear/valueProcess.js
+++ b/entity/Organisation_entity/entityfields/turnovercurrentyear/valueProcess.js
@@ -1,3 +1,6 @@
+import("Date_lib");
+import("system.SQLTYPES");
+import("Sql_lib");
 import("system.translate");
 import("Util_lib");
 import("system.datetime");
@@ -6,12 +9,10 @@ import("system.db");
 import("system.result");
 import("system.date");
 
-var currentYear = datetime.toDate(vars.get("$sys.date"), "yyyy");
+var salesCurrentYear = newSelect("sum(NET)")
+    .from("SALESORDER")
+    .where("SALESORDER.SALESORDERDATE", DateUtils.getCurrentYear(), SqlBuilder.YEAR_EQUALS(), SQLTYPES.INTEGER)
+    .and("SALESORDER.CONTACT_ID", "$field.CONTACTID")
+    .cell();
 
-var salesCurrentYear = db.cell("select SUM(NET) from salesorder where SALESORDERDATE >= '" + currentYear + "-01-01 00:00:00.000' \n\
-                                                                and CONTACT_ID = '" + vars.get("$field.CONTACTID") + "'");
-
-if(salesCurrentYear == "")
-    salesCurrentYear = 0;
-
-result.string(salesCurrentYear);
\ No newline at end of file
+result.string(salesCurrentYear || 0);
\ No newline at end of file
diff --git a/entity/Organisation_entity/entityfields/turnoverlastyear/valueProcess.js b/entity/Organisation_entity/entityfields/turnoverlastyear/valueProcess.js
index f89ea7a28de..181f0fdcedb 100644
--- a/entity/Organisation_entity/entityfields/turnoverlastyear/valueProcess.js
+++ b/entity/Organisation_entity/entityfields/turnoverlastyear/valueProcess.js
@@ -1,16 +1,16 @@
+import("system.SQLTYPES");
+import("Date_lib");
+import("Sql_lib");
 import("system.datetime");
 import("system.vars");
 import("system.db");
 import("system.result");
 import("system.date");
 
-var lastYear = parseInt(datetime.toDate(vars.get("$sys.date"), "yyyy")) - 1;
+var salesLastYear = newSelect("sum(NET)")
+    .from("SALESORDER")
+    .where("SALESORDER.SALESORDERDATE", DateUtils.getCurrentYear() - 1, SqlBuilder.YEAR_EQUALS(), SQLTYPES.INTEGER)
+    .and("SALESORDER.CONTACT_ID", "$field.CONTACTID")
+    .cell();
 
-var salesLastYear = db.cell("select SUM(NET) from salesorder where SALESORDERDATE < '" + (lastYear+1) + "-01-01 00:00:00.000' \n\
-                                                             and SALESORDERDATE >= '" + lastYear + "-01-01 00:00:00.000'  \n\
-                                                             and CONTACT_ID = '" + vars.get("$field.CONTACTID") + "'");
-
-if(salesLastYear == "")
-    salesLastYear = 0;
-
-result.string(salesLastYear);
\ No newline at end of file
+result.string(salesLastYear || 0);
\ No newline at end of file
diff --git a/entity/Prod2prod_entity/entityfields/products/children/excludedproducts_param/valueProcess.js b/entity/Prod2prod_entity/entityfields/products/children/excludedproducts_param/valueProcess.js
index 61d089f5dbb..bbca2049205 100644
--- a/entity/Prod2prod_entity/entityfields/products/children/excludedproducts_param/valueProcess.js
+++ b/entity/Prod2prod_entity/entityfields/products/children/excludedproducts_param/valueProcess.js
@@ -1,3 +1,4 @@
+import("Sql_lib");
 import("system.neon");
 import("system.db");
 import("system.vars");
@@ -34,8 +35,10 @@ result.object(excludeIDs);
 function _getParentID(pID, pIDs)
 {
     //Ermitteln welche Produkte ausgeschlossen werden müssen.
-    cond = typeof(pID) == "object" ? "in  ('" + pID.join("', '") +"')" : " =  '" + pID + "' "   
-    var parents = db.array(db.COLUMN, "select DEST_ID from PROD2PROD where SOURCE_ID " + cond);
+    var parents = newSelect("DEST_ID")
+        .from("PROD2PROD")
+        .whereIfSet("PROD2PROD.SOURCE_ID", pID, typeof(pID) == "string" ? null : SqlBuilder.IN())
+        .arrayColumn(true);
     for ( var i = 0; i < parents.length; i++)
     {    
         pIDs.push(parents[i]);
@@ -46,8 +49,10 @@ function _getParentID(pID, pIDs)
 function _getChildrenID(pID, pIDs)
 {
     //Ermitteln welche Produkte ausgeschlossen werden müssen.
-    cond = typeof(pID) == "object" ? "in  ('" + pID.join("', '") +"')" : " =  '" + pID + "' "
-    var children = db.array(db.COLUMN, "select SOURCE_ID from PROD2PROD where DEST_ID " + cond);
+    var children = newSelect("SOURCE_ID")
+        .from("PROD2PROD")
+        .whereIfSet("PROD2PROD.DEST_ID", pID, typeof(pID) == "string" ? null : SqlBuilder.IN())
+        .arrayColumn(true);
     for ( var i = 0; i < children.length; i++)
     {    
         pIDs.push(children[i]);
diff --git a/entity/Prod2prod_entity/recordcontainers/jdito/contentProcess.js b/entity/Prod2prod_entity/recordcontainers/jdito/contentProcess.js
index 468aab31584..aafbf045045 100644
--- a/entity/Prod2prod_entity/recordcontainers/jdito/contentProcess.js
+++ b/entity/Prod2prod_entity/recordcontainers/jdito/contentProcess.js
@@ -147,9 +147,11 @@ else
     if(prodid != "")
     {
         // First 3 columns are crucial, the rest is optional.
-        var data = db.table("select PROD2PRODID, SOURCE_ID, DEST_ID, QUANTITY, PRODUCTCODE, PRODUCTID, PROD2PRODID, OPTIONAL, TAKEPRICE, PRODUCTNAME "
-                    + "from PROD2PROD join PRODUCT on PROD2PROD.SOURCE_ID = PRODUCTID "
-                    + "order by PRODUCTCODE");
+        var data = newSelect("PROD2PRODID, SOURCE_ID, DEST_ID, QUANTITY, PRODUCTCODE, PRODUCTID, PROD2PRODID, OPTIONAL, TAKEPRICE, PRODUCTNAME")
+            .from("PROD2PROD")
+            .join("PRODUCT", "PROD2PROD.SOURCE_ID = PRODUCTID")
+            .orderBy("PRODUCTCODE")
+            .table();
 
         var prod2prodIdMapping = buildProd2ProdIDMapping(data);
         var childrenMapping = buildChildrenMapping(data);
diff --git a/entity/Product_entity/entityfields/productcode/onValidation.js b/entity/Product_entity/entityfields/productcode/onValidation.js
index 81b90e9b479..2e11d9ff116 100644
--- a/entity/Product_entity/entityfields/productcode/onValidation.js
+++ b/entity/Product_entity/entityfields/productcode/onValidation.js
@@ -1,15 +1,13 @@
+import("Sql_lib");
 import("system.translate");
 import("system.result");
-import("system.vars");
-import("system.db");
-import("Util_lib");
-import("Entity_lib");
 
-var codeCount, productCode;
-
-productCode = vars.get("local.value");
-codeCount = db.cell("select count(PRODUCTCODE) from PRODUCT where PRODUCTCODE = '" + productCode + "'"
-                       + " and PRODUCTID <> '" + vars.get("$field.PRODUCTID") + "'");
+var codeCount = newSelect("count(PRODUCTCODE)")
+    .from("PRODUCT")
+    .where("PRODUCT.PRODUCTCODE", "$local.value")
+    .and("PRODUCT.PRODUCTID", "$field.PRODUCTID", "# != ?")
+    .cell();
+    
 if(codeCount > 0)
 {
     result.string(translate.text("The product number already exists!"));
diff --git a/entity/Productprice_entity/entityfields/attributes/children/filteredattributes_param/valueProcess.js b/entity/Productprice_entity/entityfields/attributes/children/filteredattributes_param/valueProcess.js
index 8e1a22ffe0d..69acbaabdeb 100644
--- a/entity/Productprice_entity/entityfields/attributes/children/filteredattributes_param/valueProcess.js
+++ b/entity/Productprice_entity/entityfields/attributes/children/filteredattributes_param/valueProcess.js
@@ -1,3 +1,3 @@
 import("system.db");
 import("system.result");
-result.object(db.array(db.ROW, "select AB_ATTRIBUTEID from AB_ATTRIBUTE where ATTRIBUTE_PARENT_ID = 'ab545654-1fce-4993-b763-0ec469781302'"));
\ No newline at end of file
+result.object(db.array(db.ROW, "select AB_ATTRIBUTEID from AB_ATTRIBUTE where ATTRIBUTE_PARENT_ID = 'ab545654-1fce-4993-b763-0ec469781302'"));
diff --git a/entity/SalesprojectAnalyses_entity/recordcontainers/jdito/contentProcess.js b/entity/SalesprojectAnalyses_entity/recordcontainers/jdito/contentProcess.js
index b6d479b206e..afcd4eaacbf 100644
--- a/entity/SalesprojectAnalyses_entity/recordcontainers/jdito/contentProcess.js
+++ b/entity/SalesprojectAnalyses_entity/recordcontainers/jdito/contentProcess.js
@@ -1,3 +1,4 @@
+import("Sql_lib");
 import("system.vars");
 import("system.datetime");
 import("system.db");
@@ -10,9 +11,14 @@ import("KeywordRegistry_basic");
     
 // load data
 
-var phases = db.table("select KEYID, AB_KEYWORD_ENTRY.TITLE, count(PHASE), AB_KEYWORD_ENTRY.SORTING \n\
-from SALESPROJECT join AB_KEYWORD_ENTRY on KEYID = PHASE and  CONTAINER  = 'SalesprojectPhase' and SORTING <> 7 \n\
-group by KEYID, AB_KEYWORD_ENTRY.TITLE, AB_KEYWORD_ENTRY.SORTING order by SORTING");
+var phases = newSelect("KEYID, AB_KEYWORD_ENTRY.TITLE, count(PHASE), AB_KEYWORD_ENTRY.SORTING")
+    .from("SALESPROJECT")
+    .join("AB_KEYWORD_ENTRY", newWhere("KEYID = PHASE")
+        .and("AB_KEYWORD_ENTRY.CONTAINER", $KeywordRegistry.salesprojectPhase())
+        .and("SORTING != 7"))
+    .groupBy("KEYID, AB_KEYWORD_ENTRY.TITLE, AB_KEYWORD_ENTRY.SORTING")
+    .orderBy("SORTING")
+    .table();
 
 for(i = 0; i < phases.length; i++){
     if(phases[i][1] == "${SALESPROJECT_OFFER}"){
diff --git a/entity/Timetracking_entity/entityfields/totaltime/valueProcess.js b/entity/Timetracking_entity/entityfields/totaltime/valueProcess.js
index 0f403dcc2e9..1bb9780412c 100644
--- a/entity/Timetracking_entity/entityfields/totaltime/valueProcess.js
+++ b/entity/Timetracking_entity/entityfields/totaltime/valueProcess.js
@@ -1,7 +1,9 @@
-import("system.db");
+import("Sql_lib");
 import("system.vars");
 import("system.result");
 
-var minutes = db.cell("select sum(TRACKINGMINUTES) from TIMETRACKING");
+var minutes = newSelect("sum(TRACKINGMINUTES)")
+    .from("TIMETRACKING")
+    .cell(false, "0");
 
 result.string(minutes);
\ No newline at end of file
diff --git a/process/Campaign_lib/process.js b/process/Campaign_lib/process.js
index ac2b7375ac4..c364beebc0e 100644
--- a/process/Campaign_lib/process.js
+++ b/process/Campaign_lib/process.js
@@ -191,12 +191,11 @@ CampaignUtils.openNewCampaignView = function()
 
 CampaignUtils.getDefaultCampaignStep = function(pCampaignId)
 {
-    let selectQuery = "select CAMPAIGNSTEPID from CAMPAIGNSTEP " +
-                      "where CAMPAIGNSTEP.CAMPAIGN_ID = '" + pCampaignId + "' " +
-                      "order by CAMPAIGNSTEP.SORTING asc";
-    
-    
-    return db.cell(selectQuery)   
+    return newSelect("CAMPAIGNSTEPID")
+        .from("CAMPAIGNSTEP")
+        .where("CAMPAIGNSTEP.CAMPAIGN_ID", pCampaignId)
+        .orderBy("CAMPAIGNSTEP.SORTING asc")
+        .cell();
 }
 
 CampaignUtils.getCampaignStartDate = function(pCapmaignId)
@@ -260,8 +259,10 @@ CampaignUtils.deleteCampaignData = function(pCampaignId)
     if(pCampaignId == null || pCampaignId == "")
         return;
     
-    let allStepIdsOfCampaignQuery = "select CAMPAIGNSTEPID from CAMPAIGNSTEP where CAMPAIGN_ID = '" + pCampaignId + "'";
-    let campaignStepIds = db.array(db.COLUMN, allStepIdsOfCampaignQuery);
+    let campaignStepIds = newSelect("CAMPAIGNSTEPID")
+        .from("CAMPAIGNSTEP")
+        .where("CAMPAIGNSTEP.CAMPAIGN_ID", pCampaignId)
+        .arrayColumn();
     
     campaignStepIds.forEach(function (campaignStepId) 
     {
@@ -342,70 +343,77 @@ CampaignUtils.GetContactIdsNotInCampaignByRowIds = function(pCampaignId, pPartic
 {
     let rowIdsAsRay = _CampaignUtils._convertToSqlValuesList(pParticipantRowIds);
     
-    let query = "select CONTACT.CONTACTID from CONTACT"
-    + " where CONTACT.CONTACTID in " + rowIdsAsRay
-    + " and CONTACT.CONTACTID not in"
-    + " (select CAMPAIGNPARTICIPANT.CONTACT_ID from CAMPAIGNPARTICIPANT"
-    + " where CAMPAIGNPARTICIPANT.CAMPAIGN_ID = '" + pCampaignId + "')";
-
-    return db.array(db.COLUMN, query)
+    return newSelect("CONTACT.CONTACTID")
+        .from("CONTACT")
+        .where("CONTACT.CONTACTID", rowIdsAsRay, SqlBuilder.IN())
+        .and("CONTACT.CONTACTID", 
+            newSelect("CAMPAIGNPARTICIPANT.CONTACT_ID")
+            .from("CAMPAIGNPARTICIPANT")
+            .where("CAMPAIGNPARTICIPANT.CAMPAIGN_ID", pCampaignId)
+            , SqlBuilder.NOT_IN())
+        .arrayColumn();
 }
 
 CampaignUtils.GetContactIdsNotInCampaignByCondition = function(pCampaignId, pCondition, pRightJoinContacts)
 {
-    let query = "select CONTACT.CONTACTID from PERSON"
+    let query = newSelect("CONTACT.CONTACTID").from("PERSON");
     
-    if(pRightJoinContacts == "true")
-        query += " right"
+    if (pRightJoinContacts == "true")
+        query.rightJoin("CONTACT", "CONTACT.PERSON_ID = PERSON.PERSONID");
+    else
+        query.join("CONTACT", "CONTACT.PERSON_ID = PERSON.PERSONID");
     
-    query += " join CONTACT on (CONTACT.PERSON_ID = PERSON.PERSONID)"
-    + " join ORGANISATION on (ORGANISATION.ORGANISATIONID = CONTACT.ORGANISATION_ID)"
-    + " left join ADDRESS on (ADDRESS.ADDRESSID = CONTACT.ADDRESS_ID)"
-    + " where CONTACT.CONTACTID not in"
-    + " (select CAMPAIGNPARTICIPANT.CONTACT_ID from CAMPAIGNPARTICIPANT where"
-    + " CAMPAIGNPARTICIPANT.CAMPAIGN_ID = '" + pCampaignId + "')";
+    query.join("ORGANISATION", "ORGANISATION.ORGANISATIONID = CONTACT.ORGANISATION_ID")
+        .leftJoin("ADDRESS", "ADDRESS.ADDRESSID = CONTACT.ADDRESS_ID")
+        .where("CONTACT.CONTACTID", 
+            newSelect("CAMPAIGNPARTICIPANT.CONTACT_ID")
+            .from("CAMPAIGNPARTICIPANT")
+            .where("CAMPAIGNPARTICIPANT.CAMPAIGN_ID", pCampaignId)
+            , SqlBuilder.NOT_IN()
+        );
     
     if(pCondition != "")
-        query += " and " + pCondition;
+        query.and(pCondition);
 
-    return db.array(db.COLUMN, query);
+    return query.arraColumn();
 }
 
 CampaignUtils.GetContactIdsInCampaignByCondition = function(pCampaignId, pCondition, pRightJoinContacts)
 {
-    let query = "select CONTACT.CONTACTID from CONTACT"
+    let query = newSelect("CONTACT.CONTACTID").from("CONTACT");
     
 //    if(pRightJoinContacts == "true")
 //        query += " right"
     
-    query += " left join PERSON on (CONTACT.PERSON_ID = PERSON.PERSONID)"
-    + " left join ORGANISATION on (ORGANISATION.ORGANISATIONID = CONTACT.ORGANISATION_ID)"
-    + " left join ADDRESS on (ADDRESS.ADDRESSID = CONTACT.ADDRESS_ID)"
-    + " left join CAMPAIGNPARTICIPANT on CAMPAIGNPARTICIPANT.CONTACT_ID = CONTACT.CONTACTID"
-    + " where " + pCondition
-    + " and CAMPAIGNPARTICIPANT.CAMPAIGN_ID = '" + pCampaignId + "'";
+    query.leftJoin("PERSON", "CONTACT.PERSON_ID = PERSON.PERSONID")
+        .leftJoin("ORGANISATION", "ORGANISATION.ORGANISATIONID = CONTACT.ORGANISATION_ID")
+        .leftJoin("ADDRESS", "ADDRESS.ADDRESSID = CONTACT.ADDRESS_ID")
+        .leftJoin("CAMPAIGNPARTICIPANT", "CAMPAIGNPARTICIPANT.CONTACT_ID = CONTACT.CONTACTID")
+        .where(pCondition)
+        .and("CAMPAIGNPARTICIPANT.CAMPAIGN_ID", pCampaignId);
 
-    return db.array(db.COLUMN, query);
+    return query.arrayColumn();
 }
 
 CampaignUtils.GetContactCountByCondition = function(pCondition, pLookInCampaignOnly, pRightJoinContacts)
 {
-    let query = "select count(*) from PERSON"
+    let query = newSelect("count(*)").from("PERSON");
     
     if(pRightJoinContacts == "true")
-        query += " right"
+        query.rightJoin("CONTACT", "CONTACT.PERSON_ID = PERSON.PERSONID");
+    else
+        query.join("CONTACT", "CONTACT.PERSON_ID = PERSON.PERSONID");
     
-    query += " join CONTACT on (CONTACT.PERSON_ID = PERSON.PERSONID)"
-    query += " join ORGANISATION on (ORGANISATION.ORGANISATIONID = CONTACT.ORGANISATION_ID)"
-    query += " left join ADDRESS on (ADDRESS.ADDRESSID = CONTACT.ADDRESS_ID)"
+    query.join("ORGANISATION", "ORGANISATION.ORGANISATIONID = CONTACT.ORGANISATION_ID");
+    query.leftJoin("ADDRESS", "ADDRESS.ADDRESSID = CONTACT.ADDRESS_ID");
                 
     if(pLookInCampaignOnly == "true")
-        query += " left join CAMPAIGNPARTICIPANT on CAMPAIGNPARTICIPANT.CONTACT_ID = CONTACT.CONTACTID";
+        query.leftJoin("CAMPAIGNPARTICIPANT", "CAMPAIGNPARTICIPANT.CONTACT_ID = CONTACT.CONTACTID");
     
     if(pCondition != "")
-        query += " where " + pCondition;
+        query.where(pCondition)
     
-    return db.cell(query);
+    return query.cell();
 }
 
 /**
@@ -459,22 +467,19 @@ function _CampaignUtils() {}
 
 _CampaignUtils._selectFromContactWithJoin = function(pSelectFields, pCampaignId, pWhereCondition)
 {
-    let query = "select " + pSelectFields + " from PERSON"
-                + " join CONTACT on (CONTACT.PERSON_ID = PERSON.PERSONID)"
-                + " join ORGANISATION on (ORGANISATION.ORGANISATIONID = CONTACT.ORGANISATION_ID)"
-                + " left join ADDRESS on (ADDRESS.ADDRESSID = CONTACT.ADDRESS_ID)";
-    
-    if(pWhereCondition != "")
-    {
-        query += " where " + pWhereCondition;
-        query += " and CONTACT.CONTACTID not in" 
-                + " (select CONTACT_ID from CAMPAIGNPARTICIPANT"
-                + " where CAMPAIGNPARTICIPANT.CAMPAIGN_ID = '" + pCampaignId + "')";
-    }
-    else
-        query += " where CONTACT.CONTACTID not in" 
-                + " (select CONTACT_ID from CAMPAIGNPARTICIPANT"
-                + " where CAMPAIGNPARTICIPANT.CAMPAIGN_ID = '" + pCampaignId + "')";
+    let query = newSelect(pSelectFields)
+        .from("PERSON")
+        .join("CONTACT", "CONTACT.PERSON_ID = PERSON.PERSONID")
+        .join("ORGANISATION", "ORGANISATION.ORGANISATIONID = CONTACT.ORGANISATION_ID")
+        .leftJoin("ADDRESS", "ADDRESS.ADDRESSID = CONTACT.ADDRESS_ID")
+        .where("CONTACT.CONTACTID", 
+            newSelect("CONTACT_ID")
+            .from("CAMPAIGNPARTICIPANT")
+            .where("CAMPAIGNPARTICIPANT.CAMPAIGN_ID", pCampaignId)
+            , SqlBuilder.NOT_IN());
+    
+    if (pWhereCondition != "")
+        query.and(pWhereCondition);
     
     return query;
 }
diff --git a/process/Date_lib/process.js b/process/Date_lib/process.js
index 60a391e0f50..18a7b2b1883 100644
--- a/process/Date_lib/process.js
+++ b/process/Date_lib/process.js
@@ -155,4 +155,12 @@ DateUtils.formatDurationFromStartTillEnd = function(pStartTime, pEndTime, pLocal
 DateUtils.validateNotInFuture = function (pDate)
 {
     return Number(datetime.clearTime(pDate)) <= Number(vars.get("$sys.today"));
+}
+
+/**
+ * @return {number} the current year
+ */
+DateUtils.getCurrentYear = function ()
+{
+    return parseInt(datetime.toDate(vars.get("$sys.date"), "yyyy"));
 }
\ No newline at end of file
diff --git a/process/Loghistory_lib/process.js b/process/Loghistory_lib/process.js
index 88d811340f2..4a8ea67de39 100644
--- a/process/Loghistory_lib/process.js
+++ b/process/Loghistory_lib/process.js
@@ -130,7 +130,7 @@ LogHistoryExecutor.prototype.execute = function ()
         }
         if (this.sqlAction == 'U')
         {
-            var ids = db.array(db.ROW, "select " + conf.IDs.join(", ") + " from " + this.affectedTable + " where " + this.affectedTable + "ID = '" + idvalue + "'");
+            var ids = newSelect(conf.IDs).from(this.affectedTable).where([this.affectedTable, this.affectedTable + "ID"], idvalue).arrayRow();
             idvalue = ids[0];
             var oldid =  ids[1];
             if (oldvalues[conf.IDs[1]]) oldid =  oldvalues[conf.IDs[1]];
@@ -195,7 +195,7 @@ LogHistoryExecutor.prototype.execute = function ()
         }
         if (this.sqlAction == "U")
         {
-            for (var index in references) references[index].id = db.cell("select " + index + " from "  + this.affectedTable + " where " + primaryKey + " = '" + this.idValue + "'");
+            for (var index in references) references[index].id = newSelect(index).from(this.affectedTable).where([this.affectedTable, primaryKey], this.idValue).cell();
         }
     }
 
diff --git a/process/Neon_lib/process.js b/process/Neon_lib/process.js
index 037de688249..a5eb0b31290 100644
--- a/process/Neon_lib/process.js
+++ b/process/Neon_lib/process.js
@@ -1,3 +1,4 @@
+import("Sql_lib");
 import("Date_lib");
 import("system.vars");
 import("system.datetime");
@@ -181,7 +182,7 @@ CopyModuleUtils.copyModule = function(pInputMapping)
             if(pCondition != undefined)
                 condition = pCondition;
 
-            var dbData = db.table("select " + cols.join(", ") + " from " + pModule + " where " + condition);
+            var dbData = newSelect(cols).from(pModule).where(condition).table();
 
             //map 2d-Array to Object { $rowNumber$: { $columnName$: { value: "valueInDB" } } }
             var DataObj = {};
diff --git a/process/ObjectRelation_lib/process.js b/process/ObjectRelation_lib/process.js
index 330272e6872..447a67cf94a 100644
--- a/process/ObjectRelation_lib/process.js
+++ b/process/ObjectRelation_lib/process.js
@@ -23,80 +23,43 @@ function ObjectRelationUtils() {}
  */
 ObjectRelationUtils.getPossibleRelationTypes = function(pObjectTypes, pFullInfo, pOnlyFirstSide, pRelationTypeId, pDummyField)
 {
-    // TODO: use sql builder
-    
-    var sql = " from AB_OBJECTRELATIONTYPE main \n\
-            left join AB_OBJECTRELATIONTYPE type2 on (type2.AB_OBJECTRELATIONTYPEID <> main.AB_OBJECTRELATIONTYPEID and type2.RELATION_TYPE = main.RELATION_TYPE) ";
-    var cond = "";
-    
-    var params = [];
-    
-    if (pObjectTypes)
-    {
-        pObjectTypes.forEach(function(pObjectType)
-        {
-            if (!cond)
-                cond += "where ";
-            else
-                cond += " or ";
-            
-            cond += "case when type2.OBJECT_TYPE is null then main.OBJECT_TYPE else type2.OBJECT_TYPE end = ? ";
-            params.push([pObjectType, db.getColumnTypes("AB_OBJECTRELATIONTYPE", ["OBJECT_TYPE"])[0]]);
-        });
-    }
-    
-    if (pRelationTypeId)
-    {
-        if (!cond)
-            cond = "where ";
-        else
-            cond += " and ";
-        
-        cond += " main.AB_OBJECTRELATIONTYPEID = ? ";
-        params.push([pRelationTypeId, db.getColumnTypes("AB_OBJECTRELATIONTYPE", ["AB_OBJECTRELATIONTYPEID"])[0]]);
-    }
+    var sql = new SqlBuilder()
+        .from("AB_OBJECTRELATIONTYPE", "main")
+        .leftJoin("AB_OBJECTRELATIONTYPE", "type2.AB_OBJECTRELATIONTYPEID <> main.AB_OBJECTRELATIONTYPEID and type2.RELATION_TYPE = main.RELATION_TYPE", "type2")
+        .whereIfSet(["AB_OBJECTRELATIONTYPE", "OBJECT_TYPE", "type2"], pObjectTypes, "(case when # is null then main.OBJECT_TYPE else type2.OBJECT_TYPE end) in ?")
+        .andIfSet(["AB_OBJECTRELATIONTYPE", "AB_OBJECTRELATIONTYPEID", "main"], pRelationTypeId || null);
     
     if (pOnlyFirstSide == "1")
-    {
-        if (!cond)
-            cond = "where ";
-        else
-            cond += " and ";
-        
-        cond += " main.SIDE = 1 "
-    }
-    
-    sql += cond;
+        sql.and("main.SIDE = 1");
     
+    var fields = ["main.AB_OBJECTRELATIONTYPEID", "main.RELATION_TITLE"];
     // only id and title:
-    if (pFullInfo == undefined || pFullInfo == false)
-    {
-        sql = "select main.AB_OBJECTRELATIONTYPEID, main.RELATION_TITLE" + sql;
-    }
-    else
+    if (pFullInfo)
     {
-        sql = "select main.AB_OBJECTRELATIONTYPEID, main.RELATION_TITLE, main.RELATION_TYPE, \n\
-        case when type2.AB_OBJECTRELATIONTYPEID is null then 'same' \n\
-             when main.SIDE = 1 then 'normal'\n\
-             else 'reverse'\n\
-        end direction,\n\
-        main.HIERARCHY, \n\
-        ( case when type2.AB_OBJECTRELATIONTYPEID is null then main.OBJECT_TYPE " + // if type is 'same' (type2.AB_OBJECTRELATIONTYPEID is null) then use the same object type for dest as for source
-        "    else type2.OBJECT_TYPE end ) destObjectType, \n\
-        main.OBJECT_TYPE sourceObjectType, \n\
-        -- typeId of Object2\n\
-        case when main.SIDE = 1 then main.AB_OBJECTRELATIONTYPEID\n\
-             else type2.AB_OBJECTRELATIONTYPEID end objectrelationtypeId1,\n\
-        -- typeId of Object1\n\
-        case when type2.AB_OBJECTRELATIONTYPEID is null or main.SIDE = 2 then main.AB_OBJECTRELATIONTYPEID\n\
-             else type2.AB_OBJECTRELATIONTYPEID end objectrelationtypeId2, \n\
-        main.SIDE,\n\
-        case when type2.AB_OBJECTRELATIONTYPEID is  null then main.AB_OBJECTRELATIONTYPEID else type2.AB_OBJECTRELATIONTYPEID end,\n\
-        type2.RELATION_TITLE" + (pDummyField ? ", ''" : "") + ", main.ICON" + sql; // Icon is only saved in type1
+        fields = fields.concat([
+            "main.RELATION_TYPE",
+            "case when type2.AB_OBJECTRELATIONTYPEID is null then 'same' \n\
+                when main.SIDE = 1 then 'normal'\n\
+                else 'reverse'\n\
+                end direction",
+            "main.HIERARCHY",
+            "(case when type2.AB_OBJECTRELATIONTYPEID is null then main.OBJECT_TYPE " + // if type is 'same' (type2.AB_OBJECTRELATIONTYPEID is null) then use the same object type for dest as for source
+            "    else type2.OBJECT_TYPE end) destObjectType",
+            "main.OBJECT_TYPE sourceObjectType",
+            "-- typeId of Object2\n\
+            case when main.SIDE = 1 then main.AB_OBJECTRELATIONTYPEID \n\
+                else type2.AB_OBJECTRELATIONTYPEID end objectrelationtypeId1",
+            "-- typeId of Object1\n\
+            case when type2.AB_OBJECTRELATIONTYPEID is null or main.SIDE = 2 then main.AB_OBJECTRELATIONTYPEID\n\
+                else type2.AB_OBJECTRELATIONTYPEID end objectrelationtypeId2",
+            "main.SIDE",
+            "case when type2.AB_OBJECTRELATIONTYPEID is null then main.AB_OBJECTRELATIONTYPEID else type2.AB_OBJECTRELATIONTYPEID end",
+            "type2.RELATION_TITLE", (pDummyField ? "''" : ""), "main.ICON" // Icon is only saved in type1
+        ]);
     }
        
     // full info:
-    return (db.table([sql, params]));
+    return sql.select(fields).table();
 }
 
 /**
diff --git a/process/Product_lib/process.js b/process/Product_lib/process.js
index 1c7f91318e3..0f9cdab1cd7 100644
--- a/process/Product_lib/process.js
+++ b/process/Product_lib/process.js
@@ -540,9 +540,11 @@ Prod2ProdUtils.prototype.getParentProdIds = function()
 Prod2ProdUtils.prototype._initProd2ProdData = function()
 {
     if (this.data == undefined) {
-        this.data = db.table("select PROD2PRODID, DEST_ID, SOURCE_ID, QUANTITY, OPTIONAL, TAKEPRICE, PRODUCTCODE, PRODUCTID "
-                    + "from PROD2PROD join PRODUCT on PROD2PROD.SOURCE_ID = PRODUCTID "
-                    + "order by PRODUCTCODE ");
+        this.data = newSelect("PROD2PRODID, DEST_ID, SOURCE_ID, QUANTITY, OPTIONAL, TAKEPRICE, PRODUCTCODE, PRODUCTID")
+            .from("PROD2PROD")
+            .join("PRODUCT", "PROD2PROD.SOURCE_ID = PRODUCTID")
+            .orderBy("PRODUCTCODE")
+            .table();
     }
 }
 
diff --git a/process/Sql_lib/process.js b/process/Sql_lib/process.js
index c4f36ef31d4..47ef865b350 100644
--- a/process/Sql_lib/process.js
+++ b/process/Sql_lib/process.js
@@ -987,6 +987,20 @@ SqlBuilder.NOT_EXISTS = function()
     return "not exists ?";
 }
 
+/**
+ * Constant-like function which provides a value for pCondition if you need a "year(#) = ?" statement.
+ * Make sure you use SQLTYPES.INTEGER as type.
+ * 
+ * @return {String} 
+ * 
+ * @example
+ * var cond = newWhere("FORECAST.DATE_START", DateUtils.getCurrentYear(), SqlBuilder.YEAR_EQUALS(), SQLTYPES.INTEGER)
+ */
+SqlBuilder.YEAR_EQUALS = function ()
+{
+    return (new SqlMaskingUtils().yearFromDate("#")) + " = ?";
+}
+
 /**
  * Throws an error if pValue is null, undefined or a SqlBuilder without condition (or if pValue is a $-variable: error if the result of it is null or undefined)<br/>
  * Also throws an error if pFieldOrCond is the only parameter and it is null<br/>
diff --git a/process/StandardObject_lib/process.js b/process/StandardObject_lib/process.js
index 5e8a368ff6f..9a1f8379faf 100644
--- a/process/StandardObject_lib/process.js
+++ b/process/StandardObject_lib/process.js
@@ -1,4 +1,5 @@
 import("Organisation_lib");
+import("Sql_lib");
 import("system.db");
 import("Keyword_lib");
 import("KeywordRegistry_basic");
@@ -195,8 +196,9 @@ StandardObject.prototype.onCommunicationUpdate = function (pMediumID) {
 StandardObject.prototype._hasContactStandardAddress = function (pContactID) {
     this._assertObjectType(StandardObject.CONST_OBJECT_ADDRESS());
     
-    var databaseResult = db.cell("select ADDRESS_ID from CONTACT"
-        + " where CONTACTID = '" + pContactID + "'");
+    var databaseResult = newSelect("ADDRESS_ID").from("CONTACT")
+        .where("CONTACT.CONTACTID", pContactID)
+        .cell();
     
     return databaseResult !== "";
 }
@@ -218,7 +220,7 @@ StandardObject.prototype._setContactStandardAddress = function (pAddressID, pCon
         ["ADDRESS_ID"], 
         db.getColumnTypes("CONTACT", ["ADDRESS_ID"]), 
         [pAddressID], 
-        "CONTACTID = '" + pContactID + "'");
+        newWhere("CONTACT.CONTACTID", pContactID));
 }
 
 /**
@@ -230,13 +232,11 @@ StandardObject.prototype._setContactStandardAddress = function (pAddressID, pCon
 StandardObject.prototype._getCompanyStandardAddress = function (pOrganisationID) {
     if (OrgUtils.isPrivateOrganisationId(pOrganisationID))
         return null;
-    var addressIdResult = db.cell("select ADDRESS_ID from CONTACT"
-        + " where ORGANISATION_ID = '" + pOrganisationID + "'"
-        + " and ADDRESS_ID is not null and PERSON_ID is null");
-    
-    if (addressIdResult === "")
-        return null;
-    return addressIdResult;
+    return newSelect("ADDRESS_ID")
+        .from("CONTACT")
+        .where("CONTACT.ORGANISATION_ID", pOrganisationID)
+        .and("ADDRESS_ID is not null and PERSON_ID is null")
+        .cell() || null;
 }
 
 /**
@@ -249,12 +249,15 @@ StandardObject.prototype._getCompanyStandardAddress = function (pOrganisationID)
  * medium category.
  */
 StandardObject.prototype._hasStandardCommunicationByMedium = function (pContactID, pMediumCategory) {   
-    var dbResult = db.array(db.COLUMN, "select CHAR_VALUE from COMMUNICATION"
-        + " left join AB_KEYWORD_ENTRY on KEYID = MEDIUM_ID"
-        + " left join AB_KEYWORD_ATTRIBUTERELATION on AB_KEYWORD_ENTRY_ID = AB_KEYWORD_ENTRYID"
-        + " where ISSTANDARD = 1 and CONTACT_ID = '" + pContactID + "' and KEYID in ('" + CommUtil.getMediumIdsByCategory(pMediumCategory).join("', '") +  "')");
-    
-    return dbResult.indexOf(pMediumCategory) !== -1;
+    return newSelect("CHAR_VALUE")
+        .from("COMMUNICATION")
+        .leftJoin("AB_KEYWORD_ENTRY", "KEYID = MEDIUM_ID")
+        .leftJoin("AB_KEYWORD_ATTRIBUTERELATION", "AB_KEYWORD_ENTRY_ID = AB_KEYWORD_ENTRYID")
+        .where("ISSTANDARD = 1")
+        .and("COMMUNICATION.CONTACT_ID", pContactID)
+        .and("AB_KEYWORD_ENTRY.KEYID", CommUtil.getMediumIdsByCategory(pMediumCategory), SqlBuilder.IN())
+        .arrayColumn()
+        .indexOf(pMediumCategory) !== -1;
 }
 
 /**
@@ -286,7 +289,7 @@ StandardObject.prototype._setStandardCommunication = function (pCommunicationID,
         ["ISSTANDARD"], 
         db.getColumnTypes("COMMUNICATION", ["ISSTANDARD"]), 
         [pValue], 
-        "COMMUNICATIONID = '" + pCommunicationID + "'");
+        newWhere("COMMUNICATION.COMMUNICATIONID", pCommunicationID));
 }
 
 /**
@@ -296,7 +299,7 @@ StandardObject.prototype._setStandardCommunication = function (pCommunicationID,
  * @return The contact ID.
  */
 StandardObject.prototype._getContactIdByCommunication = function (pCommunicationID) {
-    return db.cell("select CONTACT_ID from COMMUNICATION where COMMUNICATIONID = '" + pCommunicationID + "'");
+    return newSelect("CONTACT_ID").from("COMMUNICATION").where("COMMUNICATION.COMMUNICATIONID", pCommunicationID).cell();
 }
 
 StandardObject.prototype._isOrganisationAddress = function (pAddressID) {
@@ -310,7 +313,7 @@ StandardObject.prototype._isOrganisationAddress = function (pAddressID) {
  * @return The contact ID.
  */
 StandardObject.isOrganisationAddress = function (pAddressID) {
-    var contactID = db.cell("select CONTACTID from CONTACT where ADDRESS_ID = '" + pAddressID + "'");
+    var contactID = newSelect("CONTACTID").from("CONTACT").where("CONTACT.ADDRESS_ID", pAddressID).cell();
     
     if (!contactID)
         return false;
-- 
GitLab