OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 17 | Rev 41 | 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;
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.DEFAULT))
107
                res.add(this.setDefault(f, defaultVal));
108
        }
19 ilm 109
        // Contrary to the documentation "alter column type" doesn't change the nullable
110
        // e.g. ALTER COLUMN "VARCHAR" varchar(150) DEFAULT 'testAllProps' NULL
111
        if (toAlter.contains(Properties.NULLABLE))
112
            res.add(this.setNullable(f, nullable));
17 ilm 113
        return res;
114
    }
115
 
116
    @Override
117
    public String getDropRoot(String name) {
118
        return SQLSelect.quote("DROP SCHEMA IF EXISTS %i ;", name);
119
    }
120
 
121
    @Override
122
    public String getCreateRoot(String name) {
123
        return SQLSelect.quote("CREATE SCHEMA %i ;", name);
124
    }
125
 
126
    @Override
127
    public String transfDefaultJDBC2SQL(SQLField f) {
128
        String res = (String) f.getDefaultValue();
129
        if (res != null && f.getType().getJavaType() == String.class && res.trim().toUpperCase().startsWith("STRINGDECODE")) {
130
            // MAYBE create an attribute with a mem h2 db, instead of using db of f
131
            res = (String) f.getTable().getBase().getDataSource().executeScalar("CALL " + res);
132
            // this will be given to other db system, so don't use base specific quoting
133
            res = SQLBase.quoteStringStd(res);
134
        }
135
        return res;
136
    }
137
 
138
    @Override
139
    protected Tuple2<Boolean, String> getCast() {
140
        return Tuple2.create(true, " ");
141
    }
142
 
143
    @Override
144
    public void _loadData(final File f, final SQLTable t) {
145
        checkServerLocalhost(t);
146
        t.getDBSystemRoot().getDataSource().execute(SQLSelect.quote("insert into %f select * from CSVREAD(%s, NULL, 'UTF8', ',', '\"', '\\', '\\N') ;", t, f.getAbsolutePath()));
147
    }
148
 
149
    @Override
150
    protected void _storeData(final SQLTable t, final File f) {
151
        checkServerLocalhost(t);
152
        final SQLSelect sel = SQLSyntaxPG.selectAll(t);
153
        t.getBase().getDataSource().execute(SQLSelect.quote("CALL CSVWRITE(%s, %s, 'UTF8', ',', '\"', '\\', '\\N', '\n');", f.getAbsolutePath(), sel.asString()));
154
    }
155
 
156
    @Override
157
    protected boolean isServerLocalhost(SQLServer s) {
158
        return s.getName().startsWith("mem") || s.getName().startsWith("file") || NetUtils.isSelfAddr(getAddr(s));
159
    }
160
 
161
    private String getAddr(SQLServer s) {
162
        if (s.getName().startsWith("tcp") || s.getName().startsWith("ssl")) {
163
            final int startIndex = "tcp://".length();
164
            final int endIndex = s.getName().indexOf('/', startIndex);
165
            return s.getName().substring(startIndex, endIndex < 0 ? s.getName().length() : endIndex);
166
        } else
167
            return null;
168
    }
169
 
170
    @Override
171
    public String getCreateSynonym(SQLTable t, SQLName newName) {
172
        return null;
173
    }
174
 
175
    @Override
176
    public boolean supportMultiAlterClause() {
177
        return false;
178
    }
179
 
180
    @Override
181
    public String getNullIsDataComparison(String x, boolean eq, String y) {
182
        // TODO use === or at least fix H2 :
183
        // TRUE or null => TRUE
184
        // FALSE or null => null
185
        final String nullSafe = x + " = " + y + " or ( " + x + " is null and " + y + " is null)";
186
        if (eq)
187
            return nullSafe;
188
        else
189
            return x + " <> " + y + " or (" + x + " is null and " + y + " is not null) " + " or (" + x + " is not null and " + y + " is null) ";
190
    }
191
 
192
    @Override
193
    public String getFunctionQuery(SQLBase b, Set<String> schemas) {
194
        // src is null since H2 only supports alias to Java static functions
195
        // "SELECT ALIAS_SCHEMA as \"schema\", ALIAS_NAME as \"name\", null as \"src\" FROM \"INFORMATION_SCHEMA\".FUNCTION_ALIASES where ALIAS_CATALOG='"
196
        // + this.getBase().getMDName() + "' and ALIAS_SCHEMA in (" +
197
        // toString(proceduresBySchema.keySet()) + ")";
198
 
199
        // H2 functions are per db not per schema, so this doesn't fit our structure
200
        return null;
201
    }
202
 
203
    @Override
204
    public String getTriggerQuery(SQLBase b, Set<String> schemas, Set<String> tables) {
205
        return "SELECT \"TRIGGER_NAME\", \"TABLE_SCHEMA\", \"TABLE_NAME\", \"JAVA_CLASS\" as \"ACTION\", \"SQL\" from INFORMATION_SCHEMA.TRIGGERS where " + getInfoSchemaWhere(b, schemas, tables);
206
    }
207
 
208
    private final String getInfoSchemaWhere(SQLBase b, Set<String> schemas, Set<String> tables) {
209
        final String tableWhere = tables == null ? "" : " and \"TABLE_NAME\" in (" + quoteStrings(b, tables) + ")";
210
        return "\"TABLE_CATALOG\" = '" + b.getMDName() + "' and \"TABLE_SCHEMA\" in (" + quoteStrings(b, schemas) + ") " + tableWhere;
211
    }
212
 
213
    @Override
214
    public String getColumnsQuery(SQLBase b, Set<String> schemas, Set<String> tables) {
215
        return "SELECT \"" + INFO_SCHEMA_NAMES_KEYS.get(0) + "\", \"" + INFO_SCHEMA_NAMES_KEYS.get(1) + "\", \"" + INFO_SCHEMA_NAMES_KEYS.get(2)
216
                + "\" , \"CHARACTER_SET_NAME\", \"COLLATION_NAME\" from INFORMATION_SCHEMA.\"COLUMNS\" where " + getInfoSchemaWhere(b, schemas, tables);
217
    }
218
 
219
    @Override
220
    @SuppressWarnings("unchecked")
221
    public List<Map<String, Object>> getConstraints(SQLBase b, Set<String> schemas, Set<String> tables) throws SQLException {
222
        final String sel = "SELECT \"TABLE_SCHEMA\", \"TABLE_NAME\", \"CONSTRAINT_NAME\", \n"
223
        //
224
                + "case \"CONSTRAINT_TYPE\"  when 'REFERENTIAL' then 'FOREIGN KEY' else \"CONSTRAINT_TYPE\" end as \"CONSTRAINT_TYPE\", \"COLUMN_LIST\"\n"
225
                //
226
                + "FROM INFORMATION_SCHEMA.CONSTRAINTS"
227
                // where
228
                + " where \"CONSTRAINT_TYPE\" not in ('REFERENTIAL', 'PRIMARY KEY') and\n" + getInfoSchemaWhere(b, schemas, tables);
229
        // don't cache since we don't listen on system tables
230
        final List<Map<String, Object>> res = (List<Map<String, Object>>) b.getDBSystemRoot().getDataSource().execute(sel, new IResultSetHandler(SQLDataSource.MAP_LIST_HANDLER, false));
231
        for (final Map<String, Object> m : res) {
232
            // FIXME change h2 to use ValueArray in MetaTable to handle names with ','
233
            // new ArrayList otherwise can't be encoded to XML
234
            m.put("COLUMN_NAMES", new ArrayList<String>(SQLRow.toList((String) m.remove("COLUMN_LIST"))));
235
        }
236
        return res;
237
    }
238
 
239
    @Override
240
    public String getDropTrigger(Trigger t) {
241
        return SQLBase.quoteStd("DROP TRIGGER %i", new SQLName(t.getTable().getSchema().getName(), t.getName()));
242
    }
243
}