OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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