OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

Rev Author Line No. Line
17 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
182 ilm 4
 * Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
17 ilm 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
 
41 ilm 16
import org.openconcerto.sql.model.SQLRowValuesCluster.Insert;
17 ilm 17
import org.openconcerto.sql.model.graph.DatabaseGraph;
67 ilm 18
import org.openconcerto.sql.model.graph.TablesMap;
41 ilm 19
import org.openconcerto.sql.request.UpdateBuilder;
20
import org.openconcerto.sql.utils.AlterTable;
21
import org.openconcerto.sql.utils.ChangeTable;
22
import org.openconcerto.sql.utils.ChangeTable.ConcatStep;
23
import org.openconcerto.sql.utils.ChangeTable.FCSpec;
24
import org.openconcerto.sql.utils.ReOrder;
17 ilm 25
import org.openconcerto.sql.utils.SQLCreateRoot;
41 ilm 26
import org.openconcerto.sql.utils.SQLCreateTableBase;
27
import org.openconcerto.sql.utils.SQLUtils;
17 ilm 28
import org.openconcerto.sql.utils.SQL_URL;
41 ilm 29
import org.openconcerto.utils.CollectionUtils;
182 ilm 30
import org.openconcerto.utils.Tuple2.List2;
17 ilm 31
 
32
import java.net.URISyntaxException;
33
import java.sql.SQLException;
41 ilm 34
import java.util.Arrays;
35
import java.util.Collection;
17 ilm 36
import java.util.Collections;
41 ilm 37
import java.util.Date;
38
import java.util.EnumSet;
39
import java.util.HashMap;
67 ilm 40
import java.util.HashSet;
41 ilm 41
import java.util.List;
42
import java.util.Map;
43
import java.util.Map.Entry;
17 ilm 44
import java.util.Set;
61 ilm 45
import java.util.TreeMap;
17 ilm 46
 
61 ilm 47
import net.jcip.annotations.ThreadSafe;
48
 
17 ilm 49
/**
50
 * The root of a database, in mysql a SQLBase, in postgresql a SQLSchema.
51
 *
52
 * @author Sylvain
53
 */
61 ilm 54
@ThreadSafe
17 ilm 55
public final class DBRoot extends DBStructureItemDB {
56
 
57
    static DBRoot get(SQLBase b, String n) {
58
        final DBRoot ancestor = b.getDBRoot();
59
        final DBStructureItemDB parent = ancestor == null ? b.getDB() : ancestor.getParent();
60
        return (DBRoot) parent.getChild(n);
61
    }
62
 
63
    DBRoot(DBStructureItemJDBC delegate) {
64
        super(delegate);
65
    }
66
 
67
    public final SQLBase getBase() {
68
        return this.getJDBC().getAncestor(SQLBase.class);
69
    }
70
 
71
    public SQLTable getTable(String name) {
72
        return (SQLTable) getJDBC(this.getChild(name));
73
    }
74
 
61 ilm 75
    protected final Map<String, SQLTable> getTablesMap() {
76
        return this.getSchema().getChildrenMap();
77
    }
78
 
17 ilm 79
    public SQLTable getTableDesc(String name) {
80
        return this.getDescLenient(name, SQLTable.class);
81
    }
82
 
83
    public SQLTable findTable(String name) {
84
        return this.findTable(name, false);
85
    }
86
 
87
    public SQLTable findTable(String name, final boolean mustExist) {
61 ilm 88
        final SQLTable res = this.getTable(name);
89
        if (res != null)
90
            return res;
17 ilm 91
        else
92
            return this.getDBSystemRoot().findTable(name, mustExist);
93
    }
94
 
95
    /**
96
     * Return the tables of this root.
97
     *
98
     * @return our tables.
99
     */
100
    public Set<SQLTable> getTables() {
101
        return getJDBC().getDescendants(SQLTable.class);
102
    }
103
 
41 ilm 104
    /**
105
     * Create the passed table in this root.
106
     *
107
     * @param createTable how to create the table.
108
     * @return the newly created table.
109
     * @throws SQLException if an error occurs.
110
     */
111
    public final SQLTable createTable(final SQLCreateTableBase<?> createTable) throws SQLException {
112
        return this.createTable(createTable, null);
113
    }
114
 
115
    public final SQLTable createTable(final SQLCreateTableBase<?> createTable, final Map<String, ?> undefinedNonDefaultValues) throws SQLException {
61 ilm 116
        synchronized (this.getDBSystemRoot().getTreeMutex()) {
117
            this.createTables(Collections.<SQLCreateTableBase<?>, Map<String, ?>> singletonMap(createTable, undefinedNonDefaultValues));
118
            return this.getTable(createTable.getName());
119
        }
41 ilm 120
    }
121
 
122
    public final void createTables(final SQLCreateTableBase<?>... createTables) throws SQLException {
123
        this.createTables(Arrays.asList(createTables));
124
    }
125
 
126
    public final void createTables(final Collection<? extends SQLCreateTableBase<?>> createTables) throws SQLException {
127
        this.createTables(CollectionUtils.fillMap(new HashMap<SQLCreateTableBase<?>, Map<String, ?>>(), createTables), false);
128
    }
129
 
130
    /**
131
     * Create the passed tables and undefined rows, then {@link #refetch()}.
132
     *
133
     * @param undefinedNonDefaultValues the undefined row for each table, if the value is
134
     *        <code>null</code> then no undefined row will be created.
135
     * @throws SQLException if an error occurs.
136
     */
137
    public final void createTables(final Map<? extends SQLCreateTableBase<?>, ? extends Map<String, ?>> undefinedNonDefaultValues) throws SQLException {
138
        this.createTables(undefinedNonDefaultValues, !Collections.singleton(null).containsAll(undefinedNonDefaultValues.values()));
139
    }
140
 
141
    private final void createTables(final Map<? extends SQLCreateTableBase<?>, ? extends Map<String, ?>> undefinedNonDefaultValues, final boolean atLeast1UndefRow) throws SQLException {
65 ilm 142
        final int size = undefinedNonDefaultValues.size();
143
        if (size == 0)
144
            return;
145
 
67 ilm 146
        final Set<String> tableNames = new HashSet<String>(size);
147
        for (final SQLCreateTableBase<?> ct : undefinedNonDefaultValues.keySet())
148
            tableNames.add(ct.getName());
149
 
41 ilm 150
        SQLUtils.executeAtomic(getDBSystemRoot().getDataSource(), new ConnectionHandlerNoSetup<Object, SQLException>() {
151
            @Override
152
            public Object handle(SQLDataSource ds) throws SQLException {
153
                // don't create foreign constraints now, so we can insert undefined with cycles
142 ilm 154
                final List<List<String>> createTablesSQL = ChangeTable.cat(undefinedNonDefaultValues.keySet(), getName(), EnumSet.of(ConcatStep.ADD_CONSTRAINT));
41 ilm 155
                for (final String sql : createTablesSQL.get(0))
156
                    ds.execute(sql);
157
                final Map<SQLCreateTableBase<?>, Number> newUndefIDs;
158
                final Map<SQLTable, SQLCreateTableBase<?>> newTables;
159
                if (atLeast1UndefRow) {
160
                    newUndefIDs = new HashMap<SQLCreateTableBase<?>, Number>();
161
                    newTables = new HashMap<SQLTable, SQLCreateTableBase<?>>();
67 ilm 162
                    refetch(tableNames);
41 ilm 163
                } else {
164
                    newUndefIDs = Collections.emptyMap();
165
                    newTables = null;
166
                }
167
                for (final Entry<? extends SQLCreateTableBase<?>, ? extends Map<String, ?>> e : undefinedNonDefaultValues.entrySet()) {
168
                    final SQLCreateTableBase<?> createTable = e.getKey();
169
                    final String tableName = createTable.getName();
170
                    final Map<String, ?> m = e.getValue();
171
                    // insert undefined row if requested and record its ID
172
                    if (m == null) {
173
                        SQLTable.setUndefID(getSchema(), tableName, null);
174
                    } else {
175
                        final SQLTable t = getTable(tableName);
176
                        newUndefIDs.put(createTable, null);
177
                        newTables.put(t, createTable);
178
                        if (t.isRowable()) {
179
                            final SQLRowValues vals = new SQLRowValues(t, m);
180
                            if (t.isOrdered())
181
                                vals.put(t.getOrderField().getName(), ReOrder.MIN_ORDER);
182
                            for (final SQLField f : t.getContentFields()) {
183
                                if (!vals.getFields().contains(f.getName()) && f.isNullable() != Boolean.TRUE && f.getDefaultValue() == null) {
184
                                    final Class<?> javaType = f.getType().getJavaType();
185
                                    final Object o;
186
                                    if (String.class.isAssignableFrom(javaType))
187
                                        o = "";
188
                                    else if (Number.class.isAssignableFrom(javaType))
189
                                        o = 0;
190
                                    else if (Boolean.class.isAssignableFrom(javaType))
191
                                        o = Boolean.FALSE;
192
                                    else if (Date.class.isAssignableFrom(javaType))
193
                                        o = new Date(0);
194
                                    else
195
                                        throw new UnsupportedOperationException("cannot find value for " + f.getSQLName());
196
                                    vals.put(f.getName(), o);
197
                                }
198
                            }
199
                            // PK from the DB, but use our order
200
                            // don't try to validate since table has neither undefined row nor
201
                            // constraints
83 ilm 202
                            final SQLRow undefRow = vals.getGraph().store(new Insert(false, true), false).getStoredRow(vals);
41 ilm 203
                            SQLTable.setUndefID(getSchema(), tableName, undefRow.getID());
204
                            newUndefIDs.put(createTable, undefRow.getIDNumber());
205
                        }
206
                    }
207
                }
208
                // update undefined rows pointing to other undefined rows
209
                // set default value for created foreign fields
210
                for (final Entry<SQLCreateTableBase<?>, Number> e : newUndefIDs.entrySet()) {
211
                    final SQLCreateTableBase<?> createTable = e.getKey();
212
                    final SQLTable t = getTable(createTable.getName());
213
 
214
                    final Number undefID = e.getValue();
215
                    final UpdateBuilder update;
216
                    if (undefID != null) {
217
                        update = new UpdateBuilder(t);
218
                        update.setWhere(new Where(t.getKey(), "=", undefID));
219
                    } else {
220
                        update = null;
221
                    }
222
 
223
                    final AlterTable alterTable = new AlterTable(t);
224
                    for (final FCSpec fc : createTable.getForeignConstraints()) {
225
                        if (fc.getCols().size() == 1) {
226
                            final SQLTable targetT = t.getDescLenient(fc.getRefTable(), SQLTable.class);
227
                            final Number foreignUndefID = newUndefIDs.get(newTables.get(targetT));
228
                            if (foreignUndefID != null) {
229
                                final String ffName = fc.getCols().get(0);
230
                                final String foreignUndefIDSQL = t.getField(ffName).getType().toString(foreignUndefID);
231
                                alterTable.alterColumnDefault(ffName, foreignUndefIDSQL);
232
                                update.set(ffName, foreignUndefIDSQL);
233
                            }
234
                        }
235
                    }
236
 
237
                    if (update != null && !update.isEmpty())
238
                        ds.execute(update.asString());
239
                    if (!alterTable.isEmpty())
240
                        ds.execute(alterTable.asString());
241
                }
242
                for (final String sql : createTablesSQL.get(1))
243
                    ds.execute(sql);
244
                // always execute updateVersion() after setUndefID() to avoid DB transactions
245
                // deadlock since setUndefID() itself ends with updateVersion().
246
                getSchema().updateVersion();
247
                return null;
248
            }
249
        });
67 ilm 250
        this.refetch(tableNames);
41 ilm 251
    }
252
 
17 ilm 253
    public SQLField getField(String name) {
254
        return this.getDesc(name, SQLField.class);
255
    }
256
 
257
    /**
258
     * Return the value of a metadata for this root.
259
     *
260
     * @param name name of the metadata, eg "Customer".
261
     * @return value of the metadata or <code>null</code> if it doesn't exist, eg "ACME, inc".
262
     */
263
    public final String getMetadata(final String name) {
264
        return getSchema().getFwkMetadata(name);
265
    }
266
 
267
    // since by definition DBRoot is one level above SQLTable, there's only one schema below it
268
    public final SQLSchema getSchema() {
269
        return (SQLSchema) this.getJDBC().getNonNullDBParent();
270
    }
271
 
272
    /**
273
     * Set the value of a metadata.
274
     *
275
     * @param name name of the metadata, eg "Customer".
276
     * @param value value of the metadata, eg "ACME, inc".
277
     * @return <code>true</code> if the value was set, <code>false</code> otherwise.
278
     * @throws SQLException if an error occurs while setting the value.
279
     */
280
    public final boolean setMetadata(final String name, final String value) throws SQLException {
67 ilm 281
        return getSchema().setFwkMetadata(name, getBase().quoteString(value));
17 ilm 282
    }
283
 
65 ilm 284
    public final DatabaseGraph getGraph() {
285
        return this.getDBSystemRoot().getGraph();
17 ilm 286
    }
287
 
288
    /**
289
     * Refresh this from the database.
290
     *
291
     * @throws SQLException if an error occurs.
292
     */
293
    public void refetch() throws SQLException {
65 ilm 294
        this.refetch(null);
17 ilm 295
    }
296
 
67 ilm 297
    /**
298
     * Refetch one table.
299
     *
300
     * @param tableName the name of the table, not <code>null</code>.
301
     * @return the refreshed table, <code>null</code> if it doesn't exist.
302
     * @throws SQLException if an error occurs.
303
     */
304
    public SQLTable refetchTable(final String tableName) throws SQLException {
65 ilm 305
        if (tableName == null) {
67 ilm 306
            throw new NullPointerException("Null table");
65 ilm 307
        } else {
308
            return this.getSchema().fetchTable(tableName);
309
        }
61 ilm 310
    }
311
 
67 ilm 312
    public void refetch(final Set<String> tableNames) throws SQLException {
313
        this.getBase().fetchTables(TablesMap.createFromTables(this.getSchema().getName(), tableNames));
314
    }
315
 
142 ilm 316
    public final SQLCreateRoot getDefinitionSQL() {
317
        return this.getDefinitionSQL(getDBSystemRoot().getSyntax());
93 ilm 318
    }
319
 
142 ilm 320
    public final SQLCreateRoot getDefinitionSQL(final SQLSyntax s) {
321
        return this.getDefinitionSQL(s, true);
322
    }
323
 
324
    public final SQLCreateRoot getDefinitionSQL(final SQLSyntax s, final boolean withTables) {
325
        final SQLCreateRoot res = new SQLCreateRoot(s, this.getName());
93 ilm 326
        if (withTables) {
327
            // order by name to be able to do diffs
328
            for (final SQLTable table : new TreeMap<String, SQLTable>(this.getTablesMap()).values()) {
142 ilm 329
                res.addTable(table.getCreateTable(s));
93 ilm 330
            }
17 ilm 331
        }
332
        return res;
333
    }
334
 
335
    public final String equalsDesc(final DBRoot o) {
336
        return this.equalsDesc(o, null);
337
    }
338
 
182 ilm 339
    public final String equalsDesc(final DBRoot o, final SQLSyntax otherSystem) {
17 ilm 340
        if (this == o)
341
            return null;
342
        if (null == o)
343
            return "other is null";
344
 
61 ilm 345
        final Map<String, SQLTable> thisTables = this.getTablesMap();
346
        final Map<String, SQLTable> oTables = o.getTablesMap();
17 ilm 347
 
61 ilm 348
        if (!thisTables.keySet().equals(oTables.keySet()))
349
            return "unequal table names: " + thisTables.keySet() + " != " + oTables.keySet();
350
 
351
        for (final Entry<String, SQLTable> e : thisTables.entrySet()) {
352
            final String name = e.getKey();
353
            final SQLTable t = e.getValue();
354
            final String eqDesc = t.equalsDesc(oTables.get(name), otherSystem, true);
17 ilm 355
            if (eqDesc != null)
61 ilm 356
                return "unequal " + name + ": " + eqDesc;
17 ilm 357
        }
358
        return null;
359
    }
360
 
361
    /**
362
     * Return the url pointing to this root.
363
     *
364
     * @return the url or <code>null</code> if this cannot be represented as an {@link SQL_URL} (eg
365
     *         jdbc:h2:file:/a/b/c).
366
     */
367
    public final SQL_URL getURL() {
182 ilm 368
        // check that our name doesn't contain a path, otherwise we would lose it
369
        // e.g. dbserv:8084/~/sample
370
        final List2<String> hostAndPath = this.getServer().getHostnameAndPath();
371
        final String hostname = hostAndPath.get0();
372
        // TODO return JDBCUrl
373
        if (hostname == null || hostAndPath.get1() != null)
17 ilm 374
            return null;
375
        final SQLSystem system = this.getServer().getSQLSystem();
376
        String url = system.name().toLowerCase() + "://" + this.getDBSystemRoot().getDataSource().getUsername() + "@" + hostname + "/";
377
        // handle systems w/o systemRoot
378
        if (system.getDBLevel(DBSystemRoot.class) != HierarchyLevel.SQLSERVER) {
379
            url += this.getDBSystemRoot().getName() + "/";
380
        }
381
        url += this.getName();
382
        try {
383
            return SQL_URL.create(url);
384
        } catch (URISyntaxException e) {
385
            // should not happen
386
            throw new IllegalStateException("could not produce url for " + this, e);
387
        }
388
    }
389
 
390
    /**
391
     * A string with the content of this root.
392
     *
393
     * <pre>
394
     *   /TYPE_COURANT/
395
     *   ID_TYPE_COURANT t: 4 def: null
396
     *   LABEL t: 12 def:
397
     *   ARCHIVE t: 4 def: 0
398
     *   ORDRE t: 4 def: 1
399
     * </pre>
400
     *
401
     * @return the content of this.
402
     */
403
    public String dump() {
404
        String res = "";
61 ilm 405
        for (final SQLTable table : new TreeMap<String, SQLTable>(this.getTablesMap()).values()) {
17 ilm 406
            res += table + "\n";
61 ilm 407
            for (final SQLField f : new TreeMap<String, SQLField>(table.getChildrenMap()).values()) {
17 ilm 408
                res += f.getName() + " t: " + f.getType() + " def: " + f.getDefaultValue() + "\n";
409
            }
410
            res += "\n";
411
        }
412
        return res;
413
    }
414
}