OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 17 | Rev 41 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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