2013年10月14日 星期一

SQLite Compiler


The Architecture Of SQLite [http://www.sqlite.org/arch.html]


SQL Command Processor 可以往 source code 裡面看:
CAPI3REF: Compiling An SQL Statement
KEYWORDS: {SQL statement compiler}

The sqlite3_prepare function compiles an SQL statement, and produces an equivalent internal object. This object is commonly referred to as a prepared statement in database literature, and is implemented as a bytecode program in SQLite. A bytecode program is an abstract representation of an SQL statement that is run on a virtual machine or an interpreter. For more information, see the later section, Bytecode Programming Language. I use the terms bytecode program and prepared statement interchangeably in this book.


看圖片 SQL compiler 可以再分成三段:
  1. Tokenizer
  2. Parser
  3. Code generator

接下來就往 source code 裡面看進去了。繼續努力!
SQLITE_API int sqlite3_prepare(
  sqlite3 *db,            /* Database handle */
  const char *zSql,       /* SQL statement, UTF-8 encoded */
  int nByte,              /* Maximum length of zSql in bytes. */
  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
);

註解寫的蠻詳細的

((應該使用 sqlite3_prepare_v2,不過因為相容性,所以舊的 API 也會留下來))

現在追到 sqlite3LockAndPrepare,看字面有 lock ((mutex))。



Lock 的 methods 有一對,sqlite3_mutex_enter() 以及 sqlite3_mutex_leave()。

sqlite3BtreeEnterAll() 及 sqlite3BtreeLeaveAll() 就是 backend,裡面有三個主要 modules,B+ tree,Pager,以及 OS Interface ((可以想像 B+ tree 是最頂層的抽象資料結構,每個 file fragments 以 pagers 抽象化,最後 implementor 當然就是 OS 的 file system,這個就看是 Windows 或者是 Unix 或者是你想的到的))。

((這是我的猜測與想像,B+ tree 應該是這樣子的吧?!))



鬼扯一堆,最重要的還是 sqlite3Prepare(),這個得仔細看下去了!
  1. Initialize.
  2. Try to get a read lock on all database schemas.
  3. sqlite3RunParser()
  4. sqlite3VdbeSetSql()



然後這個應該是關鍵:LEMON-generated LALR(1) parser

The Lemon Parser Generator [http://www.sqlite.org/src/doc/trunk/doc/lemon.html]



The main parser program: sqlite3Parser()


沒有留言:

張貼留言