OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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