OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 142 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
17 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.sql.model;
15
 
142 ilm 16
import org.openconcerto.sql.model.SQLSelect.LockStrength;
17 ilm 17
import org.openconcerto.utils.Tuple2;
18
 
19
import java.sql.ResultSet;
20
import java.sql.SQLException;
21
import java.util.ArrayList;
174 ilm 22
import java.util.Collection;
83 ilm 23
import java.util.Collections;
93 ilm 24
import java.util.HashSet;
17 ilm 25
import java.util.List;
93 ilm 26
import java.util.Set;
174 ilm 27
import java.util.stream.Collectors;
17 ilm 28
 
29
import org.apache.commons.dbutils.ResultSetHandler;
30
 
31
public final class SQLRowListRSH implements ResultSetHandler {
32
 
63 ilm 33
    // hashCode()/equals() needed for data source cache
83 ilm 34
    public static final class RSH implements ResultSetHandler {
63 ilm 35
        private final Tuple2<SQLTable, List<String>> names;
36
 
83 ilm 37
        // allow to create rows from arbitrary columns (and not just directly from actual fields of
38
        // the same table)
39
        // ATTN doesn't check that the types of columns are coherent with the types of the fields
40
        public RSH(final SQLTable t, final List<String> names) {
41
            this(Tuple2.create(t, names));
174 ilm 42
            // null are OK (they're ignored)
43
            final List<String> unknown = names.stream().filter(n -> n != null && !t.getFieldsName().contains(n)).collect(Collectors.toList());
44
            if (!unknown.isEmpty())
45
                throw new IllegalArgumentException("Not all names are fields of " + t + " : " + unknown);
83 ilm 46
        }
47
 
174 ilm 48
        private RSH(final Tuple2<SQLTable, List<String>> names) {
63 ilm 49
            this.names = names;
50
        }
51
 
52
        @Override
174 ilm 53
        public List<SQLRow> handle(final ResultSet rs) throws SQLException {
83 ilm 54
            // since the result will be cached, disallow its modification (e.g.avoid
55
            // ConcurrentModificationException)
56
            return Collections.unmodifiableList(SQLRow.createListFromRS(this.names.get0(), rs, this.names.get1()));
63 ilm 57
        }
58
 
59
        @Override
60
        public int hashCode() {
61
            return this.names.hashCode();
62
        }
63
 
64
        @Override
174 ilm 65
        public boolean equals(final Object obj) {
63 ilm 66
            if (this == obj)
67
                return true;
68
            if (obj == null)
69
                return false;
70
            if (getClass() != obj.getClass())
71
                return false;
72
            final RSH other = (RSH) obj;
73
            return this.names.equals(other.names);
74
        }
75
    }
76
 
83 ilm 77
    private static TableRef checkTable(final TableRef t) {
78
        if (t == null)
79
            throw new IllegalArgumentException("null table");
80
        if (!t.getTable().isRowable())
81
            throw new IllegalArgumentException("table isn't rowable : " + t);
82
        return t;
83
    }
84
 
174 ilm 85
    static Tuple2<SQLTable, List<String>> getIndexes(final SQLSelect sel, final TableRef passedTable, final boolean findTable) {
83 ilm 86
        final List<FieldRef> selectFields = sel.getSelectFields();
17 ilm 87
        final int size = selectFields.size();
88
        if (size == 0)
89
            throw new IllegalArgumentException("empty select : " + sel);
83 ilm 90
        TableRef t;
17 ilm 91
        if (findTable) {
92
            if (passedTable != null)
93
                throw new IllegalArgumentException("non null table " + passedTable);
83 ilm 94
            t = null;
17 ilm 95
        } else {
83 ilm 96
            t = checkTable(passedTable);
17 ilm 97
        }
98
        final List<String> l = new ArrayList<String>(size);
99
        for (int i = 0; i < size; i++) {
83 ilm 100
            final FieldRef field = selectFields.get(i);
101
            if (field == null) {
102
                // computed field
17 ilm 103
                l.add(null);
83 ilm 104
            } else {
105
                if (t == null) {
106
                    assert findTable;
107
                    t = checkTable(field.getTableRef());
108
                }
109
                assert t != null && t.getTable().isRowable();
110
 
111
                if (field.getTableRef().equals(t)) {
112
                    l.add(field.getField().getName());
113
                } else if (findTable) {
114
                    // prevent ambiguity : either specify a table or there must be only one table
115
                    throw new IllegalArgumentException(field + " is not in " + t);
116
                } else {
117
                    l.add(null);
118
                }
119
            }
17 ilm 120
        }
83 ilm 121
        return Tuple2.create(t.getTable(), l);
17 ilm 122
    }
123
 
124
    /**
125
     * Create a handler that don't need metadata.
174 ilm 126
     *
17 ilm 127
     * @param sel the select that will produce the result set, must only have one table.
128
     * @return a handler creating a list of {@link SQLRow}.
93 ilm 129
     * @deprecated use {@link SQLSelectHandlerBuilder}
17 ilm 130
     */
174 ilm 131
    @Deprecated
17 ilm 132
    static public ResultSetHandler createFromSelect(final SQLSelect sel) {
133
        return create(getIndexes(sel, null, true));
134
    }
135
 
136
    /**
137
     * Create a handler that don't need metadata. Useful since some JDBC drivers perform queries for
138
     * each metadata.
174 ilm 139
     *
17 ilm 140
     * @param sel the select that will produce the result set.
83 ilm 141
     * @param t the table for which to create rows.
17 ilm 142
     * @return a handler creating a list of {@link SQLRow}.
93 ilm 143
     * @deprecated use {@link SQLSelectHandlerBuilder}
17 ilm 144
     */
174 ilm 145
    @Deprecated
83 ilm 146
    static public ResultSetHandler createFromSelect(final SQLSelect sel, final TableRef t) {
17 ilm 147
        return create(getIndexes(sel, t, false));
148
    }
149
 
93 ilm 150
    static ResultSetHandler create(final Tuple2<SQLTable, List<String>> names) {
63 ilm 151
        return new RSH(names);
17 ilm 152
    }
153
 
174 ilm 154
    static public List<SQLRow> fetch(final SQLTable t, final Collection<? extends Number> ids) throws IllegalArgumentException {
155
        return fetch(t, ids, null);
156
    }
157
 
158
    static public List<SQLRow> fetch(final SQLTable t, final Collection<? extends Number> ids, final Collection<String> fields) throws IllegalArgumentException {
159
        final SQLSelect sel = new SQLSelect();
160
        if (fields == null)
161
            sel.addSelectStar(t);
162
        else
163
            sel.addAllSelect(t, fields);
164
        sel.setWhere(new Where(t.getKey(), ids));
165
        return execute(sel);
166
    }
167
 
93 ilm 168
    /**
169
     * Execute the passed select and return rows. NOTE if there's more than one table in the query
170
     * {@link #execute(SQLSelect, TableRef)} must be used.
174 ilm 171
     *
93 ilm 172
     * @param sel the query to execute.
173
     * @return rows.
174
     * @throws IllegalArgumentException if there's more than one table in the query.
175
     */
176
    static public List<SQLRow> execute(final SQLSelect sel) throws IllegalArgumentException {
177
        return execute(sel, true, true);
17 ilm 178
    }
179
 
93 ilm 180
    static public List<SQLRow> execute(final SQLSelect sel, final boolean readCache, final boolean writeCache) {
181
        return new SQLSelectHandlerBuilder(sel).setReadCache(readCache).setWriteCache(writeCache).execute();
182
    }
183
 
184
    /**
185
     * Execute the passed select and return rows of <code>t</code>. NOTE if there's only one table
186
     * in the query {@link #execute(SQLSelect)} should be used.
174 ilm 187
     *
93 ilm 188
     * @param sel the query to execute.
189
     * @param t the table to use.
190
     * @return rows of <code>t</code>.
191
     * @throws NullPointerException if <code>t</code> is <code>null</code>.
192
     */
193
    static public List<SQLRow> execute(final SQLSelect sel, final TableRef t) throws NullPointerException {
194
        return new SQLSelectHandlerBuilder(sel).setTableRef(t).execute();
195
    }
196
 
197
    static IResultSetHandler createFromSelect(final SQLSelect sel, final Tuple2<SQLTable, List<String>> indexes, final boolean readCache, final boolean writeCache) {
198
        final Set<SQLTable> tables = new HashSet<SQLTable>();
199
        // not just tables of the fields of the SELECT clause since inner joins can change the rows
200
        // returned
201
        for (final TableRef ref : sel.getTableRefs().values()) {
202
            tables.add(ref.getTable());
203
        }
204
 
142 ilm 205
        // the SELECT requesting a lock means the caller expects the DB to be accessed
206
        final boolean acquireLock = sel.getLockStrength() != LockStrength.NONE;
207
        return new IResultSetHandler(create(indexes), readCache && !acquireLock, writeCache && !acquireLock) {
93 ilm 208
            @Override
209
            public Set<? extends SQLData> getCacheModifiers() {
210
                return tables;
211
            }
212
        };
213
    }
214
 
17 ilm 215
    private final SQLTable t;
216
    private final boolean tableOnly;
217
 
174 ilm 218
    public SQLRowListRSH(final SQLTable t) {
17 ilm 219
        this(t, false);
220
    }
221
 
174 ilm 222
    public SQLRowListRSH(final SQLTable t, final boolean tableOnly) {
17 ilm 223
        super();
224
        this.t = t;
225
        this.tableOnly = tableOnly;
226
    }
227
 
174 ilm 228
    @Override
229
    public List<SQLRow> handle(final ResultSet rs) throws SQLException {
17 ilm 230
        return SQLRow.createListFromRS(this.t, rs, this.tableOnly);
231
    }
232
}