H2數據庫創建表源碼分析

H2數據庫表創建粗濾分析01

創建入口

@Test
	public void test_h2_mem() throws SQLException
	{
		JdbcConnectionPool ds = JdbcConnectionPool.create("jdbc:h2:mem:test3", "sa", "1");
//		JdbcConnectionPool ds = JdbcConnectionPool.create("jdbc:h2:E:/test2", "sa", "");
	    ds.setMaxConnections(1000);
	    
	    Connection conn = ds.getConnection() ;
	    Statement stat = conn.createStatement();
        // insert data (ddl)
	    String createTableSql = "";
	    createTableSql += "create table userInfo(								";
	    createTableSql += "    id int(4) not null primary key auto_increment, 	";
	    createTableSql += "    name char(20) not null,                        	";
	    createTableSql += "    sex int(4) not null default '0',               	";
	    createTableSql += "    degree double	                            	";
	    createTableSql += ");                                                 	";
	    //進入
	    stat.execute( createTableSql );

JdbcStatement中的execute方法

@Override
    public boolean execute(String sql) throws SQLException {
        try {
            debugCodeCall("execute", sql);
            //調用下面的私有方法
            return executeInternal(sql);
        } catch (Exception e) {
            throw logAndConvert(e);
        }
    }

    private boolean executeInternal(String sql) throws SQLException {
        int id = getNextId(TraceObject.RESULT_SET);
        checkClosedForWrite();
        try {
            closeOldResultSet();
            sql = JdbcConnection.translateSQL(sql, escapeProcessing);
            //獲取command接口
            CommandInterface command = conn.prepareCommand(sql, fetchSize);
            boolean lazy = false;
            boolean returnsResultSet;
            synchronized (session) {
                setExecutingStatement(command);
                try {
                    if (command.isQuery()) {
                        returnsResultSet = true;
                        boolean scrollable = resultSetType != ResultSet.TYPE_FORWARD_ONLY;
                        boolean updatable = resultSetConcurrency == ResultSet.CONCUR_UPDATABLE;
                        ResultInterface result = command.executeQuery(maxRows, scrollable);
                        lazy = result.isLazy();
                        resultSet = new JdbcResultSet(conn, this, command, result, id,
                                closedByResultSet, scrollable, updatable);
                    } else {
                        returnsResultSet = false;
                        //調用command
                        updateCount = command.executeUpdate();
                    }
                } finally {
                    if (!lazy) {
                        setExecutingStatement(null);
                    }
                }
            }
            if (!lazy) {
                command.close();
            }
            return returnsResultSet;
        } finally {
            afterWriting();
        }
    }

創建表的語句 updateCount = command.executeUpdate(); debug進去找到return update()

//類名CommandContainer
//command類中的代碼有點多就不貼了直接進CommandContainer
@Override
    public int update() {
        recompileIfRequired();
        setProgress(DatabaseEventListener.STATE_STATEMENT_START);
        start();
        session.setLastScopeIdentity(ValueNull.INSTANCE);
        prepared.checkParameters();
        //返回更新的行數
        int updateCount = prepared.update();
        prepared.trace(startTimeNanos, updateCount);
        setProgress(DatabaseEventListener.STATE_STATEMENT_END);
        return updateCount;
    }

代碼有點長就把主要的代碼入口貼上了
int updateCount = prepared.update();從這段代碼進入到CreateTable 中的update方法


Table table = getSchema().createTable(data);

進入到了Schema中的createTable 方法

public Table createTable(CreateTableData data) {
        //線程鎖
        synchronized (database) {
            if (!data.temporary || data.globalTemporary) {
                database.lockMeta(data.session);
            }
            data.schema = this;
            if (data.tableEngine == null) {
                DbSettings s = database.getSettings();
                if (s.defaultTableEngine != null) {
                    data.tableEngine = s.defaultTableEngine;
                } else if (s.mvStore) {
                    //
                    data.tableEngine = MVTableEngine.class.getName();
                }
            }
            if (data.tableEngine != null) {
                if (data.tableEngineParams == null) {
                    data.tableEngineParams = this.tableEngineParams;
                }
                //從這進去使用表引擎創建表 繼續往下看
                return database.getTableEngine(data.tableEngine).createTable(data);
            }
            return new RegularTable(data);
        }
    }

終於找到了位置

@Override
    public TableBase createTable(CreateTableData data) {
        Database db = data.session.getDatabase();
        
        Store store = init(db);
        MVTable table = new MVTable(data, store);
        table.init(data.session);
        //將數據放到了tableMap中
        store.tableMap.put(table.getMapName(), table);
        return table;
    }
//一個Map
final ConcurrentHashMap<String, MVTable> tableMap =
                new ConcurrentHashMap<String, MVTable>();

以上爲大體步驟省了許多細節比如: 如何分解創建表的語句

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章