001    /**
002     * Copyright (c) 2000-present 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.Index;
018    import com.liferay.portal.kernel.dao.jdbc.DataAccess;
019    import com.liferay.portal.kernel.io.unsync.UnsyncBufferedReader;
020    import com.liferay.portal.kernel.io.unsync.UnsyncStringReader;
021    import com.liferay.portal.kernel.util.StringBundler;
022    import com.liferay.portal.kernel.util.StringPool;
023    import com.liferay.portal.kernel.util.StringUtil;
024    
025    import java.io.IOException;
026    
027    import java.sql.Connection;
028    import java.sql.DatabaseMetaData;
029    import java.sql.PreparedStatement;
030    import java.sql.ResultSet;
031    import java.sql.SQLException;
032    
033    import java.util.ArrayList;
034    import java.util.List;
035    
036    /**
037     * @author Alexander Chow
038     * @author Sandeep Soni
039     * @author Ganesh Ram
040     */
041    public class SQLServerDB extends BaseDB {
042    
043            public SQLServerDB(int majorVersion, int minorVersion) {
044                    super(TYPE_SQLSERVER, majorVersion, minorVersion);
045            }
046    
047            @Override
048            public String buildSQL(String template) throws IOException {
049                    template = convertTimestamp(template);
050                    template = replaceTemplate(template, getTemplate());
051    
052                    template = reword(template);
053                    template = StringUtil.replace(template, "\ngo;\n", "\ngo\n");
054                    template = StringUtil.replace(
055                            template,
056                            new String[] {"\\\\", "\\'", "\\\"", "\\n", "\\r"},
057                            new String[] {"\\", "''", "\"", "\n", "\r"});
058    
059                    return template;
060            }
061    
062            @Override
063            public List<Index> getIndexes(Connection con) throws SQLException {
064                    List<Index> indexes = new ArrayList<>();
065    
066                    PreparedStatement ps = null;
067                    ResultSet rs = null;
068    
069                    try {
070                            DatabaseMetaData databaseMetaData = con.getMetaData();
071    
072                            if (databaseMetaData.getDatabaseMajorVersion() <=
073                                            _SQL_SERVER_2000) {
074    
075                                    return indexes;
076                            }
077    
078                            StringBundler sb = new StringBundler(6);
079    
080                            sb.append("select sys.tables.name as table_name, ");
081                            sb.append("sys.indexes.name as index_name, is_unique from ");
082                            sb.append("sys.indexes inner join sys.tables on ");
083                            sb.append("sys.tables.object_id = sys.indexes.object_id where ");
084                            sb.append("sys.indexes.name like 'LIFERAY_%' or sys.indexes.name ");
085                            sb.append("like 'IX_%'");
086    
087                            String sql = sb.toString();
088    
089                            ps = con.prepareStatement(sql);
090    
091                            rs = ps.executeQuery();
092    
093                            while (rs.next()) {
094                                    String indexName = rs.getString("index_name");
095                                    String tableName = rs.getString("table_name");
096                                    boolean unique = !rs.getBoolean("is_unique");
097    
098                                    indexes.add(new Index(indexName, tableName, unique));
099                            }
100                    }
101                    finally {
102                            DataAccess.cleanUp(null, ps, rs);
103                    }
104    
105                    return indexes;
106            }
107    
108            @Override
109            public boolean isSupportsAlterColumnType() {
110                    return _SUPPORTS_ALTER_COLUMN_TYPE;
111            }
112    
113            @Override
114            protected String buildCreateFileContent(
115                            String sqlDir, String databaseName, int population)
116                    throws IOException {
117    
118                    String suffix = getSuffix(population);
119    
120                    StringBundler sb = new StringBundler(17);
121    
122                    sb.append("drop database ");
123                    sb.append(databaseName);
124                    sb.append(";\n");
125                    sb.append("create database ");
126                    sb.append(databaseName);
127                    sb.append(";\n");
128                    sb.append("\n");
129                    sb.append("go\n");
130                    sb.append("\n");
131    
132                    if (population != BARE) {
133                            sb.append("use ");
134                            sb.append(databaseName);
135                            sb.append(";\n\n");
136                            sb.append(getCreateTablesContent(sqlDir, suffix));
137                            sb.append("\n\n");
138                            sb.append(readFile(sqlDir + "/indexes/indexes-sql-server.sql"));
139                            sb.append("\n\n");
140                            sb.append(readFile(sqlDir + "/sequences/sequences-sql-server.sql"));
141                    }
142    
143                    return sb.toString();
144            }
145    
146            @Override
147            protected String getServerName() {
148                    return "sql-server";
149            }
150    
151            @Override
152            protected String[] getTemplate() {
153                    return _SQL_SERVER;
154            }
155    
156            @Override
157            protected String reword(String data) throws IOException {
158                    try (UnsyncBufferedReader unsyncBufferedReader =
159                                    new UnsyncBufferedReader(new UnsyncStringReader(data))) {
160    
161                            StringBundler sb = new StringBundler();
162    
163                            String line = null;
164    
165                            while ((line = unsyncBufferedReader.readLine()) != null) {
166                                    if (line.startsWith(ALTER_COLUMN_NAME)) {
167                                            String[] template = buildColumnNameTokens(line);
168    
169                                            line = StringUtil.replace(
170                                                    "exec sp_rename '@table@.@old-column@', " +
171                                                            "'@new-column@', 'column';",
172                                                    REWORD_TEMPLATE, template);
173                                    }
174                                    else if (line.startsWith(ALTER_COLUMN_TYPE)) {
175                                            String[] template = buildColumnTypeTokens(line);
176    
177                                            line = StringUtil.replace(
178                                                    "alter table @table@ alter column @old-column@ @type@;",
179                                                    REWORD_TEMPLATE, template);
180                                    }
181                                    else if (line.startsWith(ALTER_TABLE_NAME)) {
182                                            String[] template = buildTableNameTokens(line);
183    
184                                            line = StringUtil.replace(
185                                                    "exec sp_rename '@old-table@', '@new-table@';",
186                                                    RENAME_TABLE_TEMPLATE, template);
187                                    }
188                                    else if (line.contains(DROP_INDEX)) {
189                                            String[] tokens = StringUtil.split(line, ' ');
190    
191                                            String tableName = tokens[4];
192    
193                                            if (tableName.endsWith(StringPool.SEMICOLON)) {
194                                                    tableName = tableName.substring(
195                                                            0, tableName.length() - 1);
196                                            }
197    
198                                            line = StringUtil.replace(
199                                                    "drop index @table@.@index@;", "@table@", tableName);
200                                            line = StringUtil.replace(line, "@index@", tokens[2]);
201                                    }
202    
203                                    sb.append(line);
204                                    sb.append("\n");
205                            }
206    
207                            return sb.toString();
208                    }
209            }
210    
211            private static final String[] _SQL_SERVER = {
212                    "--", "1", "0", "'19700101'", "GetDate()", " image", " image", " bit",
213                    " datetime", " float", " int", " bigint", " nvarchar(2000)",
214                    " nvarchar(max)", " nvarchar", "  identity(1,1)", "go"
215            };
216    
217            private static final int _SQL_SERVER_2000 = 8;
218    
219            private static final boolean _SUPPORTS_ALTER_COLUMN_TYPE = false;
220    
221    }