001    /**
002     * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portal.dao.db;
016    
017    import com.liferay.portal.kernel.dao.db.DB;
018    import com.liferay.portal.kernel.dao.db.Index;
019    import com.liferay.portal.kernel.dao.jdbc.DataAccess;
020    import com.liferay.portal.kernel.io.unsync.UnsyncBufferedReader;
021    import com.liferay.portal.kernel.io.unsync.UnsyncStringReader;
022    import com.liferay.portal.kernel.util.FileUtil;
023    import com.liferay.portal.kernel.util.GetterUtil;
024    import com.liferay.portal.kernel.util.StringBundler;
025    import com.liferay.portal.kernel.util.StringUtil;
026    
027    import java.io.IOException;
028    
029    import java.sql.Connection;
030    import java.sql.PreparedStatement;
031    import java.sql.ResultSet;
032    import java.sql.SQLException;
033    
034    import java.util.ArrayList;
035    import java.util.List;
036    import java.util.regex.Matcher;
037    import java.util.regex.Pattern;
038    
039    /**
040     * @author Alexander Chow
041     * @author Sandeep Soni
042     * @author Ganesh Ram
043     */
044    public class OracleDB extends BaseDB {
045    
046            public static DB getInstance() {
047                    return _instance;
048            }
049    
050            @Override
051            public String buildSQL(String template) throws IOException {
052                    template = _preBuildSQL(template);
053                    template = _postBuildSQL(template);
054    
055                    return template;
056            }
057    
058            @Override
059            public void buildSQLFile(String sqlDir, String fileName)
060                    throws IOException {
061    
062                    String oracle = buildTemplate(sqlDir, fileName);
063    
064                    oracle = _preBuildSQL(oracle);
065    
066                    UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
067                            new UnsyncStringReader(oracle));
068    
069                    StringBundler imageSB = new StringBundler();
070                    StringBundler journalArticleSB = new StringBundler();
071                    StringBundler journalStructureSB = new StringBundler();
072                    StringBundler journalTemplateSB = new StringBundler();
073    
074                    String line = null;
075    
076                    while ((line = unsyncBufferedReader.readLine()) != null) {
077                            if (line.startsWith("insert into Image")) {
078                                    _convertToOracleCSV(line, imageSB);
079                            }
080                            else if (line.startsWith("insert into JournalArticle (")) {
081                                    _convertToOracleCSV(line, journalArticleSB);
082                            }
083                            else if (line.startsWith("insert into JournalStructure (")) {
084                                    _convertToOracleCSV(line, journalStructureSB);
085                            }
086                            else if (line.startsWith("insert into JournalTemplate (")) {
087                                    _convertToOracleCSV(line, journalTemplateSB);
088                            }
089                    }
090    
091                    unsyncBufferedReader.close();
092    
093                    if (imageSB.length() > 0) {
094                            FileUtil.write(
095                                    sqlDir + "/" + fileName + "/" + fileName + "-oracle-image.csv",
096                                    imageSB.toString());
097                    }
098    
099                    if (journalArticleSB.length() > 0) {
100                            FileUtil.write(
101                                    sqlDir + "/" + fileName + "/" + fileName +
102                                            "-oracle-journalarticle.csv",
103                                    journalArticleSB.toString());
104                    }
105    
106                    if (journalStructureSB.length() > 0) {
107                            FileUtil.write(
108                                    sqlDir + "/" + fileName + "/" + fileName +
109                                            "-oracle-journalstructure.csv",
110                                    journalStructureSB.toString());
111                    }
112    
113                    if (journalTemplateSB.length() > 0) {
114                            FileUtil.write(
115                                    sqlDir + "/" + fileName + "/" + fileName +
116                                            "-oracle-journaltemplate.csv",
117                                    journalTemplateSB.toString());
118                    }
119    
120                    oracle = _postBuildSQL(oracle);
121    
122                    FileUtil.write(
123                            sqlDir + "/" + fileName + "/" + fileName + "-oracle.sql", oracle);
124            }
125    
126            @Override
127            public List<Index> getIndexes(Connection con) throws SQLException {
128                    List<Index> indexes = new ArrayList<Index>();
129    
130                    PreparedStatement ps = null;
131                    ResultSet rs = null;
132    
133                    try {
134                            StringBundler sb = new StringBundler(3);
135    
136                            sb.append("select index_name, table_name, uniqueness from ");
137                            sb.append("user_indexes where index_name like 'LIFERAY_%' or ");
138                            sb.append("index_name like 'IX_%'");
139    
140                            String sql = sb.toString();
141    
142                            ps = con.prepareStatement(sql);
143    
144                            rs = ps.executeQuery();
145    
146                            while (rs.next()) {
147                                    String indexName = rs.getString("index_name");
148                                    String tableName = rs.getString("table_name");
149                                    String uniqueness = rs.getString("uniqueness");
150    
151                                    boolean unique = true;
152    
153                                    if (uniqueness.equalsIgnoreCase("NONUNIQUE")) {
154                                            unique = false;
155                                    }
156    
157                                    indexes.add(new Index(indexName, tableName, unique));
158                            }
159                    }
160                    finally {
161                            DataAccess.cleanUp(null, ps, rs);
162                    }
163    
164                    return indexes;
165            }
166    
167            @Override
168            public boolean isSupportsInlineDistinct() {
169                    return _SUPPORTS_INLINE_DISTINCT;
170            }
171    
172            protected OracleDB() {
173                    super(TYPE_ORACLE);
174            }
175    
176            @Override
177            protected String buildCreateFileContent(
178                            String sqlDir, String databaseName, int population)
179                    throws IOException {
180    
181                    String suffix = getSuffix(population);
182    
183                    StringBundler sb = new StringBundler(13);
184    
185                    sb.append("drop user &1 cascade;\n");
186                    sb.append("create user &1 identified by &2;\n");
187                    sb.append("grant connect,resource to &1;\n");
188                    sb.append("connect &1/&2;\n");
189                    sb.append("set define off;\n");
190                    sb.append("\n");
191                    sb.append(
192                            readFile(
193                                    sqlDir + "/portal" + suffix + "/portal" + suffix +
194                                            "-oracle.sql"));
195                    sb.append("\n\n");
196                    sb.append(readFile(sqlDir + "/indexes/indexes-oracle.sql"));
197                    sb.append("\n\n");
198                    sb.append(readFile(sqlDir + "/sequences/sequences-oracle.sql"));
199                    sb.append("\n");
200                    sb.append("quit");
201    
202                    return sb.toString();
203            }
204    
205            @Override
206            protected String getServerName() {
207                    return "oracle";
208            }
209    
210            @Override
211            protected String[] getTemplate() {
212                    return _ORACLE;
213            }
214    
215            @Override
216            protected String replaceTemplate(String template, String[] actual) {
217    
218                    // LPS-12048
219    
220                    Matcher matcher = _varcharPattern.matcher(template);
221    
222                    StringBuffer sb = new StringBuffer();
223    
224                    while (matcher.find()) {
225                            int size = GetterUtil.getInteger(matcher.group());
226    
227                            if (size > 4000) {
228                                    size = 4000;
229                            }
230    
231                            matcher.appendReplacement(sb, "VARCHAR2(" + size + " CHAR)");
232                    }
233    
234                    matcher.appendTail(sb);
235    
236                    template = sb.toString();
237    
238                    return super.replaceTemplate(template, actual);
239            }
240    
241            @Override
242            protected String reword(String data) throws IOException {
243                    UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
244                            new UnsyncStringReader(data));
245    
246                    StringBundler sb = new StringBundler();
247    
248                    String line = null;
249    
250                    while ((line = unsyncBufferedReader.readLine()) != null) {
251                            if (line.startsWith(ALTER_COLUMN_NAME)) {
252                                    String[] template = buildColumnNameTokens(line);
253    
254                                    line = StringUtil.replace(
255                                            "alter table @table@ rename column @old-column@ to " +
256                                                    "@new-column@;",
257                                            REWORD_TEMPLATE, template);
258                            }
259                            else if (line.startsWith(ALTER_COLUMN_TYPE)) {
260                                    String[] template = buildColumnTypeTokens(line);
261    
262                                    line = StringUtil.replace(
263                                            "alter table @table@ modify @old-column@ @type@;",
264                                            REWORD_TEMPLATE, template);
265                            }
266                            else if (line.indexOf(DROP_INDEX) != -1) {
267                                    String[] tokens = StringUtil.split(line, ' ');
268    
269                                    line = StringUtil.replace(
270                                            "drop index @index@;", "@index@", tokens[2]);
271                            }
272    
273                            sb.append(line);
274                            sb.append("\n");
275                    }
276    
277                    unsyncBufferedReader.close();
278    
279                    return sb.toString();
280            }
281    
282            private void _convertToOracleCSV(String line, StringBundler sb) {
283                    int x = line.indexOf("values (");
284                    int y = line.lastIndexOf(");");
285    
286                    line = line.substring(x + 8, y);
287    
288                    line = StringUtil.replace(line, "sysdate, ", "20050101, ");
289    
290                    sb.append(line);
291                    sb.append("\n");
292            }
293    
294            private String _postBuildSQL(String template) throws IOException {
295                    template = removeLongInserts(template);
296                    template = StringUtil.replace(template, "\\n", "'||CHR(10)||'");
297    
298                    return template;
299            }
300    
301            private String _preBuildSQL(String template) throws IOException {
302                    template = convertTimestamp(template);
303                    template = replaceTemplate(template, getTemplate());
304    
305                    template = reword(template);
306                    template = StringUtil.replace(
307                            template,
308                            new String[] {"\\\\", "\\'", "\\\""},
309                            new String[] {"\\", "''", "\""});
310    
311                    return template;
312            }
313    
314            private static final String[] _ORACLE = {
315                    "--", "1", "0",
316                    "to_date('1970-01-01 00:00:00','YYYY-MM-DD HH24:MI:SS')", "sysdate",
317                    " blob", " blob", " number(1, 0)", " timestamp", " number(30,20)",
318                    " number(30,0)", " number(30,0)", " varchar2(4000)", " clob",
319                    " varchar2", "", "commit"
320            };
321    
322            private static final boolean _SUPPORTS_INLINE_DISTINCT = false;
323    
324            private static OracleDB _instance = new OracleDB();
325    
326            private static Pattern _varcharPattern = Pattern.compile(
327                    "VARCHAR(\\(\\d+\\))");
328    
329    }