h2database源碼淺析,h2database淺析

來源:互聯網
上載者:User

h2database源碼淺析,h2database淺析

最近想好好瞭解一下資料庫的原理,下載了h2database的源碼,準備好好看看。此過程的一些想法,暫且記下來,權當做讀碼筆記吧!

為了調試準備的測試案例:

@Testpublic void testExternalDb() throws Exception{Class.forName("org.h2.Driver");Connection conn = DriverManager.getConnection("jdbc:h2:./testdb", "sa", "");// add application code hereStatement stmt = conn.createStatement();stmt.executeUpdate("DROP TABLE TEST IF EXISTS");stmt.executeUpdate("CREATE TABLE TEST(ID INT PRIMARY KEY,NAME VARCHAR(255));");stmt.executeUpdate("INSERT INTO TEST VALUES(100, 'Damn,World');");stmt.executeUpdate("INSERT INTO TEST VALUES(200, 'Hello,H2');");stmt.executeUpdate("INSERT INTO TEST VALUES(150, 'Hello,World');");ResultSet rs = stmt.executeQuery("SELECT * FROM TEST where ID>120 and NAME like 'Hello%'");while (rs.next()){System.out.println(rs.getInt("ID") + "," + rs.getString("NAME"));}conn.close();}

以下為個人的一些猜測,後面會慢慢驗證:

  • h2說到底就是記憶體資料庫,其檔案版本只是記憶體內容的持久化,持久化在conn.close()的時候發生;
  • SQL語句會被h2解析成Prepared對象,然後再調用它的update()方法,其中:
    • DDL會編譯成DefineCommand
    • DML會編譯成Query, Update, Delete等對象
  • 作為例子,CreateTable是DefineCommand的一個衍生類別:
  • Query有2個衍生類別:Select和SelectUnion
  • Select.query()代碼如下:
    while (topTableFilter.next()){setCurrentRowNumber(rowNumber + 1);if (condition == null || Boolean.TRUE.equals(condition.getBooleanValue(session))){Value[] row = new Value[columnCount];for (int i = 0; i < columnCount; i++){Expression expr = expressions.get(i);row[i] = expr.getValue(session);}//...result.addRow(row);rowNumber++;//...}}


  • 可以看到,Select包含一個TableFilter,TableFilter表示待查詢的表,它同時包含一個indexConditions,用以實現index過濾:

  • TableFilter.next()會調用IndexCursor.next(),IndexCursor是根據index得到的記錄迭代器,其中find()方法相當於初始化,如針對ID>120會計算出firstRow指向{ID=150}這條記錄;
  • TableFilter可以理解成一級過濾(根據索引進行過濾),condition可以理解成二級過濾;
  • condition的類型是Condition,測試案例裡的查詢會表示成一個ConditionAndOr對象;
  • LocalResult對應於一個查詢結果的cache(難道不是消極式載入???),儲存了所有的rows,並提供next()方法;
  • Select.query()方法會將查詢結果寫入LocalResult中,並返回該LocalResult;
  • JdbcStatement會將LocalResult封裝成一個JdbcResultSet,返回給JDBC用戶端;
    public class JdbcResultSet extends TraceObject implements ResultSet{//...public boolean next() throws SQLException{try{debugCodeCall("next");checkClosed();return nextRow();}catch (Exception e){throw logAndConvert(e);}}private boolean nextRow(){boolean next = result.next();if (!next && !scrollable){result.close();}return next;}//...}


相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.