DbConnectionManager.java 28.4 KB
Newer Older
Matt Tucker's avatar
Matt Tucker committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/**
 * $RCSfile$
 * $Revision$
 * $Date$
 *
 * Copyright (C) 2004 Jive Software. All rights reserved.
 *
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution.
 */


package org.jivesoftware.database;

import org.jivesoftware.util.ClassUtils;
16
import org.jivesoftware.util.JiveGlobals;
Matt Tucker's avatar
Matt Tucker committed
17 18
import org.jivesoftware.util.Log;

19
import java.io.*;
Matt Tucker's avatar
Matt Tucker committed
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
import java.sql.*;

/**
 * Central manager of database connections. All methods are static so that they
 * can be easily accessed throughout the classes in the database package.<p>
 * <p/>
 * This class also provides a set of utility methods that abstract out
 * operations that may not work on all databases such as setting the max number
 * or rows that a query should return.
 *
 * @author Jive Software
 *
 * @see org.jivesoftware.database.ConnectionProvider
 */
public class DbConnectionManager {

36 37 38 39 40 41 42 43 44 45 46 47 48
     private static final String CHECK_VERSION =
            "SELECT majorVersion, minorVersion FROM jiveVersion";

    /**
     * Database schema major version. The schema version corresponds to the
     * product release version, but may not exactly match in the case that
     * the product version has advanced without schema changes.
     */
    private static final int CURRENT_MAJOR_VERSION = 2;

    /**
     * Database schema minor version.
     */
Gaston Dombiak's avatar
Gaston Dombiak committed
49
    private static final int CURRENT_MINOR_VERSION = 2;
50

Matt Tucker's avatar
Matt Tucker committed
51
    private static ConnectionProvider connectionProvider;
52
    private static final Object providerLock = new Object();
Matt Tucker's avatar
Matt Tucker committed
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

    // True if connection profiling is turned on. Always false by default.
    private static boolean profilingEnabled = false;

    // True if the database support transactions.
    private static boolean transactionsSupported;
    // True if the database requires large text fields to be streamed.
    private static boolean streamTextRequired;
    // True if the database supports the Statement.setMaxRows() method.
    private static boolean maxRowsSupported;
    // True if the database supports the Statement.setFetchSize() method.
    private static boolean fetchSizeSupported;
    // True if the database supports correlated subqueries.
    private static boolean subqueriesSupported;
    // True if the database supports scroll-insensitive results.
    private static boolean scrollResultsSupported;
    // True if the database supports batch updates.
    private static boolean batchUpdatesSupported;

72
    private static DatabaseType databaseType = DatabaseType.unknown;
Matt Tucker's avatar
Matt Tucker committed
73 74 75 76 77 78 79 80 81 82 83

    /**
     * Returns a database connection from the currently active connection
     * provider. (auto commit is set to true).
     */
    public static Connection getConnection() throws SQLException {
        if (connectionProvider == null) {
            synchronized (providerLock) {
                if (connectionProvider == null) {
                    // Attempt to load the connection provider classname as
                    // a Jive property.
84
                    String className = JiveGlobals.getXMLProperty("connectionProvider.className");
Matt Tucker's avatar
Matt Tucker committed
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
                    if (className != null) {
                        // Attempt to load the class.
                        try {
                            Class conClass = ClassUtils.forName(className);
                            setConnectionProvider((ConnectionProvider)conClass.newInstance());
                        }
                        catch (Exception e) {
                            Log.error("Warning: failed to create the " +
                                    "connection provider specified by connection" +
                                    "Provider.className. Using the default pool.", e);
                            setConnectionProvider(new DefaultConnectionProvider());
                        }
                    }
                    else {
                        setConnectionProvider(new DefaultConnectionProvider());
                    }
                }
            }
        }
        Connection con = connectionProvider.getConnection();

        if (con == null) {
            Log.error("WARNING: ConnectionManager.getConnection() " +
                    "failed to obtain a connection.");
        }
        // See if profiling is enabled. If yes, wrap the connection with a
        // profiled connection.
        if (profilingEnabled) {
            return new ProfiledConnection(con);
        }
        else {
            return con;
        }
    }

    /**
     * Returns a Connection from the currently active connection provider that
     * is ready to participate in transactions (auto commit is set to false).
     */
    public static Connection getTransactionConnection() throws SQLException {
        Connection con = getConnection();
        if (isTransactionsSupported()) {
            con.setAutoCommit(false);
        }
        return con;
    }

    /**
     * Closes a Connection. However, it first rolls back the transaction or
     * commits it depending on the value of <code>abortTransaction</code>.
     */
    public static void closeTransactionConnection(Connection con, boolean abortTransaction) {
        // test to see if the connection passed in is null
        if (con == null) {
            return;
        }

        // Rollback or commit the transaction
        if (isTransactionsSupported()) {
            try {
                if (abortTransaction) {
                    con.rollback();
                }
                else {
                    con.commit();
                }
            }
            catch (Exception e) {
                Log.error(e);
            }
        }
        try {
            // Reset the connection to auto-commit mode.
            if (isTransactionsSupported()) {
                con.setAutoCommit(true);
            }
        }
        catch (Exception e) {
            Log.error(e);
        }
        try {
            // Close the db connection.
            con.close();
        }
        catch (Exception e) {
            Log.error(e);
        }
    }

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
    /**
     * Closes a prepared statement and database connection (returning the connection to
     * the connection pool). This method should be called within the finally section of
     * your database logic, as in the following example:
     *
     * <pre>
     * Connection con = null;
     * PrepatedStatment pstmt = null;
     * try {
     *     con = ConnectionManager.getConnection();
     *     pstmt = con.prepareStatement("select * from blah");
     *     ....
     * }
     * catch (SQLException sqle) {
     *     Log.error(sqle);
     * }
     * finally {
     *     DbConnectionManager.closeConnection(pstmt, con);
     * }</pre>
     *
     * @param pstmt the prepated statement.
     * @param con the connection.
     */
    public static void closeConnection(PreparedStatement pstmt, Connection con) {
        try {
            if (pstmt != null) {
                pstmt.close();
            }
        }
        catch (Exception e) {
            Log.error(e);
        }
        closeConnection(con);
    }

    /**
     * Closes a database connection (returning the connection to the connection pool). Any
     * statements associated with the connection should be closed before calling this method.
     * This method should be called within the finally section of your database logic, as
     * in the following example:
     *
     * <pre>
     * Connection con = null;
     * try {
     *     con = ConnectionManager.getConnection();
     *     ....
     * }
     * catch (SQLException sqle) {
     *     Log.error(sqle);
     * }
     * finally {
     *     DbConnectionManager.closeConnection(con);
     * }</pre>
     *
     * @param con the connection.
     */
    public static void closeConnection(Connection con) {
        try {
            if (con != null) {
                con.close();
            }
        }
        catch (Exception e) {
            Log.error(e);
        }
    }

Matt Tucker's avatar
Matt Tucker committed
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
    /**
     * Creates a scroll insensitive Statement if the JDBC driver supports it, or a normal
     * Statement otherwise.
     *
     * @param con the database connection.
     * @return a Statement
     * @throws SQLException if an error occurs.
     */
    public static Statement createScrollableStatement(Connection con) throws SQLException {
        if (isScrollResultsSupported()) {
            return con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
        }
        else {
            return con.createStatement();
        }
    }

    /**
     * Creates a scroll insensitive PreparedStatement if the JDBC driver supports it, or a normal
     * PreparedStatement otherwise.
     *
     * @param con the database connection.
     * @param sql the SQL to create the PreparedStatement with.
     * @return a PreparedStatement
     * @throws java.sql.SQLException if an error occurs.
     */
    public static PreparedStatement createScrollablePreparedStatement(Connection con, String sql)
            throws SQLException {
        if (isScrollResultsSupported()) {
            return con.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
        }
        else {
            return con.prepareStatement(sql);
        }
    }

    /**
280 281 282
     * Scrolls forward in a result set the specified number of rows. If the JDBC driver
     * supports the feature, the cursor will be moved directly. Otherwise, we scroll
     * through results one by one manually by calling <tt>rs.next()</tt>.
Matt Tucker's avatar
Matt Tucker committed
283
     *
284
     * @param rs the ResultSet object to scroll.
Matt Tucker's avatar
Matt Tucker committed
285 286 287 288 289 290 291
     * @param rowNumber the row number to scroll forward to.
     * @throws SQLException if an error occurs.
     */
    public static void scrollResultSet(ResultSet rs, int rowNumber) throws SQLException {
        // If the driver supports scrollable result sets, use that feature.
        if (isScrollResultsSupported()) {
            if (rowNumber > 0) {
292
                rs.setFetchDirection(ResultSet.FETCH_FORWARD);
293
                rs.relative(rowNumber);
Matt Tucker's avatar
Matt Tucker committed
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
            }
        }
        // Otherwise, manually scroll to the correct row.
        else {
            for (int i = 0; i < rowNumber; i++) {
                rs.next();
            }
        }
    }

    /**
     * Returns the current connection provider. The only case in which this
     * method should be called is if more information about the current
     * connection provider is needed. Database connections should always be
     * obtained by calling the getConnection method of this class.
     */
    public static ConnectionProvider getConnectionProvider() {
        return connectionProvider;
    }

    /**
     * Sets the connection provider. The old provider (if it exists) is shut
     * down before the new one is started. A connection provider <b>should
     * not</b> be started before being passed to the connection manager
     * because the manager will call the start() method automatically.
     *
     * @param provider the ConnectionProvider that the manager should obtain
     *                 connections from.
     */
    public static void setConnectionProvider(ConnectionProvider provider) {
        synchronized (providerLock) {
            if (connectionProvider != null) {
                connectionProvider.destroy();
                connectionProvider = null;
            }
            connectionProvider = provider;
            connectionProvider.start();
            // Now, get a connection to determine meta data.
            Connection con = null;
            try {
                con = connectionProvider.getConnection();
                setMetaData(con);
336 337 338 339 340 341 342

                // Check to see if the database schema needs to be upgraded.
                try {
                    upgradeDatabase(con);
                }
                catch (Exception e) {
                    Log.error("Database upgrade failed. Please manually upgrade your database.", e);
343 344
                    System.out.println("Database upgrade failed. Please manually upgrade your " +
                            "database.");
345
                }
Matt Tucker's avatar
Matt Tucker committed
346 347 348 349 350
            }
            catch (Exception e) {
                Log.error(e);
            }
            finally {
351 352
                try { if (con != null) { con.close(); } }
                catch (Exception e) { Log.error(e); }
Matt Tucker's avatar
Matt Tucker committed
353 354 355
            }
        }
        // Remember what connection provider we want to use for restarts.
356
        JiveGlobals.setXMLProperty("connectionProvider.className", provider.getClass().getName());
Matt Tucker's avatar
Matt Tucker committed
357 358
    }

359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
    /**
     * Destroys the currennt connection provider. Future calls to
     * {@link #getConnectionProvider()} will return <tt>null</tt> until a new
     * ConnectionProvider is set, or one is automatically loaded by a call to
     * {@link #getConnection()}.
     */
    public static void destroyConnectionProvider() {
        synchronized (providerLock) {
            if (connectionProvider != null) {
                connectionProvider.destroy();
                connectionProvider = null;
            }
        }
    }

Matt Tucker's avatar
Matt Tucker committed
374 375 376 377 378 379
    /**
     * Retrives a large text column from a result set, automatically performing
     * streaming if the JDBC driver requires it. This is necessary because
     * different JDBC drivers have different capabilities and methods for
     * retrieving large text values.
     *
380
     * @param rs the ResultSet to retrieve the text field from.
Matt Tucker's avatar
Matt Tucker committed
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
     * @param columnIndex the column in the ResultSet of the text field.
     * @return the String value of the text field.
     */
    public static String getLargeTextField(ResultSet rs, int columnIndex) throws SQLException {
        if (isStreamTextRequired()) {
            Reader bodyReader = null;
            String value = null;
            try {
                bodyReader = rs.getCharacterStream(columnIndex);
                if (bodyReader == null) {
                    return null;
                }
                char[] buf = new char[256];
                int len;
                StringWriter out = new StringWriter(256);
                while ((len = bodyReader.read(buf)) >= 0) {
                    out.write(buf, 0, len);
                }
                value = out.toString();
                out.close();
            }
            catch (Exception e) {
                Log.error(e);
                throw new SQLException("Failed to load text field");
            }
            finally {
                try {
408 409 410
                    if (bodyReader != null) {
                        bodyReader.close();
                    }
Matt Tucker's avatar
Matt Tucker committed
411 412
                }
                catch (Exception e) {
413
                    // Ignore.
Matt Tucker's avatar
Matt Tucker committed
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
                }
            }
            return value;
        }
        else {
            return rs.getString(columnIndex);
        }
    }

    /**
     * Sets a large text column in a result set, automatically performing
     * streaming if the JDBC driver requires it. This is necessary because
     * different JDBC drivers have different capabilities and methods for
     * setting large text values.
     *
429
     * @param pstmt the PreparedStatement to set the text field in.
Matt Tucker's avatar
Matt Tucker committed
430
     * @param parameterIndex the index corresponding to the text field.
431
     * @param value the String to set.
Matt Tucker's avatar
Matt Tucker committed
432
     */
433 434 435
    public static void setLargeTextField(PreparedStatement pstmt, int parameterIndex,
            String value) throws SQLException
    {
Matt Tucker's avatar
Matt Tucker committed
436
        if (isStreamTextRequired()) {
437
            Reader bodyReader;
Matt Tucker's avatar
Matt Tucker committed
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
            try {
                bodyReader = new StringReader(value);
                pstmt.setCharacterStream(parameterIndex, bodyReader, value.length());
            }
            catch (Exception e) {
                Log.error(e);
                throw new SQLException("Failed to set text field.");
            }
            // Leave bodyReader open so that the db can read from it. It *should*
            // be garbage collected after it's done without needing to call close.
        }
        else {
            pstmt.setString(parameterIndex, value);
        }
    }

    /**
     * Sets the max number of rows that should be returned from executing a
     * statement. The operation is automatically bypassed if Jive knows that the
     * the JDBC driver or database doesn't support it.
     *
459
     * @param stmt the Statement to set the max number of rows for.
Matt Tucker's avatar
Matt Tucker committed
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
     * @param maxRows the max number of rows to return.
     */
    public static void setMaxRows(Statement stmt, int maxRows) {
        if (isMaxRowsSupported()) {
            try {
                stmt.setMaxRows(maxRows);
            }
            catch (Throwable t) {
                // Ignore. Exception may happen if the driver doesn't support
                // this operation and we didn't set meta-data correctly.
                // However, it is a good idea to update the meta-data so that
                // we don't have to incur the cost of catching an exception
                // each time.
                maxRowsSupported = false;
            }
        }
    }

    /**
     * Sets the number of rows that the JDBC driver should buffer at a time.
     * The operation is automatically bypassed if Jive knows that the
     * the JDBC driver or database doesn't support it.
     *
483
     * @param rs the ResultSet to set the fetch size for.
Matt Tucker's avatar
Matt Tucker committed
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
     * @param fetchSize the fetchSize.
     */
    public static void setFetchSize(ResultSet rs, int fetchSize) {
        if (isFetchSizeSupported()) {
            try {
                rs.setFetchSize(fetchSize);
            }
            catch (Throwable t) {
                // Ignore. Exception may happen if the driver doesn't support
                // this operation and we didn't set meta-data correctly.
                // However, it is a good idea to update the meta-data so that
                // we don't have to incur the cost of catching an exception
                // each time.
                fetchSizeSupported = false;
            }
        }
    }

    /**
     * Uses a connection from the database to set meta data information about
     * what different JDBC drivers and databases support.
     */
    private static void setMetaData(Connection con) throws SQLException {
        DatabaseMetaData metaData = con.getMetaData();
        // Supports transactions?
        transactionsSupported = metaData.supportsTransactions();
        // Supports subqueries?
        subqueriesSupported = metaData.supportsCorrelatedSubqueries();
512 513 514 515 516 517 518 519 520 521
        // Supports scroll insensitive result sets? Try/catch block is a
        // workaround for DB2 JDBC driver, which throws an exception on
        // the method call.
        try {
            scrollResultsSupported = metaData.supportsResultSetType(
                    ResultSet.TYPE_SCROLL_INSENSITIVE);
        }
        catch (Exception e) {
            scrollResultsSupported = false;
        }
Matt Tucker's avatar
Matt Tucker committed
522 523 524 525 526 527 528 529 530 531 532 533 534 535
        // Supports batch updates
        batchUpdatesSupported = metaData.supportsBatchUpdates();

        // Set defaults for other meta properties
        streamTextRequired = false;
        maxRowsSupported = true;
        fetchSizeSupported = true;

        // Get the database name so that we can perform meta data settings.
        String dbName = metaData.getDatabaseProductName().toLowerCase();
        String driverName = metaData.getDriverName().toLowerCase();

        // Oracle properties.
        if (dbName.indexOf("oracle") != -1) {
536
            databaseType = DatabaseType.oracle;
Matt Tucker's avatar
Matt Tucker committed
537
            streamTextRequired = true;
538
            scrollResultsSupported = false;
Matt Tucker's avatar
Matt Tucker committed
539 540 541 542 543 544 545 546 547
            // The i-net AUGURO JDBC driver
            if (driverName.indexOf("auguro") != -1) {
                streamTextRequired = false;
                fetchSizeSupported = true;
                maxRowsSupported = false;
            }
        }
        // Postgres properties
        else if (dbName.indexOf("postgres") != -1) {
548
            databaseType = DatabaseType.postgres;
Matt Tucker's avatar
Matt Tucker committed
549 550 551 552 553 554
            // Postgres blows, so disable scrolling result sets.
            scrollResultsSupported = false;
            fetchSizeSupported = false;
        }
        // Interbase properties
        else if (dbName.indexOf("interbase") != -1) {
555
            databaseType = DatabaseType.interbase;
Matt Tucker's avatar
Matt Tucker committed
556 557 558
            fetchSizeSupported = false;
            maxRowsSupported = false;
        }
559 560
        // SQLServer
        else if (dbName.indexOf("sql server") != -1) {
561
            databaseType = DatabaseType.sqlserver;
562 563 564 565 566
            // JDBC driver i-net UNA properties
            if (driverName.indexOf("una") != -1) {
                fetchSizeSupported = true;
                maxRowsSupported = false;
            }
Matt Tucker's avatar
Matt Tucker committed
567 568 569
        }
        // MySQL properties
        else if (dbName.indexOf("mysql") != -1) {
570
            databaseType = DatabaseType.mysql;
Matt Tucker's avatar
Matt Tucker committed
571 572
            transactionsSupported = false;
        }
573 574
        // HSQL properties
        else if (dbName.indexOf("hsql") != -1) {
575
            databaseType = DatabaseType.hsqldb;
576 577
            scrollResultsSupported = false;
        }
578 579 580 581
        // DB2 properties.
        else if (dbName.indexOf("db2") != 1) {
            databaseType = DatabaseType.db2;
        }
Matt Tucker's avatar
Matt Tucker committed
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
    }

    /**
     * Returns the database type. The possible types are constants of the
     * DatabaseType class. Any database that doesn't have its own constant
     * falls into the "Other" category.
     *
     * @return the database type.
     */
    public static DatabaseType getDatabaseType() {
        return databaseType;
    }

    /**
     * Returns true if connection profiling is turned on. You can collect
     * profiling statistics by using the static methods of the ProfiledConnection
     * class.
     *
     * @return true if connection profiling is enabled.
     */
    public static boolean isProfilingEnabled() {
        return profilingEnabled;
    }

    /**
     * Turns connection profiling on or off. You can collect profiling
     * statistics by using the static methods of the ProfiledConnection
     * class.
     *
     * @param enable true to enable profiling; false to disable.
     */
    public static void setProfilingEnabled(boolean enable) {
        // If enabling profiling, call the start method on ProfiledConnection
        if (!profilingEnabled && enable) {
            ProfiledConnection.start();
        }
        // Otherwise, if turning off, call stop method.
        else if (profilingEnabled && !enable) {
            ProfiledConnection.stop();
        }
        profilingEnabled = enable;
    }

    public static boolean isTransactionsSupported() {
        return transactionsSupported;
    }

    public static boolean isStreamTextRequired() {
        return streamTextRequired;
    }

    public static boolean isMaxRowsSupported() {
        return maxRowsSupported;
    }

    public static boolean isFetchSizeSupported() {

        return fetchSizeSupported;
    }

    public static boolean isSubqueriesSupported() {
        return subqueriesSupported;
    }

    public static boolean isScrollResultsSupported() {
        return scrollResultsSupported;
    }

    public static boolean isBatchUpdatesSupported() {
        return batchUpdatesSupported;
    }

    /**
     * A class that identifies the type of the database that Jive is connected
     * to. In most cases, we don't want to make any database specific calls
     * and have no need to know the type of database we're using. However,
     * there are certain cases where it's critical to know the database for
     * performance reasons.
     */
661 662 663
    public static enum DatabaseType {

        oracle,
Matt Tucker's avatar
Matt Tucker committed
664

665
        postgres,
Matt Tucker's avatar
Matt Tucker committed
666

667 668 669 670 671 672 673 674 675 676
        mysql,

        hsqldb,

        db2,

        sqlserver,

        interbase,

677
        unknown
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
    }

    /**
     * Checks to see if the database needs to be upgraded. This method should be
     * called once every time the application starts up.
     *
     * @throws SQLException if an error occured.
     */
    private static boolean upgradeDatabase(Connection con) throws Exception {
        int majorVersion;
        int minorVersion;
        PreparedStatement pstmt = null;
        try {
            pstmt = con.prepareStatement(CHECK_VERSION);
            ResultSet rs = pstmt.executeQuery();
            // If no results, assume the version is 2.0.
            if (!rs.next()) {
                majorVersion = 2;
                minorVersion = 0;
            }
            majorVersion = rs.getInt(1);
            minorVersion = rs.getInt(2);
            rs.close();
        }
        catch (SQLException sqle) {
            // If the table doesn't exist, an error will be thrown. Therefore
            // assume the version is 2.0.
            majorVersion = 2;
            minorVersion = 0;
        }
        finally {
            try { if (pstmt != null) { pstmt.close(); } }
            catch (Exception e) { Log.error(e); }
        }
712
        if (majorVersion == CURRENT_MAJOR_VERSION && minorVersion == CURRENT_MINOR_VERSION) {
713 714 715 716 717
            return false;
        }
        // The database is an old version that needs to be upgraded.
        Log.info("Found old database schema (" + majorVersion + "." + minorVersion + "). " +
                "Upgrading to latest schema.");
718 719
        System.out.println("Found old database schema (" + majorVersion + "." +
                minorVersion + "). " + "Upgrading to latest schema.");
720 721
        if (databaseType == DatabaseType.unknown) {
            Log.info("Warning: database type unknown. You must manually upgrade your database.");
722 723
            System.out.println("Warning: database type unknown. You must manually upgrade your " +
                    "database.");
724 725 726 727 728
            return false;
        }
        else if (databaseType == DatabaseType.interbase) {
            Log.info("Warning: automatic upgrades of Interbase are not supported. You " +
                    "must manually upgrade your database.");
729 730
            System.out.println("Warning: automatic upgrades of Interbase are not supported. You " +
                    "must manually upgrade your database.");
731 732 733 734 735
            return false;
        }
        // Run all upgrade scripts until we're up to the latest schema.
        for (int i=minorVersion; i<CURRENT_MINOR_VERSION; i++) {
            BufferedReader in = null;
736
            Statement stmt;
737 738 739 740 741 742
            try {
                // Resource will be like "/database/upgrade/2.0_to_2.1/messenger_hsqldb.sql"
                String resourceName = "/database/upgrade/" + CURRENT_MAJOR_VERSION + "." + i +
                        "_to_" + CURRENT_MAJOR_VERSION + "." + (i+1) + "/messenger_" +
                        databaseType + ".sql";
                in = new BufferedReader(new InputStreamReader(
743
                        DbConnectionManager.class.getResourceAsStream(resourceName)));
744 745
                boolean done = false;
                while (!done) {
746
                    StringBuilder command = new StringBuilder();
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
                    while (true) {
                        String line = in.readLine();
                        if (line == null) {
                            done = true;
                            break;
                        }
                        // Ignore comments and blank lines.
                        if (isSQLCommandPart(line)) {
                            command.append(line);
                        }
                        if (line.endsWith(";")) {
                            break;
                        }
                    }
                    // Send command to database.
                    if (!done && command != null) {
                        stmt = con.createStatement();
                        stmt.execute(command.toString());
                        stmt.close();
                    }
                }
            }
            finally {
                try { if (pstmt != null) { pstmt.close(); } }
                catch (Exception e) { Log.error(e); }
                if (in != null) {
                    try { in.close(); }
774 775 776
                    catch (Exception e) {
                        // Ignore.
                    }
777 778
                }
            }
Matt Tucker's avatar
Matt Tucker committed
779
        }
780 781
        Log.info("Database upgraded successfully.");
        System.out.println("Database upgraded successfully.");
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
        return true;
    }

    /**
     * Returns true if a line from a SQL schema is a valid command part.
     *
     * @param line the line of the schema.
     * @return true if a valid command part.
     */
    public static boolean isSQLCommandPart(String line) {
        line = line.trim();
        if (line.equals("")) {
            return false;
        }
        // Check to see if the line is a comment. Valid comment types:
        //   "//" is HSQLDB
        //   "--" is DB2 and Postgres
        //   "#" is MySQL
        //   "REM" is Oracle
        //   "/*" is SQLServer
802 803
        return !(line.startsWith("//") || line.startsWith("--") || line.startsWith("#") ||
                line.startsWith("REM") || line.startsWith("/*") || line.startsWith("*"));
804 805 806 807
    }

    private DbConnectionManager() {
        // Not instantiable.
Matt Tucker's avatar
Matt Tucker committed
808
    }
809
}