001/*
002 * (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Florent Guillaume
018 *     Benoit Delbosc
019 */
020
021package org.nuxeo.ecm.core.storage.sql.jdbc.dialect;
022
023import java.io.IOException;
024import java.io.Reader;
025import java.io.Serializable;
026import java.lang.reflect.Constructor;
027import java.lang.reflect.InvocationTargetException;
028import java.lang.reflect.Method;
029import java.sql.Array;
030import java.sql.Connection;
031import java.sql.DatabaseMetaData;
032import java.sql.PreparedStatement;
033import java.sql.ResultSet;
034import java.sql.SQLException;
035import java.sql.Statement;
036import java.sql.Types;
037import java.util.ArrayList;
038import java.util.Arrays;
039import java.util.Collection;
040import java.util.Collections;
041import java.util.HashMap;
042import java.util.HashSet;
043import java.util.LinkedList;
044import java.util.List;
045import java.util.Locale;
046import java.util.Map;
047import java.util.Set;
048
049import javax.transaction.xa.XAException;
050
051import org.apache.commons.codec.digest.DigestUtils;
052import org.apache.commons.lang.ArrayUtils;
053import org.apache.commons.logging.Log;
054import org.apache.commons.logging.LogFactory;
055import org.nuxeo.common.utils.StringUtils;
056import org.nuxeo.ecm.core.NXCore;
057import org.nuxeo.ecm.core.api.NuxeoException;
058import org.nuxeo.ecm.core.api.security.SecurityConstants;
059import org.nuxeo.ecm.core.storage.FulltextConfiguration;
060import org.nuxeo.ecm.core.storage.FulltextQueryAnalyzer;
061import org.nuxeo.ecm.core.storage.FulltextQueryAnalyzer.FulltextQuery;
062import org.nuxeo.ecm.core.storage.sql.ColumnType;
063import org.nuxeo.ecm.core.storage.sql.Model;
064import org.nuxeo.ecm.core.storage.sql.RepositoryDescriptor;
065import org.nuxeo.ecm.core.storage.sql.jdbc.JDBCLogger;
066import org.nuxeo.ecm.core.storage.sql.jdbc.db.Column;
067import org.nuxeo.ecm.core.storage.sql.jdbc.db.Database;
068import org.nuxeo.ecm.core.storage.sql.jdbc.db.Join;
069import org.nuxeo.ecm.core.storage.sql.jdbc.db.Table;
070import org.nuxeo.runtime.datasource.ConnectionHelper;
071
072/**
073 * Oracle-specific dialect.
074 *
075 * @author Florent Guillaume
076 */
077public class DialectOracle extends Dialect {
078
079    private static final Log log = LogFactory.getLog(DialectOracle.class);
080
081    private Constructor<?> arrayDescriptorConstructor;
082
083    private Constructor<?> arrayConstructor;
084
085    private Method arrayGetLongArrayMethod;
086
087    protected final String fulltextParameters;
088
089    protected boolean pathOptimizationsEnabled;
090
091    protected int pathOptimizationsVersion = 0;
092
093    private static final String DEFAULT_USERS_SEPARATOR = "|";
094
095    protected String usersSeparator;
096
097    protected final DialectIdType idType;
098
099    protected String idSequenceName;
100
101    protected XAErrorLogger xaErrorLogger;
102
103    protected static class XAErrorLogger {
104
105        protected final Class<?> oracleXAExceptionClass;
106
107        protected final Method m_xaError;
108
109        protected final Method m_xaErrorMessage;
110
111        protected final Method m_oracleError;
112
113        protected final Method m_oracleSQLError;
114
115        public XAErrorLogger() throws ReflectiveOperationException {
116            oracleXAExceptionClass = Thread.currentThread().getContextClassLoader().loadClass(
117                    "oracle.jdbc.xa.OracleXAException");
118            m_xaError = oracleXAExceptionClass.getMethod("getXAError", new Class[] {});
119            m_xaErrorMessage = oracleXAExceptionClass.getMethod("getXAErrorMessage",
120                    new Class[] { m_xaError.getReturnType() });
121            m_oracleError = oracleXAExceptionClass.getMethod("getOracleError", new Class[] {});
122            m_oracleSQLError = oracleXAExceptionClass.getMethod("getOracleSQLError", new Class[] {});
123        }
124
125        public void log(XAException e) throws ReflectiveOperationException {
126            int xaError = ((Integer) m_xaError.invoke(e)).intValue();
127            String xaErrorMessage = (String) m_xaErrorMessage.invoke(xaError);
128            int oracleError = ((Integer) m_oracleError.invoke(e)).intValue();
129            int oracleSQLError = ((Integer) m_oracleSQLError.invoke(e)).intValue();
130            StringBuilder builder = new StringBuilder();
131            builder.append("Oracle XA Error : " + xaError + " (" + xaErrorMessage + "),");
132            builder.append("Oracle Error : " + oracleError + ",");
133            builder.append("Oracle SQL Error : " + oracleSQLError);
134            log.warn(builder.toString(), e);
135        }
136
137    }
138
139    public DialectOracle(DatabaseMetaData metadata, RepositoryDescriptor repositoryDescriptor) {
140        super(metadata, repositoryDescriptor);
141        fulltextParameters = repositoryDescriptor == null ? null
142                : repositoryDescriptor.getFulltextAnalyzer() == null ? "" : repositoryDescriptor.getFulltextAnalyzer();
143        pathOptimizationsEnabled = repositoryDescriptor == null ? false
144                : repositoryDescriptor.getPathOptimizationsEnabled();
145        if (pathOptimizationsEnabled) {
146            pathOptimizationsVersion = repositoryDescriptor == null ? 0
147                    : repositoryDescriptor.getPathOptimizationsVersion();
148        }
149        usersSeparator = repositoryDescriptor == null ? null
150                : repositoryDescriptor.usersSeparatorKey == null ? DEFAULT_USERS_SEPARATOR
151                        : repositoryDescriptor.usersSeparatorKey;
152        String idt = repositoryDescriptor == null ? null : repositoryDescriptor.idType;
153        if (idt == null || "".equals(idt) || "varchar".equalsIgnoreCase(idt)) {
154            idType = DialectIdType.VARCHAR;
155        } else if (idt.toLowerCase().startsWith("sequence")) {
156            idType = DialectIdType.SEQUENCE;
157            if (idt.toLowerCase().startsWith("sequence:")) {
158                String[] split = idt.split(":");
159                idSequenceName = split[1].toUpperCase(Locale.ENGLISH);
160            } else {
161                idSequenceName = "HIERARCHY_SEQ";
162            }
163        } else {
164            throw new NuxeoException("Unknown id type: '" + idt + "'");
165        }
166        xaErrorLogger = newXAErrorLogger();
167        initArrayReflection();
168    }
169
170    protected XAErrorLogger newXAErrorLogger() {
171        try {
172            return new XAErrorLogger();
173        } catch (ReflectiveOperationException e) {
174            log.warn("Cannot initialize xa error loggger", e);
175            return null;
176        }
177    }
178
179    // use reflection to avoid linking dependencies
180    private void initArrayReflection() {
181        try {
182            Class<?> arrayDescriptorClass = Class.forName("oracle.sql.ArrayDescriptor");
183            arrayDescriptorConstructor = arrayDescriptorClass.getConstructor(String.class, Connection.class);
184            Class<?> arrayClass = Class.forName("oracle.sql.ARRAY");
185            arrayConstructor = arrayClass.getConstructor(arrayDescriptorClass, Connection.class, Object.class);
186            arrayGetLongArrayMethod = arrayClass.getDeclaredMethod("getLongArray");
187        } catch (ClassNotFoundException e) {
188            // query syntax unit test run without Oracle JDBC driver
189            return;
190        } catch (ReflectiveOperationException e) {
191            throw new NuxeoException(e);
192        }
193    }
194
195    @Override
196    public String getConnectionSchema(Connection connection) throws SQLException {
197        Statement st = connection.createStatement();
198        String sql = "SELECT SYS_CONTEXT('USERENV', 'SESSION_USER') FROM DUAL";
199        log.trace("SQL: " + sql);
200        ResultSet rs = st.executeQuery(sql);
201        rs.next();
202        String user = rs.getString(1);
203        log.trace("SQL:   -> " + user);
204        rs.close();
205        st.close();
206        return user;
207    }
208
209    @Override
210    public String getCascadeDropConstraintsString() {
211        return " CASCADE CONSTRAINTS";
212    }
213
214    @Override
215    public String getAddColumnString() {
216        return "ADD";
217    }
218
219    @Override
220    public JDBCInfo getJDBCTypeAndString(ColumnType type) {
221        switch (type.spec) {
222        case STRING:
223            if (type.isUnconstrained()) {
224                return jdbcInfo("NVARCHAR2(2000)", Types.VARCHAR);
225            } else if (type.isClob() || type.length > 2000) {
226                return jdbcInfo("NCLOB", Types.CLOB);
227            } else {
228                return jdbcInfo("NVARCHAR2(%d)", type.length, Types.VARCHAR);
229            }
230        case BOOLEAN:
231            return jdbcInfo("NUMBER(1,0)", Types.BIT);
232        case LONG:
233            return jdbcInfo("NUMBER(19,0)", Types.BIGINT);
234        case DOUBLE:
235            return jdbcInfo("DOUBLE PRECISION", Types.DOUBLE);
236        case TIMESTAMP:
237            return jdbcInfo("TIMESTAMP", Types.TIMESTAMP);
238        case BLOBID:
239            return jdbcInfo("VARCHAR2(250)", Types.VARCHAR);
240            // -----
241        case NODEID:
242        case NODEIDFK:
243        case NODEIDFKNP:
244        case NODEIDFKMUL:
245        case NODEIDFKNULL:
246        case NODEIDPK:
247        case NODEVAL:
248            switch (idType) {
249            case VARCHAR:
250                return jdbcInfo("VARCHAR2(36)", Types.VARCHAR);
251            case SEQUENCE:
252                return jdbcInfo("NUMBER(10,0)", Types.INTEGER);
253            default:
254                throw new AssertionError("Unknown id type: " + idType);
255            }
256        case SYSNAME:
257        case SYSNAMEARRAY:
258            return jdbcInfo("VARCHAR2(250)", Types.VARCHAR);
259        case TINYINT:
260            return jdbcInfo("NUMBER(3,0)", Types.TINYINT);
261        case INTEGER:
262            return jdbcInfo("NUMBER(10,0)", Types.INTEGER);
263        case AUTOINC:
264            return jdbcInfo("NUMBER(10,0)", Types.INTEGER);
265        case FTINDEXED:
266            return jdbcInfo("CLOB", Types.CLOB);
267        case FTSTORED:
268            return jdbcInfo("NCLOB", Types.CLOB);
269        case CLUSTERNODE:
270            return jdbcInfo("VARCHAR(25)", Types.VARCHAR);
271        case CLUSTERFRAGS:
272            return jdbcInfo("VARCHAR2(4000)", Types.VARCHAR);
273        }
274        throw new AssertionError(type);
275    }
276
277    @Override
278    public boolean isAllowedConversion(int expected, int actual, String actualName, int actualSize) {
279        // Oracle internal conversions
280        if (expected == Types.DOUBLE && actual == Types.FLOAT) {
281            return true;
282        }
283        if (expected == Types.VARCHAR && actual == Types.OTHER && actualName.equals("NVARCHAR2")) {
284            return true;
285        }
286        if (expected == Types.CLOB && actual == Types.OTHER && actualName.equals("NCLOB")) {
287            return true;
288        }
289        if (expected == Types.BIT && actual == Types.DECIMAL && actualName.equals("NUMBER") && actualSize == 1) {
290            return true;
291        }
292        if (expected == Types.TINYINT && actual == Types.DECIMAL && actualName.equals("NUMBER") && actualSize == 3) {
293            return true;
294        }
295        if (expected == Types.INTEGER && actual == Types.DECIMAL && actualName.equals("NUMBER") && actualSize == 10) {
296            return true;
297        }
298        if (expected == Types.BIGINT && actual == Types.DECIMAL && actualName.equals("NUMBER") && actualSize == 19) {
299            return true;
300        }
301        // CLOB vs VARCHAR compatibility
302        if (expected == Types.VARCHAR && actual == Types.OTHER && actualName.equals("NCLOB")) {
303            return true;
304        }
305        if (expected == Types.CLOB && actual == Types.OTHER && actualName.equals("NVARCHAR2")) {
306            return true;
307        }
308        return false;
309    }
310
311    @Override
312    public Serializable getGeneratedId(Connection connection) throws SQLException {
313        if (idType != DialectIdType.SEQUENCE) {
314            return super.getGeneratedId(connection);
315        }
316        String sql = String.format("SELECT %s.NEXTVAL FROM DUAL", idSequenceName);
317        Statement s = connection.createStatement();
318        ResultSet rs = null;
319        try {
320            rs = s.executeQuery(sql);
321            rs.next();
322            return Long.valueOf(rs.getLong(1));
323        } finally {
324            if (rs != null) {
325                rs.close();
326            }
327            s.close();
328        }
329    }
330
331    @Override
332    public void setId(PreparedStatement ps, int index, Serializable value) throws SQLException {
333        switch (idType) {
334        case VARCHAR:
335            ps.setObject(index, value);
336            break;
337        case SEQUENCE:
338            setIdLong(ps, index, value);
339            break;
340        default:
341            throw new AssertionError("Unknown id type: " + idType);
342        }
343    }
344
345    @Override
346    public void setToPreparedStatement(PreparedStatement ps, int index, Serializable value, Column column)
347            throws SQLException {
348        switch (column.getJdbcType()) {
349        case Types.VARCHAR:
350        case Types.CLOB:
351            setToPreparedStatementString(ps, index, value, column);
352            return;
353        case Types.BIT:
354            ps.setBoolean(index, ((Boolean) value).booleanValue());
355            return;
356        case Types.TINYINT:
357        case Types.SMALLINT:
358            ps.setInt(index, ((Long) value).intValue());
359            return;
360        case Types.INTEGER:
361        case Types.BIGINT:
362            ps.setLong(index, ((Number) value).longValue());
363            return;
364        case Types.DOUBLE:
365            ps.setDouble(index, ((Double) value).doubleValue());
366            return;
367        case Types.TIMESTAMP:
368            setToPreparedStatementTimestamp(ps, index, value, column);
369            return;
370        case Types.OTHER:
371            ColumnType type = column.getType();
372            if (type.isId()) {
373                setId(ps, index, value);
374                return;
375            } else if (type == ColumnType.FTSTORED) {
376                ps.setString(index, (String) value);
377                return;
378            }
379            throw new SQLException("Unhandled type: " + column.getType());
380        default:
381            throw new SQLException("Unhandled JDBC type: " + column.getJdbcType());
382        }
383    }
384
385    @Override
386    @SuppressWarnings("boxing")
387    public Serializable getFromResultSet(ResultSet rs, int index, Column column) throws SQLException {
388        switch (column.getJdbcType()) {
389        case Types.VARCHAR:
390            return getFromResultSetString(rs, index, column);
391        case Types.CLOB:
392            // Oracle cannot read CLOBs using rs.getString when the ResultSet is
393            // a ScrollableResultSet (the standard OracleResultSetImpl works
394            // fine).
395            Reader r = rs.getCharacterStream(index);
396            if (r == null) {
397                return null;
398            }
399            StringBuilder sb = new StringBuilder();
400            try {
401                int n;
402                char[] buffer = new char[4096];
403                while ((n = r.read(buffer)) != -1) {
404                    sb.append(new String(buffer, 0, n));
405                }
406            } catch (IOException e) {
407                log.error("Cannot read CLOB", e);
408            }
409            return sb.toString();
410        case Types.BIT:
411            return rs.getBoolean(index);
412        case Types.TINYINT:
413        case Types.SMALLINT:
414        case Types.INTEGER:
415        case Types.BIGINT:
416            return rs.getLong(index);
417        case Types.DOUBLE:
418            return rs.getDouble(index);
419        case Types.TIMESTAMP:
420            return getFromResultSetTimestamp(rs, index, column);
421        }
422        throw new SQLException("Unhandled JDBC type: " + column.getJdbcType());
423    }
424
425    @Override
426    protected int getMaxNameSize() {
427        return 30;
428    }
429
430    @Override
431    /* Avoid DRG-11439: index name length exceeds maximum of 25 bytes */
432    protected int getMaxIndexNameSize() {
433        return 25;
434    }
435
436    @Override
437    public String getCreateFulltextIndexSql(String indexName, String quotedIndexName, Table table,
438            List<Column> columns, Model model) {
439        return String.format("CREATE INDEX %s ON %s(%s) INDEXTYPE IS CTXSYS.CONTEXT "
440                + "PARAMETERS('%s SYNC (ON COMMIT) TRANSACTIONAL')", quotedIndexName, table.getQuotedName(),
441                columns.get(0).getQuotedName(), fulltextParameters);
442    }
443
444    protected static final String CHARS_RESERVED_STR = "%${";
445
446    protected static final Set<Character> CHARS_RESERVED = new HashSet<>(
447            Arrays.asList(ArrayUtils.toObject(CHARS_RESERVED_STR.toCharArray())));
448
449    @Override
450    public String getDialectFulltextQuery(String query) {
451        query = query.replace("*", "%"); // reserved, words with it not quoted
452        FulltextQuery ft = FulltextQueryAnalyzer.analyzeFulltextQuery(query);
453        if (ft == null) {
454            return "DONTMATCHANYTHINGFOREMPTYQUERY";
455        }
456        return FulltextQueryAnalyzer.translateFulltext(ft, "OR", "AND", "NOT", "{", "}", CHARS_RESERVED, "", "", true);
457    }
458
459    // SELECT ..., (SCORE(1) / 100) AS "_nxscore"
460    // FROM ... LEFT JOIN fulltext ON fulltext.id = hierarchy.id
461    // WHERE ... AND CONTAINS(fulltext.fulltext, ?, 1) > 0
462    // ORDER BY "_nxscore" DESC
463    @Override
464    public FulltextMatchInfo getFulltextScoredMatchInfo(String fulltextQuery, String indexName, int nthMatch,
465            Column mainColumn, Model model, Database database) {
466        String indexSuffix = model.getFulltextIndexSuffix(indexName);
467        Table ft = database.getTable(Model.FULLTEXT_TABLE_NAME);
468        Column ftMain = ft.getColumn(Model.MAIN_KEY);
469        Column ftColumn = ft.getColumn(Model.FULLTEXT_FULLTEXT_KEY + indexSuffix);
470        String score = String.format("SCORE(%d)", nthMatch);
471        String nthSuffix = nthMatch == 1 ? "" : String.valueOf(nthMatch);
472        FulltextMatchInfo info = new FulltextMatchInfo();
473        if (nthMatch == 1) {
474            // Need only one JOIN involving the fulltext table
475            info.joins = Collections.singletonList(new Join(Join.INNER, ft.getQuotedName(), null, null,
476                    ftMain.getFullQuotedName(), mainColumn.getFullQuotedName()));
477        }
478        info.whereExpr = String.format("CONTAINS(%s, ?, %d) > 0", ftColumn.getFullQuotedName(), nthMatch);
479        info.whereExprParam = fulltextQuery;
480        info.scoreExpr = String.format("(%s / 100)", score);
481        info.scoreAlias = openQuote() + "_nxscore" + nthSuffix + closeQuote();
482        info.scoreCol = new Column(mainColumn.getTable(), null, ColumnType.DOUBLE, null);
483        return info;
484    }
485
486    @Override
487    public boolean getMaterializeFulltextSyntheticColumn() {
488        return true;
489    }
490
491    @Override
492    public int getFulltextIndexedColumns() {
493        return 1;
494    }
495
496    @Override
497    public String getLikeEscaping() {
498        return " ESCAPE '\\'";
499    }
500
501    @Override
502    public boolean supportsUpdateFrom() {
503        throw new UnsupportedOperationException();
504    }
505
506    @Override
507    public boolean doesUpdateFromRepeatSelf() {
508        throw new UnsupportedOperationException();
509    }
510
511    @Override
512    public boolean needsOriginalColumnInGroupBy() {
513        // http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_10002.htm#i2080424
514        // The alias can be used in the order_by_clause but not other clauses in
515        // the query.
516        return true;
517    }
518
519    @Override
520    public boolean needsOracleJoins() {
521        return true;
522    }
523
524    @Override
525    public String getClobCast(boolean inOrderBy) {
526        return "CAST(%s AS NVARCHAR2(%d))";
527    }
528
529    @Override
530    public boolean supportsReadAcl() {
531        return aclOptimizationsEnabled;
532    }
533
534    @Override
535    public String getPrepareUserReadAclsSql() {
536        return "{CALL nx_prepare_user_read_acls(?)}";
537    }
538
539    @Override
540    public String getReadAclsCheckSql(String userIdCol) {
541        return String.format("%s = nx_hash_users(?)", userIdCol);
542    }
543
544    @Override
545    public String getUpdateReadAclsSql() {
546        return "{CALL nx_update_read_acls}";
547    }
548
549    @Override
550    public String getRebuildReadAclsSql() {
551        return "{CALL nx_rebuild_read_acls}";
552    }
553
554    @Override
555    public String getSecurityCheckSql(String idColumnName) {
556        return String.format("NX_ACCESS_ALLOWED(%s, ?, ?) = 1", idColumnName);
557    }
558
559    @Override
560    public boolean supportsFastDescendants() {
561        return pathOptimizationsEnabled;
562    }
563
564    @Override
565    public String getInTreeSql(String idColumnName, String id) {
566        String idParam;
567        switch (idType) {
568        case VARCHAR:
569            idParam = "?";
570            break;
571        case SEQUENCE:
572            // check that it's really an integer
573            if (id != null && !org.apache.commons.lang.StringUtils.isNumeric(id)) {
574                return null;
575            }
576            idParam = "CAST(? AS NUMBER(10,0))";
577            break;
578        default:
579            throw new AssertionError("Unknown id type: " + idType);
580        }
581
582        if (pathOptimizationsVersion == 2) {
583            return String.format("EXISTS(SELECT 1 FROM ancestors WHERE hierarchy_id = %s AND ancestor = %s)",
584                    idColumnName, idParam);
585        } else if (pathOptimizationsVersion == 1) {
586            // using nested table optim
587            return String.format("EXISTS(SELECT 1 FROM ancestors WHERE hierarchy_id = %s AND %s MEMBER OF ancestors)",
588                    idColumnName, idParam);
589        } else {
590            // no optimization
591            return String.format(
592                    "%s in (SELECT id FROM hierarchy WHERE LEVEL>1 AND isproperty = 0 START WITH id = %s CONNECT BY PRIOR id = parentid)",
593                    idColumnName, idParam);
594        }
595    }
596
597    @Override
598    public boolean isClusteringSupported() {
599        return true;
600    }
601
602    /*
603     * For Oracle we don't use a function to return values and delete them at the same time, because pipelined functions
604     * that need to do DML have to do it in an autonomous transaction which could cause consistency issues.
605     */
606    @Override
607    public boolean isClusteringDeleteNeeded() {
608        return true;
609    }
610
611    @Override
612    public String getClusterInsertInvalidations() {
613        return "{CALL NX_CLUSTER_INVAL(?, ?, ?, ?)}";
614    }
615
616    @Override
617    public String getClusterGetInvalidations() {
618        return "SELECT id, fragments, kind FROM cluster_invals WHERE nodeid = ?";
619    }
620
621    @Override
622    public boolean supportsPaging() {
623        return true;
624    }
625
626    @Override
627    public String addPagingClause(String sql, long limit, long offset) {
628        return String.format(
629                "SELECT * FROM (SELECT /*+ FIRST_ROWS(%d) */  a.*, ROWNUM rnum FROM (%s) a WHERE ROWNUM <= %d) WHERE rnum  > %d",
630                limit, sql, limit + offset, offset);
631    }
632
633    @Override
634    public boolean supportsWith() {
635        return false;
636    }
637
638    @Override
639    public boolean supportsArrays() {
640        return true;
641    }
642
643    @Override
644    public boolean supportsArraysReturnInsteadOfRows() {
645        return true;
646    }
647
648    @Override
649    public Serializable[] getArrayResult(Array array) throws SQLException {
650        Serializable[] ids;
651        if (array.getBaseType() == Types.NUMERIC) {
652            long[] longs;
653            try {
654                longs = (long[]) arrayGetLongArrayMethod.invoke(array);
655            } catch (IllegalAccessException e) {
656                throw new RuntimeException(e);
657            } catch (IllegalArgumentException e) {
658                throw new RuntimeException(e);
659            } catch (InvocationTargetException e) {
660                throw new RuntimeException(e);
661            }
662            ids = new Serializable[longs.length];
663            for (int i = 0; i < ids.length; i++) {
664                ids[i] = Long.valueOf(longs[i]);
665            }
666        } else {
667            ids = (Serializable[]) array.getArray();
668        }
669        return ids;
670    }
671
672    @Override
673    public boolean hasNullEmptyString() {
674        return true;
675    }
676
677    @Override
678    public Array createArrayOf(int type, Object[] elements, Connection connection) throws SQLException {
679        if (elements == null || elements.length == 0) {
680            return null;
681        }
682        String typeName;
683        switch (type) {
684        case Types.VARCHAR:
685            typeName = "NX_STRING_TABLE";
686            break;
687        case Types.OTHER: // id
688            switch (idType) {
689            case VARCHAR:
690                typeName = "NX_STRING_TABLE";
691                break;
692            case SEQUENCE:
693                typeName = "NX_INT_TABLE";
694                break;
695            default:
696                throw new AssertionError("Unknown id type: " + idType);
697            }
698            break;
699        default:
700            throw new AssertionError("Unknown type: " + type);
701        }
702        connection = ConnectionHelper.unwrap(connection);
703        try {
704            Object arrayDescriptor = arrayDescriptorConstructor.newInstance(typeName, connection);
705            return (Array) arrayConstructor.newInstance(arrayDescriptor, connection, elements);
706        } catch (ReflectiveOperationException e) {
707            throw new SQLException(e);
708        }
709    }
710
711    @Override
712    public String getSQLStatementsFilename() {
713        return "nuxeovcs/oracle.sql.txt";
714    }
715
716    @Override
717    public String getTestSQLStatementsFilename() {
718        return "nuxeovcs/oracle.test.sql.txt";
719    }
720
721    @Override
722    public Map<String, Serializable> getSQLStatementsProperties(Model model, Database database) {
723        Map<String, Serializable> properties = new HashMap<String, Serializable>();
724        switch (idType) {
725        case VARCHAR:
726            properties.put("idType", "VARCHAR2(36)");
727            properties.put("idTypeParam", "VARCHAR2");
728            properties.put("idArrayType", "NX_STRING_TABLE");
729            properties.put("idNotPresent", "'-'");
730            properties.put("sequenceEnabled", Boolean.FALSE);
731            break;
732        case SEQUENCE:
733            properties.put("idType", "NUMBER(10,0)");
734            properties.put("idTypeParam", "NUMBER");
735            properties.put("idArrayType", "NX_INT_TABLE");
736            properties.put("idNotPresent", "-1");
737            properties.put("sequenceEnabled", Boolean.TRUE);
738            properties.put("idSequenceName", idSequenceName);
739            break;
740        default:
741            throw new AssertionError("Unknown id type: " + idType);
742        }
743        properties.put("aclOptimizationsEnabled", Boolean.valueOf(aclOptimizationsEnabled));
744        properties.put("pathOptimizationsEnabled", Boolean.valueOf(pathOptimizationsEnabled));
745        properties.put("pathOptimizationsVersion1", (pathOptimizationsVersion == 1) ? true : false);
746        properties.put("pathOptimizationsVersion2", (pathOptimizationsVersion == 2) ? true : false);
747        properties.put("fulltextEnabled", Boolean.valueOf(!fulltextDisabled));
748        properties.put("fulltextSearchEnabled", Boolean.valueOf(!fulltextSearchDisabled));
749        properties.put("clusteringEnabled", Boolean.valueOf(clusteringEnabled));
750        properties.put("proxiesEnabled", Boolean.valueOf(proxiesEnabled));
751        properties.put("softDeleteEnabled", Boolean.valueOf(softDeleteEnabled));
752        if (!fulltextSearchDisabled) {
753            Table ft = database.getTable(Model.FULLTEXT_TABLE_NAME);
754            properties.put("fulltextTable", ft.getQuotedName());
755            FulltextConfiguration fti = model.getFulltextConfiguration();
756            List<String> lines = new ArrayList<String>(fti.indexNames.size());
757            for (String indexName : fti.indexNames) {
758                String suffix = model.getFulltextIndexSuffix(indexName);
759                Column ftft = ft.getColumn(Model.FULLTEXT_FULLTEXT_KEY + suffix);
760                Column ftst = ft.getColumn(Model.FULLTEXT_SIMPLETEXT_KEY + suffix);
761                Column ftbt = ft.getColumn(Model.FULLTEXT_BINARYTEXT_KEY + suffix);
762                String line = String.format("  :NEW.%s := :NEW.%s || ' ' || :NEW.%s; ", ftft.getQuotedName(),
763                        ftst.getQuotedName(), ftbt.getQuotedName());
764                lines.add(line);
765            }
766            properties.put("fulltextTriggerStatements", StringUtils.join(lines, "\n"));
767        }
768        String[] permissions = NXCore.getSecurityService().getPermissionsToCheck(SecurityConstants.BROWSE);
769        List<String> permsList = new LinkedList<String>();
770        for (String perm : permissions) {
771            permsList.add(String.format("  INTO ACLR_PERMISSION VALUES ('%s')", perm));
772        }
773        properties.put("readPermissions", StringUtils.join(permsList, "\n"));
774        properties.put("usersSeparator", getUsersSeparator());
775        properties.put("everyone", SecurityConstants.EVERYONE);
776        return properties;
777    }
778
779    protected int getOracleErrorCode(Throwable t) {
780        try {
781            Method m = t.getClass().getMethod("getOracleError");
782            Integer oracleError = (Integer) m.invoke(t);
783            if (oracleError != null) {
784                int errorCode = oracleError.intValue();
785                if (errorCode != 0) {
786                    return errorCode;
787                }
788            }
789        } catch (ReflectiveOperationException e) {
790            // ignore
791        }
792        if (t instanceof SQLException) {
793            return ((SQLException) t).getErrorCode();
794        }
795        return 0;
796    }
797
798    protected boolean isConnectionClosed(int oracleError) {
799        switch (oracleError) {
800        case 28: // your session has been killed.
801        case 1033: // Oracle initialization or shudown in progress.
802        case 1034: // Oracle not available
803        case 1041: // internal error. hostdef extension doesn't exist
804        case 1089: // immediate shutdown in progress - no operations are permitted
805        case 1090: // shutdown in progress - connection is not permitted
806        case 3113: // end-of-file on communication channel
807        case 3114: // not connected to ORACLE
808        case 12571: // TNS:packet writer failure
809        case 17002: // IO Exception
810        case 17008: // Closed Connection
811        case 17410: // No more data to read from socket
812        case 24768: // commit protocol error occured in the server
813            return true;
814        }
815        return false;
816    }
817
818    @Override
819    public boolean isConcurrentUpdateException(Throwable t) {
820        while (t.getCause() != null) {
821            t = t.getCause();
822        }
823        switch (getOracleErrorCode(t)) {
824        case 1: // ORA-00001: unique constraint violated
825        case 60: // ORA-00060: deadlock detected while waiting for resource
826        case 2291: // ORA-02291: integrity constraint ... violated - parent key not found
827            return true;
828        }
829        return false;
830    }
831
832    @Override
833    public String getValidationQuery() {
834        return "SELECT 1 FROM DUAL";
835    }
836
837    @Override
838    public String getBlobLengthFunction() {
839        return "LENGTHB";
840    }
841
842    @Override
843    public List<String> getPostCreateIdentityColumnSql(Column column) {
844        String table = column.getTable().getPhysicalName();
845        String col = column.getPhysicalName();
846        String seq = table + "_IDSEQ";
847        String trig = table + "_IDTRIG";
848        String createSeq = String.format("CREATE SEQUENCE \"%s\"", seq);
849        String createTrig = String.format("CREATE TRIGGER \"%s\"\n" //
850                + "  BEFORE INSERT ON \"%s\"\n" //
851                + "  FOR EACH ROW WHEN (NEW.\"%s\" IS NULL)\n" //
852                + "BEGIN\n" //
853                + "  SELECT \"%s\".NEXTVAL INTO :NEW.\"%s\" FROM DUAL;\n" //
854                + "END;", trig, table, col, seq, col);
855        return Arrays.asList(createSeq, createTrig);
856    }
857
858    @Override
859    public boolean hasIdentityGeneratedKey() {
860        return false;
861    }
862
863    @Override
864    public String getIdentityGeneratedKeySql(Column column) {
865        String table = column.getTable().getPhysicalName();
866        String seq = table + "_IDSEQ";
867        return String.format("SELECT \"%s\".CURRVAL FROM DUAL", seq);
868    }
869
870    @Override
871    public String getAncestorsIdsSql() {
872        return "SELECT NX_ANCESTORS(?) FROM DUAL";
873    }
874
875    @Override
876    public boolean needsNullsLastOnDescSort() {
877        return true;
878    }
879
880    @Override
881    public String getDateCast() {
882        // CAST(%s AS DATE) doesn't work, it doesn't compare exactly to DATE
883        // literals because the internal representation seems to be a float and
884        // CAST AS DATE does not truncate it
885        return "TRUNC(%s)";
886    }
887
888    @Override
889    public String castIdToVarchar(String expr) {
890        switch (idType) {
891        case VARCHAR:
892            return expr;
893        case SEQUENCE:
894            return "CAST(" + expr + " AS VARCHAR2(36))";
895        default:
896            throw new AssertionError("Unknown id type: " + idType);
897        }
898    }
899
900    @Override
901    public DialectIdType getIdType() {
902        return idType;
903    }
904
905    public String getUsersSeparator() {
906        if (usersSeparator == null) {
907            return DEFAULT_USERS_SEPARATOR;
908        }
909        return usersSeparator;
910    }
911
912    @Override
913    public String getSoftDeleteSql() {
914        return "{CALL NX_DELETE(?, ?)}";
915    }
916
917    @Override
918    public String getSoftDeleteCleanupSql() {
919        return "{CALL NX_DELETE_PURGE(?, ?, ?)}";
920    }
921
922    @Override
923    public List<String> getStartupSqls(Model model, Database database) {
924        if (aclOptimizationsEnabled) {
925            log.info("Vacuuming tables used by optimized acls");
926            return Arrays.asList("{CALL nx_vacuum_read_acls}");
927        }
928        return Collections.emptyList();
929    }
930
931    @Override
932    public List<String> checkStoredProcedure(String procName, String procCreate, String ddlMode, Connection connection,
933            JDBCLogger logger, Map<String, Serializable> properties) throws SQLException {
934        boolean compatCheck = ddlMode.contains(RepositoryDescriptor.DDL_MODE_COMPAT);
935        if (compatCheck) {
936            procCreate = "CREATE OR REPLACE " + procCreate.substring("create ".length());
937            return Collections.singletonList(procCreate);
938        }
939        try (Statement st = connection.createStatement()) {
940            String getBody;
941            if (procCreate.toLowerCase().startsWith("create trigger ")) {
942                getBody = "SELECT TRIGGER_BODY FROM USER_TRIGGERS WHERE TRIGGER_NAME = '" + procName + "'";
943            } else {
944                // works for TYPE, FUNCTION, PROCEDURE
945                getBody = "SELECT TEXT FROM ALL_SOURCE WHERE NAME = '" + procName + "' ORDER BY LINE";
946            }
947            logger.log(getBody);
948            try (ResultSet rs = st.executeQuery(getBody)) {
949                if (rs.next()) {
950                    List<String> lines = new ArrayList<>();
951                    do {
952                        lines.add(rs.getString(1));
953                    } while (rs.next());
954                    String body = org.apache.commons.lang.StringUtils.join(lines, ' ');
955                    if (normalizeString(procCreate).contains(normalizeString(body))) {
956                        logger.log("  -> exists, unchanged");
957                        return Collections.emptyList();
958                    } else {
959                        logger.log("  -> exists, old");
960                        if (!procCreate.toLowerCase().startsWith("create ")) {
961                            throw new NuxeoException("Should start with CREATE: " + procCreate);
962                        }
963                        procCreate = "CREATE OR REPLACE " + procCreate.substring("create ".length());
964                        return Collections.singletonList(procCreate);
965                    }
966                } else {
967                    logger.log("  -> missing");
968                    return Collections.singletonList(procCreate);
969                }
970            }
971        }
972    }
973
974    protected static String normalizeString(String string) {
975        return string.replaceAll("[ \n\r\t]+", " ").trim();
976    }
977
978    @Override
979    public String getSQLForDump(String sql) {
980        String sqll = sql.toLowerCase();
981        if (sqll.startsWith("{call ")) {
982            // transform something used for JDBC calls into a proper SQL*Plus dump
983            return "EXECUTE " + sql.substring("{call ".length(), sql.length() - 1); // without ; or /
984        }
985        if (sqll.endsWith("end")) {
986            sql += ";";
987        }
988        return sql + "\n/";
989    }
990
991}