Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.fmap.dal / org.gvsig.fmap.dal.db / org.gvsig.fmap.dal.db.jdbc / src / main / java / org / gvsig / fmap / dal / store / jdbc2 / spi / operations / CountOperation.java @ 45162

History | View | Annotate | Download (9.73 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2020 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
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, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.fmap.dal.store.jdbc2.spi.operations;
25

    
26
import java.sql.Connection;
27
import java.sql.ResultSet;
28
import java.sql.SQLException;
29
import java.sql.Statement;
30
import java.util.List;
31
import org.apache.commons.lang3.StringUtils;
32
import org.gvsig.expressionevaluator.Code;
33
import org.gvsig.expressionevaluator.Expression;
34
import org.gvsig.expressionevaluator.ExpressionBuilder;
35
import static org.gvsig.expressionevaluator.ExpressionBuilder.FUNCTION_LET;
36
import org.gvsig.expressionevaluator.ExpressionUtils;
37
import org.gvsig.fmap.dal.SQLBuilder.SelectBuilder;
38
import org.gvsig.fmap.dal.exception.DataException;
39
import org.gvsig.fmap.dal.expressionevaluator.FeatureAttributeEmulatorExpression;
40
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
41
import org.gvsig.fmap.dal.feature.FeatureQuery;
42
import org.gvsig.fmap.dal.feature.FeatureQueryOrder;
43
import org.gvsig.fmap.dal.feature.FeatureType;
44
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
45
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
46
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
47
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
48
import org.gvsig.fmap.dal.store.jdbc2.OperationsFactory.TableReference;
49
import static org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase.PROP_TABLE;
50
import org.gvsig.tools.evaluator.Evaluator;
51

    
52
public class CountOperation extends AbstractConnectionOperation {
53

    
54
    private final TableReference table;
55
    private final String baseFilter;
56
    private final FeatureQuery query;
57
    private final FeatureType featureType;
58

    
59
    public CountOperation(
60
            JDBCHelper helper
61
        ) {
62
        this(helper, null, null, null, null);
63
    }
64

    
65
    public CountOperation(
66
            JDBCHelper helper,
67
            FeatureType featureType,
68
            TableReference table,
69
            String baseFilter,
70
            FeatureQuery query
71
        ) {
72
        super(helper);
73
        this.featureType = featureType;
74
        this.table = table;
75
        this.baseFilter = baseFilter;
76
        this.query = query;
77
    }
78

    
79
    @Override
80
    public final Object perform(Connection conn) throws DataException {
81
        return this.count(conn);
82
    }
83

    
84
    public String getSQL() {
85
        JDBCSQLBuilderBase sqlbuilder = this.createSQLBuilder();
86
        ExpressionBuilder expbuilder = sqlbuilder.expression();
87

    
88
        SelectBuilder select = sqlbuilder.select();
89

    
90
        if (this.query != null && this.query.hasGroupByColumns()) {
91
            JDBCSQLBuilderBase subsqlbuilder = this.createSQLBuilder();
92
            SelectBuilder subselect = subsqlbuilder.select();
93
            subselect.column().value(subsqlbuilder.count().all());
94
            subselect.from().table()
95
                    .database(this.table.getDatabase())
96
                    .schema(this.table.getSchema())
97
                    .name(this.table.getTable());
98
            subselect.from().subquery(this.table.getSubquery());
99
            Evaluator filter = query == null ? null : query.getFilter();
100
            if (filter != null) {
101
                String sqlfilter = filter.getSQL();
102
                if (!StringUtils.isEmpty(sqlfilter)) {
103
                    if (this.helper.supportFilter(this.featureType, filter)) {
104
                        subselect.where().set(expbuilder.toValue(sqlfilter));
105
                    }
106
                }
107
            }
108
            if (!StringUtils.isEmpty(baseFilter)) {
109
                subselect.where().and(expbuilder.toValue(baseFilter));
110
            }
111

    
112
            FeatureQueryOrder order = query == null ? null : query.getOrder();
113
            if (order != null) {
114
                for (FeatureQueryOrder.FeatureQueryOrderMember member : order.members()) {
115
                    if (member.hasEvaluator()) {
116
                        String sqlorder = member.getEvaluator().getSQL();
117
                        if (!StringUtils.isEmpty(sqlorder)) {
118
                            subselect.order_by().custom(sqlorder);
119
                        }
120
                    } else {
121
                        subselect.order_by()
122
                                .column(member.getAttributeName())
123
                                .ascending(member.getAscending());
124
                    }
125
                }
126
            }
127

    
128
            List<String> groupbyColumns = query == null ? null : query.getGroupByColumns();
129
            if (groupbyColumns != null && !groupbyColumns.isEmpty()) {
130
                for (String columnName : groupbyColumns) {
131
                    if (this.featureType.getAttributeDescriptor(columnName) != null) {
132
                        subselect.group_by(expbuilder.column(columnName));
133
                    } else if(this.featureType.getExtraColumns().get(columnName)!=null) {
134
                        EditableFeatureAttributeDescriptor attr = this.featureType.getExtraColumns().get(columnName);
135
                        subselect.group_by(expbuilder.column(columnName));
136
                        Expression exp = ((FeatureAttributeEmulatorExpression) attr.getFeatureAttributeEmulator()).getExpression();
137
                        subselect.column().value(exp.getCode().toValue()).as(columnName);
138
                    } else {
139
                        try {
140
                            try {
141
                                Code groupByColumnCode = ExpressionUtils.compile(columnName);
142
                                if (groupByColumnCode.code() == Code.CALLABLE) {
143
                                    Code.Callable callable = (Code.Callable) groupByColumnCode;
144
                                    if (callable.name().equalsIgnoreCase(FUNCTION_LET)) {
145
                                        Code exp = callable.parameters().get(1);
146
                                        Code name = callable.parameters().get(0);
147
                                        subselect.column().value(exp.toValue())
148
                                                .as((String) ((Code.Constant) name).value());
149
                                        // nombre que se pone en la parte del groupby debe de ser el nombre de la var del set
150
                                        groupByColumnCode = exp; 
151
                                    }
152
                                }
153
                                subselect.group_by(groupByColumnCode.toValue());
154
                            } catch (Exception ex) {
155
                                throw new RuntimeException("Not able to create column by expression in groupby query", ex);
156
                            }
157
                        } catch (Exception ex) {
158
                            throw new RuntimeException("Not able to create column by expression in groupby query", ex);
159
                        }
160
                    }
161
                }
162
            }
163
            this.helper.processSpecialFunctions(subsqlbuilder, featureType, null);
164
            subsqlbuilder.setProperties(
165
                    ExpressionBuilder.Variable.class,
166
                    PROP_TABLE, table
167
            );
168
            String subsql = subselect.toString();
169
            select.from().table()
170
                    .database(this.table.getDatabase())
171
                    .schema(this.table.getSchema())
172
                    .name(this.table.getTable());
173
            select.from().subquery(subsql);
174

    
175
        } else {
176
            select.column().value(sqlbuilder.count().all());
177
            select.from().table()
178
                    .database(this.table.getDatabase())
179
                    .schema(this.table.getSchema())
180
                    .name(this.table.getTable());
181
            select.from().subquery(this.table.getSubquery());
182
            if (!StringUtils.isEmpty(baseFilter)) {
183
                sqlbuilder.select().where().set(expbuilder.custom(baseFilter));
184
            }
185
            if (this.query != null) {
186
                if (this.query.getFilter() != null && !StringUtils.isBlank(this.query.getFilter().getSQL())) {
187
                    // El and() hace un set() si no hay un filtro previo
188
                    select.where().and(expbuilder.toValue(this.query.getFilter().getSQL()));
189
                }
190
            }
191
        }
192
        this.helper.processSpecialFunctions(sqlbuilder, featureType, null);
193

    
194
        select.remove_all_columns();
195
        select.column().value(sqlbuilder.count().all());
196

    
197
        sqlbuilder.setProperties(
198
                ExpressionBuilder.Variable.class,
199
                PROP_TABLE, table
200
        );
201

    
202
        String sql = select.toString();
203
        return sql;
204
    }
205

    
206
    public long count(Connection conn) throws DataException {
207

    
208
        String sql = this.getSQL();
209
        Statement st = null;
210
        ResultSet rs = null;
211
        try {
212
            st = conn.createStatement();
213
            rs = JDBCUtils.executeQuery(st, sql);
214
            if (!rs.next()) {
215
                return 0;
216
            }
217
            return rs.getLong(1);
218

    
219
        } catch (SQLException ex) {
220
            throw new JDBCSQLException(ex);
221
        } finally {
222
            JDBCUtils.closeQuietly(st);
223
            JDBCUtils.closeQuietly(rs);
224
        }
225
    }
226
   
227
}