ExpressionSQL.java

  1. /*
  2.  * GovWay - A customizable API Gateway
  3.  * https://govway.org
  4.  *
  5.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License version 3, as published by
  9.  * the Free Software Foundation.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  *
  19.  */

  20. package org.openspcoop2.generic_project.expression.impl.sql;

  21. import java.sql.Timestamp;
  22. import java.util.ArrayList;
  23. import java.util.Arrays;
  24. import java.util.Iterator;
  25. import java.util.List;
  26. import java.util.Map;

  27. import org.openspcoop2.generic_project.beans.AliasField;
  28. import org.openspcoop2.generic_project.beans.ComplexField;
  29. import org.openspcoop2.generic_project.beans.ConstantField;
  30. import org.openspcoop2.generic_project.beans.CustomField;
  31. import org.openspcoop2.generic_project.beans.Field;
  32. import org.openspcoop2.generic_project.beans.Function;
  33. import org.openspcoop2.generic_project.beans.FunctionField;
  34. import org.openspcoop2.generic_project.beans.IAliasTableField;
  35. import org.openspcoop2.generic_project.beans.IField;
  36. import org.openspcoop2.generic_project.beans.IModel;
  37. import org.openspcoop2.generic_project.beans.UnixTimestampIntervalField;
  38. import org.openspcoop2.generic_project.exception.ExpressionException;
  39. import org.openspcoop2.generic_project.exception.ExpressionNotImplementedException;
  40. import org.openspcoop2.generic_project.expression.Index;
  41. import org.openspcoop2.generic_project.expression.LikeMode;
  42. import org.openspcoop2.generic_project.expression.SortOrder;
  43. import org.openspcoop2.generic_project.expression.impl.BetweenExpressionImpl;
  44. import org.openspcoop2.generic_project.expression.impl.Comparator;
  45. import org.openspcoop2.generic_project.expression.impl.ComparatorExpressionImpl;
  46. import org.openspcoop2.generic_project.expression.impl.ConjunctionExpressionImpl;
  47. import org.openspcoop2.generic_project.expression.impl.DateTimePartExpressionImpl;
  48. import org.openspcoop2.generic_project.expression.impl.DayFormatExpressionImpl;
  49. import org.openspcoop2.generic_project.expression.impl.ExpressionImpl;
  50. import org.openspcoop2.generic_project.expression.impl.InExpressionImpl;
  51. import org.openspcoop2.generic_project.expression.impl.LikeExpressionImpl;
  52. import org.openspcoop2.generic_project.expression.impl.OrderedField;
  53. import org.openspcoop2.generic_project.expression.impl.formatter.IObjectFormatter;
  54. import org.openspcoop2.utils.TipiDatabase;
  55. import org.openspcoop2.utils.sql.DateTimePartEnum;
  56. import org.openspcoop2.utils.sql.DayFormatEnum;
  57. import org.openspcoop2.utils.sql.ISQLQueryObject;
  58. import org.openspcoop2.utils.sql.SQLQueryObjectAlreadyExistsException;
  59. import org.openspcoop2.utils.sql.SQLQueryObjectCore;
  60. import org.openspcoop2.utils.sql.SQLQueryObjectException;

  61. /**
  62.  * ExpressionSQL
  63.  *
  64.  * @author Poli Andrea (apoli@link.it)
  65.  * @author $Author$
  66.  * @version $Rev$, $Date$
  67.  */
  68. public class ExpressionSQL extends ExpressionImpl {

  69.     private static final String EXPRESSION_NOT_INITIALIZED = "Expression is not initialized";
  70.     private static final String EXPRESSION_TYPE_PREFIX = "ExpressioneEngine (type:";
  71.     private static final String IS_NOT_AS_CAST_WITH = ") is not as cast with ";
  72.     private static final String FIELD_TYPE_UNKNOWN_PREFIX = "Field type unknown [";
  73.    
  74.     private boolean throwExpressionNotInitialized = false;
  75.    
  76.     private TipiDatabase databaseType;
  77.     public TipiDatabase getDatabaseType() {
  78.         return this.databaseType;
  79.     }

  80.     private ISQLFieldConverter sqlFieldConverter;
  81.     public ISQLFieldConverter getSqlFieldConverter() {
  82.         return this.sqlFieldConverter;
  83.     }
  84.     public void setSqlFieldConverter(ISQLFieldConverter sqlFieldConverter) {
  85.         this.sqlFieldConverter = sqlFieldConverter;
  86.     }
  87.    
  88.     private boolean usedForCountExpression = false;
  89.     public boolean isUsedForCountExpression() {
  90.         return this.usedForCountExpression;
  91.     }
  92.     public void setUsedForCountExpression(boolean usedForCountExpression) {
  93.         this.usedForCountExpression = usedForCountExpression;
  94.     }
  95.    
  96.     public ExpressionSQL(ISQLFieldConverter sqlFieldConverter) throws ExpressionException {
  97.         super();
  98.         this.sqlFieldConverter = sqlFieldConverter;
  99.         if(this.sqlFieldConverter!=null){
  100.             this.databaseType = this.sqlFieldConverter.getDatabaseType();
  101.         }
  102.     }
  103.     public ExpressionSQL(ISQLFieldConverter sqlFieldConverter,IObjectFormatter objectFormatter) throws ExpressionException{
  104.         super(objectFormatter);
  105.         this.sqlFieldConverter = sqlFieldConverter;
  106.         if(this.sqlFieldConverter!=null){
  107.             this.databaseType = this.sqlFieldConverter.getDatabaseType();
  108.         }
  109.     }
  110.     public ExpressionSQL(PaginatedExpressionSQL expression) throws ExpressionException{
  111.         super(expression);
  112.         this.sqlFieldConverter = expression.getSqlFieldConverter();
  113.         this.fieldsManuallyAdd = expression.getFieldsManuallyAdd();
  114.         /**this.checkFieldManuallyAdd = expression.checkFieldManuallyAdd;*/
  115.         if(this.sqlFieldConverter!=null){
  116.             this.databaseType = this.sqlFieldConverter.getDatabaseType();
  117.         }
  118.     }

  119.     private List<Object> fieldsManuallyAdd = new ArrayList<>();
  120.     public List<Object> getFieldsManuallyAdd() {
  121.         return this.fieldsManuallyAdd;
  122.     }
  123.     public void removeFieldManuallyAdd(Object o) {
  124.         if(this.fieldsManuallyAdd.contains(o)){
  125.             this.fieldsManuallyAdd.remove(o);
  126.         }
  127.     }
  128.    
  129.     private boolean checkFieldManuallyAdd = true;
  130.     public void setCheckFieldManuallyAdd(boolean checkFieldManuallyAdd) {
  131.         this.checkFieldManuallyAdd = checkFieldManuallyAdd;
  132.     }
  133.     @Override
  134.     public boolean inUseField(IField field,boolean checkOnlyWhereCondition) throws ExpressionNotImplementedException, ExpressionException {
  135.         return ExpressionSQL.inUse(field, checkOnlyWhereCondition, super.inUseField(field,checkOnlyWhereCondition), this.getFieldsManuallyAdd(),this.checkFieldManuallyAdd);
  136.     }
  137.     @Override
  138.     public boolean inUseModel(IModel<?> model,boolean checkOnlyWhereCondition) throws ExpressionNotImplementedException, ExpressionException {
  139.         return ExpressionSQL.inUse(model, checkOnlyWhereCondition, super.inUseModel(model,checkOnlyWhereCondition), this.getFieldsManuallyAdd(),this.checkFieldManuallyAdd);
  140.     }
  141.     @Override
  142.     public List<IField> getFields(boolean onlyWhereCondition) throws ExpressionNotImplementedException, ExpressionException{
  143.         return ExpressionSQL.getFields(onlyWhereCondition, super.getFields(onlyWhereCondition), this.getFieldsManuallyAdd(),this.checkFieldManuallyAdd);
  144.     }
  145.    
  146.    
  147.     /* ************ COMPARATOR *********** */
  148.    
  149.     public static Comparator getCorrectComparator(Comparator comparator,TipiDatabase databaseType){
  150.         if(databaseType!=null && TipiDatabase.ORACLE.equals(databaseType)){
  151.             if(Comparator.IS_EMPTY.equals(comparator)){
  152.                 return Comparator.IS_NULL; // le stringhe vuote in oracle vengono inserite come null
  153.             }
  154.             else if(Comparator.IS_NOT_EMPTY.equals(comparator)){
  155.                 return Comparator.IS_NOT_NULL; // le stringhe vuote in oracle vengono inserite come null, inoltre la ricerca <> '' non funziona
  156.             }
  157.         }
  158.         return comparator;
  159.     }
  160.    
  161.     @Override
  162.     protected Comparator getCorrectComparator(Comparator comparator){
  163.         return ExpressionSQL.getCorrectComparator(comparator, this.databaseType);
  164.     }
  165.    
  166.     /* ************ TO SQL ENGINE *********** */
  167.    
  168.    
  169.     // SQL FORCE INDEX

  170.     private String toSqlForceIndex()throws ExpressionException{
  171.        
  172.         return ExpressionSQL.sqlForceIndex(this.sqlFieldConverter, this.getForceIndexes());

  173.     }
  174.    
  175.     protected static String sqlForceIndex(ISQLFieldConverter fieldConverter,List<Index> forceIndexes) throws ExpressionException{
  176.         try{
  177.            
  178.             StringBuilder bf = new StringBuilder();
  179.            
  180.             if(!forceIndexes.isEmpty()){
  181.                 for (Iterator<Index> iterator =forceIndexes.iterator(); iterator.hasNext();) {
  182.                     Index forceIndex = iterator.next();
  183.                     String forceIndexSql = "/*+ index("+fieldConverter.toTable(forceIndex.getModel(),false)+" "+forceIndex.getName()+") */";
  184.                     bf.append(" ");
  185.                     bf.append(forceIndexSql);
  186.                 }
  187.             }
  188.                
  189.             return bf.toString();
  190.            
  191.         }catch(Exception e){
  192.             throw new ExpressionException(e);
  193.         }
  194.     }
  195.    
  196.     private void toSqlForceIndex(ISQLQueryObject sqlQueryObject)throws ExpressionException{
  197.    
  198.         ExpressionSQL.sqlForceIndex(this.sqlFieldConverter, sqlQueryObject,this.getForceIndexes());
  199.        
  200.     }
  201.    
  202.     protected static void sqlForceIndex(ISQLFieldConverter fieldConverter, ISQLQueryObject sqlQueryObject,List<Index> forceIndexes) throws ExpressionException{
  203.         try{
  204.            
  205.             if(!forceIndexes.isEmpty()){
  206.                 for (Iterator<Index> iterator =forceIndexes.iterator(); iterator.hasNext();) {
  207.                     Index forceIndex = iterator.next();
  208.                     sqlQueryObject.addSelectForceIndex(fieldConverter.toTable(forceIndex.getModel(),false), forceIndex.getName());
  209.                 }
  210.             }
  211.            
  212.         }catch(Exception e){
  213.             throw new ExpressionException(e);
  214.         }
  215.     }
  216.    
  217.    
  218.    
  219.    
  220.    
  221.     // SQL ORDER

  222.     private String toSqlOrder()throws ExpressionException{
  223.        
  224.         return ExpressionSQL.sqlOrder(this.sqlFieldConverter, this.getSortOrder(), this.getOrderedFields());

  225.     }
  226.    
  227.     protected static String sqlOrder(ISQLFieldConverter fieldConverter,SortOrder sortOrder,List<OrderedField> orderedFields) throws ExpressionException{
  228.         try{
  229.            
  230.             StringBuilder bf = new StringBuilder();
  231.             if(!SortOrder.UNSORTED.equals(sortOrder)){
  232.                    
  233.                 bf.append(" ORDER BY ");
  234.                 if(!orderedFields.isEmpty()){
  235.                     int index = 0;
  236.                     for (Iterator<OrderedField> iterator =orderedFields.iterator(); iterator.hasNext();) {
  237.                         OrderedField orderedField = iterator.next();
  238.                         IField field = orderedField.getField();
  239.                         if(index>0){
  240.                             bf.append(" , ");
  241.                         }
  242.                         bf.append(fieldConverter.toColumn(field,true));
  243.                         bf.append(" ");
  244.                         bf.append(orderedField.getSortOrder().name());
  245.                         index++;
  246.                     }
  247.                 }else{
  248.                     bf.append(" id");
  249.                     bf.append(" ");
  250.                     bf.append(sortOrder.name());
  251.                 }
  252.             }
  253.                
  254.             return bf.toString();
  255.            
  256.         }catch(Exception e){
  257.             throw new ExpressionException(e);
  258.         }
  259.     }
  260.    
  261.     private void toSqlOrder(ISQLQueryObject sqlQueryObject)throws ExpressionException{
  262.    
  263.         ExpressionSQL.sqlOrder(this.sqlFieldConverter, sqlQueryObject,this.getSortOrder(), this.getOrderedFields(), this.getGroupByFields());
  264.        
  265.     }
  266.    
  267.     protected static void sqlOrder(ISQLFieldConverter fieldConverter, ISQLQueryObject sqlQueryObject,SortOrder sortOrder,List<OrderedField> orderedFields,
  268.             List<IField> groupByFields) throws ExpressionException{
  269.         try{
  270.            
  271.             if(!SortOrder.UNSORTED.equals(sortOrder)){
  272.                
  273.                 if(!orderedFields.isEmpty()){
  274.                     for (Iterator<OrderedField> iterator = orderedFields.iterator(); iterator.hasNext();) {
  275.                         OrderedField orderedField = iterator.next();
  276.                         IField field = orderedField.getField();
  277.                        
  278.                         String columnOrderAlias = fieldConverter.toColumn(field,true,true);
  279.                         String columnOrderBy = fieldConverter.toColumn(field,true);
  280.                         sqlQueryObject.addOrderBy(columnOrderBy,SortOrder.ASC.equals(orderedField.getSortOrder()));
  281.                        
  282.                         // Search by alias
  283.                         List<String> v = new ArrayList<>();
  284.                         try{
  285.                             v = sqlQueryObject.getFieldsName();
  286.                         }catch(Exception e){v = new ArrayList<>();}
  287.                         boolean contains = false;
  288.                         /**System.out.println("SEARCH ALIAS ["+columnOrderAlias+"] ...");*/
  289.                         if(v.contains(columnOrderAlias)){
  290.                             contains = true;
  291.                             /**System.out.println("SEARCH ALIAS ["+columnOrderAlias+"] FOUND");*/
  292.                         }
  293.                        
  294.                        
  295.                         // Search by column name
  296.                         if(!contains){
  297.                             try{
  298.                                 v = ((SQLQueryObjectCore)sqlQueryObject).getFields();
  299.                             }catch(Exception e){}
  300.                             /**System.out.println("SEARCH COLUMN ["+columnOrderBy+"] ...");*/
  301.                             if(v.contains(columnOrderBy)){
  302.                                 contains = true;
  303.                                 /**System.out.println("SEARCH COLUMN ["+columnOrderBy+"] FOUND");*/
  304.                             }
  305.                         }
  306.                        
  307.                         // Search by column name (split alias)
  308.                         if(!contains){
  309.                             /**System.out.println("SEARCH COLUMN SPLIT ["+columnOrderBy+"] ...");*/
  310.                             for (int i = 0; i < v.size(); i++) {
  311.                                 String column = v.get(0);
  312.                                 /**System.out.println("SEARCH COLUMN SPLITi ["+columnOrderBy+"] ["+i+"]: "+column);*/
  313.                                 if(column.contains(" as ")){
  314.                                     String [] tmp = column.split(" as ");
  315.                                     /**System.out.println("SEARCH COLUMN SPLIT A ["+columnOrderBy+"] ["+i+"]: "+column+"   AS ["+tmp[0]+"]");*/
  316.                                     if(tmp[0].equals(columnOrderBy)){
  317.                                         contains = true;
  318.                                         /**System.out.println("FOUND COLUMN SPLIT A!!!");*/
  319.                                         break;
  320.                                     }
  321.                                 }
  322.                                 else if(column.contains(" ")){
  323.                                     String [] tmp = column.split(" ");
  324.                                     /**System.out.println("SEARCH COLUMN SPLIT ["+columnOrderBy+"] ["+i+"]: "+column+"   AS2 ["+tmp[0]+"]");*/
  325.                                     if(tmp[0].equals(columnOrderBy)){
  326.                                         contains = true;
  327.                                         /**System.out.println("FOUND COLUMN SPLIT B!!!");*/
  328.                                         break;
  329.                                     }
  330.                                 }
  331.                             }
  332.                         }
  333.                        
  334.                         /**System.out.println("FIX ORACLE ["+columnOrderBy+"]: "+!contains);*/
  335.                         // Fix per oracle
  336.                         if(!contains){
  337.                             // Devo aggiungerlo solo se la colonna non fa gia' parte del group by condition, altrimenti tale colonna finira' comunque tra i select field.
  338.                             boolean add = true;
  339.                             if(groupByFields!=null){
  340.                                 for (IField groupByField : groupByFields) {
  341.                                     if(groupByField.equals(field)){
  342.                                         add = false;
  343.                                         break;
  344.                                     }
  345.                                 }
  346.                             }
  347.                             if(add){
  348.                                 /**System.out.println("ADD SELECT FIELD ["+field.getClass().getName()+"] ["+columnOrderBy+"]");*/
  349.                                 if(field instanceof UnixTimestampIntervalField){
  350.                                     UnixTimestampIntervalField unix = (UnixTimestampIntervalField) field;
  351.                                     String alias = null;
  352.                                     if(unix.existsAlias()==false){
  353.                                         /**System.out.println("NOT EXISTS");*/
  354.                                         unix.buildAlias();
  355.                                     }
  356.                                     alias = unix.getAlias();
  357.                                     /**System.out.println("ALIAS ["+alias+"]");*/
  358.                                     sqlQueryObject.addSelectAliasField(columnOrderBy, alias);
  359.                                 }
  360.                                 else{
  361.                                     sqlQueryObject.addSelectField(columnOrderBy);
  362.                                 }
  363.                             }
  364.                         }
  365.                     }
  366.                 }else{
  367.                     sqlQueryObject.addOrderBy("id");
  368.                 }
  369.                 if(SortOrder.ASC.equals(sortOrder)){
  370.                     sqlQueryObject.setSortType(true);
  371.                 }else{
  372.                     sqlQueryObject.setSortType(false);
  373.                 }
  374.             }
  375.            
  376.         }catch(Exception e){
  377.             throw new ExpressionException(e);
  378.         }
  379.     }
  380.    
  381.    
  382.    
  383.    
  384.     // SQL GROUP BY
  385.    
  386.     private String toSqlGroupBy()throws ExpressionException{
  387.        
  388.         return ExpressionSQL.sqlGroupBy(this.sqlFieldConverter, this.groupByFields);

  389.     }
  390.    
  391.     protected static String sqlGroupBy(ISQLFieldConverter fieldConverter,List<IField> groupByFields) throws ExpressionException{
  392.         try{
  393.            
  394.             StringBuilder bf = new StringBuilder();
  395.                    
  396.             if(!groupByFields.isEmpty()){
  397.                 bf.append(" GROUP BY ");
  398.                 int index = 0;
  399.                 for (Iterator<IField> iterator =groupByFields.iterator(); iterator.hasNext();) {
  400.                     IField field = iterator.next();
  401.                     if(index>0){
  402.                         bf.append(" , ");
  403.                     }
  404.                     bf.append(fieldConverter.toColumn(field,true));
  405.                     index++;
  406.                 }
  407.             }
  408.                
  409.             return bf.toString();
  410.            
  411.         }catch(Exception e){
  412.             throw new ExpressionException(e);
  413.         }
  414.     }
  415.    
  416.     private void toSqlGroupBy(ISQLQueryObject sqlQueryObject)throws ExpressionException{
  417.        
  418.         ExpressionSQL.sqlGroupBy(this.sqlFieldConverter, sqlQueryObject, this.groupByFields);
  419.        
  420.     }
  421.    
  422.     protected static void sqlGroupBy(ISQLFieldConverter fieldConverter, ISQLQueryObject sqlQueryObject,List<IField> groupByFields) throws ExpressionException{
  423.         try{
  424.            
  425.             if(!groupByFields.isEmpty()){
  426.                 for (Iterator<IField> iterator = groupByFields.iterator(); iterator.hasNext();) {
  427.                     IField field = iterator.next();
  428.                     sqlQueryObject.addGroupBy(fieldConverter.toColumn(field,true));
  429.                 }
  430.             }
  431.            
  432.         }catch(Exception e){
  433.             throw new ExpressionException(e);
  434.         }
  435.     }
  436.    
  437.     private void toSqlGroupBySelectField(ISQLQueryObject sqlQueryObject)throws ExpressionException{
  438.        
  439.         ExpressionSQL.sqlGroupBySelectField(this.sqlFieldConverter, sqlQueryObject, this.fieldsManuallyAdd,
  440.                 this.groupByFields, this.usedForCountExpression);
  441.        
  442.     }
  443.    
  444.     protected static void sqlGroupBySelectField(ISQLFieldConverter fieldConverter,  ISQLQueryObject sqlQueryObject,
  445.             List<Object> selectFieldsManuallyAdd, List<IField> groupByFields, boolean usedForCountExpression) throws ExpressionException{
  446.         if(!usedForCountExpression){
  447.             try{
  448.                 if(groupByFields!=null){
  449.                     for (IField iField : groupByFields) {
  450.                        
  451.                         /**System.out.println("CHECK ["+iField.getFieldName()+"] ["+iField.getFieldType().getName()+"] ...");*/
  452.                        
  453.                         // check tra altri select field add manually
  454.                         boolean found = false;
  455.                         for (Object checkSelectFieldManuallyAdd : selectFieldsManuallyAdd) {
  456.                             if(checkSelectFieldManuallyAdd instanceof IField &&
  457.                                 (iField.equals((checkSelectFieldManuallyAdd)))
  458.                                 ){
  459.                                 found=true;
  460.                                 break;
  461.                             }
  462.                         }
  463.                         /**System.out.println("CHECK ["+iField.getFieldName()+"] ["+iField.getFieldType().getName()+"] found in selectFieldsManuallyAdd: "+found);*/
  464.                         if(found)
  465.                             continue;
  466.                        
  467.                         // check in sql Query Object
  468.                         String column1 = fieldConverter.toColumn(iField, true);
  469.                         String column2 = fieldConverter.toColumn(iField, false);
  470.                         /**System.out.println("CHECK ["+iField.getFieldName()+"] ["+iField.getFieldType().getName()+"] COLUMN1["+column1+"] COLUMN2["+column2+"]");*/
  471.                         boolean insert = true;
  472.                         try{
  473.                             insert = !sqlQueryObject.getFieldsName().contains(column1) && !sqlQueryObject.getFieldsName().contains(column2);
  474.                         }catch(org.openspcoop2.utils.sql.SQLQueryObjectException sql){}
  475.                         /**System.out.println("CHECK ["+iField.getFieldName()+"] ["+iField.getFieldType().getName()+"] INSERT["+insert+"]");*/
  476.                         if(insert){
  477.                             ExpressionSQL.addFieldEngine(sqlQueryObject, fieldConverter, iField, null, true);
  478.                             selectFieldsManuallyAdd.add(iField);
  479.                         }
  480.                        
  481.                     }
  482.                 }
  483.             }catch(Exception e){
  484.                 throw new ExpressionException(e.getMessage(),e);
  485.             }
  486.         }
  487.     }
  488.    
  489.    
  490.    
  491.     // SQL FROM
  492.    
  493.     protected static void sqlFrom(ISQLQueryObject sqlQueryObject,List<IField> fields,ISQLFieldConverter sqlFieldConverter,String tableNamePrincipale,
  494.             List<Object> fieldsManuallyAdd, List<OrderedField> orderByFields, List<IField> groupByFields) throws ExpressionException{
  495.         sqlFrom(sqlQueryObject, fields, sqlFieldConverter, tableNamePrincipale, fieldsManuallyAdd, orderByFields, groupByFields, true);
  496.     }
  497.     protected static void sqlFrom(ISQLQueryObject sqlQueryObject,List<IField> fields,ISQLFieldConverter sqlFieldConverter,String tableNamePrincipale,
  498.             List<Object> fieldsManuallyAdd, List<OrderedField> orderByFields, List<IField> groupByFields,
  499.             boolean ignoreAlreadyExistsException) throws ExpressionException{
  500.         try{
  501.             List<String> tables = new ArrayList<>();
  502.            
  503.             if(fields!=null){
  504.                 for (IField iField : fields) {
  505.                     String tableName = getTableName(iField,sqlFieldConverter);
  506.                     if(!tables.contains(tableName)){
  507.                         tables.add(tableName);
  508.                     }
  509.                 }
  510.             }
  511.            
  512.             if(fieldsManuallyAdd!=null){
  513.                 for (Object iField : fieldsManuallyAdd) {
  514.                     IField field = null;
  515.                     if(iField instanceof IField){
  516.                         field = (IField) iField;
  517.                         String tableName = getTableName(field,sqlFieldConverter);
  518.                         if(!tables.contains(tableName)){
  519.                             tables.add(tableName);
  520.                         }
  521.                     }
  522.                     else if(iField instanceof FunctionField){
  523.                         List<IField> fieldsFF = ((FunctionField) iField).getFields();
  524.                         for (IField iFieldFF : fieldsFF) {
  525.                             String tableName = getTableName(iFieldFF,sqlFieldConverter);
  526.                             if(!tables.contains(tableName)){
  527.                                 tables.add(tableName);
  528.                             }
  529.                         }
  530.                     }
  531.                     else{
  532.                         throw new ExpressionException(FIELD_TYPE_UNKNOWN_PREFIX+iField.getClass().getName()+"]");
  533.                     }
  534.                 }
  535.             }
  536.            
  537.             if(orderByFields!=null){
  538.                 for (OrderedField orderedField : orderByFields) {
  539.                     IField iField = orderedField.getField();
  540.                     String tableName = getTableName(iField,sqlFieldConverter);
  541.                     if(!tables.contains(tableName)){
  542.                         tables.add(tableName);
  543.                     }
  544.                 }
  545.             }
  546.            
  547.             if(groupByFields!=null){
  548.                 for (IField iField : groupByFields) {
  549.                     String tableName = getTableName(iField,sqlFieldConverter);
  550.                     if(!tables.contains(tableName)){
  551.                         tables.add(tableName);
  552.                     }
  553.                 }
  554.             }
  555.            
  556.             if(tableNamePrincipale!=null && !tables.contains(tableNamePrincipale)){
  557.                 tables.add(tableNamePrincipale);
  558.             }
  559.            
  560.             for (String tableName : tables) {
  561.                 if(tableName==null || "".equals(tableName)){
  562.                     // la tabella "" puo' essere usato come workaround per le funzioni es. unixTimestamp in CustomField
  563.                     continue;
  564.                 }
  565.                 try{
  566.                     if(tableName.contains(PREFIX_ALIAS_FIELD)){
  567.                         String originalTableName = tableName.split(PREFIX_ALIAS_FIELD)[0];
  568.                         String aliasTable = tableName.split(PREFIX_ALIAS_FIELD)[1];
  569.                         sqlQueryObject.addFromTable(originalTableName, aliasTable);
  570.                     }
  571.                     else{
  572.                         sqlQueryObject.addFromTable(tableName);
  573.                     }
  574.                 }
  575.                 catch(SQLQueryObjectAlreadyExistsException alreadyExists){
  576.                     if(!ignoreAlreadyExistsException){
  577.                         throw new ExpressionException(alreadyExists.getMessage(),alreadyExists);
  578.                     }
  579.                     else{
  580. /**                     System.out.println("ALREADY EXISTS: "+alreadyExists.getMessage());
  581. //                      alreadyExists.printStackTrace(System.out);*/
  582.                     }
  583.                 }
  584.             }
  585.         }catch(Exception e){
  586.             throw new ExpressionException(e.getMessage(),e);
  587.         }
  588.     }
  589.     private static final String PREFIX_ALIAS_FIELD = "_______ALIASFIELD_______";
  590.     private static String getTableName(IField iField,ISQLFieldConverter sqlFieldConverter) throws ExpressionException{
  591.         String tableName = null;
  592.         if(iField instanceof AliasField){
  593.             AliasField af = (AliasField) iField;
  594.             if(af.getAlias().contains(".")){
  595.                 String originaleTableName = sqlFieldConverter.toTable(iField);
  596.                 tableName = originaleTableName+PREFIX_ALIAS_FIELD+ af.getAlias().split("\\.")[0];
  597.             }else{
  598.                 tableName = sqlFieldConverter.toTable(iField);
  599.             }
  600.         }
  601.         else if(iField instanceof IAliasTableField){
  602.             IAliasTableField atf = (IAliasTableField) iField;
  603.             String originaleTableName = sqlFieldConverter.toTable(iField,false);
  604.             tableName = originaleTableName+PREFIX_ALIAS_FIELD+ atf.getAliasTable();
  605.         }
  606.         else{
  607.             tableName = sqlFieldConverter.toTable(iField);
  608.         }
  609.         /**System.out.println("ADD ["+tableName+"]");*/
  610.         return tableName;
  611.     }
  612.    
  613.     protected static void addFieldEngine(ISQLQueryObject sqlQueryObject, ISQLFieldConverter sqlFieldConverter, Object field, String aliasField, boolean appendTablePrefix)throws ExpressionException{
  614.         addFieldEngine(sqlQueryObject, sqlFieldConverter, field, aliasField, appendTablePrefix, true);
  615.     }
  616.     private static void addFieldEngine(ISQLQueryObject sqlQueryObject, ISQLFieldConverter sqlFieldConverter, Object field, String aliasField, boolean appendTablePrefix,
  617.             boolean ignoreAlreadyExistsException)throws ExpressionException{
  618.         try{        
  619.                    
  620.             if(field == null){
  621.                 throw new ExpressionException("Field is null");
  622.             }
  623.             /**System.out.println("ADD CLASS ["+field.getClass().getName()+"]...");*/
  624.             if(field instanceof FunctionField){
  625.                
  626.                 FunctionField ff = (FunctionField) field;
  627.                
  628.                 boolean customFunction = ff.isCustomFunction();
  629.                 String prefixCustomFunction = ff.getPrefixFunctionCustom();
  630.                 String suffixCustomFunction = ff.getSuffixFunctionCustom();
  631.                 Function function = ff.getFunction();
  632.                
  633.                 String functionValue = ff.getFunctionValue();
  634.                 String operator = ff.getOperator();
  635.                 List<IField> fields = ff.getFields();
  636.                 String column = null;
  637.                
  638.                 boolean timestamp = false;
  639.                 String ffFieldTypeName = ff.getFieldType().getName() + "";
  640.                 if(ffFieldTypeName.equals(Timestamp.class.getName()) ||
  641.                         ffFieldTypeName.equals(java.util.Date.class.getName()) ||
  642.                         ffFieldTypeName.equals(java.sql.Date.class.getName()) ||
  643.                         ffFieldTypeName.equals(java.util.Calendar.class.getName())){
  644.                     timestamp = true;
  645.                 }
  646.                
  647.                 String alias = ff.getAlias();
  648.                
  649.                 // calcolo colonna
  650.                 if(functionValue!=null){
  651.                     column = functionValue;
  652.                 }
  653.                 else{
  654.                     if(operator!=null){
  655.                         if(fields.size()>1 && timestamp){
  656.                             throw new ExpressionException("Multiple fields with operator and \"time\" type ("+ff.getFieldType().getName()+
  657.                                     ") not supported. For Timestamp Interval use FunctionField(new UnixTimestampIntervalField(...), Function.TIPE, columnName)");
  658.                         }
  659.                         StringBuilder bf = new StringBuilder();
  660.                         for (int i = 0; i < fields.size(); i++) {
  661.                             if(i>0){
  662.                                 bf.append(" ").append(operator).append(" ");
  663.                             }
  664.                             bf.append(sqlFieldConverter.toColumn(fields.get(i), appendTablePrefix));
  665.                         }
  666.                         column = bf.toString();
  667.                     }
  668.                     else{
  669.                         column = sqlFieldConverter.toColumn(fields.get(0), appendTablePrefix);
  670.                     }
  671.                 }
  672.                                                
  673.                 if(customFunction){
  674.                     sqlQueryObject.addSelectAliasField(prefixCustomFunction+" "+column+" "+suffixCustomFunction, alias);
  675.                 }else{
  676.                     setFunction(function, timestamp, column, alias, sqlQueryObject);
  677.                 }
  678.             }
  679.             else if(field instanceof ConstantField){
  680.                
  681.                 // Nelle costanti deve sempre essere usato l'alias.
  682.                 // Altrimenti nelle select annidate verrebbero dichiarate piu' volte le solite costanti.
  683.                 // Inoltre SQLServer pretende costanti con alias
  684.                 sqlQueryObject.addSelectAliasField(sqlFieldConverter.toColumn((ConstantField)field, appendTablePrefix), ((ConstantField)field).getAlias());
  685.                
  686.             }
  687.             else if(field instanceof CustomField){
  688.                
  689.                 if(aliasField!=null){
  690.                     sqlQueryObject.addSelectAliasField(sqlFieldConverter.toColumn((Field)field, appendTablePrefix), aliasField);
  691.                 }
  692.                 else{
  693.                     sqlQueryObject.addSelectField(sqlFieldConverter.toColumn((Field)field, appendTablePrefix));
  694.                 }
  695.             }
  696.             else if(field instanceof AliasField){
  697.                
  698.                 AliasField af = (AliasField) field;
  699.                 IField afField = af.getField();
  700.                 sqlQueryObject.addSelectAliasField( sqlFieldConverter.toColumn(afField, appendTablePrefix) , af.getAlias() );
  701.                 /**System.out.println("ADD ALIAS ["+sqlFieldConverter.toColumn(afField, appendTablePrefix)+"]["+af.getAlias()+"]...");*/
  702.                
  703.             }
  704.             else if(field instanceof Field){
  705.                
  706.                 if(aliasField!=null){
  707.                     sqlQueryObject.addSelectAliasField(sqlFieldConverter.toColumn((Field)field, appendTablePrefix), aliasField);
  708.                 }
  709.                 else{
  710.                     sqlQueryObject.addSelectField(sqlFieldConverter.toColumn((Field)field, appendTablePrefix));
  711.                 }
  712.             }
  713.             else if(field instanceof ComplexField){
  714.                 if(aliasField!=null){
  715.                     sqlQueryObject.addSelectAliasField(sqlFieldConverter.toColumn((ComplexField)field, appendTablePrefix), aliasField);
  716.                     /**System.out.println("ADD ALIAS ["+sqlFieldConverter.toColumn((ComplexField)field, appendTablePrefix)+"]["+aliasField+"]...");*/
  717.                 }else{
  718.                     sqlQueryObject.addSelectField(sqlFieldConverter.toColumn((ComplexField)field, appendTablePrefix));
  719.                     /**System.out.println("ADD ["+sqlFieldConverter.toColumn((ComplexField)field, appendTablePrefix)+"]...");*/
  720.                 }
  721.             }
  722.             else{
  723.                 throw new ExpressionException("Field unknown type: "+field.getClass().getName());
  724.             }
  725.        
  726.         }
  727.         catch(SQLQueryObjectAlreadyExistsException e){
  728.             if(!ignoreAlreadyExistsException){
  729.                 throw new ExpressionException(e.getMessage(),e);
  730.             }
  731.             else{
  732. /**             System.out.println("ALREADY EXISTS: "+e.getMessage());
  733. //              e.printStackTrace(System.out);*/
  734.             }
  735.         }
  736.         catch(Exception e){
  737.             throw new ExpressionException(e.getMessage(),e);
  738.         }
  739.     }
  740.    
  741.     protected static void addAliasFieldEngine(ISQLQueryObject sqlQueryObject, ISQLFieldConverter sqlFieldConverter, Object field, String aliasField, boolean appendTablePrefix)throws ExpressionException{
  742.         addAliasFieldEngine(sqlQueryObject, sqlFieldConverter, field, aliasField, appendTablePrefix, true);
  743.     }
  744.     private static void addAliasFieldEngine(ISQLQueryObject sqlQueryObject, ISQLFieldConverter sqlFieldConverter, Object field, String aliasField, boolean appendTablePrefix,
  745.             boolean ignoreAlreadyExistsException)throws ExpressionException{
  746.         try{        
  747.                    
  748.             if(aliasField==null && appendTablePrefix) {
  749.                 // nop
  750.             }
  751.            
  752.             if(field == null){
  753.                 throw new ExpressionException("Field is null");
  754.             }
  755.            
  756.             if(field instanceof FunctionField){
  757.                
  758.                 FunctionField ff = (FunctionField) field;
  759.                 String alias = ff.getAlias();
  760.                 sqlQueryObject.addSelectField(alias);
  761.                
  762.             }
  763.             else if(field instanceof ConstantField){
  764.                
  765.                 sqlQueryObject.addSelectField(((ConstantField)field).getAlias());
  766.                
  767.             }
  768.             else if(field instanceof CustomField){
  769.                
  770.                 sqlQueryObject.addSelectField(((CustomField)field).getAliasColumnName());
  771.                
  772.             }
  773.             else if(field instanceof AliasField){
  774.                
  775.                 AliasField af = (AliasField) field;
  776.                 sqlQueryObject.addSelectField(af.getAlias());
  777.                
  778.             }
  779.             else if(field instanceof Field){
  780.                
  781.                 sqlQueryObject.addSelectField(sqlFieldConverter.toAliasColumn(((Field)field), false));
  782.                
  783.             }
  784.             else if(field instanceof ComplexField){
  785.                
  786.                 sqlQueryObject.addSelectField(sqlFieldConverter.toAliasColumn(((ComplexField)field), false));
  787.                
  788.             }
  789.             else{
  790.                 throw new ExpressionException("Field unknown type: "+field.getClass().getName());
  791.             }
  792.        
  793.         }
  794.         catch(SQLQueryObjectAlreadyExistsException e){
  795.             if(!ignoreAlreadyExistsException){
  796.                 throw new ExpressionException(e.getMessage(),e);
  797.             }
  798.             else{
  799. /**             System.out.println("ALREADY EXISTS: "+e.getMessage());
  800. //              e.printStackTrace(System.out);*/
  801.             }
  802.         }
  803.         catch(Exception e){
  804.             throw new ExpressionException(e.getMessage(),e);
  805.         }
  806.     }
  807.    
  808.     public static void setFunction(Function function,boolean timestamp,String column,String alias,ISQLQueryObject sqlQueryObject) throws SQLQueryObjectException{
  809.         switch (function) {
  810.         case AVG:
  811.         case AVG_DOUBLE:
  812.             if(timestamp){
  813.                 sqlQueryObject.addSelectAvgTimestampField(column, alias);
  814.             }
  815.             else{
  816.                 sqlQueryObject.addSelectAvgField(column, alias);
  817.             }
  818.             break;
  819.         case MAX:
  820.             if(timestamp){
  821.                 sqlQueryObject.addSelectMaxTimestampField(column, alias);
  822.             }
  823.             else{
  824.                 sqlQueryObject.addSelectMaxField(column, alias);
  825.             }
  826.             break;
  827.         case MIN:
  828.             if(timestamp){
  829.                 sqlQueryObject.addSelectMinTimestampField(column, alias);
  830.             }
  831.             else{
  832.                 sqlQueryObject.addSelectMinField(column, alias);
  833.             }
  834.             break;
  835.         case SUM:
  836.             if(timestamp){
  837.                 sqlQueryObject.addSelectSumTimestampField(column, alias);
  838.             }
  839.             else{
  840.                 sqlQueryObject.addSelectSumField(column, alias);
  841.             }
  842.             break;
  843.         case COUNT:
  844.             sqlQueryObject.addSelectCountField(column, alias, false);
  845.             break;
  846.         case COUNT_DISTINCT:
  847.             sqlQueryObject.addSelectCountField(column, alias, true);
  848.             break;
  849.         }
  850.     }
  851.    
  852.     protected static boolean inUse(IField fieldParam,boolean checkOnlyWhereCondition,
  853.             boolean useFieldExpressionBase,List<Object> fieldsManuallyAdd,boolean checkFieldManuallyAdd) throws ExpressionException {
  854.        
  855.         if(!checkFieldManuallyAdd){
  856.             return useFieldExpressionBase;
  857.         }
  858.         if(checkOnlyWhereCondition){
  859.             return useFieldExpressionBase;
  860.         }
  861.        
  862.         for (Object iField : fieldsManuallyAdd) {
  863.             IField field = null;
  864.             if(iField instanceof IField){
  865.                 field = (IField) iField;
  866.                 boolean inUse = fieldParam.equals(field);
  867.                 if(inUse){
  868.                     return true;
  869.                 }
  870.             }
  871.             else if(iField instanceof FunctionField){
  872.                 List<IField> fieldsFF = ((FunctionField) iField).getFields();
  873.                 for (IField iFieldFF : fieldsFF) {
  874.                     boolean inUse = fieldParam.equals(iFieldFF);
  875.                     if(inUse){
  876.                         return true;
  877.                     }
  878.                 }
  879.             }
  880.             else{
  881.                 throw new ExpressionException(FIELD_TYPE_UNKNOWN_PREFIX+iField.getClass().getName()+"]");
  882.             }
  883.         }
  884.        
  885.         return useFieldExpressionBase;
  886.        
  887.     }
  888.    
  889.     protected static boolean inUse(IModel<?> model,boolean checkOnlyWhereCondition,
  890.             boolean useModelExpressionBase,List<Object> fieldsManuallyAdd,boolean checkFieldManuallyAdd) throws ExpressionException {
  891.        
  892.         if(!checkFieldManuallyAdd){
  893.             return useModelExpressionBase;
  894.         }
  895.         if(checkOnlyWhereCondition){
  896.             return useModelExpressionBase;
  897.         }
  898.        
  899.         for (Object iField : fieldsManuallyAdd) {
  900.             IField field = null;
  901.             if(iField instanceof IField){
  902.                 field = (IField) iField;
  903.                 if(inUseEngine(model, field)){
  904.                     return true;
  905.                 }
  906.             }
  907.             else if(iField instanceof FunctionField){
  908.                 List<IField> fieldsFF = ((FunctionField) iField).getFields();
  909.                 for (IField iFieldFF : fieldsFF) {
  910.                     if(inUseEngine(model, iFieldFF)){
  911.                         return true;
  912.                     }
  913.                 }
  914.             }
  915.             else{
  916.                 throw new ExpressionException(FIELD_TYPE_UNKNOWN_PREFIX+iField.getClass().getName()+"]");
  917.             }
  918.        
  919.            
  920.         }
  921.        
  922.         return useModelExpressionBase;
  923.        
  924.     }
  925.     private static boolean inUseEngine(IModel<?> model,IField field){
  926.         boolean inUse = false;
  927.         if(model.getBaseField()!=null){
  928.             // Modello di un elemento non radice
  929.             if(field instanceof ComplexField){
  930.                 ComplexField c = (ComplexField) field;
  931.                 inUse = c.getFather().equals(model.getBaseField());
  932.             }else{
  933.                 String modeClassName = model.getModeledClass().getName() + "";
  934.                 inUse = modeClassName.equals(field.getClassType().getName());
  935.             }
  936.         }
  937.         else{
  938.             String modeClassName = model.getModeledClass().getName() + "";
  939.             inUse = modeClassName.equals(field.getClassType().getName());
  940.         }
  941.         return inUse;
  942.     }
  943.    
  944.     protected static List<IField> getFields(boolean onlyWhereCondition,
  945.             List<IField> getFieldExpressionBase,List<Object> fieldsManuallyAdd,boolean checkFieldManuallyAdd) throws ExpressionException {
  946.         if(!checkFieldManuallyAdd){
  947.             return getFieldExpressionBase;
  948.         }
  949.         if(onlyWhereCondition){
  950.             return getFieldExpressionBase;
  951.         }
  952.         List<IField> newFields = new ArrayList<>();
  953.         if(getFieldExpressionBase!=null){
  954.             newFields.addAll(getFieldExpressionBase);
  955.         }
  956.         for (Object iField : fieldsManuallyAdd) {
  957.             IField field = null;
  958.             if(iField instanceof IField){
  959.                 field = (IField) iField;
  960.                 if(getFieldExpressionBase==null || (!getFieldExpressionBase.contains(field))){
  961.                     newFields.add(field);
  962.                 }
  963.             }
  964.             else if(iField instanceof FunctionField){
  965.                 List<IField> fieldsFF = ((FunctionField) iField).getFields();
  966.                 for (IField iFieldFF : fieldsFF) {
  967.                     if(getFieldExpressionBase==null || (!getFieldExpressionBase.contains(iFieldFF))){
  968.                         newFields.add(iFieldFF);
  969.                     }
  970.                 }
  971.             }
  972.             else{
  973.                 throw new ExpressionException(FIELD_TYPE_UNKNOWN_PREFIX+iField.getClass().getName()+"]");
  974.             }
  975.        
  976.         }  
  977.         return newFields;
  978.     }
  979.    
  980.    
  981.    
  982.    
  983.     /* ************ TO SQL *********** */
  984.    
  985.     public String toSql() throws ExpressionException{
  986.         if(this.expressionEngine==null &&
  987.             this.throwExpressionNotInitialized){
  988.             throw new ExpressionException(EXPRESSION_NOT_INITIALIZED);
  989.         }
  990.        
  991.         StringBuilder bf = null;
  992.         if(this.expressionEngine==null){
  993.             bf = new StringBuilder("");
  994.         }
  995.         else if(this.expressionEngine instanceof ISQLExpression){
  996.             bf = new StringBuilder(((ISQLExpression)this.expressionEngine).toSql());
  997.         }else{
  998.             throw new ExpressionException(EXPRESSION_TYPE_PREFIX+this.expressionEngine.getClass().getName()+IS_NOT_AS_CAST_WITH+ISQLExpression.class.getName());
  999.         }
  1000.        
  1001.         bf.append(toSqlGroupBy());
  1002.         bf.append(toSqlOrder());
  1003.         bf.append(toSqlForceIndex()); // Lo metto in fondo tanto sono commenti
  1004.        
  1005.         return bf.toString();
  1006.     }
  1007.     protected String toSqlPreparedStatement(List<Object> oggetti) throws ExpressionException {
  1008.         if(this.expressionEngine==null &&
  1009.             this.throwExpressionNotInitialized){
  1010.             throw new ExpressionException(EXPRESSION_NOT_INITIALIZED);
  1011.         }
  1012.        
  1013.         StringBuilder bf = null;
  1014.         if(this.expressionEngine==null){
  1015.             bf = new StringBuilder("");
  1016.         }
  1017.         else if(this.expressionEngine instanceof ISQLExpression){
  1018.             bf = new StringBuilder(((ISQLExpression)this.expressionEngine).toSqlPreparedStatement(oggetti));
  1019.         }else{
  1020.             throw new ExpressionException(EXPRESSION_TYPE_PREFIX+this.expressionEngine.getClass().getName()+IS_NOT_AS_CAST_WITH+ISQLExpression.class.getName());
  1021.         }
  1022.        
  1023.         bf.append(toSqlGroupBy());
  1024.         bf.append(toSqlOrder());
  1025.         bf.append(toSqlForceIndex()); // Lo metto in fondo tanto sono commenti
  1026.        
  1027.         return bf.toString();
  1028.     }

  1029.     protected String toSqlJPA(Map<String, Object> oggetti) throws ExpressionException {
  1030.         if(this.expressionEngine==null &&
  1031.             this.throwExpressionNotInitialized){
  1032.             throw new ExpressionException(EXPRESSION_NOT_INITIALIZED);
  1033.         }
  1034.        
  1035.         StringBuilder bf = null;
  1036.         if(this.expressionEngine==null){
  1037.             bf = new StringBuilder("");
  1038.         }else if(this.expressionEngine instanceof ISQLExpression){
  1039.             bf = new StringBuilder(((ISQLExpression)this.expressionEngine).toSqlJPA(oggetti));
  1040.         }else{
  1041.             throw new ExpressionException(EXPRESSION_TYPE_PREFIX+this.expressionEngine.getClass().getName()+IS_NOT_AS_CAST_WITH+ISQLExpression.class.getName());
  1042.         }
  1043.        
  1044.         bf.append(toSqlGroupBy());
  1045.         bf.append(toSqlOrder());
  1046.         bf.append(toSqlForceIndex()); // Lo metto in fondo tanto sono commenti
  1047.        
  1048.         return bf.toString();
  1049.     }
  1050.    
  1051.     public void toSql(ISQLQueryObject sqlQueryObject)throws ExpressionException{
  1052.         if(this.expressionEngine==null &&
  1053.             this.throwExpressionNotInitialized){
  1054.             throw new ExpressionException(EXPRESSION_NOT_INITIALIZED);
  1055.         }
  1056.         if(this.expressionEngine==null){            
  1057.             // nop
  1058.         }
  1059.         else if(this.expressionEngine instanceof ISQLExpression){
  1060.             ((ISQLExpression)this.expressionEngine).toSql(sqlQueryObject);
  1061.         }else{
  1062.             throw new ExpressionException(EXPRESSION_TYPE_PREFIX+this.expressionEngine.getClass().getName()+IS_NOT_AS_CAST_WITH+ISQLExpression.class.getName());
  1063.         }
  1064.        
  1065.         // GroupBy
  1066.         toSqlGroupBy(sqlQueryObject);
  1067.        
  1068.         // OrderBy
  1069.         toSqlOrder(sqlQueryObject);
  1070.        
  1071.         // Aggiungo select field relativi all'aggregazione
  1072.         toSqlGroupBySelectField(sqlQueryObject);
  1073.        
  1074.         // ForceIndex
  1075.         toSqlForceIndex(sqlQueryObject);
  1076.     }
  1077.    
  1078.     public void toSqlWithFromCondition(ISQLQueryObject sqlQueryObject,String tableNamePrincipale) throws ExpressionException, ExpressionNotImplementedException{
  1079.        
  1080.         // preparo condizione di where
  1081.         this.toSql(sqlQueryObject);
  1082.        
  1083.         // aggiungo condizione di from
  1084.         sqlFrom(sqlQueryObject, this.getFields(false), this.getSqlFieldConverter(), tableNamePrincipale, this.getFieldsManuallyAdd(),
  1085.                 this.getOrderedFields(),this.getGroupByFields());
  1086.     }
  1087.    
  1088.     protected void toSqlPreparedStatement(ISQLQueryObject sqlQueryObject,List<Object> oggetti)throws ExpressionException{
  1089.         if(this.expressionEngine==null &&
  1090.             this.throwExpressionNotInitialized){
  1091.             throw new ExpressionException(EXPRESSION_NOT_INITIALIZED);
  1092.         }
  1093.         if(this.expressionEngine==null){        
  1094.             // nop
  1095.         }
  1096.         else if(this.expressionEngine instanceof ISQLExpression){
  1097.             ((ISQLExpression)this.expressionEngine).toSqlPreparedStatement(sqlQueryObject,oggetti);
  1098.         }else{
  1099.             throw new ExpressionException(EXPRESSION_TYPE_PREFIX+this.expressionEngine.getClass().getName()+IS_NOT_AS_CAST_WITH+ISQLExpression.class.getName());
  1100.         }
  1101.        
  1102.         // GroupBy
  1103.         toSqlGroupBy(sqlQueryObject);
  1104.        
  1105.         // OrderBy
  1106.         toSqlOrder(sqlQueryObject);
  1107.        
  1108.         // Aggiungo select field relativi all'aggregazione
  1109.         toSqlGroupBySelectField(sqlQueryObject);
  1110.        
  1111.         // ForceIndex
  1112.         toSqlForceIndex(sqlQueryObject);
  1113.     }
  1114.    
  1115.     protected void toSqlPreparedStatementWithFromCondition(ISQLQueryObject sqlQueryObject,List<Object> oggetti,String tableNamePrincipale) throws ExpressionException, ExpressionNotImplementedException{
  1116.        
  1117.         // preparo condizione di where
  1118.         this.toSqlPreparedStatement(sqlQueryObject, oggetti);
  1119.        
  1120.         // aggiungo condizione di from
  1121.         sqlFrom(sqlQueryObject, this.getFields(false), this.getSqlFieldConverter(), tableNamePrincipale, this.getFieldsManuallyAdd(),
  1122.                 this.getOrderedFields(),this.getGroupByFields());
  1123.     }
  1124.    
  1125.     protected void toSqlJPA(ISQLQueryObject sqlQueryObject,Map<String, Object> oggetti)throws ExpressionException{
  1126.         if(this.expressionEngine==null &&
  1127.             this.throwExpressionNotInitialized){
  1128.             throw new ExpressionException(EXPRESSION_NOT_INITIALIZED);
  1129.         }
  1130.        
  1131.         if(this.expressionEngine==null){    
  1132.             // nop
  1133.         }
  1134.         else if(this.expressionEngine instanceof ISQLExpression){
  1135.             ((ISQLExpression)this.expressionEngine).toSqlJPA(sqlQueryObject,oggetti);
  1136.         }else{
  1137.             throw new ExpressionException(EXPRESSION_TYPE_PREFIX+this.expressionEngine.getClass().getName()+IS_NOT_AS_CAST_WITH+ISQLExpression.class.getName());
  1138.         }
  1139.        
  1140.         // GroupBy
  1141.         toSqlGroupBy(sqlQueryObject);
  1142.        
  1143.         // OrderBy
  1144.         toSqlOrder(sqlQueryObject);
  1145.                
  1146.         // Aggiungo select field relativi all'aggregazione
  1147.         toSqlGroupBySelectField(sqlQueryObject);
  1148.        
  1149.         // ForceIndex
  1150.         toSqlForceIndex(sqlQueryObject);
  1151.     }
  1152.    
  1153.     protected void toSqlJPAWithFromCondition(ISQLQueryObject sqlQueryObject,Map<String, Object> oggetti,String tableNamePrincipale) throws ExpressionException, ExpressionNotImplementedException{
  1154.        
  1155.         // preparo condizione di where
  1156.         this.toSqlJPA(sqlQueryObject, oggetti);
  1157.        
  1158.         // aggiungo condizione di from
  1159.         sqlFrom(sqlQueryObject, this.getFields(false), this.getSqlFieldConverter(), tableNamePrincipale, this.getFieldsManuallyAdd(),
  1160.                 this.getOrderedFields(),this.getGroupByFields());
  1161.     }
  1162.    
  1163.     public void addField(ISQLQueryObject sqlQueryObject, IField field, boolean appendTablePrefix)throws ExpressionException{
  1164.         ExpressionSQL.addFieldEngine(sqlQueryObject,this.getSqlFieldConverter(),field, null, appendTablePrefix);
  1165.         this.getFieldsManuallyAdd().add(field);
  1166.     }
  1167.     public void addField(ISQLQueryObject sqlQueryObject, IField field, String aliasField, boolean appendTablePrefix)throws ExpressionException{
  1168.         ExpressionSQL.addFieldEngine(sqlQueryObject,this.getSqlFieldConverter(),field, aliasField, appendTablePrefix);
  1169.         this.getFieldsManuallyAdd().add(field);
  1170.     }
  1171.     public void addAliasField(ISQLQueryObject sqlQueryObject, IField field, boolean appendTablePrefix)throws ExpressionException{
  1172.         ExpressionSQL.addAliasFieldEngine(sqlQueryObject,this.getSqlFieldConverter(),field, null, appendTablePrefix);
  1173.         this.getFieldsManuallyAdd().add(field);
  1174.     }
  1175.     public void addField(ISQLQueryObject sqlQueryObject, FunctionField field, boolean appendTablePrefix)throws ExpressionException{
  1176.         ExpressionSQL.addFieldEngine(sqlQueryObject,this.getSqlFieldConverter(),field, null, appendTablePrefix);
  1177.         this.getFieldsManuallyAdd().add(field);
  1178.     }
  1179.    
  1180.    
  1181.     /* ************ OBJECTS ************ */
  1182.     @Override
  1183.     protected ComparatorExpressionImpl getComparatorExpression(IField field, Object value, Comparator c) {
  1184.         return new ComparatorExpressionSQL(this.sqlFieldConverter,this.objectFormatter,field,value,c);
  1185.     }
  1186.     @Override
  1187.     protected BetweenExpressionImpl getBetweenExpression(IField field, Object lower, Object high) {
  1188.         return new BetweenExpressionSQL(this.sqlFieldConverter,this.objectFormatter,field,lower,high);
  1189.     }
  1190.     @Override
  1191.     protected InExpressionImpl getInExpression(IField field, Object... values) {
  1192.         List<Object> lista = new ArrayList<>();
  1193.         if(values!=null && values.length>0){
  1194.             lista.addAll(Arrays.asList(values));
  1195.         }
  1196.         return new InExpressionSQL(this.sqlFieldConverter,this.objectFormatter,field, lista);
  1197.     }
  1198.     @Override
  1199.     protected LikeExpressionImpl getLikeExpression(IField field, String value, LikeMode mode, boolean caseInsensitive) {
  1200.         return new LikeExpressionSQL(this.sqlFieldConverter,this.objectFormatter,field, value, mode, caseInsensitive);
  1201.     }
  1202.     @Override
  1203.     protected DateTimePartExpressionImpl getDateTimePartExpression(IField field, String value, DateTimePartEnum dateTimePartEnum) {
  1204.         return new DateTimePartExpressionSQL(this.sqlFieldConverter,this.objectFormatter,field, value, dateTimePartEnum);
  1205.     }
  1206.     @Override
  1207.     protected DayFormatExpressionImpl getDayFormatExpression(IField field, String value, DayFormatEnum dayFormatEnum) {
  1208.         return new DayFormatExpressionSQL(this.sqlFieldConverter,this.objectFormatter,field, value, dayFormatEnum);
  1209.     }
  1210.     @Override
  1211.     protected ConjunctionExpressionImpl getConjunctionExpression() {
  1212.         return new ConjunctionExpressionSQL(this.sqlFieldConverter,this.objectFormatter);
  1213.     }
  1214.    
  1215. }