⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 database.java

📁 一个用java写的开源的数据库系统
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
/* Copyrights and Licenses * * This product includes Hypersonic SQL. * Originally developed by Thomas Mueller and the Hypersonic SQL Group.  * * Copyright (c) 1995-2000 by the Hypersonic SQL Group. All rights reserved.  * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met:  *     -  Redistributions of source code must retain the above copyright notice, this list of conditions *         and the following disclaimer.  *     -  Redistributions in binary form must reproduce the above copyright notice, this list of *         conditions and the following disclaimer in the documentation and/or other materials *         provided with the distribution.  *     -  All advertising materials mentioning features or use of this software must display the *        following acknowledgment: "This product includes Hypersonic SQL."  *     -  Products derived from this software may not be called "Hypersonic SQL" nor may *        "Hypersonic SQL" appear in their names without prior written permission of the *         Hypersonic SQL Group.  *     -  Redistributions of any form whatsoever must retain the following acknowledgment: "This *          product includes Hypersonic SQL."  * This software is provided "as is" and any expressed or implied warranties, including, but * not limited to, the implied warranties of merchantability and fitness for a particular purpose are * disclaimed. In no event shall the Hypersonic SQL Group or its contributors be liable for any * direct, indirect, incidental, special, exemplary, or consequential damages (including, but * not limited to, procurement of substitute goods or services; loss of use, data, or profits; * or business interruption). However caused any on any theory of liability, whether in contract, * strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this * software, even if advised of the possibility of such damage.  * This software consists of voluntary contributions made by many individuals on behalf of the * Hypersonic SQL Group. * * * For work added by the HSQL Development Group: * * Copyright (c) 2001-2002, The HSQL Development Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer, including earlier * license statements (above) and comply with all above license conditions. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution, including earlier * license statements (above) and comply with all above license conditions. * * Neither the name of the HSQL Development Group nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */package org.hsqldb;import java.sql.SQLException;import java.sql.Types;import java.util.Enumeration;import java.util.Hashtable;import java.util.Vector;/** *  Database is the root class for HSQL Database Engine database. <p> * *  Although it either directly or indirectly provides all or most of the *  services required for DBMS functionality, this class should not be used *  directly by an application. Instead, to achieve portability and *  generality, the jdbc* classes should be used. * * @version  1.7.0 */// fredt@users 20020130 - patch 476694 by velichko - transaction savepoints// additions to different parts to support savepoint transactions// fredt@users 20020215 - patch 1.7.0 by fredt - new HsqlProperties class// support use of properties from database.properties file// fredt@users 20020218 - patch 1.7.0 by fredt - DEFAULT keyword// support for default values for table columns// fredt@users 20020305 - patch 1.7.0 - restructuring// some methods move to Table.java, some removed// fredt@users 20020221 - patch 513005 by sqlbob@users (RMP) - restructuring// fredt@users 20020221 - patch 513005 by sqlbob@users (RMP) - error trapping// boucherb@users 20020130 - patch 1.7.0 - use lookup for speed// idents listed in alpha-order for easy check of stats...// fredt@users 20020420 - patch523880 by leptipre@users - VIEW support// fredt@users 20020430 - patch 549741 by velichko - ALTER TABLE RENAME// fredt@users 20020405 - patch 1.7.0 by fredt - other ALTER TABLE statements// boucherb@users - added javadoc comments// tony_lai@users 20020820 - patch 595099 by tlai@users - use user define PK name// tony_lai@users 20020820 - patch 595073 by tlai@users - duplicated exception msg// tony_lai@users 20020820 - patch 595156 by tlai@users - violation of Integrity constraint name// tony_lai@users 20020820 - patch 1.7.1 - modification to shutdown compact process to save memory usage// boucherb@users 20020828 - patch 1.7.1 - allow reconnect to local db that has shutdown// fredt@users 20020912 - patch 1.7.1 by fredt - drop duplicate name triggers// fredt@users 20020912 - patch 1.7.1 by fredt - log alter statementsclass Database {    private String                 sName;    private UserManager            aAccess;    private Vector                 tTable;    private DatabaseInformation    dInfo;    Logger                         logger;    boolean                        bReadOnly;    private boolean                bShutdown;    private Hashtable              hAlias;    private boolean                bIgnoreCase;    private boolean                bReferentialIntegrity;    private Vector                 cSession;    private HsqlDatabaseProperties databaseProperties;    private Session                sysSession;    private static final int       CALL       = 1;    private static final int       CHECKPOINT = 2;    private static final int       COMMIT     = 3;    private static final int       CONNECT    = 4;    private static final int       CREATE     = 5;    private static final int       DELETE     = 6;    private static final int       DISCONNECT = 7;    private static final int       DROP       = 8;    private static final int       GRANT      = 9;    private static final int       INSERT     = 10;    private static final int       REVOKE     = 11;    private static final int       ROLLBACK   = 12;    private static final int       SAVEPOINT  = 13;    private static final int       SCRIPT     = 14;    private static final int       SELECT     = 15;    private static final int       SET        = 16;    private static final int       SHUTDOWN   = 17;    private static final int       UPDATE     = 18;    private static final int       SEMICOLON  = 19;    private static final int       ALTER      = 20;    private static final Hashtable hCommands  = new Hashtable(37);    static {        hCommands.put("ALTER", new Integer(ALTER));        hCommands.put("CALL", new Integer(CALL));        hCommands.put("CHECKPOINT", new Integer(CHECKPOINT));        hCommands.put("COMMIT", new Integer(COMMIT));        hCommands.put("CONNECT", new Integer(CONNECT));        hCommands.put("CREATE", new Integer(CREATE));        hCommands.put("DELETE", new Integer(DELETE));        hCommands.put("DISCONNECT", new Integer(DISCONNECT));        hCommands.put("DROP", new Integer(DROP));        hCommands.put("GRANT", new Integer(GRANT));        hCommands.put("INSERT", new Integer(INSERT));        hCommands.put("REVOKE", new Integer(REVOKE));        hCommands.put("ROLLBACK", new Integer(ROLLBACK));        hCommands.put("SAVEPOINT", new Integer(SAVEPOINT));        hCommands.put("SCRIPT", new Integer(SCRIPT));        hCommands.put("SELECT", new Integer(SELECT));        hCommands.put("SET", new Integer(SET));        hCommands.put("SHUTDOWN", new Integer(SHUTDOWN));        hCommands.put("UPDATE", new Integer(UPDATE));        hCommands.put(";", new Integer(SEMICOLON));    }    /**     *  Constructs a new Database object that mounts or creates the database     *  files specified by the supplied name.     *     * @param  name the path to and common name shared by the database files     *      this Database uses     * @exception  SQLException if the specified path and common name     *      combination is illegal or unavailable, or the database files the     *      name resolves to are in use by another process     */    Database(String name) throws SQLException {        if (Trace.TRACE) {            Trace.trace();        }        sName = name;        open();    }    /**     * Opens the database.  The database can be opened by the constructor,     * or reopened by the close(int closemode) method during a     * "shutdown compact".     * @see close(int closemode)     */    // tony_lai@users 20020820    private void open() throws SQLException {        tTable                = new Vector();        aAccess               = new UserManager();        cSession              = new Vector();        hAlias                = new Hashtable();        logger                = new Logger();        bReferentialIntegrity = true;        Library.register(hAlias);        dInfo = new DatabaseInformation(this, tTable, aAccess);        boolean newdatabase = false;        sysSession = new Session(this, new User(null, null, true, null),                                 true, false, 0);        registerSession(sysSession);        databaseProperties = new HsqlDatabaseProperties(sName);        if (sName.equals(".")) {            newdatabase = true;            databaseProperties.setProperty("sql.strict_fk", true);        } else {            newdatabase = logger.openLog(this, sysSession, sName);        }        HsqlName.sysNumber = 0;        Library.setSqlMonth(databaseProperties.isPropertyTrue("sql.month"));        Parser.setEnforceSize(            databaseProperties.isPropertyTrue("sql.enforce_size"));        Column.setCompareInLocal(            databaseProperties.isPropertyTrue("sql.compare_in_locale"));        Record.gcFrequency =            databaseProperties.getIntegerProperty("hsqldb.gc_interval", 0);        if (newdatabase) {            execute("CREATE USER SA PASSWORD \"\" ADMIN", sysSession);        }        aAccess.grant("PUBLIC", "CLASS \"java.lang.Math\"", UserManager.ALL);        aAccess.grant("PUBLIC", "CLASS \"org.hsqldb.Library\"",                      UserManager.ALL);    }    /**     *  Retrieves this Database object's name, as know to this Database     *  object.     *     * @return  this Database object's name     */    String getName() {        return sName;    }    /**     *  Retrieves this Database object's properties.     *     * @return  this Database object's properties object     */    HsqlDatabaseProperties getProperties() {        return databaseProperties;    }    /**     *  isShutdown attribute getter.     *     * @return  the value of this Database object's isShutdown attribute     */    boolean isShutdown() {        return bShutdown;    }    /**     *  Constructs a new Session that operates within (is connected to) the     *  context of this Database object. <p>     *     *  If successful, the new Session object initially operates on behalf of     *  the user specified by the supplied user name.     *     * @param  username the name of the initial user of this session. The user     *      must already exist in this Database object.     * @param  password the password of the specified user. This must match     *      the password, as known to this Database object, of the specified     *      user     * @return  a new Session object that initially that initially operates on     *      behalf of the specified user     * @throws  SQLException if the specified user does not exist or a bad     *      password is specified     */    synchronized Session connect(String username,                                 String password) throws SQLException {        User user = aAccess.getUser(username.toUpperCase(),                                    password.toUpperCase());        int size = cSession.size();        int id   = size;        for (int i = 0; i < size; i++) {            if (cSession.elementAt(i) == null) {                id = i;                break;            }        }        Session session = new Session(this, user, true, bReadOnly, id);        logger.writeToLog(session,                          "CONNECT USER " + username + " PASSWORD \""                          + password + "\"");        registerSession(session);        return session;    }    /**     *  Binds the specified Session object into this Database object's active     *  session registry. This method is typically called from {@link     *  #connect} as the final step, when a successful connection has been     *  made.     *     * @param  session the Session object to register     */    void registerSession(Session session) {        int size = cSession.size();        int id   = session.getId();        if (id >= size) {            cSession.setSize(id + 1);        }        cSession.setElementAt(session, id);    }    /**     *  A specialized SQL statement executor, tailored for use by {@link     *  WebServerConnection}. Calling this method fully connects the specified     *  user, executes the specifed statement, and then disconects.     *     * @param  user the name of the user for which to execute the specified     *      statement. The user must already exist in this Database object.     * @param  password the password of the specified user. This must match     *      the password, as known to this Database object, of the specified     *      user     * @param  statement the SQL statement to execute     * @return  the result of executing the specified statement, in a form     *      already suitable for transmitting as part of an HTTP response.     */    byte[] execute(String user, String password, String statement) {        Result r = null;        try {            Session session = connect(user, password);            r = execute(statement, session);            execute("DISCONNECT", session);// fredt@users 20020221 - patch 513005 by sqlbob@users (RMP)        } catch (SQLException e) {            r = new Result(e.getMessage(), e.getErrorCode());        } catch (Exception e) {            r = new Result(e.getMessage(), Trace.GENERAL_ERROR);        }        try {            return r.getBytes();        } catch (Exception e) {            return new byte[0];        }    }    /**     *  The main SQL statement executor. <p>     *     *  All requests to execute SQL statements against this Database object     *  eventually go through this method.     *     * @param  statement the SQL statement to execute     * @param  session an object representing a connected user and a     *      collection of session state attributes     * @return  the result of executing the specified statement, in a form     *      suitable for either wrapping in a local ResultSet object or for     *      transmitting to a remote client via the native HSQLDB protocol     */    synchronized Result execute(String statement, Session session) {        if (Record.gcFrequency != 0                && Record.memoryRecords > Record.gcFrequency) {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -