OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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