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
 
16
import org.openconcerto.sql.model.SQLField.Properties;
67 ilm 17
import org.openconcerto.sql.model.graph.TablesMap;
83 ilm 18
import org.openconcerto.sql.utils.ChangeTable.ClauseType;
132 ilm 19
import org.openconcerto.sql.utils.SQLUtils;
182 ilm 20
import org.openconcerto.utils.CollectionUtils;
83 ilm 21
import org.openconcerto.utils.ListMap;
17 ilm 22
import org.openconcerto.utils.Tuple2;
182 ilm 23
import org.openconcerto.utils.cc.ITransformer;
24
import org.openconcerto.utils.cc.Transformer;
25
import org.openconcerto.xml.XMLCodecUtils;
17 ilm 26
 
182 ilm 27
import java.beans.DefaultPersistenceDelegate;
17 ilm 28
import java.io.File;
29
import java.math.BigDecimal;
30
import java.sql.Blob;
31
import java.sql.Clob;
32
import java.sql.SQLException;
33
import java.sql.Timestamp;
34
import java.util.ArrayList;
182 ilm 35
import java.util.Arrays;
142 ilm 36
import java.util.IdentityHashMap;
17 ilm 37
import java.util.List;
38
import java.util.Map;
39
import java.util.Set;
40
 
132 ilm 41
import org.h2.constant.ErrorCode;
42
 
182 ilm 43
public class SQLSyntaxH2 extends SQLSyntax {
17 ilm 44
 
142 ilm 45
    static protected final IdentityHashMap<String, String> DATE_SPECS;
46
 
47
    static {
48
        DATE_SPECS = new IdentityHashMap<String, String>(DateProp.JAVA_DATE_SPECS_PURE);
49
        DATE_SPECS.put(DateProp.MICROSECOND, "SSS000");
182 ilm 50
 
51
        XMLCodecUtils.register(SQLSyntaxH2.class, new DefaultPersistenceDelegate(new String[] {}));
142 ilm 52
    }
53
 
182 ilm 54
    final static SQLSyntax create(DBSystemRoot sysRoot) {
55
        boolean standardArray = true;
56
        if (sysRoot != null) {
57
            try {
58
                standardArray = Arrays.equals(new String[] { "foo" }, (Object[]) sysRoot.getDataSource().executeScalar("SELECT ARRAY['foo']"));
59
            } catch (RuntimeException e) {
60
                if (SQLUtils.findWithSQLState(e).getErrorCode() == ErrorCode.COLUMN_NOT_FOUND_1)
61
                    standardArray = false;
62
                else
63
                    throw e;
64
            }
65
        }
66
        return new SQLSyntaxH2(standardArray);
67
    }
68
 
69
    private final boolean standardArray;
70
 
71
    public SQLSyntaxH2(final boolean standardArray) {
142 ilm 72
        super(SQLSystem.H2, DATE_SPECS);
182 ilm 73
        this.standardArray = standardArray;
83 ilm 74
        this.typeNames.addAll(Boolean.class, "boolean", "bool", "bit");
75
        this.typeNames.addAll(Integer.class, "integer", "int", "int4", "mediumint");
76
        this.typeNames.addAll(Byte.class, "tinyint");
77
        this.typeNames.addAll(Short.class, "smallint", "int2");
78
        this.typeNames.addAll(Long.class, "bigint", "int8");
79
        this.typeNames.addAll(BigDecimal.class, "decimal", "numeric", "number");
80
        this.typeNames.addAll(Float.class, "real");
81
        this.typeNames.addAll(Double.class, "double precision", "float", "float4", "float8");
82
        this.typeNames.addAll(Timestamp.class, "timestamp", "smalldatetime", "datetime");
142 ilm 83
        this.typeNames.addAll(java.sql.Date.class, "date");
84
        this.typeNames.addAll(java.sql.Time.class, "time");
83 ilm 85
        this.typeNames.addAll(Blob.class, "blob", "tinyblob", "mediumblob", "longblob", "image",
132 ilm 86
                // byte[]
17 ilm 87
                "bytea", "raw", "varbinary", "longvarbinary", "binary");
83 ilm 88
        this.typeNames.addAll(Clob.class, "clob", "text", "tinytext", "mediumtext", "longtext");
89
        this.typeNames.addAll(String.class, "varchar", "longvarchar", "char", "character", "CHARACTER VARYING");
17 ilm 90
    }
91
 
92
    @Override
132 ilm 93
    public int getMaximumIdentifierLength() {
94
        // http://www.h2database.com/html/advanced.html#limits_limitations
95
        return Short.MAX_VALUE;
96
    }
97
 
98
    @Override
17 ilm 99
    public String getIDType() {
100
        return " int";
101
    }
102
 
103
    @Override
83 ilm 104
    public int getMaximumVarCharLength() {
105
        // http://www.h2database.com/html/datatypes.html#varchar_type
106
        return Integer.MAX_VALUE;
107
    }
108
 
109
    @Override
17 ilm 110
    public boolean isAuto(SQLField f) {
111
        if (f.getDefaultValue() == null)
112
            return false;
113
 
83 ilm 114
        final String def = f.getDefaultValue().toUpperCase();
80 ilm 115
        // we used to use IDENTITY which translate to long
116
        return (f.getType().getJavaType() == Integer.class || f.getType().getJavaType() == Long.class) && def.contains("NEXT VALUE") && def.contains("SYSTEM_SEQUENCE");
17 ilm 117
    }
118
 
119
    @Override
120
    public String getAuto() {
80 ilm 121
        // IDENTITY means long
122
        return " SERIAL";
17 ilm 123
    }
124
 
125
    @Override
126
    public String disableFKChecks(DBRoot b) {
127
        return "SET REFERENTIAL_INTEGRITY FALSE ;";
128
    }
129
 
130
    @Override
131
    public String enableFKChecks(DBRoot b) {
132
        return "SET REFERENTIAL_INTEGRITY TRUE ;";
133
    }
134
 
135
    @SuppressWarnings("unchecked")
136
    @Override
137
    public Map<String, Object> normalizeIndexInfo(final Map m) {
138
        // NON_UNIQUE is a boolean, COLUMN_NAME has a non-quoted name
139
        return m;
140
    }
141
 
142
    @Override
143
    public String getDropIndex(String name, SQLName tableName) {
144
        return "DROP INDEX IF EXISTS " + SQLBase.quoteIdentifier(name) + ";";
145
    }
146
 
147
    protected String setNullable(SQLField f, boolean b) {
73 ilm 148
        return "ALTER COLUMN " + f.getQuotedName() + " SET " + (b ? "" : "NOT") + " NULL";
17 ilm 149
    }
150
 
151
    @Override
83 ilm 152
    public Map<ClauseType, List<String>> getAlterField(SQLField f, Set<Properties> toAlter, String type, String defaultVal, Boolean nullable) {
17 ilm 153
        final List<String> res = new ArrayList<String>();
154
        if (toAlter.contains(Properties.TYPE)) {
155
            // MAYBE implement AlterTableAlterColumn.CHANGE_ONLY_TYPE
156
            final String newDef = toAlter.contains(Properties.DEFAULT) ? defaultVal : getDefault(f, type);
157
            final boolean newNullable = toAlter.contains(Properties.NULLABLE) ? nullable : getNullable(f);
80 ilm 158
            final SQLName seqName = f.getOwnedSequence();
159
            // sequence is used for the default so if default change, remove it (same behaviour than
160
            // H2)
161
            final String seqSQL = seqName == null || toAlter.contains(Properties.DEFAULT) ? "" : " SEQUENCE " + seqName.quote();
162
            res.add("ALTER COLUMN " + f.getQuotedName() + " " + getFieldDecl(type, newDef, newNullable) + seqSQL);
17 ilm 163
        } else {
164
            if (toAlter.contains(Properties.DEFAULT))
165
                res.add(this.setDefault(f, defaultVal));
166
        }
19 ilm 167
        // Contrary to the documentation "alter column type" doesn't change the nullable
168
        // e.g. ALTER COLUMN "VARCHAR" varchar(150) DEFAULT 'testAllProps' NULL
169
        if (toAlter.contains(Properties.NULLABLE))
170
            res.add(this.setNullable(f, nullable));
83 ilm 171
        return ListMap.singleton(ClauseType.ALTER_COL, res);
17 ilm 172
    }
173
 
174
    @Override
175
    public String getDropRoot(String name) {
73 ilm 176
        return "DROP SCHEMA IF EXISTS " + SQLBase.quoteIdentifier(name) + " ;";
17 ilm 177
    }
178
 
179
    @Override
180
    public String getCreateRoot(String name) {
73 ilm 181
        return "CREATE SCHEMA " + SQLBase.quoteIdentifier(name) + " ;";
17 ilm 182
    }
183
 
184
    @Override
185
    public String transfDefaultJDBC2SQL(SQLField f) {
83 ilm 186
        String res = f.getDefaultValue();
17 ilm 187
        if (res != null && f.getType().getJavaType() == String.class && res.trim().toUpperCase().startsWith("STRINGDECODE")) {
188
            // MAYBE create an attribute with a mem h2 db, instead of using db of f
189
            res = (String) f.getTable().getBase().getDataSource().executeScalar("CALL " + res);
190
            // this will be given to other db system, so don't use base specific quoting
191
            res = SQLBase.quoteStringStd(res);
192
        }
193
        return res;
194
    }
195
 
196
    @Override
197
    protected Tuple2<Boolean, String> getCast() {
198
        return Tuple2.create(true, " ");
199
    }
200
 
201
    @Override
202
    public void _loadData(final File f, final SQLTable t) {
203
        checkServerLocalhost(t);
142 ilm 204
        final String quotedPath = quoteString(f.getAbsolutePath());
73 ilm 205
        t.getDBSystemRoot().getDataSource().execute("insert into " + t.getSQLName().quote() + " select * from CSVREAD(" + quotedPath + ", NULL, 'UTF8', ',', '\"', '\\', '\\N') ;");
17 ilm 206
    }
207
 
208
    @Override
209
    protected void _storeData(final SQLTable t, final File f) {
210
        checkServerLocalhost(t);
142 ilm 211
        final String quotedPath = quoteString(f.getAbsolutePath());
212
        final String quotedSel = quoteString(SQLSyntaxPG.selectAll(t).asString());
73 ilm 213
        t.getBase().getDataSource().execute("CALL CSVWRITE(" + quotedPath + ", " + quotedSel + ", 'UTF8', ',', '\"', '\\', '\\N', '\n');");
17 ilm 214
    }
215
 
216
    @Override
217
    public String getCreateSynonym(SQLTable t, SQLName newName) {
218
        return null;
219
    }
220
 
221
    @Override
222
    public boolean supportMultiAlterClause() {
223
        return false;
224
    }
225
 
226
    @Override
142 ilm 227
    public String getDayOfWeek(String sqlTS) {
228
        return "DAY_OF_WEEK(" + sqlTS + ")";
229
    }
230
 
231
    @Override
67 ilm 232
    public String getFormatTimestamp(String sqlTS, boolean basic) {
142 ilm 233
        return this.getFormatTimestamp(sqlTS, SQLBase.quoteStringStd(basic ? TS_BASIC_JAVA_FORMAT : TS_EXTENDED_JAVA_FORMAT));
17 ilm 234
    }
235
 
142 ilm 236
    @Override
237
    public final String getFormatTimestamp(String sqlTS, String format) {
238
        return "FORMATDATETIME(" + sqlTS + ", " + format + ")";
239
    }
240
 
241
    @Override
242
    public String quoteForTimestampFormat(String text) {
243
        return SQLBase.quoteStringStd(text);
244
    }
245
 
67 ilm 246
    // (SELECT "C1" as "num", "C2" as "name" FROM VALUES(1, 'Hello'), (2, 'World')) AS V;
17 ilm 247
    @Override
67 ilm 248
    public String getConstantTable(List<List<String>> rows, String alias, List<String> columnsAlias) {
249
        // TODO submit a bug report to ask for V("num", "name") notation
250
        final StringBuilder sb = new StringBuilder();
251
        sb.append("( SELECT ");
252
        final int colCount = columnsAlias.size();
253
        for (int i = 0; i < colCount; i++) {
254
            sb.append(SQLBase.quoteIdentifier("C" + (i + 1)));
255
            sb.append(" as ");
256
            sb.append(SQLBase.quoteIdentifier(columnsAlias.get(i)));
257
            sb.append(", ");
258
        }
259
        // remove last ", "
260
        sb.setLength(sb.length() - 2);
261
        sb.append(" FROM ");
262
        sb.append(this.getValues(rows, colCount));
263
        sb.append(" ) AS ");
264
        sb.append(SQLBase.quoteIdentifier(alias));
265
        return sb.toString();
266
    }
267
 
268
    @Override
17 ilm 269
    public String getFunctionQuery(SQLBase b, Set<String> schemas) {
67 ilm 270
        // src can be null since H2 supports alias to Java static functions
271
        // perhaps join on FUNCTION_COLUMNS to find out parameters' types
272
        final String src = "coalesce(\"SOURCE\", \"JAVA_CLASS\" || '.' || \"JAVA_METHOD\" ||' parameter(s): ' || \"COLUMN_COUNT\")";
142 ilm 273
        return "SELECT ALIAS_SCHEMA as \"schema\", ALIAS_NAME as \"name\", " + src + " as \"src\" FROM \"INFORMATION_SCHEMA\".FUNCTION_ALIASES where ALIAS_CATALOG=" + this.quoteString(b.getMDName())
274
                + " and ALIAS_SCHEMA in (" + quoteStrings(schemas) + ")";
17 ilm 275
    }
276
 
277
    @Override
67 ilm 278
    public String getTriggerQuery(SQLBase b, TablesMap tables) {
142 ilm 279
        return "SELECT \"TRIGGER_NAME\", \"TABLE_SCHEMA\", \"TABLE_NAME\", \"JAVA_CLASS\" as \"ACTION\", \"SQL\" from INFORMATION_SCHEMA.TRIGGERS " + getTablesMapJoin(tables) + " where "
67 ilm 280
                + getInfoSchemaWhere(b);
17 ilm 281
    }
282
 
142 ilm 283
    private String getTablesMapJoin(final TablesMap tables) {
284
        return getTablesMapJoin(tables, SQLBase.quoteIdentifier("TABLE_SCHEMA"), SQLBase.quoteIdentifier("TABLE_NAME"));
17 ilm 285
    }
286
 
67 ilm 287
    private final String getInfoSchemaWhere(SQLBase b) {
142 ilm 288
        return "\"TABLE_CATALOG\" = " + this.quoteString(b.getMDName());
67 ilm 289
    }
290
 
17 ilm 291
    @Override
67 ilm 292
    public String getColumnsQuery(SQLBase b, TablesMap tables) {
17 ilm 293
        return "SELECT \"" + INFO_SCHEMA_NAMES_KEYS.get(0) + "\", \"" + INFO_SCHEMA_NAMES_KEYS.get(1) + "\", \"" + INFO_SCHEMA_NAMES_KEYS.get(2)
142 ilm 294
                + "\" , \"CHARACTER_SET_NAME\", \"COLLATION_NAME\", \"SEQUENCE_NAME\" from INFORMATION_SCHEMA.\"COLUMNS\" " + getTablesMapJoin(tables) + " where " + getInfoSchemaWhere(b);
17 ilm 295
    }
296
 
297
    @Override
298
    @SuppressWarnings("unchecked")
67 ilm 299
    public List<Map<String, Object>> getConstraints(SQLBase b, TablesMap tables) throws SQLException {
17 ilm 300
        final String sel = "SELECT \"TABLE_SCHEMA\", \"TABLE_NAME\", \"CONSTRAINT_NAME\", \n"
132 ilm 301
                //
83 ilm 302
                + "case \"CONSTRAINT_TYPE\"  when 'REFERENTIAL' then 'FOREIGN KEY' else \"CONSTRAINT_TYPE\" end as \"CONSTRAINT_TYPE\", \"COLUMN_LIST\", \"CHECK_EXPRESSION\" AS \"DEFINITION\"\n"
17 ilm 303
                //
142 ilm 304
                + "FROM INFORMATION_SCHEMA.CONSTRAINTS " + getTablesMapJoin(tables)
17 ilm 305
                // where
67 ilm 306
                + " where " + getInfoSchemaWhere(b);
17 ilm 307
        // don't cache since we don't listen on system tables
308
        final List<Map<String, Object>> res = (List<Map<String, Object>>) b.getDBSystemRoot().getDataSource().execute(sel, new IResultSetHandler(SQLDataSource.MAP_LIST_HANDLER, false));
309
        for (final Map<String, Object> m : res) {
310
            // FIXME change h2 to use ValueArray in MetaTable to handle names with ','
311
            // new ArrayList otherwise can't be encoded to XML
312
            m.put("COLUMN_NAMES", new ArrayList<String>(SQLRow.toList((String) m.remove("COLUMN_LIST"))));
313
        }
314
        return res;
315
    }
316
 
317
    @Override
318
    public String getDropTrigger(Trigger t) {
73 ilm 319
        return "DROP TRIGGER " + new SQLName(t.getTable().getSchema().getName(), t.getName()).quote();
17 ilm 320
    }
83 ilm 321
 
322
    @Override
323
    public String getUpdate(SQLTable t, List<String> tables, Map<String, String> setPart) throws UnsupportedOperationException {
324
        if (tables.size() > 0)
325
            throw new UnsupportedOperationException();
326
        return super.getUpdate(t, tables, setPart);
327
    }
132 ilm 328
 
329
    @Override
330
    public boolean isDeadLockException(SQLException exn) {
331
        final SQLException stateExn = SQLUtils.findWithSQLState(exn);
332
        // in H2 deadlock is only detected at the table level (e.g DDL)
333
        // in MVCC, if two transactions modify the same row the second one will repeatedly throw
334
        // CONCURRENT_UPDATE_1 until LockTimeout
335
        // otherwise, the second one will timeout while waiting for the table lock
336
        return stateExn.getErrorCode() == ErrorCode.DEADLOCK_1 || stateExn.getErrorCode() == ErrorCode.LOCK_TIMEOUT_1;
337
    }
182 ilm 338
 
339
    @Override
340
    public boolean isTableNotFoundException(Exception exn) {
341
        final SQLException stateExn = SQLUtils.findWithSQLState(exn);
342
        return stateExn.getErrorCode() == ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1 || stateExn.getErrorCode() == ErrorCode.SCHEMA_NOT_FOUND_1;
343
    }
344
 
345
    @Override
346
    public String getSessionIDExpression() {
347
        return "SESSION_ID()";
348
    }
349
 
350
    @Override
351
    public String getSessionsQuery(final DBSystemRoot sysRoot, final boolean includeSelf) {
352
        final String allRows = "SELECT \"ID\", \"STATEMENT\" as \"QUERY\", \"USER_NAME\" FROM INFORMATION_SCHEMA.SESSIONS";
353
        if (includeSelf)
354
            return allRows;
355
        return allRows + " WHERE \"ID\" != " + this.getSessionIDExpression();
356
    }
357
 
358
    @Override
359
    public String getVersionFunction() {
360
        return "H2VERSION()";
361
    }
362
 
363
    @Override
364
    public String getAllowConnectionsQuery(String sysRootName, final boolean allow) {
365
        return "SET EXCLUSIVE " + (allow ? "0" : "1");
366
    }
367
 
368
    @Override
369
    public boolean isConnectionDisallowedException(SQLException exn) {
370
        return exn.getErrorCode() == ErrorCode.DATABASE_IS_IN_EXCLUSIVE_MODE;
371
    }
372
 
373
    @Override
374
    public String getSQLArray(final List<String> sqlExpressions, final String type) {
375
        // H2 cannot specify type in SQL, so cast each item
376
        final ITransformer<? super String, ?> tf = type == null ? Transformer.nopTransformer() : (s) -> {
377
            return this.cast(s, type);
378
        };
379
        final String items = CollectionUtils.join(sqlExpressions, ", ", tf);
380
        if (this.standardArray) {
381
            return "ARRAY[" + items + ']';
382
        } else {
383
            // For the comma, see http://h2database.com/html/grammar.html#array
384
            return '(' + items + (sqlExpressions.size() == 1 ? ",)" : ")");
385
        }
386
    }
387
 
388
    @Override
389
    public String getSQLArrayContains(String arrayExpression, String itemExpression) {
390
        return "ARRAY_CONTAINS(" + arrayExpression + ", " + itemExpression + ")";
391
    }
392
 
393
    @Override
394
    public String getSQLArrayLength(final String arrayExpression) {
395
        return "ARRAY_LENGTH(" + arrayExpression + ")";
396
    }
397
 
398
    @Override
399
    public String getSQLArrayConcat(final String arrayExpression, final String array2Expression) {
400
        return "array_cat(" + arrayExpression + ", " + array2Expression + ")";
401
    }
402
 
403
    @Override
404
    public String getSQLArrayAppend(final String arrayExpression, final String itemExpression) {
405
        return "array_append(" + arrayExpression + ", " + itemExpression + ")";
406
    }
407
 
408
    @Override
409
    public String getSQLArraySlice(final String arrayExpression, final String index1Expression, final String index2Expression) {
410
        return "ARRAY_SLICE(" + arrayExpression + ", " + index1Expression + ", " + index2Expression + ")";
411
    }
17 ilm 412
}