001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
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            public String buildSQL(String template) throws IOException {
051                    template = _preBuildSQL(template);
052                    template = _postBuildSQL(template);
053    
054                    return template;
055            }
056    
057            public void buildSQLFile(String sqlDir, String fileName)
058                    throws IOException {
059    
060                    String oracle = buildTemplate(sqlDir, fileName);
061    
062                    oracle = _preBuildSQL(oracle);
063    
064                    UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
065                            new UnsyncStringReader(oracle));
066    
067                    StringBundler imageSB = new StringBundler();
068                    StringBundler journalArticleSB = new StringBundler();
069                    StringBundler journalStructureSB = new StringBundler();
070                    StringBundler journalTemplateSB = new StringBundler();
071    
072                    String line = null;
073    
074                    while ((line = unsyncBufferedReader.readLine()) != null) {
075                            if (line.startsWith("insert into Image")) {
076                                    _convertToOracleCSV(line, imageSB);
077                            }
078                            else if (line.startsWith("insert into JournalArticle (")) {
079                                    _convertToOracleCSV(line, journalArticleSB);
080                            }
081                            else if (line.startsWith("insert into JournalStructure (")) {
082                                    _convertToOracleCSV(line, journalStructureSB);
083                            }
084                            else if (line.startsWith("insert into JournalTemplate (")) {
085                                    _convertToOracleCSV(line, journalTemplateSB);
086                            }
087                    }
088    
089                    unsyncBufferedReader.close();
090    
091                    if (imageSB.length() > 0) {
092                            FileUtil.write(
093                                    sqlDir + "/" + fileName + "/" + fileName + "-oracle-image.csv",
094                                    imageSB.toString());
095                    }
096    
097                    if (journalArticleSB.length() > 0) {
098                            FileUtil.write(
099                                    sqlDir + "/" + fileName + "/" + fileName +
100                                            "-oracle-journalarticle.csv",
101                                    journalArticleSB.toString());
102                    }
103    
104                    if (journalStructureSB.length() > 0) {
105                            FileUtil.write(
106                                    sqlDir + "/" + fileName + "/" + fileName +
107                                            "-oracle-journalstructure.csv",
108                                    journalStructureSB.toString());
109                    }
110    
111                    if (journalTemplateSB.length() > 0) {
112                            FileUtil.write(
113                                    sqlDir + "/" + fileName + "/" + fileName +
114                                            "-oracle-journaltemplate.csv",
115                                    journalTemplateSB.toString());
116                    }
117    
118                    oracle = _postBuildSQL(oracle);
119    
120                    FileUtil.write(
121                            sqlDir + "/" + fileName + "/" + fileName + "-oracle.sql", oracle);
122            }
123    
124            public List<Index> getIndexes() throws SQLException {
125                    List<Index> indexes = new ArrayList<Index>();
126    
127                    Connection con = null;
128                    PreparedStatement ps = null;
129                    ResultSet rs = null;
130    
131                    try {
132                            con = DataAccess.getConnection();
133    
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(con, ps, rs);
162                    }
163    
164                    return indexes;
165            }
166    
167            protected OracleDB() {
168                    super(TYPE_ORACLE);
169            }
170    
171            protected String buildCreateFileContent(
172                            String sqlDir, String databaseName, int population)
173                    throws IOException {
174    
175                    String suffix = getSuffix(population);
176    
177                    StringBundler sb = new StringBundler(13);
178    
179                    sb.append("drop user &1 cascade;\n");
180                    sb.append("create user &1 identified by &2;\n");
181                    sb.append("grant connect,resource to &1;\n");
182                    sb.append("connect &1/&2;\n");
183                    sb.append("set define off;\n");
184                    sb.append("\n");
185                    sb.append(
186                            readFile(
187                                    sqlDir + "/portal" + suffix + "/portal" + suffix +
188                                            "-oracle.sql"));
189                    sb.append("\n\n");
190                    sb.append(readFile(sqlDir + "/indexes/indexes-oracle.sql"));
191                    sb.append("\n\n");
192                    sb.append(readFile(sqlDir + "/sequences/sequences-oracle.sql"));
193                    sb.append("\n");
194                    sb.append("quit");
195    
196                    return sb.toString();
197            }
198    
199            protected String getServerName() {
200                    return "oracle";
201            }
202    
203            protected String[] getTemplate() {
204                    return _ORACLE;
205            }
206    
207            protected String replaceTemplate(String template, String[] actual) {
208    
209                    // LPS-12048
210    
211                    Matcher matcher = _varcharPattern.matcher(template);
212    
213                    StringBuffer sb = new StringBuffer();
214    
215                    while (matcher.find()) {
216                            int size = GetterUtil.getInteger(matcher.group()) * 4;
217    
218                            if (size > 4000) {
219                                    size = 4000;
220                            }
221    
222                            matcher.appendReplacement(sb, "VARCHAR(" + size + ")");
223                    }
224    
225                    matcher.appendTail(sb);
226    
227                    template = sb.toString();
228    
229                    return super.replaceTemplate(template, actual);
230            }
231    
232            protected String reword(String data) throws IOException {
233                    UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
234                            new UnsyncStringReader(data));
235    
236                    StringBundler sb = new StringBundler();
237    
238                    String line = null;
239    
240                    while ((line = unsyncBufferedReader.readLine()) != null) {
241                            if (line.startsWith(ALTER_COLUMN_NAME)) {
242                                    String[] template = buildColumnNameTokens(line);
243    
244                                    line = StringUtil.replace(
245                                            "alter table @table@ rename column @old-column@ to " +
246                                                    "@new-column@;",
247                                            REWORD_TEMPLATE, template);
248                            }
249                            else if (line.startsWith(ALTER_COLUMN_TYPE)) {
250                                    String[] template = buildColumnTypeTokens(line);
251    
252                                    line = StringUtil.replace(
253                                            "alter table @table@ modify @old-column@ @type@;",
254                                            REWORD_TEMPLATE, template);
255                            }
256                            else if (line.indexOf(DROP_INDEX) != -1) {
257                                    String[] tokens = StringUtil.split(line, " ");
258    
259                                    line = StringUtil.replace(
260                                            "drop index @index@;", "@index@", tokens[2]);
261                            }
262    
263                            sb.append(line);
264                            sb.append("\n");
265                    }
266    
267                    unsyncBufferedReader.close();
268    
269                    return sb.toString();
270            }
271    
272            private void _convertToOracleCSV(String line, StringBundler sb) {
273                    int x = line.indexOf("values (");
274                    int y = line.lastIndexOf(");");
275    
276                    line = line.substring(x + 8, y);
277    
278                    line = StringUtil.replace(line, "sysdate, ", "20050101, ");
279    
280                    sb.append(line);
281                    sb.append("\n");
282            }
283    
284            private String _preBuildSQL(String template) throws IOException {
285                    template = convertTimestamp(template);
286                    template = replaceTemplate(template, getTemplate());
287    
288                    template = reword(template);
289                    template = StringUtil.replace(
290                            template,
291                            new String[] {"\\\\", "\\'", "\\\""},
292                            new String[] {"\\", "''", "\""});
293    
294                    return template;
295            }
296    
297            private String _postBuildSQL(String template) throws IOException {
298                    template = removeLongInserts(template);
299                    template = StringUtil.replace(template, "\\n", "'||CHR(10)||'");
300    
301                    return template;
302            }
303    
304            private static String[] _ORACLE = {
305                    "--", "1", "0",
306                    "to_date('1970-01-01 00:00:00','YYYY-MM-DD HH24:MI:SS')", "sysdate",
307                    " blob", " number(1, 0)", " timestamp",
308                    " number(30,20)", " number(30,0)", " number(30,0)",
309                    " varchar2(4000)", " clob", " varchar2",
310                    "", "commit"
311            };
312    
313            private static OracleDB _instance = new OracleDB();
314    
315            private static Pattern _varcharPattern = Pattern.compile(
316                    "VARCHAR(\\(\\d+\\))");
317    
318    }