OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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