OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 61 | 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;
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;
38
import java.io.Writer;
39
import java.math.BigDecimal;
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 ilm 67
        this.typeNames.putAll(Short.class, "smallint");
17 ilm 68
        this.typeNames.putAll(Integer.class, "integer", "int");
69
        this.typeNames.putAll(Long.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);
61 ilm 201
        String newDef = toAlter.contains(Properties.DEFAULT) ? defaultVal : getDefault(f, newType);
202
        // MySQL doesn't support "NOT NULL DEFAULT NULL" so use the equivalent "NOT NULL"
203
        if (!newNullable && newDef != null && newDef.trim().toUpperCase().equals("NULL"))
204
            newDef = null;
17 ilm 205
 
67 ilm 206
        return Collections.singletonList(SQLSelect.quote("MODIFY COLUMN %n " + getFieldDecl(newType, newDef, newNullable), f));
17 ilm 207
    }
208
 
209
    @Override
210
    public String getDropRoot(String name) {
211
        return SQLSelect.quote("DROP DATABASE IF EXISTS %i ;", name);
212
    }
213
 
214
    @Override
215
    public String getCreateRoot(String name) {
216
        return SQLSelect.quote("CREATE DATABASE %i ;", name);
217
    }
218
 
219
    @Override
220
    protected void _storeData(final SQLTable t, final File file) {
221
        checkServerLocalhost(t);
222
        final CollectionMap<String, String> charsets = new CollectionMap<String, String>();
223
        for (final SQLField f : t.getFields()) {
224
            final Object charset = f.getInfoSchema().get("CHARACTER_SET_NAME");
225
            // non string field
226
            if (charset != null)
227
                charsets.put(charset, f.getName());
228
        }
229
        if (charsets.size() > 1)
230
            // MySQL dumps strings in binary, so fields must be consistent otherwise the
231
            // file is invalid
232
            throw new IllegalArgumentException(t + " has more than on character set : " + charsets);
233
        // if no string cols there should only be values within ASCII (eg dates, ints, etc)
234
        final String charset = charsets.size() == 0 ? "UTF8" : charsets.keySet().iterator().next();
235
        final String cols = CollectionUtils.join(t.getOrderedFields(), ",", new ITransformer<SQLField, String>() {
236
            @Override
237
            public String transformChecked(SQLField input) {
238
                return SQLBase.quoteStringStd(input.getName());
239
            }
240
        });
241
        try {
242
            final File tmp = File.createTempFile(SQLSyntaxMySQL.class.getSimpleName() + "storeData", ".txt");
243
            // mysql cannot overwrite files
244
            tmp.delete();
245
            final SQLSelect sel = new SQLSelect(t.getBase(), true).addSelectStar(t);
246
            // store the data in the temp file
247
            t.getBase().getDataSource().execute(t.getBase().quote("SELECT " + cols + " UNION " + sel.asString() + " INTO OUTFILE %s " + getDATA_OPTIONS(t) + ";", tmp.getAbsolutePath()));
248
            // then read it to remove superfluous escape char and convert to utf8
249
            final BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(tmp), charset));
250
            final Writer w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
251
            int count;
252
            final char[] buf = new char[1000 * 1024];
253
            int offset = 0;
254
            final char[] wbuf = new char[buf.length];
255
            boolean wasBackslash = false;
256
            while ((count = r.read(buf, offset, buf.length - offset)) != -1) {
257
                int wbufLength = 0;
258
                for (int i = 0; i < count; i++) {
259
                    final char c = buf[i];
260
                    // MySQL escapes the field delimiter (which other systems do as well)
261
                    // but also "LINES TERMINATED BY" which others don't understand
262
                    if (wasBackslash && c == '\n')
263
                        // overwrite the backslash
264
                        wbuf[wbufLength - 1] = c;
265
                    else
266
                        wbuf[wbufLength++] = c;
267
                    wasBackslash = c == '\\';
268
                }
269
                // the read buffer ends with a backslash
270
                if (wasBackslash) {
271
                    // restore state one char before
272
                    wbufLength--;
273
                    wasBackslash = wbuf[wbufLength - 1] == '\\';
274
                    buf[0] = '\\';
275
                    offset = 1;
276
                } else
277
                    offset = 0;
278
                w.write(wbuf, 0, wbufLength);
279
            }
280
            r.close();
281
            w.close();
282
            tmp.delete();
283
        } catch (IOException e) {
284
            throw new IllegalStateException(e);
285
        }
286
    }
287
 
288
    private static String getDATA_OPTIONS(DBStructureItem<?> i) {
289
        return i.getAnc(SQLBase.class).quote("FIELDS TERMINATED BY ',' ENCLOSED BY '\"' ESCAPED BY %s LINES TERMINATED BY '\n' ", "\\");
290
    }
291
 
292
    @Override
293
    public void _loadData(final File f, final SQLTable t) {
294
        // we always store in utf8 regardless of the encoding of the columns
295
        final SQLDataSource ds = t.getDBSystemRoot().getDataSource();
296
        try {
297
            SQLUtils.executeAtomic(ds, new SQLFactory<Object>() {
298
                @Override
299
                public Object create() throws SQLException {
300
                    final String charsetClause;
301
                    final Connection conn = ((DelegatingConnection) ds.getConnection()).getInnermostDelegate();
302
                    if (((com.mysql.jdbc.Connection) conn).versionMeetsMinimum(5, 0, 38)) {
303
                        charsetClause = "CHARACTER SET utf8 ";
304
                    } else {
305
                        // variable name is in the first column
306
                        final String dbCharset = ds.executeA1("show variables like 'character_set_database'")[1].toString().trim().toLowerCase();
307
                        if (dbCharset.equals("utf8")) {
308
                            charsetClause = "";
309
                        } else {
310
                            throw new IllegalStateException("the database charset is not utf8 and this version doesn't support specifying another one : " + dbCharset);
311
                        }
312
                    }
313
                    ds.execute(t.getBase().quote("LOAD DATA LOCAL INFILE %s INTO TABLE %f " + charsetClause + getDATA_OPTIONS(t) + " IGNORE 1 LINES;", f.getAbsolutePath(), t));
314
                    return null;
315
                }
316
            });
317
        } catch (Exception e) {
318
            throw new IllegalStateException("Couldn't load " + f + " into " + t, e);
319
        }
320
    }
321
 
322
    @Override
323
    public SQLBase createBase(SQLServer server, String name, String login, String pass, IClosure<SQLDataSource> dsInit) {
324
        return new MySQLBase(server, name, login, pass, dsInit);
325
    }
326
 
327
    @Override
328
    public String getNullIsDataComparison(String x, boolean eq, String y) {
329
        final String nullSafe = x + " <=> " + y;
330
        if (eq)
331
            return nullSafe;
332
        else
333
            return "NOT (" + nullSafe + ")";
334
    }
67 ilm 335
 
17 ilm 336
 
337
    @Override
67 ilm 338
    public String getFormatTimestamp(String sqlTS, boolean basic) {
339
        return "DATE_FORMAT(" + sqlTS + ", " + SQLBase.quoteStringStd(basic ? "%Y%m%dT%H%i%s.%f" : "%Y-%m-%dT%H:%i:%s.%f") + ")";
340
    }
341
 
342
    private final void getRow(StringBuilder sb, List<String> row, final int requiredColCount, List<String> columnsAlias) {
343
        // should be OK since requiredColCount is computed from columnsAlias in getConstantTable()
344
        assert columnsAlias == null || requiredColCount == columnsAlias.size();
345
        final int actualColCount = row.size();
346
        if (actualColCount != requiredColCount)
347
            throw new IllegalArgumentException("Wrong number of columns, should be " + requiredColCount + " but row is " + row);
348
        for (int i = 0; i < actualColCount; i++) {
349
            sb.append(row.get(i));
350
            if (columnsAlias != null) {
351
                sb.append(" as ");
352
                sb.append(SQLBase.quoteIdentifier(columnsAlias.get(i)));
353
            }
354
            if (i < actualColCount - 1)
355
                sb.append(", ");
356
        }
357
    }
358
 
359
    @Override
360
    public String getConstantTable(List<List<String>> rows, String alias, List<String> columnsAlias) {
361
        final int rowCount = rows.size();
362
        if (rowCount < 1)
363
            throw new IllegalArgumentException("Empty rows will cause a syntax error");
364
        final int colCount = columnsAlias.size();
365
        if (colCount < 1)
366
            throw new IllegalArgumentException("Empty columns will cause a syntax error");
367
        final StringBuilder sb = new StringBuilder(rows.size() * 64);
368
        sb.append("( SELECT ");
369
        // aliases needed only for the first row
370
        getRow(sb, rows.get(0), colCount, columnsAlias);
371
        for (int i = 1; i < rowCount; i++) {
372
            sb.append("\nUNION ALL\nSELECT ");
373
            getRow(sb, rows.get(i), colCount, null);
374
        }
375
        sb.append(" ) as ");
376
        sb.append(SQLBase.quoteIdentifier(alias));
377
        return sb.toString();
378
    }
379
 
380
    @Override
17 ilm 381
    public String getFunctionQuery(SQLBase b, Set<String> schemas) {
382
        // MySQL puts the db name in schema
383
        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 = '"
384
                + b.getMDName() + "'";
385
    }
386
 
387
    @Override
67 ilm 388
    public String getTriggerQuery(SQLBase b, TablesMap tables) {
389
        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 "
390
                + getMySQLTablesMapJoin(b, tables, "EVENT_OBJECT_SCHEMA", "EVENT_OBJECT_TABLE");
17 ilm 391
    }
392
 
67 ilm 393
    private String getMySQLTablesMapJoin(final SQLBase b, final TablesMap tables, final String schemaCol, final String tableCol) {
394
        // MySQL only has "null" schemas through JDBC
395
        assert tables.size() <= 1;
396
        // but in information_schema, the TABLE_CATALOG is always NULL and TABLE_SCHEMA has the JDBC
397
        // database name
398
        final TablesMap translated;
399
        if (tables.size() == 0) {
400
            translated = tables;
401
        } else {
402
            assert tables.keySet().equals(Collections.singleton(null)) : tables;
403
            translated = new TablesMap(1);
404
            translated.put(b.getMDName(), tables.get(null));
405
        }
406
        return getTablesMapJoin(b, translated, schemaCol, tableCol);
17 ilm 407
    }
408
 
409
    @Override
67 ilm 410
    public String getColumnsQuery(SQLBase b, TablesMap tables) {
17 ilm 411
        return "SELECT null as \"" + INFO_SCHEMA_NAMES_KEYS.get(0) + "\", \"" + INFO_SCHEMA_NAMES_KEYS.get(1) + "\", \"" + INFO_SCHEMA_NAMES_KEYS.get(2)
67 ilm 412
                + "\" , \"CHARACTER_SET_NAME\", \"COLLATION_NAME\" from INFORMATION_SCHEMA.\"COLUMNS\" " + getMySQLTablesMapJoin(b, tables, "TABLE_SCHEMA", "TABLE_NAME");
17 ilm 413
    }
414
 
415
    @Override
416
    @SuppressWarnings("unchecked")
67 ilm 417
    public List<Map<String, Object>> getConstraints(SQLBase b, TablesMap tables) throws SQLException {
17 ilm 418
        final String sel = "SELECT null as \"TABLE_SCHEMA\", c.\"TABLE_NAME\", c.\"CONSTRAINT_NAME\", tc.\"CONSTRAINT_TYPE\", \"COLUMN_NAME\", c.\"ORDINAL_POSITION\"\n"
419
                // from
420
                + " FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE c\n"
421
                // "-- sub-select otherwise at least 15s\n" +
67 ilm 422
                + "JOIN (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS T " + getMySQLTablesMapJoin(b, tables, "TABLE_SCHEMA", "TABLE_NAME")
17 ilm 423
                + ") 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 424
                // requested tables
425
                + getMySQLTablesMapJoin(b, tables, "c.TABLE_SCHEMA", "c.TABLE_NAME")
426
                // order
17 ilm 427
                + "order by c.\"TABLE_SCHEMA\", c.\"TABLE_NAME\", c.\"CONSTRAINT_NAME\", c.\"ORDINAL_POSITION\"";
428
        // don't cache since we don't listen on system tables
429
        final List<Map<String, Object>> res = (List<Map<String, Object>>) b.getDBSystemRoot().getDataSource().execute(sel, new IResultSetHandler(SQLDataSource.MAP_LIST_HANDLER, false));
430
        mergeColumnNames(res);
431
        return res;
432
    }
433
 
434
    static void mergeColumnNames(final List<Map<String, Object>> res) {
435
        final Iterator<Map<String, Object>> listIter = res.iterator();
436
        List<String> l = null;
437
        while (listIter.hasNext()) {
438
            final Map<String, Object> m = listIter.next();
439
            // don't leave the meaningless position (it will always be equal to 1)
440
            final int pos = ((Number) m.remove("ORDINAL_POSITION")).intValue();
441
            if (pos == 1) {
442
                l = new ArrayList<String>();
443
                m.put("COLUMN_NAMES", l);
444
            } else {
445
                listIter.remove();
446
            }
447
            l.add((String) m.remove("COLUMN_NAME"));
448
        }
449
    }
450
 
451
    @Override
452
    public String getDropTrigger(Trigger t) {
453
        return SQLBase.quoteStd("DROP TRIGGER %i", new SQLName(t.getTable().getSchema().getName(), t.getName()));
454
    }
455
 
456
    @Override
457
    public String getUpdate(final SQLTable t, List<String> tables, Map<String, String> setPart) {
458
        final List<String> l = new ArrayList<String>(tables);
459
        l.add(0, t.getSQLName().quote());
460
        return CollectionUtils.join(l, ", ") + "\nSET " + CollectionUtils.join(setPart.entrySet(), ",\n", new ITransformer<Entry<String, String>, String>() {
461
            @Override
462
            public String transformChecked(Entry<String, String> input) {
463
                // MySQL needs to prefix the fields, since there's no designated table to update
464
                return t.getField(input.getKey()).getSQLName(t).quote() + " = " + input.getValue();
465
            }
466
        });
467
    }
468
 
469
    public OutsideClause getSetTableComment(final String comment) {
470
        return new OutsideClause() {
471
            @Override
472
            public ClauseType getType() {
473
                return ClauseType.OTHER;
474
            }
475
 
476
            @Override
477
            public String asString(SQLName tableName) {
478
                return "ALTER TABLE " + tableName.quote() + " COMMENT = " + SQLBase.quoteStringStd(comment) + ";";
479
            }
480
        };
481
    }
482
}