Initialization
The first callback function to implement is xCreate(), which creates the virtual table. This is called oncespecifically, when the first database connection declares the virtual table via the CREATE VIRTUAL TABLE statement.
xCreate()'s job is to set up the virtual table environment and initialize any necessary resources. The implementation (vt_create()) is in Listing Three. It allocates a vtab struct and passes it back to SQLite using the vtable pointer reference it passes in (pp_vt). SQLite also passes in a reference to the database connection, so you store a reference to it in your vtab structure. In so doing, SQLite has a reference to a new vtab struct, which in turn has a reference to the database connection.
In addition to allocating a vtab structure, vt_create() also declares the table using sqlite3_declare_table(), passing SQLite the SQL (DDL) defining the virtual table's schema. Here, the SQL is contained in the global variable DDL in Listing Four (available online; see www.ddj.com/code/).
The xDestroy() function is essentially the reverse of this xCreate() process, and is called to clean up the resources associated with the virtual table.
static int vt_create( sqlite3 *db, void *pAux, int argc, const char *const*argv, sqlite3_vtab **pp_vt, char **pzErr ) { int rc = SQLITE_OK; vtab* p_vt; /* Allocate the sqlite3_vtab/vtab structure itself */ p_vt = (vtab*)sqlite3_malloc(sizeof(*p_vt)); if(p_vt == NULL) { return SQLITE_NOMEM; } p_vt->db = db; apr_pool_create(&p_vt->pool, NULL); /* Declare the vtable's structure */ rc = sqlite3_declare_vtab(db, ddl); /* Success. Set *pp_vt and return */ *pp_vt = &p_vt->base; return SQLITE_OK; }
The xConnect() and xDisconnect() functions are similar to xCreate()/xDestroy() with one exception. xCreate() and xDestroy() are designed to do one-time initialization/destruction of the virtual table, while xConnect() and xDisconnect() are intended to connect/disconnect a database with an existing virtual table. The distinction only matters if you have shared resource(s) associated with the virtual table that must be available to all database connections. If you don't have any, then these functions are essentially identical.