OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 41 | Rev 61 | 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.sql.model.SQLTable.Index;
57 ilm 18
import org.openconcerto.sql.model.graph.Link.Rule;
17 ilm 19
import org.openconcerto.sql.utils.ChangeTable.ClauseType;
20
import org.openconcerto.sql.utils.ChangeTable.OutsideClause;
21 ilm 21
import org.openconcerto.sql.utils.SQLUtils;
17 ilm 22
import org.openconcerto.sql.utils.SQLUtils.SQLFactory;
23
import org.openconcerto.utils.CollectionMap;
24
import org.openconcerto.utils.CollectionUtils;
25
import org.openconcerto.utils.Tuple2;
26
import org.openconcerto.utils.cc.IClosure;
27
import org.openconcerto.utils.cc.ITransformer;
28
 
29
import java.io.BufferedReader;
30
import java.io.BufferedWriter;
31
import java.io.File;
32
import java.io.FileInputStream;
33
import java.io.FileOutputStream;
34
import java.io.IOException;
35
import java.io.InputStreamReader;
36
import java.io.OutputStreamWriter;
37
import java.io.Writer;
38
import java.math.BigDecimal;
39
import java.math.BigInteger;
40
import java.sql.Blob;
41
import java.sql.Clob;
42
import java.sql.Connection;
43
import java.sql.SQLException;
44
import java.sql.Timestamp;
45
import java.util.ArrayList;
46
import java.util.Collections;
47
import java.util.Date;
48
import java.util.Iterator;
49
import java.util.List;
50
import java.util.Map;
21 ilm 51
import java.util.Map.Entry;
17 ilm 52
import java.util.Set;
53
 
54
import org.apache.commons.dbcp.DelegatingConnection;
55
 
21 ilm 56
/**
57
 * MySQL can enable compression with the "useCompression" connection property. Compression status
58
 * can be checked with "show global status like 'Compression';".
59
 *
60
 * @author Sylvain CUAZ
61
 */
17 ilm 62
class SQLSyntaxMySQL extends SQLSyntax {
63
 
64
    SQLSyntaxMySQL() {
65
        super(SQLSystem.MYSQL);
66
        this.typeNames.putAll(Boolean.class, "boolean", "bool", "bit");
67
        this.typeNames.putAll(Integer.class, "integer", "int");
68
        this.typeNames.putAll(Long.class, "bigint");
69
        this.typeNames.putAll(BigInteger.class, "bigint");
70
        this.typeNames.putAll(BigDecimal.class, "decimal", "numeric");
71
        this.typeNames.putAll(Float.class, "float");
72
        this.typeNames.putAll(Double.class, "double precision", "real");
73
        this.typeNames.putAll(Timestamp.class, "timestamp");
74
        this.typeNames.putAll(java.util.Date.class, "time");
75
        this.typeNames.putAll(Blob.class, "blob", "tinyblob", "mediumblob", "longblob", "varbinary", "binary");
76
        this.typeNames.putAll(Clob.class, "text", "tinytext", "mediumtext", "longtext", "varchar", "char");
77
        this.typeNames.putAll(String.class, "varchar", "char");
78
    }
79
 
80
    public String getIDType() {
81
        return " int";
82
    }
83
 
84
    @Override
85
    public boolean isAuto(SQLField f) {
86
        return "YES".equals(f.getMetadata("IS_AUTOINCREMENT"));
87
    }
88
 
89
    @Override
90
    public String getAuto() {
91
        return this.getIDType() + " AUTO_INCREMENT NOT NULL";
92
    }
93
 
94
    @Override
95
    public String getDateAndTimeType() {
96
        return "datetime";
97
    }
98
 
99
    @Override
100
    protected String getAutoDateType(SQLField f) {
101
        return "timestamp";
102
    }
103
 
104
    @Override
105
    protected Tuple2<Boolean, String> getCast() {
106
        return null;
107
    }
108
 
109
    @Override
110
    protected boolean supportsDefault(String typeName) {
111
        return !typeName.contains("text") && !typeName.contains("blob");
112
    }
113
 
114
    @Override
115
    public String transfDefaultJDBC2SQL(SQLField f) {
116
        final Class<?> javaType = f.getType().getJavaType();
117
        String res = (String) f.getDefaultValue();
118
        if (res == null)
119
            // either no default or NULL default
120
            // see http://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html
121
            // (works the same way for 5.1 and 6.0)
122
            if (Boolean.FALSE.equals(f.isNullable()))
123
                res = null;
124
            else {
125
                res = "NULL";
126
            }
127
        else if (javaType == String.class)
128
            // this will be given to other db system, so don't use base specific quoting
129
            res = SQLBase.quoteStringStd(res);
130
        // MySQL 5.0.24a puts empty strings when not specifying default
131
        else if (res.length() == 0)
132
            res = null;
133
        // quote neither functions nor CURRENT_TIMESTAMP
134
        else if (Date.class.isAssignableFrom(javaType) && !res.trim().endsWith("()") && !res.toLowerCase().contains("timestamp"))
135
            res = SQLBase.quoteStringStd(res);
136
        else if (javaType == Boolean.class)
137
            res = res.equals("0") ? "FALSE" : "TRUE";
138
        return res;
139
    }
140
 
141
    @Override
142
    public String getCreateTableSuffix() {
143
        return " ENGINE = InnoDB ";
144
    }
145
 
146
    @Override
147
    public String disableFKChecks(DBRoot b) {
148
        return "SET FOREIGN_KEY_CHECKS=0;";
149
    }
150
 
151
    @Override
152
    public String enableFKChecks(DBRoot b) {
153
        return "SET FOREIGN_KEY_CHECKS=1;";
154
    }
155
 
156
    @Override
157
    public String getDropFK() {
158
        return "DROP FOREIGN KEY ";
159
    }
160
 
161
    @Override
57 ilm 162
    protected String getRuleSQL(Rule r) {
163
        if (r == Rule.SET_DEFAULT)
164
            throw new UnsupportedOperationException(r + " isn't supported");
165
        return super.getRuleSQL(r);
166
    }
167
 
168
    @Override
17 ilm 169
    public String getDropConstraint() {
170
        // in MySQL there's only 2 types of constraints : foreign keys and unique
171
        // fk are handled by getDropFK(), so this is just for unique
172
        // in MySQL UNIQUE constraint and index are one and the same thing
173
        return "DROP INDEX ";
174
    }
175
 
176
    @Override
177
    public Map<String, Object> normalizeIndexInfo(final Map m) {
178
        final Map<String, Object> res = copyIndexInfoMap(m);
179
        final Object nonUnique = res.get("NON_UNIQUE");
180
        // some newer versions of MySQL now return Boolean
181
        res.put("NON_UNIQUE", nonUnique instanceof Boolean ? nonUnique : Boolean.valueOf((String) nonUnique));
182
        res.put("COLUMN_NAME", res.get("COLUMN_NAME"));
183
        return res;
184
    }
185
 
186
    @Override
187
    public String getDropIndex(String name, SQLName tableName) {
188
        return "DROP INDEX " + SQLBase.quoteIdentifier(name) + " on " + tableName.quote() + ";";
189
    }
190
 
191
    @Override
192
    protected String getCreateIndex(String cols, SQLName tableName, Index i) {
193
        final String method = i.getMethod() != null ? " USING " + i.getMethod() : "";
194
        return super.getCreateIndex(cols, tableName, i) + method;
195
    }
196
 
197
    @Override
198
    public List<String> getAlterField(SQLField f, Set<Properties> toAlter, String type, String defaultVal, Boolean nullable) {
199
        final boolean newNullable = toAlter.contains(Properties.NULLABLE) ? nullable : getNullable(f);
200
        final String newType = toAlter.contains(Properties.TYPE) ? type : getType(f);
201
        final String newDef = toAlter.contains(Properties.DEFAULT) ? defaultVal : getDefault(f, newType);
202
 
203
        return Collections.singletonList(SQLSelect.quote("MODIFY COLUMN %n " + newType + getNullableClause(newNullable) + getDefaultClause(newDef), f));
204
    }
205
 
206
    @Override
207
    public String getDropRoot(String name) {
208
        return SQLSelect.quote("DROP DATABASE IF EXISTS %i ;", name);
209
    }
210
 
211
    @Override
212
    public String getCreateRoot(String name) {
213
        return SQLSelect.quote("CREATE DATABASE %i ;", name);
214
    }
215
 
216
    @Override
217
    protected void _storeData(final SQLTable t, final File file) {
218
        checkServerLocalhost(t);
219
        final CollectionMap<String, String> charsets = new CollectionMap<String, String>();
220
        for (final SQLField f : t.getFields()) {
221
            final Object charset = f.getInfoSchema().get("CHARACTER_SET_NAME");
222
            // non string field
223
            if (charset != null)
224
                charsets.put(charset, f.getName());
225
        }
226
        if (charsets.size() > 1)
227
            // MySQL dumps strings in binary, so fields must be consistent otherwise the
228
            // file is invalid
229
            throw new IllegalArgumentException(t + " has more than on character set : " + charsets);
230
        // if no string cols there should only be values within ASCII (eg dates, ints, etc)
231
        final String charset = charsets.size() == 0 ? "UTF8" : charsets.keySet().iterator().next();
232
        final String cols = CollectionUtils.join(t.getOrderedFields(), ",", new ITransformer<SQLField, String>() {
233
            @Override
234
            public String transformChecked(SQLField input) {
235
                return SQLBase.quoteStringStd(input.getName());
236
            }
237
        });
238
        try {
239
            final File tmp = File.createTempFile(SQLSyntaxMySQL.class.getSimpleName() + "storeData", ".txt");
240
            // mysql cannot overwrite files
241
            tmp.delete();
242
            final SQLSelect sel = new SQLSelect(t.getBase(), true).addSelectStar(t);
243
            // store the data in the temp file
244
            t.getBase().getDataSource().execute(t.getBase().quote("SELECT " + cols + " UNION " + sel.asString() + " INTO OUTFILE %s " + getDATA_OPTIONS(t) + ";", tmp.getAbsolutePath()));
245
            // then read it to remove superfluous escape char and convert to utf8
246
            final BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(tmp), charset));
247
            final Writer w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
248
            int count;
249
            final char[] buf = new char[1000 * 1024];
250
            int offset = 0;
251
            final char[] wbuf = new char[buf.length];
252
            boolean wasBackslash = false;
253
            while ((count = r.read(buf, offset, buf.length - offset)) != -1) {
254
                int wbufLength = 0;
255
                for (int i = 0; i < count; i++) {
256
                    final char c = buf[i];
257
                    // MySQL escapes the field delimiter (which other systems do as well)
258
                    // but also "LINES TERMINATED BY" which others don't understand
259
                    if (wasBackslash && c == '\n')
260
                        // overwrite the backslash
261
                        wbuf[wbufLength - 1] = c;
262
                    else
263
                        wbuf[wbufLength++] = c;
264
                    wasBackslash = c == '\\';
265
                }
266
                // the read buffer ends with a backslash
267
                if (wasBackslash) {
268
                    // restore state one char before
269
                    wbufLength--;
270
                    wasBackslash = wbuf[wbufLength - 1] == '\\';
271
                    buf[0] = '\\';
272
                    offset = 1;
273
                } else
274
                    offset = 0;
275
                w.write(wbuf, 0, wbufLength);
276
            }
277
            r.close();
278
            w.close();
279
            tmp.delete();
280
        } catch (IOException e) {
281
            throw new IllegalStateException(e);
282
        }
283
    }
284
 
285
    private static String getDATA_OPTIONS(DBStructureItem<?> i) {
286
        return i.getAnc(SQLBase.class).quote("FIELDS TERMINATED BY ',' ENCLOSED BY '\"' ESCAPED BY %s LINES TERMINATED BY '\n' ", "\\");
287
    }
288
 
289
    @Override
290
    public void _loadData(final File f, final SQLTable t) {
291
        // we always store in utf8 regardless of the encoding of the columns
292
        final SQLDataSource ds = t.getDBSystemRoot().getDataSource();
293
        try {
294
            SQLUtils.executeAtomic(ds, new SQLFactory<Object>() {
295
                @Override
296
                public Object create() throws SQLException {
297
                    final String charsetClause;
298
                    final Connection conn = ((DelegatingConnection) ds.getConnection()).getInnermostDelegate();
299
                    if (((com.mysql.jdbc.Connection) conn).versionMeetsMinimum(5, 0, 38)) {
300
                        charsetClause = "CHARACTER SET utf8 ";
301
                    } else {
302
                        // variable name is in the first column
303
                        final String dbCharset = ds.executeA1("show variables like 'character_set_database'")[1].toString().trim().toLowerCase();
304
                        if (dbCharset.equals("utf8")) {
305
                            charsetClause = "";
306
                        } else {
307
                            throw new IllegalStateException("the database charset is not utf8 and this version doesn't support specifying another one : " + dbCharset);
308
                        }
309
                    }
310
                    ds.execute(t.getBase().quote("LOAD DATA LOCAL INFILE %s INTO TABLE %f " + charsetClause + getDATA_OPTIONS(t) + " IGNORE 1 LINES;", f.getAbsolutePath(), t));
311
                    return null;
312
                }
313
            });
314
        } catch (Exception e) {
315
            throw new IllegalStateException("Couldn't load " + f + " into " + t, e);
316
        }
317
    }
318
 
319
    @Override
320
    public SQLBase createBase(SQLServer server, String name, String login, String pass, IClosure<SQLDataSource> dsInit) {
321
        return new MySQLBase(server, name, login, pass, dsInit);
322
    }
323
 
324
    @Override
325
    public String getNullIsDataComparison(String x, boolean eq, String y) {
326
        final String nullSafe = x + " <=> " + y;
327
        if (eq)
328
            return nullSafe;
329
        else
330
            return "NOT (" + nullSafe + ")";
331
    }
332
 
333
    @Override
334
    public String getFunctionQuery(SQLBase b, Set<String> schemas) {
335
        // MySQL puts the db name in schema
336
        return "SELECT null as \"schema\", ROUTINE_NAME as \"name\", ROUTINE_DEFINITION as \"src\" FROM \"information_schema\".ROUTINES where ROUTINE_CATALOG is null and ROUTINE_SCHEMA = '"
337
                + b.getMDName() + "'";
338
    }
339
 
340
    @Override
341
    public String getTriggerQuery(SQLBase b, Set<String> schemas, Set<String> tables) {
342
        return "SELECT \"TRIGGER_NAME\", null as \"TABLE_SCHEMA\", EVENT_OBJECT_TABLE as \"TABLE_NAME\", ACTION_STATEMENT as \"ACTION\", null as \"SQL\" from INFORMATION_SCHEMA.TRIGGERS where "
343
                + getInfoSchemaWhere("\"EVENT_OBJECT_CATALOG\"", b, "EVENT_OBJECT_SCHEMA", schemas, "EVENT_OBJECT_TABLE", tables);
344
    }
345
 
346
    private final String getInfoSchemaWhere(final String catCol, SQLBase b, final String schemaCol, Set<String> schemas, final String tableCol, Set<String> tables) {
347
        final String tableWhere = tables == null ? "" : " and " + tableCol + " in (" + quoteStrings(b, tables) + ")";
348
        return catCol + " is null and " + schemaCol + " = '" + b.getMDName() + "' " + tableWhere;
349
    }
350
 
351
    @Override
352
    public String getColumnsQuery(SQLBase b, Set<String> schemas, Set<String> tables) {
353
        return "SELECT null as \"" + INFO_SCHEMA_NAMES_KEYS.get(0) + "\", \"" + INFO_SCHEMA_NAMES_KEYS.get(1) + "\", \"" + INFO_SCHEMA_NAMES_KEYS.get(2)
354
                + "\" , \"CHARACTER_SET_NAME\", \"COLLATION_NAME\" from INFORMATION_SCHEMA.\"COLUMNS\" where "
355
                + getInfoSchemaWhere("\"TABLE_CATALOG\"", b, "TABLE_SCHEMA", schemas, "TABLE_NAME", tables);
356
    }
357
 
358
    @Override
359
    @SuppressWarnings("unchecked")
360
    public List<Map<String, Object>> getConstraints(SQLBase b, Set<String> schemas, Set<String> tables) throws SQLException {
361
        final String sel = "SELECT null as \"TABLE_SCHEMA\", c.\"TABLE_NAME\", c.\"CONSTRAINT_NAME\", tc.\"CONSTRAINT_TYPE\", \"COLUMN_NAME\", c.\"ORDINAL_POSITION\"\n"
362
                // from
363
                + " FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE c\n"
364
                // "-- sub-select otherwise at least 15s\n" +
365
                + "JOIN (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS T where " + getInfoSchemaWhere("\"CONSTRAINT_CATALOG\"", b, "TABLE_SCHEMA", schemas, "TABLE_NAME", tables)
366
                + ") tc on tc.\"TABLE_SCHEMA\" = c.\"TABLE_SCHEMA\" and tc.\"TABLE_NAME\"=c.\"TABLE_NAME\" and tc.\"CONSTRAINT_NAME\"=c.\"CONSTRAINT_NAME\"\n"
367
                // where
41 ilm 368
                + " where " + getInfoSchemaWhere("c.\"TABLE_CATALOG\"", b, "c.TABLE_SCHEMA", schemas, "c.TABLE_NAME", tables)
17 ilm 369
                + "order by c.\"TABLE_SCHEMA\", c.\"TABLE_NAME\", c.\"CONSTRAINT_NAME\", c.\"ORDINAL_POSITION\"";
370
        // don't cache since we don't listen on system tables
371
        final List<Map<String, Object>> res = (List<Map<String, Object>>) b.getDBSystemRoot().getDataSource().execute(sel, new IResultSetHandler(SQLDataSource.MAP_LIST_HANDLER, false));
372
        mergeColumnNames(res);
373
        return res;
374
    }
375
 
376
    static void mergeColumnNames(final List<Map<String, Object>> res) {
377
        final Iterator<Map<String, Object>> listIter = res.iterator();
378
        List<String> l = null;
379
        while (listIter.hasNext()) {
380
            final Map<String, Object> m = listIter.next();
381
            // don't leave the meaningless position (it will always be equal to 1)
382
            final int pos = ((Number) m.remove("ORDINAL_POSITION")).intValue();
383
            if (pos == 1) {
384
                l = new ArrayList<String>();
385
                m.put("COLUMN_NAMES", l);
386
            } else {
387
                listIter.remove();
388
            }
389
            l.add((String) m.remove("COLUMN_NAME"));
390
        }
391
    }
392
 
393
    @Override
394
    public String getDropTrigger(Trigger t) {
395
        return SQLBase.quoteStd("DROP TRIGGER %i", new SQLName(t.getTable().getSchema().getName(), t.getName()));
396
    }
397
 
398
    @Override
399
    public String getUpdate(final SQLTable t, List<String> tables, Map<String, String> setPart) {
400
        final List<String> l = new ArrayList<String>(tables);
401
        l.add(0, t.getSQLName().quote());
402
        return CollectionUtils.join(l, ", ") + "\nSET " + CollectionUtils.join(setPart.entrySet(), ",\n", new ITransformer<Entry<String, String>, String>() {
403
            @Override
404
            public String transformChecked(Entry<String, String> input) {
405
                // MySQL needs to prefix the fields, since there's no designated table to update
406
                return t.getField(input.getKey()).getSQLName(t).quote() + " = " + input.getValue();
407
            }
408
        });
409
    }
410
 
411
    public OutsideClause getSetTableComment(final String comment) {
412
        return new OutsideClause() {
413
            @Override
414
            public ClauseType getType() {
415
                return ClauseType.OTHER;
416
            }
417
 
418
            @Override
419
            public String asString(SQLName tableName) {
420
                return "ALTER TABLE " + tableName.quote() + " COMMENT = " + SQLBase.quoteStringStd(comment) + ";";
421
            }
422
        };
423
    }
424
}