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

History | View | Annotate | Download (8.9 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 org.gvsig.expressionevaluator.ExpressionUtils;
36
import org.gvsig.fmap.dal.SQLBuilder.SelectBuilder;
37
import org.gvsig.fmap.dal.exception.DataException;
38
import org.gvsig.fmap.dal.expressionevaluator.FeatureAttributeEmulatorExpression;
39
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
40
import org.gvsig.fmap.dal.feature.FeatureQuery;
41
import org.gvsig.fmap.dal.feature.FeatureType;
42
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
43
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
44
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
45
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
46
import org.gvsig.fmap.dal.store.jdbc2.OperationsFactory.TableReference;
47
import static org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase.PROP_TABLE;
48
import org.gvsig.tools.evaluator.Evaluator;
49

    
50
public class CountOperation extends AbstractConnectionOperation {
51

    
52
    private final TableReference table;
53
    private final String baseFilter;
54
    private final FeatureQuery query;
55
    private final FeatureType featureType;
56

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

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

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

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

    
86
        SelectBuilder select = sqlbuilder.select();
87

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

    
110

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

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

    
177
        select.remove_all_columns();
178
        select.column().value(sqlbuilder.count().all());
179

    
180
        sqlbuilder.setProperties(
181
                ExpressionBuilder.Variable.class,
182
                PROP_TABLE, table
183
        );
184

    
185
        String sql = select.toString();
186
        return sql;
187
    }
188

    
189
    public long count(Connection conn) throws DataException {
190

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

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