SQLite学习笔记(14)-虚拟机
虚拟机(Virtual Machine)VDBE是SQLite的核心,它的上层模块和下层模块都是本质上都是为它服务的。它的实现位于vbde.c,vdbe.h,vdbeapi.c,vdbeInt.h,和vdbemem.c等几个文件中。它通过底层的基础设施B-Tree执行由编译器(Compiler)生成的字节代码,这种字节代码程序语言 (bytecode programming lauguage)是为了进行查询、读取和修改数据库而专门设计的。 字节代码在内存中被封装成sqlit_stmt对象(内部叫做Vdbe),Vdbe(或者说statement)包含执行程序所需要的一切: a) a bytecode program b) names and data types for all result columns c) values bound to input parameters d) a program counter e) an execution stack of operands f) an arbitrary amount of "numbered"memory cells g) other run-time state information (such asopen BTree objects,sorters,lists,sets) 其代码位于vdbeInt.h,如下所示: struct Vdbe { sqlite3 *db; /* The database connection that owns this statement */ Op *aOp; /* Space to hold the virtual machine's program */ Mem *aMem; /* The memory locations */ Mem **apArg; /* Arguments to currently executing user function */ Mem *aColName; /* Column names to return */ Mem *pResultSet; /* Pointer to an array of results */ Parse *pParse; /* Parsing context used to create this Vdbe */ int nMem; /* Number of memory locations currently allocated */ int nOp; /* Number of instructions in the program */ int nCursor; /* Number of slots in apCsr[] */ u32 magic; /* Magic number for sanity checking */ char *zErrMsg; /* Error message written here */ Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */ VdbeCursor **apCsr; /* One element of this array for each open cursor */ Mem *aVar; /* Values for the OP_Variable opcode. */ char **azVar; /* Name of variables */ ynVar nVar; /* Number of entries in aVar[] */ ynVar nzVar; /* Number of entries in azVar[] */ u32 cacheCtr; /* VdbeCursor row cache generation counter */ int pc; /* The program counter */ int rc; /* Value to return */ …… }; 字节代码和汇编程序十分类似,每一条指令由操作码和五个操作数构成:P1,P2 P3,P4,和P5。Opcode为一定功能的操作码,为了理解,可以看成一个函数。P1、P2和P3都是32位有符号整数,P2通常是跳转指令的目标地址。P4是以联合体的形式进行定义,有时是32位有符号整数,有时是64有符号整数等等。P5是一个8位无符号整数,一般用来做标识。有的程序可以使用五个操作数,而有的程序一个都不用。和C API不同的是,VDBE操作码经常变化,所以不应该用字节码写程序。其代码如下所示:
|