OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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