{
    "mode": "perldoc",
    "parameter": "DBD::SQLite::VirtualTable",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/DBD%3A%3ASQLite%3A%3AVirtualTable/json",
    "generated": "2026-06-13T14:49:20Z",
    "synopsis": "# register the virtual table module within sqlite\n$dbh->sqlitecreatemodule(modname => \"DBD::SQLite::VirtualTable::Subclass\");\n# create a virtual table\n$dbh->do(\"CREATE VIRTUAL TABLE vtbl USING modname(arg1, arg2, ...)\")\n# use it as any regular table\nmy $sth = $dbh->prepare(\"SELECT * FROM vtbl WHERE ...\");\nNote : VirtualTable subclasses or instances are not called directly from Perl code; everything\nhappens indirectly through SQL statements within SQLite.",
    "sections": {
        "NAME": {
            "content": "DBD::SQLite::VirtualTable -- SQLite virtual tables implemented in Perl\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "# register the virtual table module within sqlite\n$dbh->sqlitecreatemodule(modname => \"DBD::SQLite::VirtualTable::Subclass\");\n\n# create a virtual table\n$dbh->do(\"CREATE VIRTUAL TABLE vtbl USING modname(arg1, arg2, ...)\")\n\n# use it as any regular table\nmy $sth = $dbh->prepare(\"SELECT * FROM vtbl WHERE ...\");\n\nNote : VirtualTable subclasses or instances are not called directly from Perl code; everything\nhappens indirectly through SQL statements within SQLite.\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "This module is an abstract class for implementing SQLite virtual tables, written in Perl. Such\ntables look like regular tables, and are accessed through regular SQL instructions and regular\nDBI API; but the implementation is done through hidden calls to a Perl class. This is the same\nidea as Perl's tied variables, but at the SQLite level.\n\nThe current abstract class cannot be used directly, so the synopsis above is just to give a\ngeneral idea. Concrete, usable classes bundled with the present distribution are :\n\n*   DBD::SQLite::VirtualTable::FileContent : implements a virtual column that exposes file\ncontents. This is especially useful in conjunction with a fulltext index; see\nDBD::SQLite::Fulltextsearch.\n\n*   DBD::SQLite::VirtualTable::PerlData : binds to a Perl array within the Perl program. This\ncan be used for simple import/export operations, for debugging purposes, for joining data\nfrom different sources, etc.\n\nOther Perl virtual tables may also be published separately on CPAN.\n\nThe following chapters document the structure of the abstract class and explain how to write new\nsubclasses; this is meant for module authors, not for end users. If you just need to use a\nvirtual table module, refer to that module's documentation.\n",
            "subsections": []
        },
        "ARCHITECTURE": {
            "content": "",
            "subsections": [
                {
                    "name": "Classes",
                    "content": "A virtual table module for SQLite is implemented through a pair of classes :\n\n*   the table class implements methods for creating or connecting a virtual table, for\ndestroying it, for opening new searches, etc.\n\n*   the cursor class implements methods for performing a specific SQL statement\n"
                },
                {
                    "name": "Methods",
                    "content": "Most methods in both classes are not called directly from Perl code : instead, they are\ncallbacks, called from the sqlite kernel. Following common Perl conventions, such methods have\nnames in uppercase.\n"
                }
            ]
        },
        "TABLE METHODS": {
            "content": "",
            "subsections": [
                {
                    "name": "Class methods for registering the module",
                    "content": "CREATEMODULE\n$class->CREATEMODULE($sqlitemodulename);\n\nCalled when the client code invokes\n\n$dbh->sqlitecreatemodule($sqlitemodulename => $class);\n\nThe default implementation is empty.\n\nDESTROYMODULE\n$class->DESTROYMODULE();\n\nCalled automatically when the database handle is disconnected. The default implementation is\nempty.\n"
                },
                {
                    "name": "Class methods for creating a vtable instance",
                    "content": "CREATE\n$class->CREATE($dbhref, $modulename, $dbname, $vtabname, @args);\n\nCalled when sqlite receives a statement\n\nCREATE VIRTUAL TABLE $dbname.$vtabname USING $modulename(@args)\n\nThe default implementation just calls \"NEW\".\n\nCONNECT\n$class->CONNECT($dbhref, $modulename, $dbname, $vtabname, @args);\n\nCalled when attempting to access a virtual table that had been created during previous database\nconnection. The creation arguments were stored within the sqlite database and are passed again\nto the CONNECT method.\n\nThe default implementation just calls \"NEW\".\n\nPREPARESELF\n$class->PREPARESELF($dbhref, $modulename, $dbname, $vtabname, @args);\n\nPrepares the datastructure for a virtual table instance. @args is just the collection of strings\n(comma-separated) that were given within the \"CREATE VIRTUAL TABLE\" statement; each subclass\nshould decide what to do with this information,\n\nThe method parses @args to differentiate between *options* (strings of shape $key=$value or\n$key=\"$value\", stored in \"$self->{options}\"), and *columns* (other @args, stored in\n\"$self->{columns}\"). It creates a hashref with the following fields :\n\n\"dbhref\"\na weak reference to the $dbh database handle (see Scalar::Util for an explanation of weak\nreferences).\n\n\"modulename\"\nname of the module as declared to sqlite (not to be confounded with the Perl class name).\n\n\"dbname\"\nname of the database (usuallly 'main' or 'temp'), but it may also be an attached database\n\n\"vtabname\"\nname of the virtual table\n\n\"columns\"\narrayref of column declarations\n\n\"options\"\nhashref of option declarations\n\nThis method should not be redefined, since it performs general work which is supposed to be\nuseful for all subclasses. Instead, subclasses may override the \"NEW\" method.\n\nNEW\n$class->NEW($dbhref, $modulename, $dbname, $vtabname, @args);\n\nInstantiates a virtual table.\n"
                },
                {
                    "name": "Instance methods called from the sqlite kernel",
                    "content": "DROP\nCalled whenever a virtual table is destroyed from the database through the \"DROP TABLE\" SQL\ninstruction.\n\nJust after the \"DROP()\" call, the Perl instance will be destroyed (and will therefore\nautomatically call the \"DESTROY()\" method if such a method is present).\n\nThe default implementation for DROP is empty.\n\nNote : this corresponds to the \"xDestroy\" method in the SQLite documentation; here it was not\nnamed \"DESTROY\", to avoid any confusion with the standard Perl method \"DESTROY\" for object\ndestruction.\n\nDISCONNECT\nCalled for every virtual table just before the database handle is disconnected.\n\nJust after the \"DISCONNECT()\" call, the Perl instance will be destroyed (and will therefore\nautomatically call the \"DESTROY()\" method if such a method is present).\n\nThe default implementation for DISCONNECT is empty.\n\nVTABTODECLARE\nThis method is called automatically just after \"CREATE\" or \"CONNECT\", to register the columns of\nthe virtual table within the sqlite kernel. The method should return a string containing a SQL\n\"CREATE TABLE\" statement; but only the column declaration parts will be considered. Columns may\nbe declared with the special keyword \"HIDDEN\", which means that they are used internally for the\nthe virtual table implementation, and are not visible to users -- see\n<http://sqlite.org/c3ref/declarevtab.html> and <http://www.sqlite.org/vtab.html#hiddencol> for\ndetailed explanations.\n\nThe default implementation returns:\n\nCREATE TABLE $self->{vtabname}(@{$self->{columns}})\n\nBESTINDEX\nmy $indexinfo = $vtab->BESTINDEX($constraints, $orderby)\n\nThis is the most complex method to redefined in subclasses. This method will be called at the\nbeginning of a new query on the virtual table; the job of the method is to assemble some\ninformation that will be used\n\na)  by the sqlite kernel to decide about the best search strategy\n\nb)  by the cursor \"FILTER\" method to produce the desired subset of rows from the virtual table.\n\nBy calling this method, the SQLite core is saying to the virtual table that it needs to access\nsome subset of the rows in the virtual table and it wants to know the most efficient way to do\nthat access. The \"BESTINDEX\" method replies with information that the SQLite core can then use\nto conduct an efficient search of the virtual table.\n\nThe method takes as input a list of $constraints and a list of $orderby instructions. It\nreturns a hashref of indexing properties, described below; furthermore, the method also adds\nsupplementary information within the input $constraints. Detailed explanations are given in\n<http://sqlite.org/vtab.html#xbestindex>.\n\nInput constraints\nElements of the $constraints arrayref correspond to specific clauses of the \"WHERE ...\" part of\nthe SQL query. Each constraint is a hashref with keys :\n\n\"col\"\nthe integer index of the column on the left-hand side of the constraint\n\n\"op\"\nthe comparison operator, expressed as string containing '=', '>', '>=', '<', '<=' or\n'MATCH'.\n\n\"usable\"\na boolean indicating if that constraint is usable; some constraints might not be usable\nbecause of the way tables are ordered in a join.\n\nThe $constraints arrayref is used both for input and for output. While iterating over the array,\nthe method should add the following keys into usable constraints :\n\n\"argvIndex\"\nAn index into the @values array that will be passed to the cursor's \"FILTER\" method. In\nother words, if the current constraint corresponds to the SQL fragment \"WHERE ... AND foo <\n123 ...\", and the corresponding \"argvIndex\" takes value 5, this means that the \"FILTER\"\nmethod will receive 123 in $values[5].\n\n\"omit\"\nA boolean telling to the sqlite core that it can safely omit to double check that constraint\nbefore returning the resultset to the calling program; this means that the FILTER method has\nfulfilled the filtering job on that constraint and there is no need to do any further\nchecking.\n\nThe \"BESTINDEX\" method will not necessarily receive all constraints from the SQL \"WHERE\" clause\n: for example a constraint like \"col1 < col2 + col3\" cannot be handled at this level.\nFurthemore, the \"BESTINDEX\" might decide to ignore some of the received constraints. This is\nwhy a second pass over the results will be performed by the sqlite core.\n\n\"orderby\" input information\nThe $orderby arrayref corresponds to the \"ORDER BY\" clauses in the SQL query. Each entry is a\nhashref with keys :\n\n\"col\"\nthe integer index of the column being ordered\n\n\"desc\"\na boolean telling of the ordering is DESCending or ascending\n\nThis information could be used by some subclasses for optimizing the query strategfy; but\nusually the sqlite core will perform another sorting pass once all results are gathered.\n\nHashref information returned by BESTINDEX\nThe method should return a hashref with the following keys :\n\n\"idxNum\"\nAn arbitrary integer associated with that index; this information will be passed back to\n\"FILTER\".\n\n\"idxStr\"\nAn arbitrary str associated with that index; this information will be passed back to\n\"FILTER\".\n\n\"orderByConsumed\"\nA boolean telling the sqlite core if the $orderby information has been taken into account\nor not.\n\n\"estimatedCost\"\nA float that should be set to the estimated number of disk access operations required to\nexecute this query against the virtual table. The SQLite core will often call BESTINDEX\nmultiple times with different constraints, obtain multiple cost estimates, then choose the\nquery plan that gives the lowest estimate.\n\n\"estimatedRows\"\nAn integer giving the estimated number of rows returned by that query.\n\nOPEN\nCalled to instantiate a new cursor. The default implementation appends \"::Cursor\" to the current\nclassname and calls \"NEW()\" within that cursor class.\n\nSQLITEUPDATE\nThis is the dispatch method implementing the \"xUpdate()\" callback for virtual tables. The\ndefault implementation applies the algorithm described in <http://sqlite.org/vtab.html#xupdate>\nto decide to call \"INSERT\", \"DELETE\" or \"UPDATE\"; so there is no reason to override this method\nin subclasses.\n\nINSERT\nmy $rowid = $vtab->INSERT($newrowid, @values);\n\nThis method should be overridden in subclasses to implement insertion of a new row into the\nvirtual table. The size of the @values array corresponds to the number of columns declared\nthrough \"VTABTODECLARE\". The $newrowid may be explicitly given, or it may be \"undef\", in\nwhich case the method must compute a new id and return it as the result of the method call.\n\nDELETE\n$vtab->INSERT($oldrowid);\n\nThis method should be overridden in subclasses to implement deletion of a row from the virtual\ntable.\n\nUPDATE\n$vtab->UPDATE($oldrowid, $newrowid, @values);\n\nThis method should be overridden in subclasses to implement a row update within the virtual\ntable. Usually $oldrowid is equal to $newrowid, which is a regular update; however, the rowid\ncould be changed from a SQL statement such as\n\nUPDATE table SET rowid=rowid+1 WHERE ...;\n\nFINDFUNCTION\n$vtab->FINDFUNCTION($numargs, $funcname);\n\nWhen a function uses a column from a virtual table as its first argument, this method is called\nto see if the virtual table would like to overload the function. Parameters are the number of\narguments to the function, and the name of the function. If no overloading is desired, this\nmethod should return false. To overload the function, this method should return a coderef to the\nfunction implementation.\n\nEach virtual table keeps a cache of results from FINDFUNCTION calls, so the method will be\ncalled only once for each pair \"($numargs, $funcname)\".\n\nBEGINTRANSACTION\nCalled to begin a transaction on the virtual table.\n\nSYNCTRANSACTION\nCalled to signal the start of a two-phase commit on the virtual table.\n\nSYNCTRANSACTION\nCalled to commit a virtual table transaction.\n\nROLLBACKTRANSACTION\nCalled to rollback a virtual table transaction.\n\nRENAME\n$vtab->RENAME($newname)\n\nCalled to rename a virtual table.\n\nSAVEPOINT\n$vtab->SAVEPOINT($savepoint)\n\nCalled to signal the virtual table to save its current state at savepoint $savepoint (an\ninteger).\n\nROLLBACKTO\n$vtab->ROLLBACKTO($savepoint)\n\nCalled to signal the virtual table to return to the state $savepoint. This will invalidate all\nsavepoints with values greater than $savepoint.\n\nRELEASE\n$vtab->RELEASE($savepoint)\n\nCalled to invalidate all savepoints with values greater or equal to $savepoint.\n"
                },
                {
                    "name": "Utility instance methods",
                    "content": "Methods in this section are in lower case, because they are not called directly from the sqlite\nkernel; these are utility methods to be called from other methods described above.\n\ndbh\nThis method returns the database handle ($dbh) associated with the current virtual table.\n"
                }
            ]
        },
        "CURSOR METHODS": {
            "content": "",
            "subsections": [
                {
                    "name": "Class methods",
                    "content": "NEW\nmy $cursor = $cursorclass->NEW($vtable, @args)\n\nInstantiates a new cursor. The default implementation just returns a blessed hashref with keys\n\"vtable\" and \"args\".\n"
                },
                {
                    "name": "Instance methods",
                    "content": "FILTER\n$cursor->FILTER($idxNum, $idxStr, @values);\n\nThis method begins a search of a virtual table.\n\nThe $idxNum and $idxStr arguments correspond to values returned by \"BESTINDEX\" for the chosen\nindex. The specific meanings of those values are unimportant to SQLite, as long as \"BESTINDEX\"\nand \"FILTER\" agree on what that meaning is.\n\nThe \"BESTINDEX\" method may have requested the values of certain expressions using the\n\"argvIndex\" values of the $constraints list. Those values are passed to \"FILTER\" through the\n@values array.\n\nIf the virtual table contains one or more rows that match the search criteria, then the cursor\nmust be left point at the first row. Subsequent calls to \"EOF\" must return false. If there are\nno rows match, then the cursor must be left in a state that will cause \"EOF\" to return true. The\nSQLite engine will use the \"COLUMN\" and \"ROWID\" methods to access that row content. The \"NEXT\"\nmethod will be used to advance to the next row.\n\nEOF\nThis method must return false if the cursor currently points to a valid row of data, or true\notherwise. This method is called by the SQL engine immediately after each \"FILTER\" and \"NEXT\"\ninvocation.\n\nNEXT\nThis method advances the cursor to the next row of a result set initiated by \"FILTER\". If the\ncursor is already pointing at the last row when this method is called, then the cursor no longer\npoints to valid data and a subsequent call to the \"EOF\" method must return true. If the cursor\nis successfully advanced to another row of content, then subsequent calls to \"EOF\" must return\nfalse.\n\nCOLUMN\nmy $value = $cursor->COLUMN($idxCol);\n\nThe SQLite core invokes this method in order to find the value for the N-th column of the\ncurrent row. N is zero-based so the first column is numbered 0.\n\nROWID\nmy $value = $cursor->ROWID;\n\nReturns the *rowid* of row that the cursor is currently pointing at.\n"
                }
            ]
        },
        "SEE ALSO": {
            "content": "SQLite::VirtualTable is another module for virtual tables written in Perl, but designed for the\nreverse use case : instead of starting a Perl program, and embedding the SQLite library into it,\nthe intended use is to start an sqlite program, and embed the Perl interpreter into it.\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "Laurent Dami <dami@cpan.org>\n",
            "subsections": []
        },
        "COPYRIGHT AND LICENSE": {
            "content": "Copyright Laurent Dami, 2014.\n\nParts of the code are borrowed from SQLite::VirtualTable, copyright (C) 2006, 2009 by Qindel\nFormacion y Servicios, S. L.\n\nThis library is free software; you can redistribute it and/or modify it under the same terms as\nPerl itself.\n",
            "subsections": []
        }
    },
    "summary": "DBD::SQLite::VirtualTable -- SQLite virtual tables implemented in Perl",
    "flags": [],
    "examples": [],
    "see_also": []
}