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 @ 45166

History | View | Annotate | Download (9.02 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

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

    
160
        } else {
161
            select.column().value(sqlbuilder.count().all());
162
            select.from().table()
163
                    .database(this.table.getDatabase())
164
                    .schema(this.table.getSchema())
165
                    .name(this.table.getTable());
166
            select.from().subquery(this.table.getSubquery());
167
            if (!StringUtils.isEmpty(baseFilter)) {
168
                sqlbuilder.select().where().set(expbuilder.custom(baseFilter));
169
            }
170
            if (this.query != null) {
171
                if (this.query.getFilter() != null && !StringUtils.isBlank(this.query.getFilter().getSQL())) {
172
                    // El and() hace un set() si no hay un filtro previo
173
                    select.where().and(expbuilder.toValue(this.query.getFilter().getSQL()));
174
                }
175
            }
176
        }
177
        this.helper.processSpecialFunctions(sqlbuilder, featureType, null);
178

    
179
        select.remove_all_columns();
180
        select.column().value(sqlbuilder.count().all());
181

    
182
        sqlbuilder.setProperties(
183
                ExpressionBuilder.Variable.class,
184
                PROP_TABLE, table
185
        );
186

    
187
        String sql = select.toString();
188
        return sql;
189
    }
190

    
191
    public long count(Connection conn) throws DataException {
192

    
193
        String sql = this.getSQL();
194
        Statement st = null;
195
        ResultSet rs = null;
196
        try {
197
            st = conn.createStatement();
198
            rs = JDBCUtils.executeQuery(st, sql);
199
            if (!rs.next()) {
200
                return 0;
201
            }
202
            return rs.getLong(1);
203

    
204
        } catch (SQLException ex) {
205
            throw new JDBCSQLException(ex);
206
        } finally {
207
            JDBCUtils.closeQuietly(st);
208
            JDBCUtils.closeQuietly(rs);
209
        }
210
    }
211
   
212
}