OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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