OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 151 | Rev 174 | Go to most recent revision | 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 static org.openconcerto.xml.JDOM2Utils.OUTPUTTER;
17
 
17 ilm 18
import org.openconcerto.sql.Log;
83 ilm 19
import org.openconcerto.sql.model.SQLSelect.ArchiveMode;
142 ilm 20
import org.openconcerto.sql.model.SQLSelect.LockStrength;
17 ilm 21
import org.openconcerto.sql.model.SQLSyntax.ConstraintType;
22
import org.openconcerto.sql.model.SQLTableEvent.Mode;
23
import org.openconcerto.sql.model.graph.DatabaseGraph;
24
import org.openconcerto.sql.model.graph.Link;
61 ilm 25
import org.openconcerto.sql.model.graph.Link.Rule;
93 ilm 26
import org.openconcerto.sql.model.graph.SQLKey;
27
import org.openconcerto.sql.model.graph.SQLKey.Type;
67 ilm 28
import org.openconcerto.sql.model.graph.TablesMap;
17 ilm 29
import org.openconcerto.sql.request.UpdateBuilder;
30
import org.openconcerto.sql.utils.ChangeTable;
144 ilm 31
import org.openconcerto.sql.utils.PartialUniqueTrigger;
17 ilm 32
import org.openconcerto.sql.utils.SQLCreateMoveableTable;
144 ilm 33
import org.openconcerto.sql.utils.UniqueConstraintCreatorHelper;
17 ilm 34
import org.openconcerto.utils.CollectionUtils;
35
import org.openconcerto.utils.CompareUtils;
36
import org.openconcerto.utils.ExceptionUtils;
73 ilm 37
import org.openconcerto.utils.ListMap;
83 ilm 38
import org.openconcerto.utils.SetMap;
39
import org.openconcerto.utils.StringUtils;
25 ilm 40
import org.openconcerto.utils.Tuple2;
61 ilm 41
import org.openconcerto.utils.Tuple3;
83 ilm 42
import org.openconcerto.utils.Value;
61 ilm 43
import org.openconcerto.utils.cc.CopyOnWriteMap;
132 ilm 44
import org.openconcerto.utils.cc.CustomEquals;
17 ilm 45
import org.openconcerto.utils.change.CollectionChangeEventCreator;
46
 
47
import java.math.BigDecimal;
48
import java.sql.DatabaseMetaData;
49
import java.sql.ResultSet;
50
import java.sql.SQLException;
51
import java.util.ArrayList;
67 ilm 52
import java.util.Arrays;
17 ilm 53
import java.util.Collection;
54
import java.util.Collections;
132 ilm 55
import java.util.EnumSet;
17 ilm 56
import java.util.HashMap;
57
import java.util.HashSet;
58
import java.util.Iterator;
59
import java.util.LinkedHashMap;
60
import java.util.LinkedHashSet;
25 ilm 61
import java.util.LinkedList;
17 ilm 62
import java.util.List;
73 ilm 63
import java.util.ListIterator;
17 ilm 64
import java.util.Map;
67 ilm 65
import java.util.Map.Entry;
17 ilm 66
import java.util.Set;
83 ilm 67
import java.util.regex.Matcher;
68
import java.util.regex.Pattern;
17 ilm 69
 
132 ilm 70
import org.apache.commons.dbutils.ResultSetHandler;
71
import org.jdom2.Element;
72
 
61 ilm 73
import net.jcip.annotations.GuardedBy;
93 ilm 74
import net.jcip.annotations.Immutable;
61 ilm 75
 
17 ilm 76
/**
77
 * Une table SQL. Connait ses champs, notamment sa clef primaire et ses clefs externes. Une table
78
 * peut aussi faire des diagnostic sur son intégrité, ou sur la validité d'une valeur d'un de ses
79
 * champs. Enfin elle permet d'accéder aux lignes qui la composent.
80
 *
81
 * @author ILM Informatique 4 mai 2004
82
 * @see #getField(String)
83
 * @see #getKey()
84
 * @see #getForeignKeys()
85
 * @see #checkIntegrity()
86
 * @see #checkValidity(String, int)
87
 * @see #getRow(int)
88
 */
65 ilm 89
public final class SQLTable extends SQLIdentifier implements SQLData, TableRef {
17 ilm 90
 
132 ilm 91
    private static final String UNDEF_TABLE_TABLENAME_FIELD = "TABLENAME";
92
    private static final String UNDEF_TABLE_ID_FIELD = "UNDEFINED_ID";
93
 
17 ilm 94
    /**
95
     * The {@link DBRoot#setMetadata(String, String) meta data} configuring the policy regarding
96
     * undefined IDs for a particular root. Can be either :
97
     * <dl>
67 ilm 98
     * <dt>inDB</dt>
99
     * <dd>all undefined IDs must be in {@value #undefTable}. Allow different IDs like "min" but
100
     * without the performance penalty</dd>
17 ilm 101
     * <dt>min</dt>
102
     * <dd>for min("ID")</dd>
103
     * <dt>nonexistant</dt>
104
     * <dd>(the default) {@link SQLRow#NONEXISTANT_ID}</dd>
105
     * <dt><i>any other value</i></dt>
106
     * <dd>parsed as a number</dd>
107
     * </dl>
108
     */
109
    public static final String UNDEFINED_ID_POLICY = "undefined ID policy";
41 ilm 110
    public static final String undefTable = SQLSchema.FWK_TABLENAME_PREFIX + "UNDEFINED_IDS";
17 ilm 111
    // {SQLSchema=>{TableName=>UndefID}}
112
    private static final Map<SQLSchema, Map<String, Number>> UNDEFINED_IDs = new HashMap<SQLSchema, Map<String, Number>>();
132 ilm 113
    private static final ResultSetHandler UNDEF_RSH = new ResultSetHandler() {
114
        @Override
115
        public Object handle(ResultSet rs) throws SQLException {
116
            final Map<String, Number> res = new HashMap<String, Number>();
117
            while (rs.next()) {
118
                res.put(rs.getString(UNDEF_TABLE_TABLENAME_FIELD), (Number) rs.getObject(UNDEF_TABLE_ID_FIELD));
119
            }
120
            return res;
121
        }
122
    };
17 ilm 123
 
124
    @SuppressWarnings("unchecked")
125
    private static final Map<String, Number> getUndefIDs(final SQLSchema schema) {
126
        if (!UNDEFINED_IDs.containsKey(schema)) {
127
            final Map<String, Number> r;
128
            if (schema.contains(undefTable)) {
129
                final SQLBase b = schema.getBase();
130
                final SQLTable undefT = schema.getTable(undefTable);
80 ilm 131
                final SQLSelect sel = new SQLSelect().addSelectStar(undefT);
132 ilm 132
                // don't use the cache as the result is stored in UNDEFINED_IDs
133
                r = (Map<String, Number>) b.getDataSource().execute(sel.asString(), new IResultSetHandler(UNDEF_RSH, false));
73 ilm 134
                // be called early, since it's more likely that some transaction will create table,
135
                // set its undefined ID, then use it in requests, than some other transaction
136
                // needing the undefined ID. TODO The real fix is one tree per transaction.
137
                undefT.addTableModifiedListener(new ListenerAndConfig(new SQLTableModifiedListener() {
17 ilm 138
                    @Override
139
                    public void tableModified(SQLTableEvent evt) {
140
                        synchronized (UNDEFINED_IDs) {
141
                            UNDEFINED_IDs.remove(schema);
142
                            undefT.removeTableModifiedListener(this);
143
                        }
144
                    }
73 ilm 145
                }, false));
17 ilm 146
            } else {
147
                r = Collections.emptyMap();
148
            }
149
            UNDEFINED_IDs.put(schema, r);
150
        }
151
        return UNDEFINED_IDs.get(schema);
152
    }
153
 
83 ilm 154
    static final void removeUndefID(SQLSchema s) {
155
        synchronized (UNDEFINED_IDs) {
156
            UNDEFINED_IDs.remove(s);
157
        }
158
    }
159
 
67 ilm 160
    static final Tuple2<Boolean, Number> getUndefID(SQLSchema b, String tableName) {
17 ilm 161
        synchronized (UNDEFINED_IDs) {
61 ilm 162
            final Map<String, Number> map = getUndefIDs(b);
163
            return Tuple2.create(map.containsKey(tableName), map.get(tableName));
17 ilm 164
        }
165
    }
166
 
67 ilm 167
    private static final SQLCreateMoveableTable getCreateUndefTable(SQLSyntax syntax) {
168
        final SQLCreateMoveableTable createTable = new SQLCreateMoveableTable(syntax, undefTable);
132 ilm 169
        createTable.addVarCharColumn(UNDEF_TABLE_TABLENAME_FIELD, 250);
170
        createTable.addColumn(UNDEF_TABLE_ID_FIELD, syntax.getIDType());
171
        createTable.setPrimaryKey(UNDEF_TABLE_TABLENAME_FIELD);
67 ilm 172
        return createTable;
173
    }
174
 
175
    private static final SQLTable getUndefTable(SQLSchema schema, boolean create) throws SQLException {
176
        final SQLTable undefT = schema.getTable(undefTable);
177
        if (undefT != null || !create) {
178
            return undefT;
179
        } else {
180
            schema.getDBSystemRoot().getDataSource().execute(getCreateUndefTable(SQLSyntax.get(schema)).asString(schema.getDBRoot().getName()));
181
            schema.updateVersion();
182
            return schema.fetchTable(undefTable);
183
        }
184
    }
185
 
17 ilm 186
    public static final void setUndefID(SQLSchema schema, String tableName, Integer value) throws SQLException {
67 ilm 187
        setUndefIDs(schema, Collections.singletonMap(tableName, value));
188
    }
189
 
190
    // return modified count
191
    public static final int setUndefIDs(SQLSchema schema, Map<String, ? extends Number> values) throws SQLException {
17 ilm 192
        synchronized (UNDEFINED_IDs) {
67 ilm 193
            final SQLTable undefT = getUndefTable(schema, true);
132 ilm 194
            final SQLType undefType = undefT.getField(UNDEF_TABLE_ID_FIELD).getType();
67 ilm 195
            final List<List<String>> toInsert = new ArrayList<List<String>>();
196
            final List<List<String>> toUpdate = new ArrayList<List<String>>();
197
            final Map<String, Number> currentValues = getUndefIDs(schema);
198
            final SQLBase b = schema.getBase();
199
            final SQLSystem system = b.getServer().getSQLSystem();
200
            for (final Entry<String, ? extends Number> e : values.entrySet()) {
201
                final String tableName = e.getKey();
202
                final Number undefValue = e.getValue();
203
                final List<List<String>> l;
204
                if (!currentValues.containsKey(tableName)) {
205
                    l = toInsert;
206
                } else if (CompareUtils.equals(currentValues.get(tableName), undefValue)) {
207
                    l = null;
208
                } else {
209
                    l = toUpdate;
210
                }
211
                if (l != null) {
212
                    final String undefSQL;
213
                    if (undefValue == null && system == SQLSystem.POSTGRESQL)
214
                        // column "UNDEFINED_ID" is of type integer but expression is of type text
215
                        undefSQL = "cast( NULL as " + undefType.getTypeName() + ")";
216
                    else
217
                        undefSQL = undefType.toString(undefValue);
218
                    l.add(Arrays.asList(b.quoteString(tableName), undefSQL));
219
                }
220
            }
142 ilm 221
            final SQLSyntax syntax = schema.getDBSystemRoot().getSyntax();
67 ilm 222
            if (toInsert.size() > 0) {
17 ilm 223
                // INSERT
132 ilm 224
                SQLRowValues.insertCount(undefT, "(" + SQLSyntax.quoteIdentifiers(Arrays.asList(UNDEF_TABLE_TABLENAME_FIELD, UNDEF_TABLE_ID_FIELD)) + ") " + syntax.getValues(toInsert, 2));
67 ilm 225
            }
226
            if (toUpdate.size() > 0) {
17 ilm 227
                // UPDATE
67 ilm 228
                // h2 doesn't support multi-table UPDATE
229
                if (system == SQLSystem.H2) {
230
                    final StringBuilder updates = new StringBuilder();
231
                    for (final List<String> l : toUpdate) {
132 ilm 232
                        final UpdateBuilder update = new UpdateBuilder(undefT).set(UNDEF_TABLE_ID_FIELD, l.get(1));
233
                        update.setWhere(Where.createRaw(undefT.getField(UNDEF_TABLE_TABLENAME_FIELD).getFieldRef() + " = " + l.get(0)));
67 ilm 234
                        updates.append(update.asString());
235
                        updates.append(";\n");
236
                    }
237
                    schema.getDBSystemRoot().getDataSource().execute(updates.toString());
238
                } else {
239
                    final UpdateBuilder update = new UpdateBuilder(undefT);
240
                    final String constantTableAlias = "newUndef";
241
                    update.addRawTable(syntax.getConstantTable(toUpdate, constantTableAlias, Arrays.asList("t", "v")), null);
132 ilm 242
                    update.setWhere(Where.createRaw(undefT.getField(UNDEF_TABLE_TABLENAME_FIELD).getFieldRef() + " = " + new SQLName(constantTableAlias, "t").quote()));
243
                    update.set(UNDEF_TABLE_ID_FIELD, new SQLName(constantTableAlias, "v").quote());
67 ilm 244
                    schema.getDBSystemRoot().getDataSource().execute(update.asString());
245
                }
17 ilm 246
            }
67 ilm 247
            final int res = toInsert.size() + toUpdate.size();
248
            if (res > 0) {
17 ilm 249
                undefT.fireTableModified(SQLRow.NONEXISTANT_ID);
250
            }
67 ilm 251
            return res;
17 ilm 252
        }
253
    }
254
 
73 ilm 255
    static private boolean AFTER_TX_DEFAULT = true;
256
 
257
    static public void setDefaultAfterTransaction(final boolean val) {
258
        AFTER_TX_DEFAULT = val;
259
    }
260
 
261
    static public final class ListenerAndConfig {
262
 
263
        private final SQLTableModifiedListener l;
132 ilm 264
        private final Boolean afterTx;
73 ilm 265
 
132 ilm 266
        /**
267
         * Create a new instance.
268
         *
269
         * @param l the listener.
270
         * @param afterTx <code>true</code> if <code>l</code> should only be called once a
271
         *        transaction is committed, <code>false</code> to be called in real-time (i.e.
272
         *        called a second time if a transaction is aborted), <code>null</code> to be called
273
         *        both in real-time and after the transaction succeeds.
274
         */
275
        public ListenerAndConfig(SQLTableModifiedListener l, Boolean afterTx) {
73 ilm 276
            super();
277
            if (l == null)
278
                throw new NullPointerException("Null listener");
279
            this.l = l;
280
            this.afterTx = afterTx;
281
        }
282
 
283
        public final SQLTableModifiedListener getListener() {
284
            return this.l;
285
        }
286
 
132 ilm 287
        public final Boolean callOnlyAfterTx() {
73 ilm 288
            return this.afterTx;
289
        }
290
 
291
        @Override
292
        public int hashCode() {
293
            final int prime = 31;
294
            int result = 1;
132 ilm 295
            result = prime * result + (this.afterTx == null ? 0 : this.afterTx.hashCode());
73 ilm 296
            result = prime * result + this.l.hashCode();
297
            return result;
298
        }
299
 
300
        @Override
301
        public boolean equals(Object obj) {
302
            if (this == obj)
303
                return true;
304
            if (obj == null)
305
                return false;
306
            if (getClass() != obj.getClass())
307
                return false;
308
            final ListenerAndConfig other = (ListenerAndConfig) obj;
132 ilm 309
            return CompareUtils.equals(this.afterTx, other.afterTx) && this.l.equals(other.l);
73 ilm 310
        }
311
    }
312
 
67 ilm 313
    @GuardedBy("this")
314
    private String version;
61 ilm 315
    private final CopyOnWriteMap<String, SQLField> fields;
316
    @GuardedBy("this")
142 ilm 317
    private Set<SQLField> primaryKeys;
17 ilm 318
    // the vast majority of our code use getKey(), so cache it for performance
61 ilm 319
    @GuardedBy("this")
17 ilm 320
    private SQLField primaryKey;
321
    // true if there's at most 1 primary key
61 ilm 322
    @GuardedBy("this")
17 ilm 323
    private boolean primaryKeyOK;
61 ilm 324
    @GuardedBy("this")
17 ilm 325
    private Set<SQLField> keys;
61 ilm 326
    @GuardedBy("this")
93 ilm 327
    private Map<String, FieldGroup> fieldsGroups;
328
    @GuardedBy("this")
17 ilm 329
    private final Map<String, Trigger> triggers;
330
    // null means it couldn't be retrieved
61 ilm 331
    @GuardedBy("this")
17 ilm 332
    private Set<Constraint> constraints;
333
    // always immutable so that fire can iterate safely ; to modify it, simply copy it before
334
    // (adding listeners is a lot less common than firing events)
63 ilm 335
    @GuardedBy("listenersMutex")
73 ilm 336
    private List<ListenerAndConfig> tableModifiedListeners;
337
    @GuardedBy("listenersMutex")
338
    private final ListMap<TransactionPoint, FireState> transactions;
339
    private final TransactionListener txListener;
63 ilm 340
    private final Object listenersMutex = new String("tableModifiedListeners mutex");
17 ilm 341
    // the id that foreign keys pointing to this, can use instead of NULL
342
    // a null value meaning not yet known
61 ilm 343
    @GuardedBy("this")
17 ilm 344
    private Integer undefinedID;
345
 
61 ilm 346
    @GuardedBy("this")
17 ilm 347
    private String comment;
61 ilm 348
    @GuardedBy("this")
17 ilm 349
    private String type;
350
 
351
    // empty table
352
    SQLTable(SQLSchema schema, String name) {
353
        super(schema, name);
354
        this.tableModifiedListeners = Collections.emptyList();
73 ilm 355
        this.transactions = new ListMap<TransactionPoint, FireState>();
356
        this.txListener = new TransactionListener() {
357
            @Override
358
            public void transactionEnded(TransactionPoint point) {
132 ilm 359
                fireFromTransaction(point);
73 ilm 360
            }
361
        };
61 ilm 362
        // needed for getOrderedFields()
363
        this.fields = new CopyOnWriteMap<String, SQLField>() {
364
            @Override
365
            public Map<String, SQLField> copy(Map<? extends String, ? extends SQLField> src) {
366
                return new LinkedHashMap<String, SQLField>(src);
367
            }
368
        };
369
        assert isOrdered(this.fields);
142 ilm 370
        this.primaryKeys = Collections.emptySet();
17 ilm 371
        this.primaryKey = null;
372
        this.primaryKeyOK = true;
373
        this.keys = null;
93 ilm 374
        this.fieldsGroups = null;
17 ilm 375
        this.triggers = new HashMap<String, Trigger>();
376
        // by default non-null, ie ok, only set to null on error
377
        this.constraints = new HashSet<Constraint>();
378
        // not known
379
        this.undefinedID = null;
67 ilm 380
        assert !this.undefinedIDKnown();
17 ilm 381
    }
382
 
383
    // *** setter
384
 
61 ilm 385
    synchronized void clearNonPersistent() {
17 ilm 386
        this.triggers.clear();
387
        // non-null, see ctor
388
        this.constraints = new HashSet<Constraint>();
389
    }
390
 
391
    // * from XML
392
 
393
    void loadFields(Element xml) {
67 ilm 394
        synchronized (this) {
395
            this.version = SQLSchema.getVersion(xml);
396
        }
397
 
17 ilm 398
        final LinkedHashMap<String, SQLField> newFields = new LinkedHashMap<String, SQLField>();
83 ilm 399
        for (final Element elementField : xml.getChildren("field")) {
17 ilm 400
            final SQLField f = SQLField.create(this, elementField);
401
            newFields.put(f.getName(), f);
402
        }
403
 
404
        final Element primary = xml.getChild("primary");
405
        final List<String> newPrimaryKeys = new ArrayList<String>();
83 ilm 406
        for (final Element elementField : primary.getChildren("field")) {
17 ilm 407
            final String fieldName = elementField.getAttributeValue("name");
408
            newPrimaryKeys.add(fieldName);
409
        }
410
 
61 ilm 411
        synchronized (getTreeMutex()) {
412
            synchronized (this) {
67 ilm 413
                this.setState(newFields, newPrimaryKeys, null);
17 ilm 414
 
61 ilm 415
                final Element triggersElem = xml.getChild("triggers");
416
                if (triggersElem != null)
83 ilm 417
                    for (final Element triggerElem : triggersElem.getChildren()) {
61 ilm 418
                        this.addTrigger(Trigger.fromXML(this, triggerElem));
419
                    }
17 ilm 420
 
61 ilm 421
                final Element constraintsElem = xml.getChild("constraints");
422
                if (constraintsElem == null)
423
                    this.addConstraint((Constraint) null);
424
                else
83 ilm 425
                    for (final Element elem : constraintsElem.getChildren()) {
61 ilm 426
                        this.addConstraint(Constraint.fromXML(this, elem));
427
                    }
428
 
429
                final Element commentElem = xml.getChild("comment");
430
                if (commentElem != null)
431
                    this.setComment(commentElem.getText());
432
                this.setType(xml.getAttributeValue("type"));
17 ilm 433
            }
61 ilm 434
        }
17 ilm 435
    }
436
 
61 ilm 437
    synchronized private void addTrigger(final Trigger t) {
17 ilm 438
        this.triggers.put(t.getName(), t);
439
    }
440
 
61 ilm 441
    synchronized private void addConstraint(final Constraint c) {
17 ilm 442
        if (c == null) {
443
            this.constraints = null;
444
        } else {
445
            if (this.constraints == null)
446
                this.constraints = new HashSet<Constraint>();
447
            this.constraints.add(c);
448
        }
449
    }
450
 
451
    // * from JDBC
452
 
453
    public void fetchFields() throws SQLException {
67 ilm 454
        this.getBase().fetchTables(TablesMap.createBySchemaFromTable(this));
61 ilm 455
    }
17 ilm 456
 
457
    /**
458
     * Fetch fields from the passed args.
459
     *
460
     * @param metaData the metadata.
461
     * @param rs the resultSet of a getColumns(), the cursor must be on a row.
67 ilm 462
     * @param version the version of the schema.
17 ilm 463
     * @return whether the <code>rs</code> has more row.
464
     * @throws SQLException if an error occurs.
465
     * @throws IllegalStateException if the current row of <code>rs</code> doesn't describe this.
466
     */
67 ilm 467
    boolean fetchFields(DatabaseMetaData metaData, ResultSet rs, String version) throws SQLException {
17 ilm 468
        if (!this.isUs(rs))
469
            throw new IllegalStateException("rs current row does not describe " + this);
470
 
61 ilm 471
        synchronized (getTreeMutex()) {
472
            synchronized (this) {
67 ilm 473
                this.version = version;
474
 
61 ilm 475
                // we need to match the database ordering of fields
476
                final LinkedHashMap<String, SQLField> newFields = new LinkedHashMap<String, SQLField>();
477
                // fields
478
                boolean hasNext = true;
479
                while (hasNext && this.isUs(rs)) {
480
                    final SQLField f = SQLField.create(this, rs);
481
                    newFields.put(f.getName(), f);
482
                    hasNext = rs.next();
483
                }
17 ilm 484
 
61 ilm 485
                final List<String> newPrimaryKeys = new ArrayList<String>();
486
                final ResultSet pkRS = metaData.getPrimaryKeys(this.getBase().getMDName(), this.getSchema().getName(), this.getName());
487
                while (pkRS.next()) {
488
                    newPrimaryKeys.add(pkRS.getString("COLUMN_NAME"));
489
                }
17 ilm 490
 
61 ilm 491
                this.setState(newFields, newPrimaryKeys, null);
17 ilm 492
 
61 ilm 493
                return hasNext;
494
            }
495
        }
17 ilm 496
    }
497
 
498
    void emptyFields() {
499
        this.setState(new LinkedHashMap<String, SQLField>(), Collections.<String> emptyList(), null);
500
    }
501
 
502
    private boolean isUs(final ResultSet rs) throws SQLException {
503
        final String n = rs.getString("TABLE_NAME");
504
        final String s = rs.getString("TABLE_SCHEM");
505
        return n.equals(this.getName()) && CompareUtils.equals(s, this.getSchema().getName());
506
    }
507
 
80 ilm 508
    void addTrigger(Map<String, Object> m) {
17 ilm 509
        this.addTrigger(new Trigger(this, m));
510
    }
511
 
512
    void addConstraint(Map<String, Object> m) {
513
        this.addConstraint(m == null ? null : new Constraint(this, m));
514
    }
515
 
516
    // must be called in setState() after fields have been set (for isRowable())
63 ilm 517
    private int fetchUndefID() {
151 ilm 518
        final int res;
63 ilm 519
        final SQLField pk;
520
        synchronized (this) {
521
            pk = isRowable() ? this.getKey() : null;
522
        }
523
        if (pk != null) {
61 ilm 524
            final Tuple2<Boolean, Number> currentValue = getUndefID(this.getSchema(), this.getName());
525
            if (!currentValue.get0()) {
151 ilm 526
                // no row
527
                res = this.findMinID(pk);
17 ilm 528
            } else {
529
                // a row
61 ilm 530
                final Number id = currentValue.get1();
17 ilm 531
                res = id == null ? SQLRow.NONEXISTANT_ID : id.intValue();
532
            }
533
        } else
534
            res = SQLRow.NONEXISTANT_ID;
535
        return res;
536
    }
537
 
538
    // no undef id found
63 ilm 539
    private int findMinID(SQLField pk) {
17 ilm 540
        final String debugUndef = "fwk_sql.debug.undefined_id";
541
        if (System.getProperty(debugUndef) != null)
542
            Log.get().warning("The system property '" + debugUndef + "' is deprecated, use the '" + UNDEFINED_ID_POLICY + "' metadata");
543
 
544
        final String policy = getSchema().getFwkMetadata(UNDEFINED_ID_POLICY);
545
        if (Boolean.getBoolean(debugUndef) || "min".equals(policy)) {
80 ilm 546
            final SQLSelect sel = new SQLSelect(true).addSelect(pk, "min");
17 ilm 547
            final Number undef = (Number) this.getBase().getDataSource().executeScalar(sel.asString());
548
            if (undef == null) {
549
                // empty table
550
                throw new IllegalStateException(this + " is empty, can not infer UNDEFINED_ID");
551
            } else {
142 ilm 552
                final SQLSyntax syntax = SQLSyntax.get(this);
553
                final String update = syntax.getInsertOne(new SQLName(this.getDBRoot().getName(), undefTable), Arrays.asList(UNDEF_TABLE_TABLENAME_FIELD, UNDEF_TABLE_ID_FIELD),
554
                        syntax.quoteString(this.getName()), String.valueOf(undef));
17 ilm 555
                Log.get().config("the first row (which should be the undefined):\n" + update);
556
                return undef.intValue();
557
            }
67 ilm 558
        } else if ("inDB".equals(policy)) {
559
            throw new IllegalStateException("Not in " + new SQLName(this.getDBRoot().getName(), undefTable) + " : " + this.getName());
17 ilm 560
        } else if (policy != null && !"nonexistant".equals(policy)) {
561
            final int res = Integer.parseInt(policy);
562
            if (res < SQLRow.MIN_VALID_ID)
563
                throw new IllegalStateException("ID is not valid : " + res);
564
            return res;
565
        } else {
566
            // by default assume NULL is used
567
            return SQLRow.NONEXISTANT_ID;
568
        }
569
    }
570
 
571
    // * from Java
572
 
573
    void mutateTo(SQLTable table) {
61 ilm 574
        synchronized (getTreeMutex()) {
575
            synchronized (this) {
576
                this.clearNonPersistent();
67 ilm 577
                this.version = table.version;
61 ilm 578
                this.setState(table.fields, table.getPKsNames(), table.undefinedID);
83 ilm 579
                for (final Trigger t : table.triggers.values()) {
580
                    this.addTrigger(new Trigger(this, t));
581
                }
582
                if (table.constraints == null) {
61 ilm 583
                    this.constraints = null;
83 ilm 584
                } else {
585
                    for (final Constraint c : table.constraints) {
586
                        this.constraints.add(new Constraint(this, c));
587
                    }
61 ilm 588
                }
589
                this.setType(table.getType());
590
                this.setComment(table.getComment());
591
            }
17 ilm 592
        }
593
    }
594
 
595
    // * update attributes
596
 
61 ilm 597
    static private <K, V> boolean isOrdered(Map<K, V> m) {
598
        if (m instanceof CopyOnWriteMap)
599
            return isOrdered(((CopyOnWriteMap<K, V>) m).copy(Collections.<K, V> emptyMap()));
600
        return (m instanceof LinkedHashMap);
601
    }
602
 
83 ilm 603
    private void setState(Map<String, SQLField> fields, final List<String> primaryKeys, final Integer undef) {
61 ilm 604
        assert isOrdered(fields);
17 ilm 605
        // checks new fields' table (don't use ==, see below)
606
        for (final SQLField newField : fields.values()) {
607
            if (!newField.getTable().getSQLName().equals(this.getSQLName()))
608
                throw new IllegalArgumentException(newField + " is in table " + newField.getTable().getSQLName() + " not us: " + this.getSQLName());
609
        }
61 ilm 610
        synchronized (getTreeMutex()) {
611
            synchronized (this) {
612
                final CollectionChangeEventCreator c = this.createChildrenCreator();
17 ilm 613
 
61 ilm 614
                if (!fields.keySet().containsAll(this.getFieldsName())) {
615
                    for (String removed : CollectionUtils.substract(this.getFieldsName(), fields.keySet())) {
65 ilm 616
                        this.fields.remove(removed).dropped();
61 ilm 617
                    }
618
                }
17 ilm 619
 
61 ilm 620
                for (final SQLField newField : fields.values()) {
621
                    if (getChildrenNames().contains(newField.getName())) {
622
                        // re-use old instances by refreshing existing ones
623
                        this.getField(newField.getName()).mutateTo(newField);
624
                    } else {
625
                        final SQLField fieldToAdd;
626
                        // happens when the new structure is loaded in-memory
627
                        // before the current one is mutated to it
628
                        // (we already checked the fullname of the table)
629
                        if (newField.getTable() != this)
630
                            fieldToAdd = new SQLField(this, newField);
631
                        else
632
                            fieldToAdd = newField;
633
                        this.fields.put(newField.getName(), fieldToAdd);
634
                    }
635
                }
636
 
142 ilm 637
                // order matters (e.g. for indexes)
638
                final Set<SQLField> newPK = new LinkedHashSet<SQLField>();
61 ilm 639
                for (final String pk : primaryKeys)
142 ilm 640
                    newPK.add(this.getField(pk));
641
                this.primaryKeys = Collections.unmodifiableSet(newPK);
61 ilm 642
                this.primaryKey = primaryKeys.size() == 1 ? this.getField(primaryKeys.get(0)) : null;
643
                this.primaryKeyOK = primaryKeys.size() <= 1;
644
 
93 ilm 645
                this.keys = null;
646
                this.fieldsGroups = null;
647
 
61 ilm 648
                // don't fetch the ID now as it could be too early (e.g. we just created the table
649
                // but haven't inserted the undefined row)
650
                this.undefinedID = undef;
651
                this.fireChildrenChanged(c);
17 ilm 652
            }
653
        }
654
    }
655
 
656
    // *** getter
657
 
61 ilm 658
    synchronized void setType(String type) {
17 ilm 659
        this.type = type;
660
    }
661
 
61 ilm 662
    public synchronized final String getType() {
17 ilm 663
        return this.type;
664
    }
665
 
61 ilm 666
    synchronized void setComment(String comm) {
17 ilm 667
        this.comment = comm;
668
    }
669
 
61 ilm 670
    public synchronized final String getComment() {
17 ilm 671
        return this.comment;
672
    }
673
 
61 ilm 674
    public synchronized final Trigger getTrigger(String name) {
17 ilm 675
        return this.triggers.get(name);
676
    }
677
 
61 ilm 678
    public synchronized final Map<String, Trigger> getTriggers() {
17 ilm 679
        return Collections.unmodifiableMap(this.triggers);
680
    }
681
 
682
    /**
683
     * The constraints on this table.
684
     *
685
     * @return the constraints or <code>null</code> if they couldn't be retrieved.
686
     */
61 ilm 687
    public synchronized final Set<Constraint> getAllConstraints() {
17 ilm 688
        return this.constraints == null ? null : Collections.unmodifiableSet(this.constraints);
689
    }
690
 
691
    /**
83 ilm 692
     * The CHECK and UNIQUE constraints on this table. This is useful since types
693
     * {@link ConstraintType#FOREIGN_KEY FOREIGN_KEY} and {@link ConstraintType#PRIMARY_KEY
132 ilm 694
     * PRIMARY_KEY} are already available through {@link #getForeignLinks()} and
83 ilm 695
     * {@link #getPrimaryKeys()} ; type {@link ConstraintType#DEFAULT DEFAULT} through
696
     * {@link SQLField#getDefaultValue()}.
41 ilm 697
     *
698
     * @return the constraints or <code>null</code> if they couldn't be retrieved.
699
     */
61 ilm 700
    public synchronized final Set<Constraint> getConstraints() {
41 ilm 701
        if (this.constraints == null)
702
            return null;
703
        final Set<Constraint> res = new HashSet<Constraint>();
704
        for (final Constraint c : this.constraints) {
83 ilm 705
            if (c.getType() == ConstraintType.CHECK || c.getType() == ConstraintType.UNIQUE) {
41 ilm 706
                res.add(c);
707
            }
708
        }
709
        return res;
710
    }
711
 
712
    /**
17 ilm 713
     * Returns a specific constraint.
714
     *
715
     * @param type type of constraint, e.g. {@link ConstraintType#UNIQUE}.
716
     * @param cols the fields names, e.g. ["NAME"].
717
     * @return the matching constraint, <code>null</code> if it cannot be found or if constraints
718
     *         couldn't be retrieved.
719
     */
144 ilm 720
    public final Constraint getConstraint(ConstraintType type, List<String> cols) {
721
        if (type == null)
722
            throw new IllegalArgumentException("Missing type");
723
        final Set<Constraint> res = this.getConstraints(type, cols, false);
724
        if (res == null)
725
            return null;
726
        if (res.size() > 1)
727
            throw new IllegalStateException("More than one constraint matches (use getConstraints()) : " + res);
728
        return CollectionUtils.getSole(res);
729
    }
730
 
731
    /**
732
     * Search for constraints.
733
     *
734
     * @param type type of constraint, can be <code>null</code>.
735
     * @param cols the fields names, not <code>null</code>.
736
     * @param containing <code>true</code> if {@link Constraint#getCols() constraints columns}
737
     *        should {@link Collection#containsAll(Collection) contains all} the passed columns,
738
     *        <code>false</code> if they should be equal.
739
     * @return the matching constraints, <code>null</code> if constraints couldn't be retrieved.
740
     */
741
    public synchronized final Set<Constraint> getConstraints(ConstraintType type, List<String> cols, final boolean containing) {
742
        if (cols == null)
743
            throw new IllegalArgumentException("Missing columns");
17 ilm 744
        if (this.constraints == null)
745
            return null;
144 ilm 746
        final Set<Constraint> res = new HashSet<>();
17 ilm 747
        for (final Constraint c : this.constraints) {
144 ilm 748
            if ((type == null || c.getType() == type) && (containing ? c.getCols().containsAll(cols) : c.getCols().equals(cols))) {
749
                res.add(c);
17 ilm 750
            }
751
        }
144 ilm 752
        return res;
17 ilm 753
    }
754
 
755
    /**
756
     * Whether rows of this table can be represented as SQLRow.
757
     *
758
     * @return <code>true</code> if rows of this table can be represented as SQLRow.
759
     */
61 ilm 760
    public synchronized boolean isRowable() {
17 ilm 761
        return this.getPrimaryKeys().size() == 1 && Number.class.isAssignableFrom(this.getKey().getType().getJavaType());
762
    }
763
 
764
    public SQLSchema getSchema() {
765
        return (SQLSchema) this.getParent();
766
    }
767
 
768
    public SQLBase getBase() {
769
        return this.getSchema().getBase();
770
    }
771
 
73 ilm 772
    synchronized final String getVersion() {
773
        return this.version;
774
    }
775
 
17 ilm 776
    /**
777
     * Return the primary key of this table.
778
     *
779
     * @return the field which is the key of this table, or <code>null</code> if it doesn't exist.
780
     * @throws IllegalStateException if there's more than one primary key.
781
     */
65 ilm 782
    @Override
61 ilm 783
    public synchronized SQLField getKey() {
17 ilm 784
        if (!this.primaryKeyOK)
785
            throw new IllegalStateException(this + " has more than 1 primary key: " + this.getPrimaryKeys());
786
        return this.primaryKey;
787
    }
788
 
789
    /**
790
     * Return the primary keys of this table.
791
     *
792
     * @return the fields (SQLField) which are the keys of this table, can be empty.
793
     */
61 ilm 794
    public synchronized Set<SQLField> getPrimaryKeys() {
142 ilm 795
        return this.primaryKeys;
17 ilm 796
    }
797
 
132 ilm 798
    public final Set<Link> getForeignLinks() {
799
        return this.getDBSystemRoot().getGraph().getForeignLinks(this);
800
    }
801
 
17 ilm 802
    /**
803
     * Return the foreign keys of this table.
804
     *
805
     * @return a Set of SQLField which are foreign keys of this table.
806
     */
807
    public Set<SQLField> getForeignKeys() {
808
        return this.getDBSystemRoot().getGraph().getForeignKeys(this);
809
    }
810
 
811
    public Set<String> getForeignKeysNames() {
132 ilm 812
        return DatabaseGraph.getNames(this.getForeignLinks());
17 ilm 813
    }
814
 
815
    public Set<List<SQLField>> getForeignKeysFields() {
816
        return this.getDBSystemRoot().getGraph().getForeignKeysFields(this);
817
    }
818
 
819
    public Set<SQLField> getForeignKeys(String foreignTable) {
820
        return this.getForeignKeys(this.getTable(foreignTable));
821
    }
822
 
823
    public Set<SQLField> getForeignKeys(SQLTable foreignTable) {
824
        return this.getDBSystemRoot().getGraph().getForeignFields(this, foreignTable);
825
    }
826
 
827
    public SQLTable getForeignTable(String foreignField) {
65 ilm 828
        return this.getField(foreignField).getForeignTable();
17 ilm 829
    }
830
 
19 ilm 831
    public SQLTable findReferentTable(String tableName) {
832
        return this.getDBSystemRoot().getGraph().findReferentTable(this, tableName);
833
    }
834
 
17 ilm 835
    /**
836
     * Renvoie toutes les clefs de cette table. C'est à dire les clefs primaires plus les clefs
837
     * externes.
838
     *
839
     * @return toutes les clefs de cette table, can be empty.
840
     */
61 ilm 841
    public synchronized Set<SQLField> getKeys() {
17 ilm 842
        if (this.keys == null) {
132 ilm 843
            this.keys = this.getFields(VirtualFields.KEYS);
17 ilm 844
        }
845
        return this.keys;
846
    }
847
 
93 ilm 848
    @Immutable
849
    static public final class FieldGroup {
850
        private final String field;
851
        private final SQLKey key;
852
 
853
        private FieldGroup(final SQLKey key, final String field) {
854
            assert (key == null) != (field == null);
855
            this.key = key;
856
            this.field = key == null ? field : CollectionUtils.getSole(key.getFields());
857
        }
858
 
859
        /**
860
         * The key type for this group.
861
         *
862
         * @return the key type, <code>null</code> for a simple field.
863
         */
864
        public final Type getKeyType() {
865
            if (this.key == null)
866
                return null;
867
            return this.key.getType();
868
        }
869
 
870
        /**
871
         * The key for this group.
872
         *
873
         * @return the key, <code>null</code> for a simple field.
874
         */
156 ilm 875
        public final SQLKey getRawKey() {
93 ilm 876
            return this.key;
877
        }
878
 
879
        /**
156 ilm 880
         * The key for this group.
881
         *
882
         * @return the key, never <code>null</code>.
883
         * @throws IllegalStateException for a simple field.
884
         */
885
        public final SQLKey getKey() throws IllegalStateException {
886
            if (this.key == null)
887
                throw new IllegalStateException("Not a key : " + this);
888
            return this.key;
889
        }
890
 
891
        /**
892
         * The foreign link for this group.
893
         *
894
         * @return the foreign link, never <code>null</code>.
895
         * @throws IllegalStateException for a simple field or a primary key.
896
         */
897
        public final Link getForeignLink() throws IllegalStateException {
898
            if (this.key != null) {
899
                final Link foreignLink = this.key.getForeignLink();
900
                if (foreignLink != null)
901
                    return foreignLink;
902
            }
903
            throw new IllegalStateException("Not a foreign key : " + this);
904
        }
905
 
906
        /**
93 ilm 907
         * The one and only field of this group.
908
         *
909
         * @return the only field of this group, only <code>null</code> if this group is a
910
         *         {@link #getKey() key} with more than one field.
911
         */
912
        public String getSingleField() {
913
            return this.field;
914
        }
915
 
916
        public final List<String> getFields() {
917
            return this.key == null ? Arrays.asList(this.field) : this.key.getFields();
918
        }
919
 
920
        @Override
921
        public String toString() {
922
            return this.getClass().getSimpleName() + " " + (this.key != null ? this.key.toString() : this.field);
923
        }
924
    }
925
 
926
    /**
927
     * Return the fields grouped by key.
928
     *
929
     * @return for each field of this table the matching group.
930
     */
931
    public synchronized Map<String, FieldGroup> getFieldGroups() {
932
        if (this.fieldsGroups == null) {
933
            final Map<String, FieldGroup> res = new LinkedHashMap<String, FieldGroup>();
934
            // set order
935
            for (final String field : this.getFieldsName()) {
936
                res.put(field, new FieldGroup(null, field));
937
            }
132 ilm 938
            for (final Link l : this.getForeignLinks()) {
93 ilm 939
                indexKey(res, SQLKey.createForeignKey(l));
940
            }
941
            final SQLKey pk = SQLKey.createPrimaryKey(this);
942
            if (pk != null)
943
                indexKey(res, pk);
944
 
945
            this.fieldsGroups = Collections.unmodifiableMap(res);
946
        }
947
        return this.fieldsGroups;
948
    }
949
 
950
    static private final void indexKey(final Map<String, FieldGroup> m, final SQLKey k) {
951
        final FieldGroup group = new FieldGroup(k, null);
952
        for (final String field : k.getFields()) {
953
            final FieldGroup previous = m.put(field, group);
954
            assert previous.getKeyType() == null;
955
        }
956
    }
957
 
17 ilm 958
    public String toString() {
959
        return "/" + this.getName() + "/";
960
    }
961
 
962
    /**
963
     * Return the field named <i>fieldName </i> in this table.
964
     *
965
     * @param fieldName the name of the field.
966
     * @return the matching field, never <code>null</code>.
967
     * @throws IllegalArgumentException if the field is not in this table.
968
     * @see #getFieldRaw(String)
969
     */
65 ilm 970
    @Override
17 ilm 971
    public SQLField getField(String fieldName) {
972
        SQLField res = this.getFieldRaw(fieldName);
19 ilm 973
        if (res == null) {
61 ilm 974
            throw new IllegalArgumentException("unknown field " + fieldName + " in " + this.getName() + ". The table " + this.getName() + " contains the followins fields: " + this.getFieldsName());
19 ilm 975
        }
17 ilm 976
        return res;
977
    }
978
 
979
    /**
980
     * Return the field named <i>fieldName</i> in this table.
981
     *
982
     * @param fieldName the name of the field.
983
     * @return the matching field or <code>null</code> if none exists.
984
     */
985
    public SQLField getFieldRaw(String fieldName) {
61 ilm 986
        return this.fields.get(fieldName);
17 ilm 987
    }
988
 
989
    /**
990
     * Return all the fields in this table.
991
     *
992
     * @return a Set of the fields.
993
     */
994
    public Set<SQLField> getFields() {
995
        return new HashSet<SQLField>(this.fields.values());
996
    }
997
 
132 ilm 998
    /**
999
     * An immutable set of fields.
1000
     *
1001
     * @author Sylvain
1002
     */
1003
    @Immutable
1004
    static public final class VirtualFields {
1005
 
151 ilm 1006
        // must be set first, as they are used by others (e.g. create())
1007
        static public final VirtualFields NONE = new VirtualFields(EnumSet.noneOf(VirtualFieldPartition.class));
1008
        static public final VirtualFields ALL = new VirtualFields(EnumSet.allOf(VirtualFieldPartition.class));
1009
 
132 ilm 1010
        static public final VirtualFields ORDER = new VirtualFields(VirtualFieldPartition.ORDER);
1011
        static public final VirtualFields ARCHIVE = new VirtualFields(VirtualFieldPartition.ARCHIVE);
1012
        static public final VirtualFields METADATA = new VirtualFields(VirtualFieldPartition.METADATA);
1013
        static public final VirtualFields PRIMARY_KEY = new VirtualFields(VirtualFieldPartition.PRIMARY_KEY);
1014
        static public final VirtualFields FOREIGN_KEYS = new VirtualFields(VirtualFieldPartition.FOREIGN_KEYS);
1015
        /**
1016
         * All specific fields of this table without keys.
1017
         */
1018
        static public final VirtualFields LOCAL_CONTENT = new VirtualFields(VirtualFieldPartition.LOCAL_CONTENT);
1019
 
1020
        /**
1021
         * {@link #LOCAL_CONTENT local content fields} with {@link #FOREIGN_KEYS}.
1022
         */
1023
        static public final VirtualFields CONTENT = LOCAL_CONTENT.union(FOREIGN_KEYS);
1024
        /**
1025
         * {@link #CONTENT content fields} with {@link #METADATA}.
1026
         */
1027
        static public final VirtualFields CONTENT_AND_METADATA = CONTENT.union(METADATA);
1028
        /**
1029
         * {@link #PRIMARY_KEY} with {@link #FOREIGN_KEYS}.
1030
         */
1031
        static public final VirtualFields KEYS = PRIMARY_KEY.union(FOREIGN_KEYS);
1032
 
151 ilm 1033
        static private VirtualFields create(final EnumSet<VirtualFieldPartition> set) {
1034
            if (set.isEmpty())
1035
                return NONE;
1036
            else if (set.equals(ALL.set))
1037
                return ALL;
1038
            else
1039
                return new VirtualFields(set);
1040
        }
1041
 
132 ilm 1042
        private final EnumSet<VirtualFieldPartition> set;
1043
 
1044
        // use constants above
1045
        private VirtualFields(final VirtualFieldPartition single) {
1046
            this(EnumSet.of(single));
1047
        }
1048
 
1049
        // private since parameter is not copied
1050
        private VirtualFields(final EnumSet<VirtualFieldPartition> set) {
1051
            if (set == null)
1052
                throw new NullPointerException("Null set");
1053
            this.set = set;
1054
        }
1055
 
151 ilm 1056
        public final boolean contains(VirtualFields other) {
1057
            return this == other || this == ALL || this != NONE && this.set.containsAll(other.set);
1058
        }
1059
 
132 ilm 1060
        public final VirtualFields union(VirtualFields... other) {
151 ilm 1061
            // optimizations
1062
            if (this == ALL || other.length == 0 || other.length == 1 && this.contains(other[0]))
1063
                return this;
1064
            if (other.length == 1 && other[0].contains(this))
1065
                return other[0];
1066
 
132 ilm 1067
            final EnumSet<VirtualFieldPartition> set = this.set.clone();
1068
            for (final VirtualFields o : other)
1069
                set.addAll(o.set);
151 ilm 1070
            return create(set);
132 ilm 1071
        }
1072
 
1073
        public final VirtualFields intersection(VirtualFields... other) {
151 ilm 1074
            // optimizations
1075
            if (this == NONE || other.length == 0 || other.length == 1 && other[0].contains(this))
1076
                return this;
1077
            if (other.length == 1 && this.contains(other[0]))
1078
                return other[0];
1079
 
132 ilm 1080
            final EnumSet<VirtualFieldPartition> set = this.set.clone();
1081
            for (final VirtualFields o : other)
1082
                set.retainAll(o.set);
151 ilm 1083
            return create(set);
132 ilm 1084
        }
1085
 
1086
        public final VirtualFields difference(VirtualFields... other) {
151 ilm 1087
            // optimizations
1088
            if (this == NONE || other.length == 0 || other.length == 1 && Collections.disjoint(this.set, other[0].set))
1089
                return this;
1090
 
132 ilm 1091
            final EnumSet<VirtualFieldPartition> set = this.set.clone();
1092
            for (final VirtualFields o : other)
1093
                set.removeAll(o.set);
151 ilm 1094
            return create(set);
132 ilm 1095
        }
1096
 
1097
        public final VirtualFields complement() {
1098
            // optimizations
1099
            if (this == ALL)
1100
                return NONE;
1101
            else if (this == NONE)
1102
                return ALL;
1103
            return new VirtualFields(EnumSet.complementOf(this.set));
1104
        }
1105
 
1106
        @Override
1107
        public int hashCode() {
1108
            final int prime = 31;
1109
            return prime + this.set.hashCode();
1110
        }
1111
 
1112
        @Override
1113
        public boolean equals(Object obj) {
1114
            if (this == obj)
1115
                return true;
1116
            if (obj == null)
1117
                return false;
1118
            if (getClass() != obj.getClass())
1119
                return false;
1120
            final VirtualFields other = (VirtualFields) obj;
1121
            return this.set.equals(other.set);
1122
        }
151 ilm 1123
 
1124
        @Override
1125
        public String toString() {
1126
            return this.getClass().getSimpleName() + " " + this.set;
1127
        }
132 ilm 1128
    }
1129
 
1130
    /**
1131
     * A partition of the fields (except that some can be empty). Being a partition allow to use
1132
     * {@link EnumSet#complementOf(EnumSet)}.
1133
     *
1134
     * @author Sylvain
1135
     * @see VirtualFields
1136
     */
1137
    static public enum VirtualFieldPartition {
83 ilm 1138
        ORDER {
1139
            @Override
132 ilm 1140
            Set<SQLField> getFields(SQLTable t) {
83 ilm 1141
                final SQLField orderField = t.getOrderField();
1142
                return orderField == null ? Collections.<SQLField> emptySet() : Collections.singleton(orderField);
1143
            }
1144
        },
1145
        ARCHIVE {
1146
            @Override
1147
            Set<SQLField> getFields(SQLTable t) {
1148
                final SQLField f = t.getArchiveField();
1149
                return f == null ? Collections.<SQLField> emptySet() : Collections.singleton(f);
1150
            }
1151
        },
1152
        METADATA {
1153
            @Override
1154
            Set<SQLField> getFields(SQLTable t) {
1155
                final Set<SQLField> res = new HashSet<SQLField>(4);
1156
                res.add(t.getCreationDateField());
1157
                res.add(t.getCreationUserField());
1158
                res.add(t.getModifDateField());
1159
                res.add(t.getModifUserField());
1160
                res.remove(null);
1161
                return res;
1162
            }
1163
        },
1164
        PRIMARY_KEY {
1165
            @Override
1166
            Set<SQLField> getFields(SQLTable t) {
1167
                return t.getPrimaryKeys();
1168
            }
1169
        },
1170
        FOREIGN_KEYS {
1171
            @Override
132 ilm 1172
            Set<SQLField> getFields(SQLTable t) {
1173
                return DatabaseGraph.getColsUnion(t.getForeignLinks());
83 ilm 1174
            }
93 ilm 1175
        },
1176
        /**
1177
         * {@link #CONTENT content fields} without {@link #FOREIGN_KEYS}
1178
         */
1179
        LOCAL_CONTENT {
1180
            @Override
132 ilm 1181
            Set<SQLField> getFields(SQLTable t) {
1182
                throw new IllegalStateException(this + " is any field not in another set");
93 ilm 1183
            }
83 ilm 1184
        };
1185
 
1186
        abstract Set<SQLField> getFields(final SQLTable t);
1187
    }
1188
 
132 ilm 1189
    public final Set<SQLField> getFields(final VirtualFields vfs) {
1190
        return getFields(vfs.set);
83 ilm 1191
    }
1192
 
132 ilm 1193
    final Set<SQLField> getFields(final Set<VirtualFieldPartition> vf) {
1194
        if (vf.isEmpty())
1195
            return Collections.emptySet();
144 ilm 1196
        else if (vf.equals(VirtualFields.ALL.set))
1197
            return Collections.unmodifiableSet(this.getFields());
83 ilm 1198
 
132 ilm 1199
        final Set<SQLField> res;
1200
        // LOCAL_CONTENT is just ALL minus every other set
1201
        if (!vf.contains(VirtualFieldPartition.LOCAL_CONTENT)) {
1202
            res = new HashSet<SQLField>();
1203
            for (final VirtualFieldPartition v : vf) {
1204
                res.addAll(v.getFields(this));
83 ilm 1205
            }
132 ilm 1206
        } else {
1207
            res = this.getFields();
1208
            // don't use EnumSet.complementOf(EnumSet.copyOf()) as it makes multiple copies
1209
            for (final VirtualFieldPartition v : VirtualFieldPartition.values()) {
1210
                if (!vf.contains(v)) {
1211
                    res.removeAll(v.getFields(this));
1212
                }
1213
            }
83 ilm 1214
        }
142 ilm 1215
        return Collections.unmodifiableSet(res);
83 ilm 1216
    }
1217
 
132 ilm 1218
    public final Set<String> getFieldsNames(final VirtualFields vfs) {
144 ilm 1219
        if (vfs.equals(VirtualFields.ALL))
1220
            return this.getFieldsName();
132 ilm 1221
        final Set<String> res = new HashSet<String>();
1222
        for (final SQLField f : this.getFields(vfs)) {
1223
            res.add(f.getName());
83 ilm 1224
        }
1225
        return res;
1226
    }
1227
 
142 ilm 1228
    public final List<SQLField> getFields(final Collection<String> names) {
1229
        return this.getFields(names, new ArrayList<SQLField>());
1230
    }
1231
 
1232
    public final <T extends Collection<SQLField>> T getFields(final Collection<String> names, final T res) {
1233
        return this.getFields(names, res, true);
1234
    }
1235
 
1236
    public final <T extends Collection<SQLField>> T getFields(final Collection<String> names, final T res, final boolean required) {
1237
        for (final String name : names) {
1238
            final SQLField f = required ? this.getField(name) : this.getFieldRaw(name);
1239
            if (f != null)
1240
                res.add(f);
1241
        }
1242
        return res;
1243
    }
1244
 
17 ilm 1245
    /**
1246
     * Retourne les champs du contenu de cette table. C'est à dire ni la clef primaire, ni les
1247
     * champs d'archive et d'ordre.
1248
     *
1249
     * @return les champs du contenu de cette table.
132 ilm 1250
     * @see VirtualFields#CONTENT
17 ilm 1251
     */
1252
    public Set<SQLField> getContentFields() {
1253
        return this.getContentFields(false);
1254
    }
1255
 
61 ilm 1256
    public synchronized Set<SQLField> getContentFields(final boolean includeMetadata) {
132 ilm 1257
        return this.getFields(includeMetadata ? VirtualFields.CONTENT_AND_METADATA : VirtualFields.CONTENT);
17 ilm 1258
    }
1259
 
1260
    /**
1261
     * Retourne les champs du contenu local de cette table. C'est à dire uniquement les champs du
1262
     * contenu qui ne sont pas des clefs externes.
1263
     *
1264
     * @return les champs du contenu local de cette table.
1265
     * @see #getContentFields()
1266
     */
61 ilm 1267
    public synchronized Set<SQLField> getLocalContentFields() {
132 ilm 1268
        return this.getFields(VirtualFields.LOCAL_CONTENT);
17 ilm 1269
    }
1270
 
1271
    /**
1272
     * Return the names of all the fields.
1273
     *
1274
     * @return the names of all the fields.
1275
     */
1276
    public Set<String> getFieldsName() {
1277
        return this.fields.keySet();
1278
    }
1279
 
1280
    /**
1281
     * Return all the fields in this table. The order is the same across reboot.
1282
     *
1283
     * @return a List of the fields.
1284
     */
1285
    public List<SQLField> getOrderedFields() {
1286
        return new ArrayList<SQLField>(this.fields.values());
1287
    }
1288
 
1289
    @Override
61 ilm 1290
    public Map<String, SQLField> getChildrenMap() {
1291
        return this.fields.getImmutable();
17 ilm 1292
    }
1293
 
1294
    public final SQLTable getTable(String name) {
1295
        return this.getDesc(name, SQLTable.class);
1296
    }
1297
 
1298
    /**
1299
     * Retourne le nombre total de lignes contenues dans cette table.
1300
     *
1301
     * @return le nombre de lignes de cette table.
1302
     */
1303
    public int getRowCount() {
67 ilm 1304
        return this.getRowCount(true);
1305
    }
1306
 
1307
    public int getRowCount(final boolean includeUndefined) {
83 ilm 1308
        return this.getRowCount(includeUndefined, ArchiveMode.BOTH);
1309
    }
1310
 
1311
    public int getRowCount(final boolean includeUndefined, final ArchiveMode archiveMode) {
67 ilm 1312
        final SQLSelect sel = new SQLSelect(true).addSelectFunctionStar("count").addFrom(this);
1313
        sel.setExcludeUndefined(!includeUndefined);
83 ilm 1314
        sel.setArchivedPolicy(archiveMode);
17 ilm 1315
        final Number count = (Number) this.getBase().getDataSource().execute(sel.asString(), new IResultSetHandler(SQLDataSource.SCALAR_HANDLER, false));
1316
        return count.intValue();
1317
    }
1318
 
1319
    /**
1320
     * The maximum value of the order field.
1321
     *
1322
     * @return the maximum value of the order field, or -1 if this table is empty.
1323
     */
1324
    public BigDecimal getMaxOrder() {
1325
        return this.getMaxOrder(true);
1326
    }
1327
 
83 ilm 1328
    public BigDecimal getMaxOrder(Boolean useCache) {
1329
        final SQLField orderField = this.getOrderField();
1330
        if (orderField == null)
17 ilm 1331
            throw new IllegalStateException(this + " is not ordered");
83 ilm 1332
        final SQLSelect sel = new SQLSelect(true).addSelect(orderField, "max");
17 ilm 1333
        try {
1334
            final BigDecimal maxOrder = (BigDecimal) this.getBase().getDataSource().execute(sel.asString(), new IResultSetHandler(SQLDataSource.SCALAR_HANDLER, useCache));
1335
            return maxOrder == null ? BigDecimal.ONE.negate() : maxOrder;
1336
        } catch (ClassCastException e) {
144 ilm 1337
            throw new IllegalStateException(orderField.getSQLName() + " must be " + SQLSyntax.get(this).getOrderDefinition(false), e);
17 ilm 1338
        }
1339
    }
1340
 
1341
    /**
1342
     * Retourne la ligne correspondant à l'ID passé.
1343
     *
1344
     * @param ID l'identifiant de la ligne à retourner.
1345
     * @return une ligne existant dans la base sinon <code>null</code>.
1346
     * @see #getValidRow(int)
1347
     */
1348
    public SQLRow getRow(int ID) {
1349
        SQLRow row = this.getUncheckedRow(ID);
1350
        return row.exists() ? row : null;
1351
    }
1352
 
1353
    /**
1354
     * Retourne une la ligne demandée sans faire aucune vérification.
1355
     *
1356
     * @param ID l'identifiant de la ligne à retourner.
1357
     * @return la ligne demandée, jamais <code>null</code>.
1358
     */
1359
    private SQLRow getUncheckedRow(int ID) {
1360
        return new SQLRow(this, ID);
1361
    }
1362
 
1363
    /**
1364
     * Retourne la ligne valide correspondant à l'ID passé.
1365
     *
1366
     * @param ID l'identifiant de la ligne à retourner.
1367
     * @return une ligne existante et non archivée dans la base sinon <code>null</code>.
1368
     * @see SQLRow#isValid()
1369
     */
1370
    public SQLRow getValidRow(int ID) {
1371
        SQLRow row = this.getRow(ID);
1372
        return row.isValid() ? row : null;
1373
    }
1374
 
1375
    /**
1376
     * Vérifie la validité de cet ID. C'est à dire qu'il existe une ligne non archivée avec cet ID,
1377
     * dans cette table.
1378
     *
1379
     * @param ID l'identifiant.
1380
     * @return <code>null</code> si l'ID est valide, sinon une SQLRow qui est soit inexistante, soit
1381
     *         archivée.
1382
     */
1383
    public SQLRow checkValidity(int ID) {
144 ilm 1384
        // don't bother locking if we're outside a transaction
1385
        final SQLRow row = SQLRow.createFromSelect(this, VirtualFields.PRIMARY_KEY.union(VirtualFields.ARCHIVE), ID, LockStrength.NONE);
17 ilm 1386
        // l'inverse de getValidRow()
1387
        return row.isValid() ? null : row;
1388
    }
1389
 
1390
    /**
1391
     * Vérifie cette table est intègre. C'est à dire que toutes ses clefs externes pointent sur des
1392
     * lignes existantes et non effacées. Cette méthode retourne une liste constituée de triplet :
1393
     * SQLRow (la ligne incohérente), SQLField (le champ incohérent), SQLRow (la ligne invalide de
1394
     * la table étrangère).
1395
     *
61 ilm 1396
     * @return a list of inconsistencies or <code>null</code> if this table is not rowable.
17 ilm 1397
     */
61 ilm 1398
    public List<Tuple3<SQLRow, SQLField, SQLRow>> checkIntegrity() {
1399
        final SQLField pk;
1400
        final Set<SQLField> fks;
1401
        synchronized (this) {
1402
            if (!this.isRowable())
1403
                return null;
1404
            pk = this.getKey();
1405
            fks = this.getForeignKeys();
1406
        }
17 ilm 1407
 
61 ilm 1408
        final List<Tuple3<SQLRow, SQLField, SQLRow>> inconsistencies = new ArrayList<Tuple3<SQLRow, SQLField, SQLRow>>();
17 ilm 1409
        // si on a pas de relation externe, c'est OK
61 ilm 1410
        if (!fks.isEmpty()) {
80 ilm 1411
            final SQLSelect sel = new SQLSelect();
17 ilm 1412
            // on ne vérifie pas les lignes archivées mais l'indéfinie oui.
1413
            sel.setExcludeUndefined(false);
61 ilm 1414
            sel.addSelect(pk);
1415
            sel.addAllSelect(fks);
17 ilm 1416
            this.getBase().getDataSource().execute(sel.asString(), new ResultSetHandler() {
1417
                public Object handle(ResultSet rs) throws SQLException {
1418
                    while (rs.next()) {
61 ilm 1419
                        for (final SQLField fk : fks) {
1420
                            final SQLRow pb = SQLTable.this.checkValidity(fk.getName(), rs.getInt(fk.getFullName()));
17 ilm 1421
                            if (pb != null) {
61 ilm 1422
                                final SQLRow row = SQLTable.this.getRow(rs.getInt(pk.getFullName()));
1423
                                inconsistencies.add(Tuple3.create(row, fk, pb));
17 ilm 1424
                            }
1425
                        }
1426
                    }
1427
                    // on s'en sert pas
1428
                    return null;
1429
                }
1430
            });
1431
        }
1432
 
1433
        return inconsistencies;
1434
    }
1435
 
1436
    /**
1437
     * Vérifie que l'on peut affecter <code>foreignID</code> au champ <code>foreignKey</code> de
1438
     * cette table. C'est à dire vérifie que la table sur laquelle pointe <code>foreignKey</code>
1439
     * contient bien une ligne d'ID <code>foreignID</code> et de plus qu'elle n'a pas été archivée.
1440
     *
1441
     * @param foreignKey le nom du champ.
1442
     * @param foreignID l'ID que l'on souhaite tester.
1443
     * @return une SQLRow décrivant l'incohérence ou <code>null</code> sinon.
1444
     * @throws IllegalArgumentException si le champ passé n'est pas une clef étrangère.
1445
     * @see #checkValidity(int)
1446
     */
1447
    public SQLRow checkValidity(String foreignKey, int foreignID) {
1448
        final SQLField fk = this.getField(foreignKey);
1449
        final SQLTable foreignTable = this.getDBSystemRoot().getGraph().getForeignTable(fk);
1450
        if (foreignTable == null)
1451
            throw new IllegalArgumentException("Impossible de tester '" + foreignKey + "' avec " + foreignID + " dans " + this + ". Ce n'est pas une clef étrangère.");
1452
        return foreignTable.checkValidity(foreignID);
1453
    }
1454
 
1455
    public SQLRow checkValidity(String foreignKey, Number foreignID) {
1456
        // NULL is valid
1457
        if (foreignID == null)
1458
            return null;
1459
        else
1460
            return this.checkValidity(foreignKey, foreignID.intValue());
1461
    }
1462
 
1463
    public boolean isOrdered() {
1464
        return this.getOrderField() != null;
1465
    }
1466
 
1467
    public SQLField getOrderField() {
1468
        return this.getFieldRaw(orderField);
1469
    }
1470
 
19 ilm 1471
    /**
1472
     * The number of fractional digits of the order field.
1473
     *
1474
     * @return the number of fractional digits of the order field.
1475
     */
1476
    public final int getOrderDecimalDigits() {
1477
        return this.getOrderField().getType().getDecimalDigits().intValue();
1478
    }
1479
 
1480
    public final BigDecimal getOrderULP() {
1481
        return BigDecimal.ONE.scaleByPowerOfTen(-this.getOrderDecimalDigits());
1482
    }
1483
 
17 ilm 1484
    public boolean isArchivable() {
1485
        return this.getArchiveField() != null;
1486
    }
1487
 
1488
    public SQLField getArchiveField() {
1489
        return this.getFieldRaw(archiveField);
1490
    }
1491
 
1492
    public SQLField getCreationDateField() {
1493
        return this.getFieldRaw("CREATION_DATE");
1494
    }
1495
 
1496
    public SQLField getCreationUserField() {
1497
        return this.getFieldRaw("ID_USER_COMMON_CREATE");
1498
    }
1499
 
1500
    public SQLField getModifDateField() {
1501
        return this.getFieldRaw("MODIFICATION_DATE");
1502
    }
1503
 
1504
    public SQLField getModifUserField() {
1505
        return this.getFieldRaw("ID_USER_COMMON_MODIFY");
1506
    }
1507
 
1508
    /**
1509
     * The id of this table which means empty. Tables that aren't rowable or which use NULL to
1510
     * signify empty have no UNDEFINED_ID.
1511
     *
1512
     * @return the empty id or {@link SQLRow#NONEXISTANT_ID} if this table has no UNDEFINED_ID.
1513
     */
1514
    public final int getUndefinedID() {
63 ilm 1515
        return this.getUndefinedID(false).intValue();
1516
    }
1517
 
67 ilm 1518
    // if false getUndefinedID() might contact the DB
1519
    synchronized final boolean undefinedIDKnown() {
1520
        return this.undefinedID != null;
1521
    }
1522
 
1523
    /*
1524
     * No longer save the undefined IDs. We mustn't search undefined IDs when loading structure
1525
     * since the undefined rows might not yet be inserted. When getUndefinedID() was called, we used
1526
     * to save the ID alongside the table structure with the new structure version. Which is wrong
1527
     * since we haven't refreshed the table structure. One solution would be to create an undefined
1528
     * ID version : when loading, as with the structure, we now have to check the saved version
1529
     * against the one in the metadata table, but since FWK_UNDEFINED_ID is small and already
1530
     * cached, we might as well simplify and forego the version altogether.
1531
     */
1532
 
63 ilm 1533
    private final Integer getUndefinedID(final boolean internal) {
61 ilm 1534
        Integer res = null;
1535
        synchronized (this) {
1536
            if (this.undefinedID != null)
1537
                res = this.undefinedID;
1538
        }
1539
        if (res == null) {
63 ilm 1540
            if (!internal && this.getSchema().isFetchAllUndefinedIDs()) {
61 ilm 1541
                // init all undefined, MAYBE one request with UNION ALL
1542
                for (final SQLTable sibling : this.getSchema().getTables()) {
67 ilm 1543
                    Integer siblingRes = sibling.getUndefinedID(true);
63 ilm 1544
                    assert siblingRes != null;
1545
                    if (sibling == this)
1546
                        res = siblingRes;
17 ilm 1547
                }
61 ilm 1548
            } else {
1549
                res = this.fetchUndefID();
1550
                synchronized (this) {
1551
                    this.undefinedID = res;
1552
                }
17 ilm 1553
            }
1554
        }
67 ilm 1555
        assert this.undefinedIDKnown();
63 ilm 1556
        return res;
17 ilm 1557
    }
1558
 
21 ilm 1559
    public final Number getUndefinedIDNumber() {
1560
        final int res = this.getUndefinedID();
1561
        if (res == SQLRow.NONEXISTANT_ID)
1562
            return null;
1563
        else
1564
            return res;
1565
    }
1566
 
17 ilm 1567
    // static
1568
 
1569
    static private final String orderField = "ORDRE";
1570
    static private final String archiveField = "ARCHIVE";
1571
 
1572
    // /////// ******** OLD CODE ********
1573
 
1574
    /*
1575
     * Gestion des événements
1576
     */
1577
 
1578
    public void addTableModifiedListener(SQLTableModifiedListener l) {
73 ilm 1579
        this.addTableModifiedListener(new ListenerAndConfig(l, AFTER_TX_DEFAULT));
1580
    }
1581
 
1582
    public void addTableModifiedListener(ListenerAndConfig l) {
25 ilm 1583
        this.addTableModifiedListener(l, false);
1584
    }
1585
 
73 ilm 1586
    public void addPremierTableModifiedListener(ListenerAndConfig l) {
25 ilm 1587
        this.addTableModifiedListener(l, true);
1588
    }
1589
 
73 ilm 1590
    private void addTableModifiedListener(ListenerAndConfig l, final boolean before) {
63 ilm 1591
        synchronized (this.listenersMutex) {
73 ilm 1592
            final List<ListenerAndConfig> newListeners = new ArrayList<ListenerAndConfig>(this.tableModifiedListeners.size() + 1);
25 ilm 1593
            if (before)
1594
                newListeners.add(l);
1595
            newListeners.addAll(this.tableModifiedListeners);
1596
            if (!before)
1597
                newListeners.add(l);
17 ilm 1598
            this.tableModifiedListeners = Collections.unmodifiableList(newListeners);
1599
        }
1600
    }
1601
 
1602
    public void removeTableModifiedListener(SQLTableModifiedListener l) {
73 ilm 1603
        this.removeTableModifiedListener(new ListenerAndConfig(l, AFTER_TX_DEFAULT));
1604
    }
1605
 
1606
    public void removeTableModifiedListener(ListenerAndConfig l) {
63 ilm 1607
        synchronized (this.listenersMutex) {
73 ilm 1608
            final List<ListenerAndConfig> newListeners = new ArrayList<ListenerAndConfig>(this.tableModifiedListeners);
17 ilm 1609
            if (newListeners.remove(l))
1610
                this.tableModifiedListeners = Collections.unmodifiableList(newListeners);
1611
        }
1612
    }
1613
 
25 ilm 1614
    private static final class BridgeListener implements SQLTableModifiedListener {
1615
 
1616
        private final SQLTableListener l;
1617
 
1618
        private BridgeListener(SQLTableListener l) {
1619
            super();
1620
            this.l = l;
1621
        }
1622
 
1623
        @Override
1624
        public void tableModified(SQLTableEvent evt) {
1625
            final Mode mode = evt.getMode();
1626
            if (mode == Mode.ROW_ADDED)
1627
                this.l.rowAdded(evt.getTable(), evt.getId());
1628
            else if (mode == Mode.ROW_UPDATED)
1629
                this.l.rowModified(evt.getTable(), evt.getId());
1630
            else if (mode == Mode.ROW_DELETED)
1631
                this.l.rowDeleted(evt.getTable(), evt.getId());
1632
        }
1633
 
1634
        @Override
1635
        public int hashCode() {
1636
            return this.l.hashCode();
1637
        }
1638
 
1639
        @Override
1640
        public boolean equals(Object obj) {
1641
            return obj instanceof BridgeListener && this.l.equals(((BridgeListener) obj).l);
1642
        }
1643
    }
1644
 
17 ilm 1645
    /**
1646
     * Ajoute un listener sur cette table.
1647
     *
1648
     * @param l the listener.
1649
     * @deprecated use {@link #addTableModifiedListener(SQLTableModifiedListener)}
1650
     */
1651
    public void addTableListener(SQLTableListener l) {
25 ilm 1652
        this.addTableModifiedListener(new BridgeListener(l));
17 ilm 1653
    }
1654
 
1655
    public void removeTableListener(SQLTableListener l) {
25 ilm 1656
        this.removeTableModifiedListener(new BridgeListener(l));
17 ilm 1657
    }
1658
 
1659
    /**
1660
     * Previent tous les listeners de la table qu'il y a eu une modification ou ajout si modif de
1661
     * d'une ligne particuliere.
1662
     *
1663
     * @param id -1 signifie tout est modifié.
1664
     */
1665
    public void fireTableModified(final int id) {
1666
        this.fire(Mode.ROW_UPDATED, id);
1667
    }
1668
 
1669
    public void fireRowAdded(final int id) {
1670
        this.fire(Mode.ROW_ADDED, id);
1671
    }
1672
 
1673
    public void fireRowDeleted(final int id) {
1674
        this.fire(Mode.ROW_DELETED, id);
1675
    }
1676
 
1677
    public void fireTableModified(final int id, Collection<String> fields) {
1678
        this.fire(new SQLTableEvent(this, id, Mode.ROW_UPDATED, fields));
1679
    }
1680
 
1681
    private void fire(final Mode mode, final int id) {
1682
        this.fire(new SQLTableEvent(this, id, mode, null));
1683
    }
1684
 
1685
    public final void fire(SQLTableEvent evt) {
25 ilm 1686
        this.fireTableModified(evt);
1687
    }
1688
 
73 ilm 1689
    // the listeners and the event that was notified to them
1690
    static private class FireState extends Tuple2<List<ListenerAndConfig>, SQLTableEvent> {
1691
        public FireState(final List<ListenerAndConfig> listeners, final SQLTableEvent evt) {
1692
            super(listeners, evt);
1693
        }
1694
 
1695
        private DispatchingState createDispatchingState(final Boolean callbackAfterTxListeners, final boolean oppositeEvt) {
1696
            final List<SQLTableModifiedListener> listeners = new LinkedList<SQLTableModifiedListener>();
1697
            for (final ListenerAndConfig l : get0()) {
132 ilm 1698
                if (callbackAfterTxListeners == null || l.callOnlyAfterTx() == null || callbackAfterTxListeners == l.callOnlyAfterTx())
73 ilm 1699
                    listeners.add(l.getListener());
1700
            }
1701
            return new DispatchingState(listeners, oppositeEvt ? get1().opposite() : get1());
1702
        }
1703
    }
1704
 
1705
    static private class DispatchingState extends Tuple2<Iterator<SQLTableModifiedListener>, SQLTableEvent> {
1706
        public DispatchingState(final List<SQLTableModifiedListener> listeners, final SQLTableEvent evt) {
1707
            super(listeners.iterator(), evt);
1708
        }
1709
    }
1710
 
1711
    static private final ThreadLocal<LinkedList<DispatchingState>> events = new ThreadLocal<LinkedList<DispatchingState>>() {
25 ilm 1712
        @Override
73 ilm 1713
        protected LinkedList<DispatchingState> initialValue() {
1714
            return new LinkedList<DispatchingState>();
25 ilm 1715
        }
1716
    };
1717
 
1718
    // allow to maintain the dispatching of events in order when a listener itself fires an event
73 ilm 1719
    static private void fireTableModified(DispatchingState newTuple) {
1720
        final LinkedList<DispatchingState> linkedList = events.get();
25 ilm 1721
        // add new event
1722
        linkedList.addLast(newTuple);
1723
        // process all pending events
73 ilm 1724
        DispatchingState currentTuple;
25 ilm 1725
        while ((currentTuple = linkedList.peekFirst()) != null) {
1726
            final Iterator<SQLTableModifiedListener> iter = currentTuple.get0();
1727
            final SQLTableEvent currentEvt = currentTuple.get1();
1728
            while (iter.hasNext()) {
1729
                final SQLTableModifiedListener l = iter.next();
1730
                l.tableModified(currentEvt);
17 ilm 1731
            }
25 ilm 1732
            // not removeFirst() since the item might have been already removed
1733
            linkedList.pollFirst();
17 ilm 1734
        }
1735
    }
1736
 
1737
    private void fireTableModified(final SQLTableEvent evt) {
132 ilm 1738
        if (evt.getTable() != this)
1739
            throw new IllegalArgumentException("Wrong table : " + this + " ; " + evt);
73 ilm 1740
        final FireState fireState;
132 ilm 1741
        final TransactionPoint point = evt.getTransactionPoint();
73 ilm 1742
        final Boolean callbackAfterTxListeners;
63 ilm 1743
        synchronized (this.listenersMutex) {
73 ilm 1744
            // no need to copy since this.tableModifiedListeners is immutable
1745
            fireState = new FireState(this.tableModifiedListeners, evt);
1746
            if (point == null) {
1747
                // call back every listener
1748
                callbackAfterTxListeners = null;
132 ilm 1749
            } else if (point.isActive()) {
1750
                addFireStates(point, Collections.singleton(fireState));
1751
                callbackAfterTxListeners = false;
1752
                // to free DB resources, it is allowed to fire events after the transaction ended
1753
            } else if (!point.wasCommitted()) {
1754
                throw new IllegalStateException("Fire after an aborted transaction point");
1755
            } else if (point.getSavePoint() != null) {
1756
                addFireStates(point, Collections.singleton(fireState));
1757
                callbackAfterTxListeners = false;
73 ilm 1758
            } else {
132 ilm 1759
                callbackAfterTxListeners = null;
73 ilm 1760
            }
17 ilm 1761
        }
73 ilm 1762
        fireTableModified(fireState.createDispatchingState(callbackAfterTxListeners, false));
17 ilm 1763
    }
1764
 
132 ilm 1765
    private void addFireStates(TransactionPoint point, final Collection<FireState> fireStates) {
1766
        assert Thread.holdsLock(this.listenersMutex) : "Unsafe to access this.transactions";
1767
        // if multiple save points are released before firing, we must go back to the still active
1768
        // point
1769
        while (!point.isActive())
1770
            point = point.getPrevious();
1771
        if (!this.transactions.containsKey(point))
1772
            point.addListener(this.txListener);
1773
        this.transactions.addAll(point, fireStates);
1774
    }
1775
 
73 ilm 1776
    // a transaction was committed or aborted, we must either notify listeners that wanted the
1777
    // transaction to commit, or re-notify the listeners that didn't want to wait
132 ilm 1778
    protected void fireFromTransaction(final TransactionPoint point) {
1779
        final boolean committed = point.wasCommitted();
1780
        // if it's a released savePoint, add all our states to the previous point (and thus don't
1781
        // fire now)
1782
        final boolean releasedSavePoint = committed && point.getSavePoint() != null;
73 ilm 1783
        final List<FireState> states;
1784
        synchronized (this.listenersMutex) {
1785
            states = this.transactions.remove(point);
132 ilm 1786
            if (releasedSavePoint) {
1787
                this.addFireStates(point, states);
1788
            }
73 ilm 1789
        }
132 ilm 1790
        if (!releasedSavePoint) {
1791
            final ListIterator<FireState> iter = CollectionUtils.getListIterator(states, !committed);
1792
            while (iter.hasNext()) {
1793
                final FireState state = iter.next();
1794
                fireTableModified(state.createDispatchingState(committed, !committed));
1795
            }
73 ilm 1796
        }
1797
    }
1798
 
61 ilm 1799
    public synchronized String toXML() {
17 ilm 1800
        final StringBuilder sb = new StringBuilder(16000);
1801
        sb.append("<table name=\"");
142 ilm 1802
        sb.append(OUTPUTTER.escapeAttributeEntities(this.getName()));
17 ilm 1803
        sb.append("\"");
1804
 
1805
        final String schemaName = this.getSchema().getName();
1806
        if (schemaName != null) {
1807
            sb.append(" schema=\"");
142 ilm 1808
            sb.append(OUTPUTTER.escapeAttributeEntities(schemaName));
17 ilm 1809
            sb.append('"');
1810
        }
1811
 
67 ilm 1812
        SQLSchema.appendVersionAttr(this.version, sb);
17 ilm 1813
 
1814
        if (getType() != null) {
1815
            sb.append(" type=\"");
142 ilm 1816
            sb.append(OUTPUTTER.escapeAttributeEntities(getType()));
17 ilm 1817
            sb.append('"');
1818
        }
1819
 
1820
        sb.append(">\n");
1821
 
1822
        if (this.getComment() != null) {
1823
            sb.append("<comment>");
142 ilm 1824
            sb.append(OUTPUTTER.escapeElementEntities(this.getComment()));
17 ilm 1825
            sb.append("</comment>\n");
1826
        }
65 ilm 1827
        for (SQLField field : this.fields.values()) {
17 ilm 1828
            sb.append(field.toXML());
1829
        }
1830
        sb.append("<primary>\n");
1831
        for (SQLField element : this.primaryKeys) {
1832
            sb.append(element.toXML());
1833
        }
1834
        sb.append("</primary>\n");
1835
        // avoid writing unneeded chars
1836
        if (this.triggers.size() > 0) {
1837
            sb.append("<triggers>\n");
1838
            for (Trigger t : this.triggers.values()) {
1839
                sb.append(t.toXML());
1840
            }
1841
            sb.append("</triggers>\n");
1842
        }
1843
        if (this.constraints != null) {
1844
            sb.append("<constraints>\n");
1845
            for (Constraint t : this.constraints) {
1846
                sb.append(t.toXML());
1847
            }
1848
            sb.append("</constraints>\n");
1849
        }
1850
        sb.append("</table>");
1851
        return sb.toString();
1852
    }
1853
 
25 ilm 1854
    @Override
1855
    public SQLTableModifiedListener createTableListener(final SQLDataListener l) {
1856
        return new SQLTableModifiedListener() {
1857
            @Override
1858
            public void tableModified(SQLTableEvent evt) {
132 ilm 1859
                l.dataChanged(evt);
17 ilm 1860
            }
1861
        };
1862
    }
1863
 
65 ilm 1864
    @Override
17 ilm 1865
    public SQLTable getTable() {
1866
        return this;
1867
    }
1868
 
65 ilm 1869
    @Override
1870
    public String getAlias() {
1871
        return getName();
1872
    }
1873
 
1874
    @Override
1875
    public String getSQL() {
93 ilm 1876
        // always use fullname, otherwise must check the datasource's
1877
        // default schema
65 ilm 1878
        return getSQLName().quote();
1879
    }
1880
 
17 ilm 1881
    public boolean equalsDesc(SQLTable o) {
1882
        return this.equalsDesc(o, true) == null;
1883
    }
1884
 
1885
    /**
1886
     * Compare this table and its descendants. This do not compare undefinedID as it isn't part of
1887
     * the structure per se.
1888
     *
1889
     * @param o the table to compare.
1890
     * @param compareName whether to also compare the name, useful for comparing 2 tables in the
1891
     *        same schema.
1892
     * @return <code>null</code> if attributes and children of this and <code>o</code> are equals,
1893
     *         otherwise a String explaining the differences.
1894
     */
1895
    public String equalsDesc(SQLTable o, boolean compareName) {
1896
        return this.equalsDesc(o, null, compareName);
1897
    }
1898
 
61 ilm 1899
    // ATTN otherSystem can be null, meaning compare exactly (even if the system of this table and
1900
    // the system of the other table do not support the same features and thus tables cannot be
1901
    // equal)
1902
    // if otherSystem isn't null, then this method is more lenient and return true if the two tables
1903
    // are the closest possible. NOTE that otherSystem is not required to be the system of the other
1904
    // table, it might be something else if the other table was loaded into a system different than
1905
    // the one which created the dump.
1906
    public synchronized String equalsDesc(SQLTable o, SQLSystem otherSystem, boolean compareName) {
17 ilm 1907
        if (o == null)
1908
            return "other table is null";
1909
        final boolean name = !compareName || this.getName().equals(o.getName());
1910
        if (!name)
1911
            return "name unequal : " + this.getName() + " " + o.getName();
1912
        // TODO triggers, but wait for the dumping of functions
1913
        // which mean wait for psql 8.4 pg_get_functiondef()
1914
        // if (this.getServer().getSQLSystem() == o.getServer().getSQLSystem()) {
1915
        // if (!this.getTriggers().equals(o.getTriggers()))
1916
        // return "triggers unequal : " + this.getTriggers() + " " + o.getTriggers();
1917
        // } else {
1918
        // if (!this.getTriggers().keySet().equals(o.getTriggers().keySet()))
1919
        // return "triggers names unequal : " + this.getTriggers() + " " + o.getTriggers();
1920
        // }
1921
        final boolean checkComment = otherSystem == null || this.getServer().getSQLSystem().isTablesCommentSupported() && otherSystem.isTablesCommentSupported();
1922
        if (checkComment && !CompareUtils.equals(this.getComment(), o.getComment()))
132 ilm 1923
            return "comment unequal : " + SQLBase.quoteStringStd(this.getComment()) + " != " + SQLBase.quoteStringStd(o.getComment());
17 ilm 1924
        return this.equalsChildren(o, otherSystem);
1925
    }
1926
 
61 ilm 1927
    private synchronized String equalsChildren(SQLTable o, SQLSystem otherSystem) {
17 ilm 1928
        if (!this.getChildrenNames().equals(o.getChildrenNames()))
1929
            return "fields differences: " + this.getChildrenNames() + "\n" + o.getChildrenNames();
1930
 
1931
        final String noLink = equalsChildrenNoLink(o, otherSystem);
1932
        if (noLink != null)
1933
            return noLink;
1934
 
1935
        // foreign keys
132 ilm 1936
        final Set<Link> thisLinks = this.getForeignLinks();
1937
        final Set<Link> oLinks = o.getForeignLinks();
17 ilm 1938
        if (thisLinks.size() != oLinks.size())
1939
            return "different number of foreign keys " + thisLinks + " != " + oLinks;
132 ilm 1940
        final SQLSystem thisSystem = this.getServer().getSQLSystem();
17 ilm 1941
        for (final Link l : thisLinks) {
1942
            final Link ol = o.getDBSystemRoot().getGraph().getForeignLink(o, l.getCols());
1943
            if (ol == null)
1944
                return "no foreign key for " + l.getLabel();
1945
            final SQLName thisPath = l.getTarget().getContextualSQLName(this);
1946
            final SQLName oPath = ol.getTarget().getContextualSQLName(o);
1947
            if (thisPath.getItemCount() != oPath.getItemCount())
1948
                return "unequal path size : " + thisPath + " != " + oPath;
1949
            if (!thisPath.getName().equals(oPath.getName()))
1950
                return "unequal referenced table name : " + thisPath.getName() + " != " + oPath.getName();
61 ilm 1951
            if (!getRule(l.getUpdateRule(), thisSystem, otherSystem).equals(getRule(ol.getUpdateRule(), thisSystem, otherSystem)))
57 ilm 1952
                return "unequal update rule for " + l + ": " + l.getUpdateRule() + " != " + ol.getUpdateRule();
61 ilm 1953
            if (!getRule(l.getDeleteRule(), thisSystem, otherSystem).equals(getRule(ol.getDeleteRule(), thisSystem, otherSystem)))
57 ilm 1954
                return "unequal delete rule for " + l + ": " + l.getDeleteRule() + " != " + ol.getDeleteRule();
17 ilm 1955
        }
1956
 
83 ilm 1957
        final Set<Constraint> thisConstraints;
1958
        final Set<Constraint> otherConstraints;
17 ilm 1959
        try {
83 ilm 1960
            final Tuple2<Set<Constraint>, Set<Index>> thisConstraintsAndIndexes = this.getConstraintsAndIndexes();
1961
            final Tuple2<Set<Constraint>, Set<Index>> otherConstraintsAndIndexes = o.getConstraintsAndIndexes();
17 ilm 1962
            // order irrelevant
83 ilm 1963
            final Set<Index> thisIndexesSet = thisConstraintsAndIndexes.get1();
1964
            final Set<Index> oIndexesSet = otherConstraintsAndIndexes.get1();
17 ilm 1965
            if (!thisIndexesSet.equals(oIndexesSet))
1966
                return "indexes differences: " + thisIndexesSet + "\n" + oIndexesSet;
83 ilm 1967
            thisConstraints = thisConstraintsAndIndexes.get0();
1968
            otherConstraints = otherConstraintsAndIndexes.get0();
17 ilm 1969
        } catch (SQLException e) {
1970
            // MAYBE fetch indexes with the rest to avoid exn now
1971
            return "couldn't get indexes: " + ExceptionUtils.getStackTrace(e);
1972
        }
132 ilm 1973
        if (!CustomEquals.equals(thisConstraints, otherConstraints, otherSystem == null || otherSystem.equals(thisSystem) ? null : Constraint.getInterSystemHashStrategy()))
83 ilm 1974
            return "constraints unequal : '" + thisConstraints + "' != '" + otherConstraints + "'";
17 ilm 1975
 
1976
        return null;
1977
    }
1978
 
83 ilm 1979
    private final Tuple2<Set<Constraint>, Set<Index>> getConstraintsAndIndexes() throws SQLException {
1980
        final Set<Constraint> thisConstraints;
1981
        final Set<Index> thisIndexes;
1982
        if (this.getServer().getSQLSystem() != SQLSystem.MSSQL) {
1983
            thisConstraints = this.getConstraints();
1984
            thisIndexes = new HashSet<Index>(this.getIndexes(true));
1985
        } else {
1986
            thisConstraints = new HashSet<Constraint>(this.getConstraints());
1987
            thisIndexes = new HashSet<Index>();
1988
            for (final Index i : this.getIndexes()) {
1989
                final Value<String> where = i.getMSUniqueWhere();
1990
                if (!where.hasValue()) {
1991
                    // regular index
1992
                    thisIndexes.add(i);
1993
                } else if (where.getValue() == null) {
1994
                    final Map<String, Object> map = new HashMap<String, Object>();
1995
                    map.put("CONSTRAINT_NAME", i.getName());
1996
                    map.put("CONSTRAINT_TYPE", "UNIQUE");
1997
                    map.put("COLUMN_NAMES", i.getCols());
1998
                    map.put("DEFINITION", null);
1999
                    thisConstraints.add(new Constraint(this, map));
2000
                } else {
2001
                    // remove extra IS NOT NULL, but does *not* translate [ARCHIVE]=(0) into
2002
                    // "ARCHIVE" = 0
2003
                    thisIndexes.add(this.createUniqueIndex(i.getName(), i.getCols(), where.getValue()));
2004
                }
2005
            }
2006
        }
2007
        return Tuple2.create(thisConstraints, thisIndexes);
2008
    }
2009
 
61 ilm 2010
    private final Rule getRule(Rule r, SQLSystem thisSystem, SQLSystem otherSystem) {
2011
        // compare exactly
2012
        if (otherSystem == null)
2013
            return r;
2014
        // see http://code.google.com/p/h2database/issues/detail?id=352
2015
        if (r == Rule.NO_ACTION && (thisSystem == SQLSystem.H2 || otherSystem == SQLSystem.H2))
2016
            return Rule.RESTRICT;
2017
        else
2018
            return r;
2019
    }
2020
 
17 ilm 2021
    /**
2022
     * Compare the fields of this table, ignoring foreign constraints.
2023
     *
2024
     * @param o the table to compare.
2025
     * @param otherSystem the system <code>o</code> originates from, can be <code>null</code>.
2026
     * @return <code>null</code> if each fields of this exists in <code>o</code> and is equal to it.
2027
     */
61 ilm 2028
    public synchronized final String equalsChildrenNoLink(SQLTable o, SQLSystem otherSystem) {
17 ilm 2029
        for (final SQLField f : this.getFields()) {
2030
            final SQLField oField = o.getField(f.getName());
2031
            final boolean isPrimary = this.getPrimaryKeys().contains(f);
2032
            if (isPrimary != o.getPrimaryKeys().contains(oField))
2033
                return f + " is a primary not in " + o.getPrimaryKeys();
2034
            final String equalsDesc = f.equalsDesc(oField, otherSystem, !isPrimary);
2035
            if (equalsDesc != null)
2036
                return equalsDesc;
2037
        }
2038
        return null;
2039
    }
2040
 
2041
    public final SQLCreateMoveableTable getCreateTable() {
142 ilm 2042
        return this.getCreateTable(SQLSyntax.get(this));
17 ilm 2043
    }
2044
 
142 ilm 2045
    public synchronized final SQLCreateMoveableTable getCreateTable(final SQLSyntax syntax) {
2046
        final SQLSystem system = syntax.getSystem();
67 ilm 2047
        final SQLCreateMoveableTable res = new SQLCreateMoveableTable(syntax, this.getDBRoot().getName(), this.getName());
17 ilm 2048
        for (final SQLField f : this.getOrderedFields()) {
2049
            res.addColumn(f);
2050
        }
2051
        // primary keys
2052
        res.setPrimaryKey(getPKsNames());
2053
        // foreign keys
132 ilm 2054
        for (final Link l : this.getForeignLinks())
17 ilm 2055
            // don't generate explicit CREATE INDEX for fk, we generate all indexes below
2056
            // (this also avoid creating a fk index that wasn't there)
2057
            res.addForeignConstraint(l, false);
2058
        // constraints
2059
        if (this.constraints != null)
41 ilm 2060
            for (final Constraint added : this.getConstraints()) {
17 ilm 2061
                if (added.getType() == ConstraintType.UNIQUE) {
2062
                    res.addUniqueConstraint(added.getName(), added.getCols());
2063
                } else
2064
                    throw new UnsupportedOperationException("unsupported constraint: " + added);
2065
            }
2066
        // indexes
2067
        try {
83 ilm 2068
            // MS unique constraint are not standard so we're forced to create indexes "where col is
2069
            // not null" in addUniqueConstraint(). Thus when converting to another system we must
2070
            // parse indexes to recreate actual constraints.
2071
            final boolean convertMSIndex = this.getServer().getSQLSystem() == SQLSystem.MSSQL && system != SQLSystem.MSSQL;
2072
            for (final Index i : this.getIndexes(true)) {
2073
                Value<String> msWhere = null;
2074
                if (convertMSIndex && (msWhere = i.getMSUniqueWhere()).hasValue()) {
2075
                    if (msWhere.getValue() != null)
2076
                        Log.get().warning("MS filter might not be valid in " + system + " : " + msWhere.getValue());
2077
                    res.addUniqueConstraint(i.getName(), i.getCols(), msWhere.getValue());
142 ilm 2078
                } else {
83 ilm 2079
                    // partial unique index sometimes cannot be handled natively by the DB system
2080
                    if (i.isUnique() && i.getFilter() != null && !system.isIndexFilterConditionSupported())
144 ilm 2081
                        res.addUniqueConstraint(i.getName(), i.createUniqueHelper());
83 ilm 2082
                    else
142 ilm 2083
                        res.addIndex(i);
17 ilm 2084
                }
83 ilm 2085
            }
17 ilm 2086
        } catch (SQLException e) {
2087
            // MAYBE fetch indexes with the rest to avoid exn now
2088
            throw new IllegalStateException("could not get indexes", e);
2089
        }
83 ilm 2090
        // TODO triggers, but they are system dependent and we would have to parse the SQL
2091
        // definitions to replace the different root/table name in DeferredClause.asString()
17 ilm 2092
        if (this.getComment() != null)
2093
            res.addOutsideClause(syntax.getSetTableComment(getComment()));
2094
        return res;
2095
    }
2096
 
2097
    public final List<String> getPKsNames() {
2098
        return this.getPKsNames(new ArrayList<String>());
2099
    }
2100
 
61 ilm 2101
    public synchronized final <C extends Collection<String>> C getPKsNames(C pks) {
17 ilm 2102
        for (final SQLField f : this.getPrimaryKeys()) {
2103
            pks.add(f.getName());
2104
        }
2105
        return pks;
2106
    }
2107
 
2108
    public final String[] getPKsNamesArray() {
2109
        return getPKsNames().toArray(new String[0]);
2110
    }
2111
 
2112
    /**
2113
     * Return the indexes mapped by column names. Ie a key will have as value every index that
65 ilm 2114
     * mentions it, and a multi-column index will be in several entries. Note: this is not robust
2115
     * since {@link Index#getCols()} isn't.
17 ilm 2116
     *
2117
     * @return the indexes mapped by column names.
2118
     * @throws SQLException if an error occurs.
2119
     */
83 ilm 2120
    public final SetMap<String, Index> getIndexesByField() throws SQLException {
17 ilm 2121
        final List<Index> indexes = this.getIndexes();
83 ilm 2122
        final SetMap<String, Index> res = new SetMap<String, Index>(indexes.size()) {
2123
            @Override
2124
            public Set<Index> createCollection(Collection<? extends Index> v) {
2125
                final HashSet<Index> res = new HashSet<Index>(4);
2126
                res.addAll(v);
2127
                return res;
2128
            }
2129
        };
17 ilm 2130
        for (final Index i : indexes)
2131
            for (final String col : i.getCols())
83 ilm 2132
                res.add(col, i);
17 ilm 2133
        return res;
2134
    }
2135
 
2136
    /**
65 ilm 2137
     * Return the indexes on the passed columns names. Note: this is not robust since
2138
     * {@link Index#getCols()} isn't.
2139
     *
2140
     * @param cols fields names.
2141
     * @return the matching indexes.
2142
     * @throws SQLException if an error occurs.
2143
     */
2144
    public final List<Index> getIndexes(final List<String> cols) throws SQLException {
2145
        final List<Index> res = new ArrayList<Index>();
2146
        for (final Index i : this.getIndexes())
2147
            if (i.getCols().equals(cols))
2148
                res.add(i);
2149
        return res;
2150
    }
2151
 
2152
    /**
17 ilm 2153
     * Return the indexes of this table. Except the primary key as every system generates it
2154
     * automatically.
2155
     *
2156
     * @return the list of indexes.
142 ilm 2157
     * @throws SQLException if an error occurs while accessing the DB.
17 ilm 2158
     */
142 ilm 2159
    public final List<Index> getIndexes() throws SQLException {
83 ilm 2160
        return this.getIndexes(false);
2161
    }
2162
 
142 ilm 2163
    public synchronized final List<Index> getIndexes(final boolean normalized) throws SQLException {
17 ilm 2164
        // in pg, a unique constraint creates a unique index that is not removeable
2165
        // (except of course if we drop the constraint)
2166
        // in mysql unique constraints and indexes are one and the same thing
2167
        // so we must return them only in one (either getConstraints() or getIndexes())
2168
        // anyway in all systems, a unique constraint or index achieve the same function
2169
        // and so only generates the constraint and not the index
2170
        final Set<List<String>> uniqConstraints;
2171
        if (this.constraints != null) {
2172
            uniqConstraints = new HashSet<List<String>>();
2173
            for (final Constraint c : this.constraints) {
2174
                if (c.getType() == ConstraintType.UNIQUE)
2175
                    uniqConstraints.add(c.getCols());
2176
            }
2177
        } else
2178
            uniqConstraints = Collections.emptySet();
2179
 
2180
        final List<Index> indexes = new ArrayList<Index>();
2181
        Index currentIndex = null;
142 ilm 2182
        for (final Map<String, Object> norm : this.getDBSystemRoot().getSyntax().getIndexInfo(this)) {
17 ilm 2183
            final Index index = new Index(norm);
2184
            final short seq = ((Number) norm.get("ORDINAL_POSITION")).shortValue();
2185
            if (seq == 1) {
2186
                if (canAdd(currentIndex, uniqConstraints))
2187
                    indexes.add(currentIndex);
2188
                currentIndex = index;
2189
            } else {
2190
                // continuing a multi-field index
2191
                currentIndex.add(index);
2192
            }
2193
        }
2194
        if (canAdd(currentIndex, uniqConstraints))
2195
            indexes.add(currentIndex);
2196
 
83 ilm 2197
        if (normalized) {
2198
            indexes.addAll(this.getPartialUniqueIndexes());
2199
        }
2200
 
17 ilm 2201
        // MAYBE another request to find out index.getMethod() (eg pg.getIndexesReq())
2202
        return indexes;
2203
    }
2204
 
2205
    private boolean canAdd(final Index currentIndex, final Set<List<String>> uniqConstraints) {
2206
        if (currentIndex == null || currentIndex.isPKIndex())
2207
            return false;
2208
 
2209
        return !currentIndex.isUnique() || !uniqConstraints.contains(currentIndex.getCols());
2210
    }
2211
 
83 ilm 2212
    // MAYBE inline
2213
    protected synchronized final List<Index> getPartialUniqueIndexes() throws SQLException {
2214
        final SQLSystem thisSystem = this.getServer().getSQLSystem();
2215
        final List<Index> indexes = new ArrayList<Index>();
2216
        // parse triggers, TODO remove them from triggers to output in getCreateTable()
2217
        if (thisSystem == SQLSystem.H2) {
2218
            for (final Trigger t : this.triggers.values()) {
144 ilm 2219
                Matcher matcher = ChangeTable.H2_UNIQUE_TRIGGER_PATTERN.matcher(t.getSQL());
83 ilm 2220
                if (matcher.find()) {
2221
                    final String indexName = ChangeTable.getIndexName(t.getName(), thisSystem);
2222
                    final String[] javaCols = ChangeTable.H2_LIST_PATTERN.split(matcher.group(1).trim());
2223
                    final List<String> cols = new ArrayList<String>(javaCols.length);
2224
                    for (final String javaCol : javaCols) {
2225
                        cols.add(StringUtils.unDoubleQuote(javaCol));
2226
                    }
2227
                    final String where = StringUtils.unDoubleQuote(matcher.group(2).trim());
2228
                    indexes.add(createUniqueIndex(indexName, cols, where));
144 ilm 2229
                } else {
2230
                    matcher = ChangeTable.H2_UNIQUE_TRIGGER_CLASS_PATTERN.matcher(t.getSQL());
2231
                    if (matcher.find()) {
2232
                        final String className = matcher.group(1);
2233
                        final Class<?> triggerClass;
2234
                        try {
2235
                            triggerClass = Class.forName(className);
2236
                        } catch (ClassNotFoundException e) {
151 ilm 2237
                            // throw new SQLException("Class not found for " + t, e);
2238
                            e.printStackTrace();
2239
                            continue;
144 ilm 2240
                        }
2241
                        PartialUniqueTrigger n;
2242
                        try {
2243
                            n = (PartialUniqueTrigger) triggerClass.newInstance();
2244
                        } catch (Exception e) {
151 ilm 2245
                            // throw new SQLException("Couldn't instantiate class for " + t, e);
2246
                            e.printStackTrace();
2247
                            continue;
144 ilm 2248
                        }
2249
                        final String indexName = ChangeTable.getIndexName(t.getName(), thisSystem);
2250
                        final Index idx = createUniqueIndex(indexName, n.getColumns(), n.getWhere());
2251
                        idx.setH2Class(n.getClass());
2252
                        indexes.add(idx);
2253
                    }
83 ilm 2254
                }
2255
            }
2256
        } else if (thisSystem == SQLSystem.MYSQL) {
2257
            for (final Trigger t : this.triggers.values()) {
2258
                if (t.getAction().contains(ChangeTable.MYSQL_TRIGGER_EXCEPTION)) {
2259
                    final String indexName = ChangeTable.getIndexName(t.getName(), thisSystem);
2260
                    // MySQL needs a pair of triggers
2261
                    final Trigger t2 = indexName == null ? null : this.triggers.get(indexName + ChangeTable.MYSQL_TRIGGER_SUFFIX_2);
2262
                    // and their body must match
2263
                    if (t2 != null && t2.getAction().equals(t.getAction())) {
2264
                        final Matcher matcher = ChangeTable.MYSQL_UNIQUE_TRIGGER_PATTERN.matcher(t.getAction());
2265
                        if (!matcher.find())
2266
                            throw new IllegalStateException("Couldn't parse " + t.getAction());
2267
                        // parse table name
2268
                        final SQLName parsedName = SQLName.parse(matcher.group(1).trim());
2269
                        if (!this.getName().equals(parsedName.getName()))
2270
                            throw new IllegalStateException("Name mismatch : " + this.getSQLName() + " != " + parsedName);
17 ilm 2271
 
83 ilm 2272
                        final String[] wheres = ChangeTable.MYSQL_WHERE_PATTERN.split(matcher.group(2).trim());
2273
                        final String userWhere = wheres[0];
2274
 
2275
                        final List<String> cols = new ArrayList<String>(wheres.length - 1);
2276
                        for (int i = 1; i < wheres.length; i++) {
2277
                            final Matcher eqMatcher = ChangeTable.MYSQL_WHERE_EQ_PATTERN.matcher(wheres[i].trim());
2278
                            if (!eqMatcher.matches())
2279
                                throw new IllegalStateException("Invalid where clause " + wheres[i]);
2280
                            cols.add(SQLName.parse(eqMatcher.group(2).trim()).getName());
2281
                        }
2282
                        if (cols.isEmpty())
2283
                            throw new IllegalStateException("No columns in " + Arrays.asList(wheres));
2284
                        indexes.add(createUniqueIndex(indexName, cols, userWhere));
2285
                    }
2286
                }
2287
            }
2288
        }
2289
        return indexes;
2290
    }
2291
 
2292
    public static class SQLIndex {
2293
 
2294
        private static final Pattern NORMALIZE_SPACES = Pattern.compile("\\s+");
2295
 
17 ilm 2296
        private final String name;
83 ilm 2297
        // SQL, e.g. : lower("name"), "age"
17 ilm 2298
        private final List<String> attrs;
2299
        private final boolean unique;
2300
        private String method;
83 ilm 2301
        private final String filter;
17 ilm 2302
 
83 ilm 2303
        public SQLIndex(final String name, final List<String> attributes, final boolean unique, final String filter) {
2304
            this(name, attributes, false, unique, filter);
17 ilm 2305
        }
2306
 
83 ilm 2307
        public SQLIndex(final String name, final List<String> attributes, final boolean quoteAll, final boolean unique, final String filter) {
17 ilm 2308
            super();
2309
            this.name = name;
83 ilm 2310
            this.attrs = new ArrayList<String>(attributes.size());
2311
            for (final String attr : attributes)
2312
                this.addAttr(quoteAll ? SQLBase.quoteIdentifier(attr) : attr);
2313
            this.unique = unique;
17 ilm 2314
            this.method = null;
83 ilm 2315
            // helps when comparing
2316
            this.filter = filter == null ? null : NORMALIZE_SPACES.matcher(filter.trim()).replaceAll(" ");
17 ilm 2317
        }
2318
 
2319
        public final String getName() {
2320
            return this.name;
2321
        }
2322
 
2323
        public final boolean isUnique() {
2324
            return this.unique;
2325
        }
2326
 
2327
        /**
2328
         * All attributes forming this index.
2329
         *
2330
         * @return the components of this index, eg ["lower(name)", "age"].
2331
         */
2332
        public final List<String> getAttrs() {
83 ilm 2333
            return Collections.unmodifiableList(this.attrs);
17 ilm 2334
        }
2335
 
83 ilm 2336
        protected final void addAttr(final String attr) {
2337
            this.attrs.add(attr);
17 ilm 2338
        }
2339
 
2340
        public final void setMethod(String method) {
2341
            this.method = method;
2342
        }
2343
 
2344
        public final String getMethod() {
2345
            return this.method;
2346
        }
2347
 
2348
        /**
2349
         * Filter for partial index.
2350
         *
2351
         * @return the where clause or <code>null</code>.
2352
         */
2353
        public final String getFilter() {
2354
            return this.filter;
2355
        }
2356
 
2357
        @Override
2358
        public String toString() {
83 ilm 2359
            return getClass().getSimpleName() + " " + this.getName() + " unique: " + this.isUnique() + " cols: " + this.getAttrs() + " filter: " + this.getFilter();
17 ilm 2360
        }
2361
 
2362
        // ATTN don't use name since it is often auto-generated (eg by a UNIQUE field)
2363
        @Override
2364
        public boolean equals(Object obj) {
83 ilm 2365
            if (obj instanceof SQLIndex) {
2366
                final SQLIndex o = (SQLIndex) obj;
2367
                return this.isUnique() == o.isUnique() && this.getAttrs().equals(o.getAttrs()) && CompareUtils.equals(this.getFilter(), o.getFilter())
2368
                        && CompareUtils.equals(this.getMethod(), o.getMethod());
2369
            } else {
17 ilm 2370
                return false;
83 ilm 2371
            }
17 ilm 2372
        }
2373
 
2374
        // ATTN use cols, so use only after cols are done
2375
        @Override
2376
        public int hashCode() {
2377
            return this.getAttrs().hashCode() + ((Boolean) this.isUnique()).hashCode();
2378
        }
2379
    }
83 ilm 2380
 
2381
    private final Index createUniqueIndex(final String name, final List<String> cols, final String where) {
2382
        final Index res = new Index(name, cols.get(0), false, where);
2383
        for (int i = 1; i < cols.size(); i++) {
2384
            res.addFromMD(cols.get(i));
2385
        }
2386
        return res;
2387
    }
2388
 
2389
    private final String removeParens(String filter) {
2390
        if (filter != null) {
2391
            filter = filter.trim();
2392
            final SQLSystem sys = this.getServer().getSQLSystem();
2393
            // postgreSQL always wrap filter with parens, ATTN we shouldn't remove from
2394
            // "(A) and (B)" but still support "(A = (0))"
2395
            if ((sys == SQLSystem.POSTGRESQL || sys == SQLSystem.MSSQL) && filter.startsWith("(") && filter.endsWith(")")) {
2396
                filter = filter.substring(1, filter.length() - 1);
2397
            }
2398
        }
2399
        return filter;
2400
    }
2401
 
144 ilm 2402
    @GuardedBy("uniqueH2Triggers")
2403
    private final Map<Tuple2<List<String>, String>, Class<? extends PartialUniqueTrigger>> uniqueH2Triggers = new HashMap<>();
2404
 
2405
    public final void registerH2UniqueTrigger(Class<? extends PartialUniqueTrigger> uniqTriggerClass) throws InstantiationException, IllegalAccessException {
2406
        final PartialUniqueTrigger newInstance = uniqTriggerClass.newInstance();
2407
        final Tuple2<List<String>, String> key = Tuple2.create(newInstance.getColumns(), newInstance.getWhere().toUpperCase());
2408
        synchronized (this.uniqueH2Triggers) {
2409
            this.uniqueH2Triggers.put(key, uniqTriggerClass);
2410
        }
2411
    }
2412
 
2413
    public static final String workAroundForH2WhereTrigger(final String where) {
2414
        return where.toUpperCase().replaceAll("[()]", "");
2415
    }
2416
 
2417
    public final Class<? extends PartialUniqueTrigger> getH2UniqueTriggerClass(final List<String> cols, final String where) {
2418
        final Tuple2<List<String>, String> key = Tuple2.create(cols, workAroundForH2WhereTrigger(where));
2419
        synchronized (this.uniqueH2Triggers) {
2420
            return this.uniqueH2Triggers.get(key);
2421
        }
2422
    }
2423
 
83 ilm 2424
    public final class Index extends SQLIndex {
2425
 
2426
        private final List<String> cols;
144 ilm 2427
        private Class<? extends PartialUniqueTrigger> h2Class;
83 ilm 2428
 
2429
        Index(final Map<String, Object> row) {
2430
            this((String) row.get("INDEX_NAME"), (String) row.get("COLUMN_NAME"), (Boolean) row.get("NON_UNIQUE"), (String) row.get("FILTER_CONDITION"));
2431
        }
2432
 
2433
        Index(final String name, String col, Boolean nonUnique, String filter) {
2434
            super(name, Collections.<String> emptyList(), !nonUnique, removeParens(filter));
2435
            this.cols = new ArrayList<String>();
2436
            this.addFromMD(col);
2437
        }
2438
 
2439
        public final SQLTable getTable() {
2440
            return SQLTable.this;
2441
        }
2442
 
2443
        /**
2444
         * The table columns in this index. Note that due to DB system limitation this list is
2445
         * incomplete (e.g. missing expressions).
2446
         *
2447
         * @return the unquoted columns, e.g. ["age"].
2448
         */
2449
        public final List<String> getCols() {
2450
            return this.cols;
2451
        }
2452
 
2453
        public final List<SQLField> getFields() {
2454
            final List<SQLField> res = new ArrayList<SQLField>(this.getCols().size());
2455
            for (final String f : this.getCols())
2456
                res.add(getTable().getField(f));
2457
            return res;
2458
        }
2459
 
2460
        /**
2461
         * Adds a column to this multi-field index.
2462
         *
2463
         * @param name the name of the index.
2464
         * @param col the column to add.
2465
         * @param unique whether the index is unique.
2466
         * @throws IllegalStateException if <code>name</code> and <code>unique</code> are not the
2467
         *         same as these.
2468
         */
2469
        private final void add(final Index o) {
2470
            assert o.getAttrs().size() == 1;
2471
            if (!o.getName().equals(this.getName()) || this.isUnique() != o.isUnique())
2472
                throw new IllegalStateException("incoherence");
2473
            this.cols.addAll(o.getCols());
2474
            this.addAttr(o.getAttrs().get(0));
2475
        }
2476
 
2477
        // col is either an expression or a column name
2478
        protected void addFromMD(String col) {
2479
            if (getTable().contains(col)) {
2480
                // e.g. age
2481
                this.cols.add(col);
2482
                this.addAttr(SQLBase.quoteIdentifier(col));
2483
            } else {
2484
                // e.g. lower("name")
2485
                this.addAttr(col);
2486
            }
2487
        }
2488
 
2489
        final boolean isPKIndex() {
2490
            return this.isUnique() && this.getCols().equals(getTable().getPKsNames()) && this.getCols().size() == this.getAttrs().size();
2491
        }
2492
 
2493
        private final Pattern getColPattern(final String col) {
2494
            // e.g. ([NOM] IS NOT NULL AND [PRENOM] IS NOT NULL AND [ARCHIVE]=(0))
2495
            return Pattern.compile("(?i:\\s+AND\\s+)?" + Pattern.quote(new SQLName(col).quoteMS()) + "\\s+(?i)IS\\s+NOT\\s+NULL(\\s+AND\\s+)?");
2496
        }
2497
 
2498
        // in MS SQL we're forced to add IS NOT NULL to get the standard behaviour
2499
        // return none if it's not a unique index, otherwise the value of the where for the partial
2500
        // index (can be null)
2501
        final Value<String> getMSUniqueWhere() {
2502
            assert getServer().getSQLSystem() == SQLSystem.MSSQL;
2503
            if (this.isUnique() && this.getFilter() != null) {
2504
                String filter = this.getFilter().trim();
2505
                // for each column, remove its NOT NULL clause
2506
                for (final String col : getCols()) {
2507
                    final Matcher matcher = this.getColPattern(col).matcher(filter);
2508
                    if (matcher.find()) {
2509
                        filter = matcher.replaceFirst("").trim();
2510
                    } else {
2511
                        return Value.getNone();
2512
                    }
2513
                }
2514
                // what is the left is the actual filter
2515
                filter = filter.trim();
2516
                return Value.getSome(filter.isEmpty() ? null : filter);
2517
            }
2518
            return Value.getNone();
2519
        }
144 ilm 2520
 
2521
        final void setH2Class(final Class<? extends PartialUniqueTrigger> triggerClass) {
2522
            this.h2Class = triggerClass;
2523
        }
2524
 
2525
        final UniqueConstraintCreatorHelper createUniqueHelper() {
2526
            final Class<? extends PartialUniqueTrigger> h2Class = this.h2Class == null ? getH2UniqueTriggerClass(getCols(), getFilter()) : this.h2Class;
2527
            final String comment = h2Class == null ? null : "Unique constraint on " + getCols() + (getFilter() == null ? "" : " where " + getFilter());
2528
            return new UniqueConstraintCreatorHelper(getCols(), getFilter(), comment) {
2529
                @Override
2530
                public Object getObject(SQLSyntax s) {
2531
                    if (s.getSystem() == SQLSystem.H2)
2532
                        return h2Class;
2533
                    else
2534
                        return super.getObject(s);
2535
                }
2536
            };
2537
        }
83 ilm 2538
    }
17 ilm 2539
}