OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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