.\" Man page generated from reStructuredText. . . .nr rst2man-indent-level 0 . .de1 rstReportMargin \\$1 \\n[an-margin] level \\n[rst2man-indent-level] level margin: \\n[rst2man-indent\\n[rst2man-indent-level]] - \\n[rst2man-indent0] \\n[rst2man-indent1] \\n[rst2man-indent2] .. .de1 INDENT .\" .rstReportMargin pre: . RS \\$1 . nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin] . nr rst2man-indent-level +1 .\" .rstReportMargin post: .. .de UNINDENT . RE .\" indent \\n[an-margin] .\" old: \\n[rst2man-indent\\n[rst2man-indent-level]] .nr rst2man-indent-level -1 .\" new: \\n[rst2man-indent\\n[rst2man-indent-level]] .in \\n[rst2man-indent\\n[rst2man-indent-level]]u .. .TH "SQLITE-UTILS" "1" "Nov 01, 2022" "" "sqlite-utils" .SH NAME sqlite-utils \- sqlite-utils documentation .sp \fICLI tool and Python utility functions for manipulating SQLite databases\fP .sp This library and command\-line utility helps create SQLite databases from an existing collection of data. .sp Most of the functionality is available as either a Python API or through the \fBsqlite\-utils\fP command\-line tool. .sp sqlite\-utils is not intended to be a full ORM: the focus is utility helpers to make creating the initial database and populating it with data as productive as possible. .sp It is designed as a useful complement to \fI\%Datasette\fP\&. .sp \fI\%Cleaning data with sqlite\-utils and Datasette\fP provides a tutorial introduction (and accompanying ten minute video) about using this tool. .SH CONTENTS .SS Installation .sp \fBsqlite\-utils\fP is tested on Linux, macOS and Windows. .SS Using Homebrew .sp The \fI\%sqlite\-utils command\-line tool\fP can be installed on macOS using Homebrew: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C brew install sqlite\-utils .ft P .fi .UNINDENT .UNINDENT .sp If you have it installed and want to upgrade to the most recent release, you can run: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C brew upgrade sqlite\-utils .ft P .fi .UNINDENT .UNINDENT .sp Then run \fBsqlite\-utils \-\-version\fP to confirm the installed version. .SS Using pip .sp The \fI\%sqlite\-utils package\fP on PyPI includes both the \fI\%sqlite_utils Python library\fP and the \fBsqlite\-utils\fP command\-line tool. You can install them using \fBpip\fP like so: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C pip install sqlite\-utils .ft P .fi .UNINDENT .UNINDENT .SS Using pipx .sp \fI\%pipx\fP is a tool for installing Python command\-line applications in their own isolated environments. You can use \fBpipx\fP to install the \fBsqlite\-utils\fP command\-line tool like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C pipx install sqlite\-utils .ft P .fi .UNINDENT .UNINDENT .SS sqlite\-utils command\-line tool .sp The \fBsqlite\-utils\fP command\-line tool can be used to manipulate SQLite databases in a number of different ways. .sp Once \fI\%installed\fP the tool should be available as \fBsqlite\-utils\fP\&. It can also be run using \fBpython \-m sqlite_utils\fP\&. .INDENT 0.0 .IP \(bu 2 \fI\%Running SQL queries\fP .INDENT 2.0 .IP \(bu 2 \fI\%Returning JSON\fP .INDENT 2.0 .IP \(bu 2 \fI\%Newline\-delimited JSON\fP .IP \(bu 2 \fI\%JSON arrays\fP .IP \(bu 2 \fI\%Binary data in JSON\fP .IP \(bu 2 \fI\%Nested JSON values\fP .UNINDENT .IP \(bu 2 \fI\%Returning CSV or TSV\fP .IP \(bu 2 \fI\%Table\-formatted output\fP .IP \(bu 2 \fI\%Returning raw data, such as binary content\fP .IP \(bu 2 \fI\%Using named parameters\fP .IP \(bu 2 \fI\%UPDATE, INSERT and DELETE\fP .IP \(bu 2 \fI\%Defining custom SQL functions\fP .IP \(bu 2 \fI\%SQLite extensions\fP .IP \(bu 2 \fI\%Attaching additional databases\fP .UNINDENT .IP \(bu 2 \fI\%Querying data directly using an in\-memory database\fP .INDENT 2.0 .IP \(bu 2 \fI\%Running queries directly against CSV or JSON\fP .IP \(bu 2 \fI\%Explicitly specifying the format\fP .IP \(bu 2 \fI\%Joining in\-memory data against existing databases using \-\-attach\fP .IP \(bu 2 \fI\%\-\-schema, \-\-analyze, \-\-dump and \-\-save\fP .UNINDENT .IP \(bu 2 \fI\%Returning all rows in a table\fP .IP \(bu 2 \fI\%Listing tables\fP .IP \(bu 2 \fI\%Listing views\fP .IP \(bu 2 \fI\%Listing indexes\fP .IP \(bu 2 \fI\%Listing triggers\fP .IP \(bu 2 \fI\%Showing the schema\fP .IP \(bu 2 \fI\%Analyzing tables\fP .INDENT 2.0 .IP \(bu 2 \fI\%Saving the analyzed table details\fP .UNINDENT .IP \(bu 2 \fI\%Creating an empty database\fP .IP \(bu 2 \fI\%Inserting JSON data\fP .INDENT 2.0 .IP \(bu 2 \fI\%Inserting binary data\fP .IP \(bu 2 \fI\%Inserting newline\-delimited JSON\fP .IP \(bu 2 \fI\%Flattening nested JSON objects\fP .UNINDENT .IP \(bu 2 \fI\%Inserting CSV or TSV data\fP .INDENT 2.0 .IP \(bu 2 \fI\%Alternative delimiters and quote characters\fP .IP \(bu 2 \fI\%CSV files without a header row\fP .UNINDENT .IP \(bu 2 \fI\%Inserting unstructured data with \-\-lines and \-\-text\fP .IP \(bu 2 \fI\%Applying conversions while inserting data\fP .INDENT 2.0 .IP \(bu 2 \fI\%\-\-convert with \-\-lines\fP .IP \(bu 2 \fI\%\-\-convert with \-\-text\fP .UNINDENT .IP \(bu 2 \fI\%Insert\-replacing data\fP .IP \(bu 2 \fI\%Upserting data\fP .IP \(bu 2 \fI\%Executing SQL in bulk\fP .IP \(bu 2 \fI\%Inserting data from files\fP .IP \(bu 2 \fI\%Converting data in columns\fP .INDENT 2.0 .IP \(bu 2 \fI\%Importing additional modules\fP .IP \(bu 2 \fI\%Using a convert() function to execute initialization\fP .IP \(bu 2 \fI\%sqlite\-utils convert recipes\fP .IP \(bu 2 \fI\%Saving the result to a different column\fP .IP \(bu 2 \fI\%Converting a column into multiple columns\fP .UNINDENT .IP \(bu 2 \fI\%Creating tables\fP .IP \(bu 2 \fI\%Duplicating tables\fP .IP \(bu 2 \fI\%Dropping tables\fP .IP \(bu 2 \fI\%Transforming tables\fP .INDENT 2.0 .IP \(bu 2 \fI\%Adding a primary key to a rowid table\fP .UNINDENT .IP \(bu 2 \fI\%Extracting columns into a separate table\fP .IP \(bu 2 \fI\%Creating views\fP .IP \(bu 2 \fI\%Dropping views\fP .IP \(bu 2 \fI\%Adding columns\fP .IP \(bu 2 \fI\%Adding columns automatically on insert/update\fP .IP \(bu 2 \fI\%Adding foreign key constraints\fP .INDENT 2.0 .IP \(bu 2 \fI\%Adding multiple foreign keys at once\fP .IP \(bu 2 \fI\%Adding indexes for all foreign keys\fP .UNINDENT .IP \(bu 2 \fI\%Setting defaults and not null constraints\fP .IP \(bu 2 \fI\%Creating indexes\fP .IP \(bu 2 \fI\%Configuring full\-text search\fP .IP \(bu 2 \fI\%Executing searches\fP .IP \(bu 2 \fI\%Enabling cached counts\fP .IP \(bu 2 \fI\%Optimizing index usage with ANALYZE\fP .IP \(bu 2 \fI\%Vacuum\fP .IP \(bu 2 \fI\%Optimize\fP .IP \(bu 2 \fI\%WAL mode\fP .IP \(bu 2 \fI\%Dumping the database to SQL\fP .IP \(bu 2 \fI\%Loading SQLite extensions\fP .IP \(bu 2 \fI\%SpatiaLite helpers\fP .INDENT 2.0 .IP \(bu 2 \fI\%Adding spatial indexes\fP .UNINDENT .IP \(bu 2 \fI\%Installing packages\fP .IP \(bu 2 \fI\%Uninstalling packages\fP .UNINDENT .SS Running SQL queries .sp The \fBsqlite\-utils query\fP command lets you run queries directly against a SQLite database file. This is the default subcommand, so the following two examples work the same way: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils query dogs.db "select * from dogs" $ sqlite\-utils dogs.db "select * from dogs" .ft P .fi .UNINDENT .UNINDENT .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 In Python: \fI\%db.query()\fP CLI reference: \fI\%sqlite\-utils query\fP .UNINDENT .UNINDENT .SS Returning JSON .sp The default format returned for queries is JSON: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils dogs.db "select * from dogs" [{"id": 1, "age": 4, "name": "Cleo"}, {"id": 2, "age": 2, "name": "Pancakes"}] .ft P .fi .UNINDENT .UNINDENT .SS Newline\-delimited JSON .sp Use \fB\-\-nl\fP to get back newline\-delimited JSON objects: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils dogs.db "select * from dogs" \-\-nl {"id": 1, "age": 4, "name": "Cleo"} {"id": 2, "age": 2, "name": "Pancakes"} .ft P .fi .UNINDENT .UNINDENT .SS JSON arrays .sp You can use \fB\-\-arrays\fP to request arrays instead of objects: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils dogs.db "select * from dogs" \-\-arrays [[1, 4, "Cleo"], [2, 2, "Pancakes"]] .ft P .fi .UNINDENT .UNINDENT .sp You can also combine \fB\-\-arrays\fP and \fB\-\-nl\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils dogs.db "select * from dogs" \-\-arrays \-\-nl [1, 4, "Cleo"] [2, 2, "Pancakes"] .ft P .fi .UNINDENT .UNINDENT .sp If you want to pretty\-print the output further, you can pipe it through \fBpython \-mjson.tool\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils dogs.db "select * from dogs" | python \-mjson.tool [ { "id": 1, "age": 4, "name": "Cleo" }, { "id": 2, "age": 2, "name": "Pancakes" } ] .ft P .fi .UNINDENT .UNINDENT .SS Binary data in JSON .sp Binary strings are not valid JSON, so BLOB columns containing binary data will be returned as a JSON object containing base64 encoded data, that looks like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils dogs.db "select name, content from images" | python \-mjson.tool [ { "name": "transparent.gif", "content": { "$base64": true, "encoded": "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" } } ] .ft P .fi .UNINDENT .UNINDENT .SS Nested JSON values .sp If one of your columns contains JSON, by default it will be returned as an escaped string: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils dogs.db "select * from dogs" | python \-mjson.tool [ { "id": 1, "name": "Cleo", "friends": "[{\e"name\e": \e"Pancakes\e"}, {\e"name\e": \e"Bailey\e"}]" } ] .ft P .fi .UNINDENT .UNINDENT .sp You can use the \fB\-\-json\-cols\fP option to automatically detect these JSON columns and output them as nested JSON data: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils dogs.db "select * from dogs" \-\-json\-cols | python \-mjson.tool [ { "id": 1, "name": "Cleo", "friends": [ { "name": "Pancakes" }, { "name": "Bailey" } ] } ] .ft P .fi .UNINDENT .UNINDENT .SS Returning CSV or TSV .sp You can use the \fB\-\-csv\fP option to return results as CSV: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils dogs.db "select * from dogs" \-\-csv id,age,name 1,4,Cleo 2,2,Pancakes .ft P .fi .UNINDENT .UNINDENT .sp This will default to including the column names as a header row. To exclude the headers, use \fB\-\-no\-headers\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils dogs.db "select * from dogs" \-\-csv \-\-no\-headers 1,4,Cleo 2,2,Pancakes .ft P .fi .UNINDENT .UNINDENT .sp Use \fB\-\-tsv\fP instead of \fB\-\-csv\fP to get back tab\-separated values: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils dogs.db "select * from dogs" \-\-tsv id age name 1 4 Cleo 2 2 Pancakes .ft P .fi .UNINDENT .UNINDENT .SS Table\-formatted output .sp You can use the \fB\-\-table\fP option (or \fB\-t\fP shortcut) to output query results as a table: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils dogs.db "select * from dogs" \-\-table id age name \-\-\-\- \-\-\-\-\- \-\-\-\-\-\-\-\- 1 4 Cleo 2 2 Pancakes .ft P .fi .UNINDENT .UNINDENT .sp You can use the \fB\-\-fmt\fP option to specify different table formats, for example \fBrst\fP for reStructuredText: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils dogs.db "select * from dogs" \-\-fmt rst ==== ===== ======== id age name ==== ===== ======== 1 4 Cleo 2 2 Pancakes ==== ===== ======== .ft P .fi .UNINDENT .UNINDENT .sp Available \fB\-\-fmt\fP options are: .INDENT 0.0 .IP \(bu 2 \fBasciidoc\fP .IP \(bu 2 \fBdouble_grid\fP .IP \(bu 2 \fBdouble_outline\fP .IP \(bu 2 \fBfancy_grid\fP .IP \(bu 2 \fBfancy_outline\fP .IP \(bu 2 \fBgithub\fP .IP \(bu 2 \fBgrid\fP .IP \(bu 2 \fBheavy_grid\fP .IP \(bu 2 \fBheavy_outline\fP .IP \(bu 2 \fBhtml\fP .IP \(bu 2 \fBjira\fP .IP \(bu 2 \fBlatex\fP .IP \(bu 2 \fBlatex_booktabs\fP .IP \(bu 2 \fBlatex_longtable\fP .IP \(bu 2 \fBlatex_raw\fP .IP \(bu 2 \fBmediawiki\fP .IP \(bu 2 \fBmixed_grid\fP .IP \(bu 2 \fBmixed_outline\fP .IP \(bu 2 \fBmoinmoin\fP .IP \(bu 2 \fBorgtbl\fP .IP \(bu 2 \fBoutline\fP .IP \(bu 2 \fBpipe\fP .IP \(bu 2 \fBplain\fP .IP \(bu 2 \fBpresto\fP .IP \(bu 2 \fBpretty\fP .IP \(bu 2 \fBpsql\fP .IP \(bu 2 \fBrounded_grid\fP .IP \(bu 2 \fBrounded_outline\fP .IP \(bu 2 \fBrst\fP .IP \(bu 2 \fBsimple\fP .IP \(bu 2 \fBsimple_grid\fP .IP \(bu 2 \fBsimple_outline\fP .IP \(bu 2 \fBtextile\fP .IP \(bu 2 \fBtsv\fP .IP \(bu 2 \fBunsafehtml\fP .IP \(bu 2 \fByoutrack\fP .UNINDENT .sp This list can also be found by running \fBsqlite\-utils query \-\-help\fP\&. .SS Returning raw data, such as binary content .sp If your table contains binary data in a \fBBLOB\fP you can use the \fB\-\-raw\fP option to output specific columns directly to standard out. .sp For example, to retrieve a binary image from a \fBBLOB\fP column and store it in a file you can use the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils photos.db "select contents from photos where id=1" \-\-raw > myphoto.jpg .ft P .fi .UNINDENT .UNINDENT .SS Using named parameters .sp You can pass named parameters to the query using \fB\-p\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils query dogs.db "select :num * :num2" \-p num 5 \-p num2 6 [{":num * :num2": 30}] .ft P .fi .UNINDENT .UNINDENT .sp These will be correctly quoted and escaped in the SQL query, providing a safe way to combine other values with SQL. .SS UPDATE, INSERT and DELETE .sp If you execute an \fBUPDATE\fP, \fBINSERT\fP or \fBDELETE\fP query the command will return the number of affected rows: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils dogs.db "update dogs set age = 5 where name = \(aqCleo\(aq" [{"rows_affected": 1}] .ft P .fi .UNINDENT .UNINDENT .SS Defining custom SQL functions .sp You can use the \fB\-\-functions\fP option to pass a block of Python code that defines additional functions which can then be called by your SQL query. .sp This example defines a function which extracts the domain from a URL: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils query sites.db "select url, domain(url) from urls" \-\-functions \(aq from urllib.parse import urlparse def domain(url): return urlparse(url).netloc \(aq .ft P .fi .UNINDENT .UNINDENT .sp Every callable object defined in the block will be registered as a SQL function with the same name, with the exception of functions with names that begin with an underscore. .SS SQLite extensions .sp You can load SQLite extension modules using the \fB\-\-load\-extension\fP option, see \fI\%Loading SQLite extensions\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils dogs.db "select spatialite_version()" \-\-load\-extension=spatialite [{"spatialite_version()": "4.3.0a"}] .ft P .fi .UNINDENT .UNINDENT .SS Attaching additional databases .sp SQLite supports cross\-database SQL queries, which can join data from tables in more than one database file. .sp You can attach one or more additional databases using the \fB\-\-attach\fP option, providing an alias to use for that database and the path to the SQLite file on disk. .sp This example attaches the \fBbooks.db\fP database under the alias \fBbooks\fP and then runs a query that combines data from that database with the default \fBdogs.db\fP database: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C sqlite\-utils dogs.db \-\-attach books books.db \e \(aqselect * from sqlite_master union all select * from books.sqlite_master\(aq .ft P .fi .UNINDENT .UNINDENT .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 In Python: \fI\%db.attach()\fP .UNINDENT .UNINDENT .SS Querying data directly using an in\-memory database .sp The \fBsqlite\-utils memory\fP command works similar to \fBsqlite\-utils query\fP, but allows you to execute queries against an in\-memory database. .sp You can also pass this command CSV or JSON files which will be loaded into a temporary in\-memory table, allowing you to execute SQL against that data without a separate step to first convert it to SQLite. .sp Without any extra arguments, this command executes SQL against the in\-memory database directly: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils memory \(aqselect sqlite_version()\(aq [{"sqlite_version()": "3.35.5"}] .ft P .fi .UNINDENT .UNINDENT .sp It takes all of the same output formatting options as \fI\%sqlite\-utils query\fP: \fB\-\-csv\fP and \fB\-\-csv\fP and \fB\-\-table\fP and \fB\-\-nl\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils memory \(aqselect sqlite_version()\(aq \-\-csv sqlite_version() 3.35.5 $ sqlite\-utils memory \(aqselect sqlite_version()\(aq \-\-fmt grid +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ | sqlite_version() | +====================+ | 3.35.5 | +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ .ft P .fi .UNINDENT .UNINDENT .SS Running queries directly against CSV or JSON .sp If you have data in CSV or JSON format you can load it into an in\-memory SQLite database and run queries against it directly in a single command using \fBsqlite\-utils memory\fP like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils memory data.csv "select * from data" .ft P .fi .UNINDENT .UNINDENT .sp You can pass multiple files to the command if you want to run joins between data from different files: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils memory one.csv two.json "select * from one join two on one.id = two.other_id" .ft P .fi .UNINDENT .UNINDENT .sp If your data is JSON it should be the same format supported by the \fI\%sqlite\-utils insert command\fP \- so either a single JSON object (treated as a single row) or a list of JSON objects. .sp CSV data can be comma\- or tab\- delimited. .sp The in\-memory tables will be named after the files without their extensions. The tool also sets up aliases for those tables (using SQL views) as \fBt1\fP, \fBt2\fP and so on, or you can use the alias \fBt\fP to refer to the first table: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils memory example.csv "select * from t" .ft P .fi .UNINDENT .UNINDENT .sp If two files have the same name they will be assigned a numeric suffix: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils memory foo/data.csv bar/data.csv "select * from data_2" .ft P .fi .UNINDENT .UNINDENT .sp To read from standard input, use either \fB\-\fP or \fBstdin\fP as the filename \- then use \fBstdin\fP or \fBt\fP or \fBt1\fP as the table name: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ cat example.csv | sqlite\-utils memory \- "select * from stdin" .ft P .fi .UNINDENT .UNINDENT .sp Incoming CSV data will be assumed to use \fButf\-8\fP\&. If your data uses a different character encoding you can specify that with \fB\-\-encoding\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ cat example.csv | sqlite\-utils memory \- "select * from stdin" \-\-encoding=latin\-1 .ft P .fi .UNINDENT .UNINDENT .sp If you are joining across multiple CSV files they must all use the same encoding. .sp Column types will be automatically detected in CSV or TSV data, using the same mechanism as \fB\-\-detect\-types\fP described in \fI\%Inserting CSV or TSV data\fP\&. You can pass the \fB\-\-no\-detect\-types\fP option to disable this automatic type detection and treat all CSV and TSV columns as \fBTEXT\fP\&. .SS Explicitly specifying the format .sp By default, \fBsqlite\-utils memory\fP will attempt to detect the incoming data format (JSON, TSV or CSV) automatically. .sp You can instead specify an explicit format by adding a \fB:csv\fP, \fB:tsv\fP, \fB:json\fP or \fB:nl\fP (for newline\-delimited JSON) suffix to the filename. For example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils memory one.dat:csv two.dat:nl "select * from one union select * from two" .ft P .fi .UNINDENT .UNINDENT .sp Here the contents of \fBone.dat\fP will be treated as CSV and the contents of \fBtwo.dat\fP will be treated as newline\-delimited JSON. .sp To explicitly specify the format for data piped into the tool on standard input, use \fBstdin:format\fP \- for example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ cat one.dat | sqlite\-utils memory stdin:csv "select * from stdin" .ft P .fi .UNINDENT .UNINDENT .SS Joining in\-memory data against existing databases using \-\-attach .sp The \fI\%attach option\fP can be used to attach database files to the in\-memory connection, enabling joins between in\-memory data loaded from a file and tables in existing SQLite database files. An example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ echo "id\en1\en3\en5" | sqlite\-utils memory \- \-\-attach trees trees.db \e "select * from trees.trees where rowid in (select id from stdin)" .ft P .fi .UNINDENT .UNINDENT .sp Here the \fB\-\-attach trees trees.db\fP option makes the \fBtrees.db\fP database available with an alias of \fBtrees\fP\&. .sp \fBselect * from trees.trees where ...\fP can then query the \fBtrees\fP table in that database. .sp The CSV data that was piped into the script is available in the \fBstdin\fP table, so \fB\&... where rowid in (select id from stdin)\fP can be used to return rows from the \fBtrees\fP table that match IDs that were piped in as CSV content. .SS \-\-schema, \-\-analyze, \-\-dump and \-\-save .sp To see the in\-memory database schema that would be used for a file or for multiple files, use \fB\-\-schema\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C % sqlite\-utils memory dogs.csv \-\-schema CREATE TABLE [dogs] ( [id] INTEGER, [age] INTEGER, [name] TEXT ); CREATE VIEW t1 AS select * from [dogs]; CREATE VIEW t AS select * from [dogs]; .ft P .fi .UNINDENT .UNINDENT .sp You can run the equivalent of the \fI\%analyze\-tables\fP command using \fB\-\-analyze\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C % sqlite\-utils memory dogs.csv \-\-analyze dogs.id: (1/3) Total rows: 2 Null rows: 0 Blank rows: 0 Distinct values: 2 dogs.name: (2/3) Total rows: 2 Null rows: 0 Blank rows: 0 Distinct values: 2 dogs.age: (3/3) Total rows: 2 Null rows: 0 Blank rows: 0 Distinct values: 2 .ft P .fi .UNINDENT .UNINDENT .sp You can output SQL that will both create the tables and insert the full data used to populate the in\-memory database using \fB\-\-dump\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C % sqlite\-utils memory dogs.csv \-\-dump BEGIN TRANSACTION; CREATE TABLE [dogs] ( [id] INTEGER, [age] INTEGER, [name] TEXT ); INSERT INTO "dogs" VALUES(\(aq1\(aq,\(aq4\(aq,\(aqCleo\(aq); INSERT INTO "dogs" VALUES(\(aq2\(aq,\(aq2\(aq,\(aqPancakes\(aq); CREATE VIEW t1 AS select * from [dogs]; CREATE VIEW t AS select * from [dogs]; COMMIT; .ft P .fi .UNINDENT .UNINDENT .sp Passing \fB\-\-save other.db\fP will instead use that SQL to populate a new database file: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C % sqlite\-utils memory dogs.csv \-\-save dogs.db .ft P .fi .UNINDENT .UNINDENT .sp These features are mainly intended as debugging tools \- for much more finely grained control over how data is inserted into a SQLite database file see \fI\%Inserting JSON data\fP and \fI\%Inserting CSV or TSV data\fP\&. .SS Returning all rows in a table .sp You can return every row in a specified table using the \fBrows\fP command: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils rows dogs.db dogs [{"id": 1, "age": 4, "name": "Cleo"}, {"id": 2, "age": 2, "name": "Pancakes"}] .ft P .fi .UNINDENT .UNINDENT .sp This command accepts the same output options as \fBquery\fP \- so you can pass \fB\-\-nl\fP, \fB\-\-csv\fP, \fB\-\-tsv\fP, \fB\-\-no\-headers\fP, \fB\-\-table\fP and \fB\-\-fmt\fP\&. .sp You can use the \fB\-c\fP option to specify a subset of columns to return: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils rows dogs.db dogs \-c age \-c name [{"age": 4, "name": "Cleo"}, {"age": 2, "name": "Pancakes"}] .ft P .fi .UNINDENT .UNINDENT .sp You can filter rows using a where clause with the \fB\-\-where\fP option: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils rows dogs.db dogs \-c name \-\-where \(aqname = "Cleo"\(aq [{"name": "Cleo"}] .ft P .fi .UNINDENT .UNINDENT .sp Or pass named parameters using \fB\-\-where\fP in combination with \fB\-p\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils rows dogs.db dogs \-c name \-\-where \(aqname = :name\(aq \-p name Cleo [{"name": "Cleo"}] .ft P .fi .UNINDENT .UNINDENT .sp You can define a sort order using \fB\-\-order column\fP or \fB\-\-order \(aqcolumn desc\(aq\fP\&. .sp Use \fB\-\-limit N\fP to only return the first \fBN\fP rows. Use \fB\-\-offset N\fP to return rows starting from the specified offset. .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 In Python: \fI\%table.rows\fP CLI reference: \fI\%sqlite\-utils rows\fP .UNINDENT .UNINDENT .SS Listing tables .sp You can list the names of tables in a database using the \fBtables\fP command: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils tables mydb.db [{"table": "dogs"}, {"table": "cats"}, {"table": "chickens"}] .ft P .fi .UNINDENT .UNINDENT .sp You can output this list in CSV using the \fB\-\-csv\fP or \fB\-\-tsv\fP options: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils tables mydb.db \-\-csv \-\-no\-headers dogs cats chickens .ft P .fi .UNINDENT .UNINDENT .sp If you just want to see the FTS4 tables, you can use \fB\-\-fts4\fP (or \fB\-\-fts5\fP for FTS5 tables): .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils tables docs.db \-\-fts4 [{"table": "docs_fts"}] .ft P .fi .UNINDENT .UNINDENT .sp Use \fB\-\-counts\fP to include a count of the number of rows in each table: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils tables mydb.db \-\-counts [{"table": "dogs", "count": 12}, {"table": "cats", "count": 332}, {"table": "chickens", "count": 9}] .ft P .fi .UNINDENT .UNINDENT .sp Use \fB\-\-columns\fP to include a list of columns in each table: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils tables dogs.db \-\-counts \-\-columns [{"table": "Gosh", "count": 0, "columns": ["c1", "c2", "c3"]}, {"table": "Gosh2", "count": 0, "columns": ["c1", "c2", "c3"]}, {"table": "dogs", "count": 2, "columns": ["id", "age", "name"]}] .ft P .fi .UNINDENT .UNINDENT .sp Use \fB\-\-schema\fP to include the schema of each table: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils tables dogs.db \-\-schema \-\-table table schema \-\-\-\-\-\-\- \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- Gosh CREATE TABLE Gosh (c1 text, c2 text, c3 text) Gosh2 CREATE TABLE Gosh2 (c1 text, c2 text, c3 text) dogs CREATE TABLE [dogs] ( [id] INTEGER, [age] INTEGER, [name] TEXT) .ft P .fi .UNINDENT .UNINDENT .sp The \fB\-\-nl\fP, \fB\-\-csv\fP, \fB\-\-tsv\fP, \fB\-\-table\fP and \fB\-\-fmt\fP options are also available. .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 In Python: \fI\%db.tables or db.table_names()\fP CLI reference: \fI\%sqlite\-utils tables\fP .UNINDENT .UNINDENT .SS Listing views .sp The \fBviews\fP command shows any views defined in the database: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils views sf\-trees.db \-\-table \-\-counts \-\-columns \-\-schema view count columns schema \-\-\-\-\-\-\-\-\- \-\-\-\-\-\-\- \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- demo_view 189144 [\(aqqSpecies\(aq] CREATE VIEW demo_view AS select qSpecies from Street_Tree_List hello 1 [\(aqsqlite_version()\(aq] CREATE VIEW hello as select sqlite_version() .ft P .fi .UNINDENT .UNINDENT .sp It takes the same options as the \fBtables\fP command: .INDENT 0.0 .IP \(bu 2 \fB\-\-columns\fP .IP \(bu 2 \fB\-\-schema\fP .IP \(bu 2 \fB\-\-counts\fP .IP \(bu 2 \fB\-\-nl\fP .IP \(bu 2 \fB\-\-csv\fP .IP \(bu 2 \fB\-\-tsv\fP .IP \(bu 2 \fB\-\-table\fP .UNINDENT .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 In Python: \fI\%db.views or db.view_names()\fP CLI reference: \fI\%sqlite\-utils views\fP .UNINDENT .UNINDENT .SS Listing indexes .sp The \fBindexes\fP command lists any indexes configured for the database: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils indexes covid.db \-\-table table index_name seqno cid name desc coll key \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- \-\-\-\-\-\-\- \-\-\-\-\- \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- \-\-\-\-\-\- \-\-\-\-\-\- \-\-\-\-\- johns_hopkins_csse_daily_reports idx_johns_hopkins_csse_daily_reports_combined_key 0 12 combined_key 0 BINARY 1 johns_hopkins_csse_daily_reports idx_johns_hopkins_csse_daily_reports_country_or_region 0 1 country_or_region 0 BINARY 1 johns_hopkins_csse_daily_reports idx_johns_hopkins_csse_daily_reports_province_or_state 0 2 province_or_state 0 BINARY 1 johns_hopkins_csse_daily_reports idx_johns_hopkins_csse_daily_reports_day 0 0 day 0 BINARY 1 ny_times_us_counties idx_ny_times_us_counties_date 0 0 date 1 BINARY 1 ny_times_us_counties idx_ny_times_us_counties_fips 0 3 fips 0 BINARY 1 ny_times_us_counties idx_ny_times_us_counties_county 0 1 county 0 BINARY 1 ny_times_us_counties idx_ny_times_us_counties_state 0 2 state 0 BINARY 1 .ft P .fi .UNINDENT .UNINDENT .sp It shows indexes across all tables. To see indexes for specific tables, list those after the database: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils indexes covid.db johns_hopkins_csse_daily_reports \-\-table .ft P .fi .UNINDENT .UNINDENT .sp The command defaults to only showing the columns that are explicitly part of the index. To also include auxiliary columns use the \fB\-\-aux\fP option \- these columns will be listed with a \fBkey\fP of \fB0\fP\&. .sp The command takes the same format options as the \fBtables\fP and \fBviews\fP commands. .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 In Python: \fI\%table.indexes\fP CLI reference: \fI\%sqlite\-utils indexes\fP .UNINDENT .UNINDENT .SS Listing triggers .sp The \fBtriggers\fP command shows any triggers configured for the database: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils triggers global\-power\-plants.db \-\-table name table sql \-\-\-\-\-\-\-\-\-\-\-\-\-\-\- \-\-\-\-\-\-\-\-\- \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- plants_insert plants CREATE TRIGGER [plants_insert] AFTER INSERT ON [plants] BEGIN INSERT OR REPLACE INTO [_counts] VALUES ( \(aqplants\(aq, COALESCE( (SELECT count FROM [_counts] WHERE [table] = \(aqplants\(aq), 0 ) + 1 ); END .ft P .fi .UNINDENT .UNINDENT .sp It defaults to showing triggers for all tables. To see triggers for one or more specific tables pass their names as arguments: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils triggers global\-power\-plants.db plants .ft P .fi .UNINDENT .UNINDENT .sp The command takes the same format options as the \fBtables\fP and \fBviews\fP commands. .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 In Python: \fI\%table.triggers or db.triggers\fP CLI reference: \fI\%sqlite\-utils triggers\fP .UNINDENT .UNINDENT .SS Showing the schema .sp The \fBsqlite\-utils schema\fP command shows the full SQL schema for the database: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils schema dogs.db CREATE TABLE "dogs" ( [id] INTEGER PRIMARY KEY, [name] TEXT ); .ft P .fi .UNINDENT .UNINDENT .sp This will show the schema for every table and index in the database. To view the schema just for a specified subset of tables pass those as additional arguments: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils schema dogs.db dogs chickens \&... .ft P .fi .UNINDENT .UNINDENT .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 In Python: \fI\%table.schema\fP or \fI\%db.schema\fP CLI reference: \fI\%sqlite\-utils schema\fP .UNINDENT .UNINDENT .SS Analyzing tables .sp When working with a new database it can be useful to get an idea of the shape of the data. The \fBsqlite\-utils analyze\-tables\fP command inspects specified tables (or all tables) and calculates some useful details about each of the columns in those tables. .sp To inspect the \fBtags\fP table in the \fBgithub.db\fP database, run the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils analyze\-tables github.db tags tags.repo: (1/3) Total rows: 261 Null rows: 0 Blank rows: 0 Distinct values: 14 Most common: 88: 107914493 75: 140912432 27: 206156866 Least common: 1: 209590345 2: 206649770 2: 303218369 tags.name: (2/3) Total rows: 261 Null rows: 0 Blank rows: 0 Distinct values: 175 Most common: 10: 0.2 9: 0.1 7: 0.3 Least common: 1: 0.1.1 1: 0.11.1 1: 0.1a2 tags.sha: (3/3) Total rows: 261 Null rows: 0 Blank rows: 0 Distinct values: 261 .ft P .fi .UNINDENT .UNINDENT .sp For each column this tool displays the number of null rows, the number of blank rows (rows that contain an empty string), the number of distinct values and, for columns that are not entirely distinct, the most common and least common values. .sp If you do not specify any tables every table in the database will be analyzed: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils analyze\-tables github.db .ft P .fi .UNINDENT .UNINDENT .sp If you wish to analyze one or more specific columns, use the \fB\-c\fP option: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils analyze\-tables github.db tags \-c sha .ft P .fi .UNINDENT .UNINDENT .SS Saving the analyzed table details .sp \fBanalyze\-tables\fP can take quite a while to run for large database files. You can save the results of the analysis to a database table called \fB_analyze_tables_\fP using the \fB\-\-save\fP option: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils analyze\-tables github.db \-\-save .ft P .fi .UNINDENT .UNINDENT .sp The \fB_analyze_tables_\fP table has the following schema: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CREATE TABLE [_analyze_tables_] ( [table] TEXT, [column] TEXT, [total_rows] INTEGER, [num_null] INTEGER, [num_blank] INTEGER, [num_distinct] INTEGER, [most_common] TEXT, [least_common] TEXT, PRIMARY KEY ([table], [column]) ); .ft P .fi .UNINDENT .UNINDENT .sp The \fBmost_common\fP and \fBleast_common\fP columns will contain nested JSON arrays of the most common and least common values that look like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C [ ["Del Libertador, Av", 5068], ["Alberdi Juan Bautista Av.", 4612], ["Directorio Av.", 4552], ["Rivadavia, Av", 4532], ["Yerbal", 4512], ["Cosquín", 4472], ["Estado Plurinacional de Bolivia", 4440], ["Gordillo Timoteo", 4424], ["Montiel", 4360], ["Condarco", 4288] ] .ft P .fi .UNINDENT .UNINDENT .SS Creating an empty database .sp You can create a new empty database file using the \fBcreate\-database\fP command: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils create\-database empty.db .ft P .fi .UNINDENT .UNINDENT .sp To enable \fI\%WAL mode\fP on the newly created database add the \fB\-\-enable\-wal\fP option: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils create\-database empty.db \-\-enable\-wal .ft P .fi .UNINDENT .UNINDENT .sp To enable SpatiaLite metadata on a newly created database, add the \fB\-\-init\-spatialite\fP flag: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils create\-database empty.db \-\-init\-spatialite .ft P .fi .UNINDENT .UNINDENT .sp That will look for SpatiaLite in a set of predictable locations. To load it from somewhere else, use the \fB\-\-load\-extension\fP option: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils create\-database empty.db \-\-init\-spatialite \-\-load\-extension /path/to/spatialite.so .ft P .fi .UNINDENT .UNINDENT .SS Inserting JSON data .sp If you have data as JSON, you can use \fBsqlite\-utils insert tablename\fP to insert it into a database. The table will be created with the correct (automatically detected) columns if it does not already exist. .sp You can pass in a single JSON object or a list of JSON objects, either as a filename or piped directly to standard\-in (by using \fB\-\fP as the filename). .sp Here\(aqs the simplest possible example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ echo \(aq{"name": "Cleo", "age": 4}\(aq | sqlite\-utils insert dogs.db dogs \- .ft P .fi .UNINDENT .UNINDENT .sp To specify a column as the primary key, use \fB\-\-pk=column_name\fP\&. .sp To create a compound primary key across more than one column, use \fB\-\-pk\fP multiple times. .sp If you feed it a JSON list it will insert multiple records. For example, if \fBdogs.json\fP looks like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C [ { "id": 1, "name": "Cleo", "age": 4 }, { "id": 2, "name": "Pancakes", "age": 2 }, { "id": 3, "name": "Toby", "age": 6 } ] .ft P .fi .UNINDENT .UNINDENT .sp You can import all three records into an automatically created \fBdogs\fP table and set the \fBid\fP column as the primary key like so: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils insert dogs.db dogs dogs.json \-\-pk=id .ft P .fi .UNINDENT .UNINDENT .sp You can skip inserting any records that have a primary key that already exists using \fB\-\-ignore\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils insert dogs.db dogs dogs.json \-\-ignore .ft P .fi .UNINDENT .UNINDENT .sp You can delete all the existing rows in the table before inserting the new records using \fB\-\-truncate\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils insert dogs.db dogs dogs.json \-\-truncate .ft P .fi .UNINDENT .UNINDENT .sp You can add the \fB\-\-analyze\fP option to run \fBANALYZE\fP against the table after the rows have been inserted. .SS Inserting binary data .sp You can insert binary data into a BLOB column by first encoding it using base64 and then structuring it like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C [ { "name": "transparent.gif", "content": { "$base64": true, "encoded": "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" } } ] .ft P .fi .UNINDENT .UNINDENT .SS Inserting newline\-delimited JSON .sp You can also import \fI\%newline\-delimited JSON\fP using the \fB\-\-nl\fP option: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ echo \(aq{"id": 1, "name": "Cleo"} {"id": 2, "name": "Suna"}\(aq | sqlite\-utils insert creatures.db creatures \- \-\-nl .ft P .fi .UNINDENT .UNINDENT .sp Newline\-delimited JSON consists of full JSON objects separated by newlines. .sp If you are processing data using \fBjq\fP you can use the \fBjq \-c\fP option to output valid newline\-delimited JSON. .sp Since \fI\%Datasette\fP can export newline\-delimited JSON, you can combine the Datasette and \fBsqlite\-utils\fP like so: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ curl \-L "https://latest.datasette.io/fixtures/facetable.json?_shape=array&_nl=on" \e | sqlite\-utils insert nl\-demo.db facetable \- \-\-pk=id \-\-nl .ft P .fi .UNINDENT .UNINDENT .sp You can also pipe \fBsqlite\-utils\fP together to create a new SQLite database file containing the results of a SQL query against another database: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils sf\-trees.db \e "select TreeID, qAddress, Latitude, Longitude from Street_Tree_List" \-\-nl \e | sqlite\-utils insert saved.db trees \- \-\-nl # This creates saved.db with a single table called trees: $ sqlite\-utils saved.db "select * from trees limit 5" \-\-csv TreeID,qAddress,Latitude,Longitude 141565,501X Baker St,37.7759676911831,\-122.441396661871 232565,940 Elizabeth St,37.7517102172731,\-122.441498017841 119263,495X Lakeshore Dr,, 207368,920 Kirkham St,37.760210314285,\-122.47073935813 188702,1501 Evans Ave,37.7422086702947,\-122.387293152263 .ft P .fi .UNINDENT .UNINDENT .SS Flattening nested JSON objects .sp \fBsqlite\-utils insert\fP and \fBsqlite\-utils memory\fP both expect incoming JSON data to consist of an array of JSON objects, where the top\-level keys of each object will become columns in the created database table. .sp If your data is nested you can use the \fB\-\-flatten\fP option to create columns that are derived from the nested data. .sp Consider this example document, in a file called \fBlog.json\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C { "httpRequest": { "latency": "0.112114537s", "requestMethod": "GET", "requestSize": "534", "status": 200 }, "insertId": "6111722f000b5b4c4d4071e2", "labels": { "service": "datasette\-io" } } .ft P .fi .UNINDENT .UNINDENT .sp Inserting this into a table using \fBsqlite\-utils insert logs.db logs log.json\fP will create a table with the following schema: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CREATE TABLE [logs] ( [httpRequest] TEXT, [insertId] TEXT, [labels] TEXT ); .ft P .fi .UNINDENT .UNINDENT .sp With the \fB\-\-flatten\fP option columns will be created using \fBtopkey_nextkey\fP column names \- so running \fBsqlite\-utils insert logs.db logs log.json \-\-flatten\fP will create the following schema instead: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CREATE TABLE [logs] ( [httpRequest_latency] TEXT, [httpRequest_requestMethod] TEXT, [httpRequest_requestSize] TEXT, [httpRequest_status] INTEGER, [insertId] TEXT, [labels_service] TEXT ); .ft P .fi .UNINDENT .UNINDENT .SS Inserting CSV or TSV data .sp If your data is in CSV format, you can insert it using the \fB\-\-csv\fP option: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils insert dogs.db dogs dogs.csv \-\-csv .ft P .fi .UNINDENT .UNINDENT .sp For tab\-delimited data, use \fB\-\-tsv\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils insert dogs.db dogs dogs.tsv \-\-tsv .ft P .fi .UNINDENT .UNINDENT .sp Data is expected to be encoded as Unicode UTF\-8. If your data is an another character encoding you can specify it using the \fB\-\-encoding\fP option: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils insert dogs.db dogs dogs.tsv \-\-tsv \-\-encoding=latin\-1 .ft P .fi .UNINDENT .UNINDENT .sp A progress bar is displayed when inserting data from a file. You can hide the progress bar using the \fB\-\-silent\fP option. .sp By default every column inserted from a CSV or TSV file will be of type \fBTEXT\fP\&. To automatically detect column types \- resulting in a mix of \fBTEXT\fP, \fBINTEGER\fP and \fBFLOAT\fP columns, use the \fB\-\-detect\-types\fP option (or its shortcut \fB\-d\fP). .sp For example, given a \fBcreatures.csv\fP file containing this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C name,age,weight Cleo,6,45.5 Dori,1,3.5 .ft P .fi .UNINDENT .UNINDENT .sp The following command: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils insert creatures.db creatures creatures.csv \-\-csv \-\-detect\-types .ft P .fi .UNINDENT .UNINDENT .sp Will produce this schema: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils schema creatures.db CREATE TABLE "creatures" ( [name] TEXT, [age] INTEGER, [weight] FLOAT ); .ft P .fi .UNINDENT .UNINDENT .sp You can set the \fBSQLITE_UTILS_DETECT_TYPES\fP environment variable if you want \fB\-\-detect\-types\fP to be the default behavior: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ export SQLITE_UTILS_DETECT_TYPES=1 .ft P .fi .UNINDENT .UNINDENT .SS Alternative delimiters and quote characters .sp If your file uses a delimiter other than \fB,\fP or a quote character other than \fB"\fP you can attempt to detect delimiters or you can specify them explicitly. .sp The \fB\-\-sniff\fP option can be used to attempt to detect the delimiters: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C sqlite\-utils insert dogs.db dogs dogs.csv \-\-sniff .ft P .fi .UNINDENT .UNINDENT .sp Alternatively, you can specify them using the \fB\-\-delimiter\fP and \fB\-\-quotechar\fP options. .sp Here\(aqs a CSV file that uses \fB;\fP for delimiters and the \fB|\fP symbol for quote characters: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C name;description Cleo;|Very fine; a friendly dog| Pancakes;A local corgi .ft P .fi .UNINDENT .UNINDENT .sp You can import that using: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils insert dogs.db dogs dogs.csv \-\-delimiter=";" \-\-quotechar="|" .ft P .fi .UNINDENT .UNINDENT .sp Passing \fB\-\-delimiter\fP, \fB\-\-quotechar\fP or \fB\-\-sniff\fP implies \fB\-\-csv\fP, so you can omit the \fB\-\-csv\fP option. .SS CSV files without a header row .sp The first row of any CSV or TSV file is expected to contain the names of the columns in that file. .sp If your file does not include this row, you can use the \fB\-\-no\-headers\fP option to specify that the tool should not use that fist row as headers. .sp If you do this, the table will be created with column names called \fBuntitled_1\fP and \fBuntitled_2\fP and so on. You can then rename them using the \fBsqlite\-utils transform ... \-\-rename\fP command, see \fI\%Transforming tables\fP\&. .SS Inserting unstructured data with \-\-lines and \-\-text .sp If you have an unstructured file you can insert its contents into a table with a single \fBline\fP column containing each line from the file using \fB\-\-lines\fP\&. This can be useful if you intend to further analyze those lines using SQL string functions or \fI\%sqlite\-utils convert\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils insert logs.db loglines logfile.log \-\-lines .ft P .fi .UNINDENT .UNINDENT .sp This will produce the following schema: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CREATE TABLE [loglines] ( [line] TEXT ); .ft P .fi .UNINDENT .UNINDENT .sp You can also insert the entire contents of the file into a single column called \fBtext\fP using \fB\-\-text\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils insert content.db content file.txt \-\-text .ft P .fi .UNINDENT .UNINDENT .sp The schema here will be: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CREATE TABLE [content] ( [text] TEXT ); .ft P .fi .UNINDENT .UNINDENT .SS Applying conversions while inserting data .sp The \fB\-\-convert\fP option can be used to apply a Python conversion function to imported data before it is inserted into the database. It works in a similar way to \fI\%sqlite\-utils convert\fP\&. .sp Your Python function will be passed a dictionary called \fBrow\fP for each item that is being imported. You can modify that dictionary and return it \- or return a fresh dictionary \- to change the data that will be inserted. .sp Given a JSON file called \fBdogs.json\fP containing this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C [ {"id": 1, "name": "Cleo"}, {"id": 2, "name": "Pancakes"} ] .ft P .fi .UNINDENT .UNINDENT .sp The following command will insert that data and add an \fBis_good\fP column set to \fB1\fP for each dog: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils insert dogs.db dogs dogs.json \-\-convert \(aqrow["is_good"] = 1\(aq .ft P .fi .UNINDENT .UNINDENT .sp The \fB\-\-convert\fP option also works with the \fB\-\-csv\fP, \fB\-\-tsv\fP and \fB\-\-nl\fP insert options. .sp As with \fBsqlite\-utils convert\fP you can use \fB\-\-import\fP to import additional Python modules, see \fI\%Importing additional modules\fP for details. .sp You can also pass code that runs some initialization steps and defines a \fBconvert(value)\fP function, see \fI\%Using a convert() function to execute initialization\fP\&. .SS \-\-convert with \-\-lines .sp Things work slightly differently when combined with the \fB\-\-lines\fP or \fB\-\-text\fP options. .sp With \fB\-\-lines\fP, instead of being passed a \fBrow\fP dictionary your function will be passed a \fBline\fP string representing each line of the input. Given a file called \fBaccess.log\fP containing the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C INFO: 127.0.0.1:60581 \- GET / HTTP/1.1 200 OK INFO: 127.0.0.1:60581 \- GET /foo/\-/static/app.css?cead5a HTTP/1.1 200 OK .ft P .fi .UNINDENT .UNINDENT .sp You could convert it into structured data like so: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils insert logs.db loglines access.log \-\-convert \(aq type, source, _, verb, path, _, status, _ = line.split() return { "type": type, "source": source, "verb": verb, "path": path, "status": status, }\(aq \-\-lines .ft P .fi .UNINDENT .UNINDENT .sp The resulting table would look like this: .TS center; |l|l|l|l|l|. _ T{ type T} T{ source T} T{ verb T} T{ path T} T{ status T} _ T{ INFO: T} T{ 127.0.0.1:60581 T} T{ GET T} T{ / T} T{ 200 T} _ T{ INFO: T} T{ 127.0.0.1:60581 T} T{ GET T} T{ /foo/\-/static/app.css?cead5a T} T{ 200 T} _ .TE .SS \-\-convert with \-\-text .sp With \fB\-\-text\fP the entire input to the command will be made available to the function as a variable called \fBtext\fP\&. .sp The function can return a single dictionary which will be inserted as a single row, or it can return a list or iterator of dictionaries, each of which will be inserted. .sp Here\(aqs how to use \fB\-\-convert\fP and \fB\-\-text\fP to insert one record per word in the input: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ echo \(aqA bunch of words\(aq | sqlite\-utils insert words.db words \- \e \-\-text \-\-convert \(aq({"word": w} for w in text.split())\(aq .ft P .fi .UNINDENT .UNINDENT .sp The result looks like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils dump words.db BEGIN TRANSACTION; CREATE TABLE [words] ( [word] TEXT ); INSERT INTO "words" VALUES(\(aqA\(aq); INSERT INTO "words" VALUES(\(aqbunch\(aq); INSERT INTO "words" VALUES(\(aqof\(aq); INSERT INTO "words" VALUES(\(aqwords\(aq); COMMIT; .ft P .fi .UNINDENT .UNINDENT .SS Insert\-replacing data .sp The \fB\-\-replace\fP option to \fBinsert\fP causes any existing records with the same primary key to be replaced entirely by the new records. .sp To replace a dog with in ID of 2 with a new record, run the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ echo \(aq{"id": 2, "name": "Pancakes", "age": 3}\(aq | \e sqlite\-utils insert dogs.db dogs \- \-\-pk=id \-\-replace .ft P .fi .UNINDENT .UNINDENT .SS Upserting data .sp Upserting is update\-or\-insert. If a row exists with the specified primary key the provided columns will be updated. If no row exists that row will be created. .sp Unlike \fBinsert \-\-replace\fP, an upsert will ignore any column values that exist but are not present in the upsert document. .sp For example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ echo \(aq{"id": 2, "age": 4}\(aq | \e sqlite\-utils upsert dogs.db dogs \- \-\-pk=id .ft P .fi .UNINDENT .UNINDENT .sp This will update the dog with an ID of 2 to have an age of 4, creating a new record (with a null name) if one does not exist. If a row DOES exist the name will be left as\-is. .sp The command will fail if you reference columns that do not exist on the table. To automatically create missing columns, use the \fB\-\-alter\fP option. .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 \fBupsert\fP in sqlite\-utils 1.x worked like \fBinsert ... \-\-replace\fP does in 2.x. See \fI\%issue #66\fP for details of this change. .UNINDENT .UNINDENT .SS Executing SQL in bulk .sp If you have a JSON, newline\-delimited JSON, CSV or TSV file you can execute a bulk SQL query using each of the records in that file using the \fBsqlite\-utils bulk\fP command. .sp The command takes the database file, the SQL to be executed and the file containing records to be used when evaluating the SQL query. .sp The SQL query should include \fB:named\fP parameters that match the keys in the records. .sp For example, given a \fBchickens.csv\fP CSV file containing the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C id,name 1,Blue 2,Snowy 3,Azi 4,Lila 5,Suna 6,Cardi .ft P .fi .UNINDENT .UNINDENT .sp You could insert those rows into a pre\-created \fBchickens\fP table like so: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils bulk chickens.db \e \(aqinsert into chickens (id, name) values (:id, :name)\(aq \e chickens.csv \-\-csv .ft P .fi .UNINDENT .UNINDENT .sp This command takes the same options as the \fBsqlite\-utils insert\fP command \- so it defaults to expecting JSON but can accept other formats using \fB\-\-csv\fP or \fB\-\-tsv\fP or \fB\-\-nl\fP or other options described above. .sp By default all of the SQL queries will be executed in a single transaction. To commit every 20 records, use \fB\-\-batch\-size 20\fP\&. .SS Inserting data from files .sp The \fBinsert\-files\fP command can be used to insert the content of files, along with their metadata, into a SQLite table. .sp Here\(aqs an example that inserts all of the GIF files in the current directory into a \fBgifs.db\fP database, placing the file contents in an \fBimages\fP table: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils insert\-files gifs.db images *.gif .ft P .fi .UNINDENT .UNINDENT .sp You can also pass one or more directories, in which case every file in those directories will be added recursively: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils insert\-files gifs.db images path/to/my\-gifs .ft P .fi .UNINDENT .UNINDENT .sp By default this command will create a table with the following schema: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CREATE TABLE [images] ( [path] TEXT PRIMARY KEY, [content] BLOB, [size] INTEGER ); .ft P .fi .UNINDENT .UNINDENT .sp Content will be treated as binary by default and stored in a \fBBLOB\fP column. You can use the \fB\-\-text\fP option to store that content in a \fBTEXT\fP column instead. .sp You can customize the schema using one or more \fB\-c\fP options. For a table schema that includes just the path, MD5 hash and last modification time of the file, you would use this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils insert\-files gifs.db images *.gif \-c path \-c md5 \-c mtime \-\-pk=path .ft P .fi .UNINDENT .UNINDENT .sp This will result in the following schema: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CREATE TABLE [images] ( [path] TEXT PRIMARY KEY, [md5] TEXT, [mtime] FLOAT ); .ft P .fi .UNINDENT .UNINDENT .sp Note that there\(aqs no \fBcontent\fP column here at all \- if you specify custom columns using \fB\-c\fP you need to include \fB\-c content\fP to create that column. .sp You can change the name of one of these columns using a \fB\-c colname:coldef\fP parameter. To rename the \fBmtime\fP column to \fBlast_modified\fP you would use this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils insert\-files gifs.db images *.gif \e \-c path \-c md5 \-c last_modified:mtime \-\-pk=path .ft P .fi .UNINDENT .UNINDENT .sp You can pass \fB\-\-replace\fP or \fB\-\-upsert\fP to indicate what should happen if you try to insert a file with an existing primary key. Pass \fB\-\-alter\fP to cause any missing columns to be added to the table. .sp The full list of column definitions you can use is as follows: .INDENT 0.0 .TP .B \fBname\fP The name of the file, e.g. \fBcleo.jpg\fP .TP .B \fBpath\fP The path to the file relative to the root folder, e.g. \fBpictures/cleo.jpg\fP .TP .B \fBfullpath\fP The fully resolved path to the image, e.g. \fB/home/simonw/pictures/cleo.jpg\fP .TP .B \fBsha256\fP The SHA256 hash of the file contents .TP .B \fBmd5\fP The MD5 hash of the file contents .TP .B \fBmode\fP The permission bits of the file, as an integer \- you may want to convert this to octal .TP .B \fBcontent\fP The binary file contents, which will be stored as a BLOB .TP .B \fBcontent_text\fP The text file contents, which will be stored as TEXT .TP .B \fBmtime\fP The modification time of the file, as floating point seconds since the Unix epoch .TP .B \fBctime\fP The creation time of the file, as floating point seconds since the Unix epoch .TP .B \fBmtime_int\fP The modification time as an integer rather than a float .TP .B \fBctime_int\fP The creation time as an integer rather than a float .TP .B \fBmtime_iso\fP The modification time as an ISO timestamp, e.g. \fB2020\-07\-27T04:24:06.654246\fP .TP .B \fBctime_iso\fP The creation time is an ISO timestamp .TP .B \fBsize\fP The integer size of the file in bytes .TP .B \fBstem\fP The filename without the extension \- for \fBfile.txt.gz\fP this would be \fBfile.txt\fP .TP .B \fBsuffix\fP The file extension \- for \fBfile.txt.gz\fP this would be \fB\&.gz\fP .UNINDENT .sp You can insert data piped from standard input like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C cat dog.jpg | sqlite\-utils insert\-files dogs.db pics \- \-\-name=dog.jpg .ft P .fi .UNINDENT .UNINDENT .sp The \fB\-\fP argument indicates data should be read from standard input. The string passed using the \fB\-\-name\fP option will be used for the file name and path values. .sp When inserting data from standard input only the following column definitions are supported: \fBname\fP, \fBpath\fP, \fBcontent\fP, \fBcontent_text\fP, \fBsha256\fP, \fBmd5\fP and \fBsize\fP\&. .SS Converting data in columns .sp The \fBconvert\fP command can be used to transform the data in a specified column \- for example to parse a date string into an ISO timestamp, or to split a string of tags into a JSON array. .sp The command accepts a database, table, one or more columns and a string of Python code to be executed against the values from those columns. The following example would replace the values in the \fBheadline\fP column in the \fBarticles\fP table with an upper\-case version: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils convert content.db articles headline \(aqvalue.upper()\(aq .ft P .fi .UNINDENT .UNINDENT .sp The Python code is passed as a string. Within that Python code the \fBvalue\fP variable will be the value of the current column. .sp The code you provide will be compiled into a function that takes \fBvalue\fP as a single argument. If you break your function body into multiple lines the last line should be a \fBreturn\fP statement: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils convert content.db articles headline \(aq value = str(value) return value.upper()\(aq .ft P .fi .UNINDENT .UNINDENT .sp Your code will be automatically wrapped in a function, but you can also define a function called \fBconvert(value)\fP which will be called, if available: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils convert content.db articles headline \(aq def convert(value): return value.upper()\(aq .ft P .fi .UNINDENT .UNINDENT .sp Use a \fBCODE\fP value of \fB\-\fP to read from standard input: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ cat mycode.py | sqlite\-utils convert content.db articles headline \- .ft P .fi .UNINDENT .UNINDENT .sp Where \fBmycode.py\fP contains a fragment of Python code that looks like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C def convert(value): return value.upper() .ft P .fi .UNINDENT .UNINDENT .sp The conversion will be applied to every row in the specified table. You can limit that to just rows that match a \fBWHERE\fP clause using \fB\-\-where\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils convert content.db articles headline \(aqvalue.upper()\(aq \e \-\-where "headline like \(aq%cat%\(aq" .ft P .fi .UNINDENT .UNINDENT .sp You can include named parameters in your where clause and populate them using one or more \fB\-\-param\fP options: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils convert content.db articles headline \(aqvalue.upper()\(aq \e \-\-where "headline like :query" \e \-\-param query \(aq%cat%\(aq .ft P .fi .UNINDENT .UNINDENT .sp The \fB\-\-dry\-run\fP option will output a preview of the conversion against the first ten rows, without modifying the database. .SS Importing additional modules .sp You can specify Python modules that should be imported and made available to your code using one or more \fB\-\-import\fP options. This example uses the \fBtextwrap\fP module to wrap the \fBcontent\fP column at 100 characters: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils convert content.db articles content \e \(aq"\en".join(textwrap.wrap(value, 100))\(aq \e \-\-import=textwrap .ft P .fi .UNINDENT .UNINDENT .sp This supports nested imports as well, for example to use \fI\%ElementTree\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils convert content.db articles content \e \(aqxml.etree.ElementTree.fromstring(value).attrib["title"]\(aq \e \-\-import=xml.etree.ElementTree .ft P .fi .UNINDENT .UNINDENT .SS Using a convert() function to execute initialization .sp In some cases you may need to execute one\-off initialization code at the start of the run. You can do that by providing code that runs before defining your \fBconvert(value)\fP function. .sp The following example adds a new \fBscore\fP column, then updates it to list a random number \- after first seeding the random number generator to ensure that multiple runs produce the same results: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils add\-column content.db articles score float \-\-not\-null\-default 1.0 $ sqlite\-utils convert content.db articles score \(aq import random random.seed(10) def convert(value): return random.random() \(aq .ft P .fi .UNINDENT .UNINDENT .SS sqlite\-utils convert recipes .sp Various built\-in recipe functions are available for common operations. These are: .INDENT 0.0 .TP .B \fBr.jsonsplit(value, delimiter=\(aq,\(aq, type=)\fP Convert a string like \fBa,b,c\fP into a JSON array \fB["a", "b", "c"]\fP .sp The \fBdelimiter\fP parameter can be used to specify a different delimiter. .sp The \fBtype\fP parameter can be set to \fBfloat\fP or \fBint\fP to produce a JSON array of different types, for example if the column\(aqs string value was \fB1.2,3,4.5\fP the following: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C r.jsonsplit(value, type=float) .ft P .fi .UNINDENT .UNINDENT .sp Would produce an array like this: \fB[1.2, 3.0, 4.5]\fP .TP .B \fBr.parsedate(value, dayfirst=False, yearfirst=False, errors=None)\fP Parse a date and convert it to ISO date format: \fByyyy\-mm\-dd\fP .sp In the case of dates such as \fB03/04/05\fP U.S. \fBMM/DD/YY\fP format is assumed \- you can use \fBdayfirst=True\fP or \fByearfirst=True\fP to change how these ambiguous dates are interpreted. .sp Use the \fBerrors=\fP parameter to specify what should happen if a value cannot be parsed. .sp By default, if any value cannot be parsed an error will be occurred and all values will be left as they were. .sp Set \fBerrors=r.IGNORE\fP to ignore any values that cannot be parsed, leaving them unchanged. .sp Set \fBerrors=r.SET_NULL\fP to set any values that cannot be parsed to \fBnull\fP\&. .TP .B \fBr.parsedatetime(value, dayfirst=False, yearfirst=False, errors=None)\fP Parse a datetime and convert it to ISO datetime format: \fByyyy\-mm\-ddTHH:MM:SS\fP .UNINDENT .sp These recipes can be used in the code passed to \fBsqlite\-utils convert\fP like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils convert my.db mytable mycolumn \e \(aqr.jsonsplit(value)\(aq .ft P .fi .UNINDENT .UNINDENT .sp To use any of the documented parameters, do this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils convert my.db mytable mycolumn \e \(aqr.jsonsplit(value, delimiter=":")\(aq .ft P .fi .UNINDENT .UNINDENT .SS Saving the result to a different column .sp The \fB\-\-output\fP and \fB\-\-output\-type\fP options can be used to save the result of the conversion to a separate column, which will be created if that column does not already exist: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils convert content.db articles headline \(aqvalue.upper()\(aq \e \-\-output headline_upper .ft P .fi .UNINDENT .UNINDENT .sp The type of the created column defaults to \fBtext\fP, but a different column type can be specified using \fB\-\-output\-type\fP\&. This example will create a new floating point column called \fBid_as_a_float\fP with a copy of each item\(aqs ID increased by 0.5: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils convert content.db articles id \(aqfloat(value) + 0.5\(aq \e \-\-output id_as_a_float \e \-\-output\-type float .ft P .fi .UNINDENT .UNINDENT .sp You can drop the original column at the end of the operation by adding \fB\-\-drop\fP\&. .SS Converting a column into multiple columns .sp Sometimes you may wish to convert a single column into multiple derived columns. For example, you may have a \fBlocation\fP column containing \fBlatitude,longitude\fP values which you wish to split out into separate \fBlatitude\fP and \fBlongitude\fP columns. .sp You can achieve this using the \fB\-\-multi\fP option to \fBsqlite\-utils convert\fP\&. This option expects your Python code to return a Python dictionary: new columns well be created and populated for each of the keys in that dictionary. .sp For the \fBlatitude,longitude\fP example you would use the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils convert demo.db places location \e \(aqbits = value.split(",") return { "latitude": float(bits[0]), "longitude": float(bits[1]), }\(aq \-\-multi .ft P .fi .UNINDENT .UNINDENT .sp The type of the returned values will be taken into account when creating the new columns. In this example, the resulting database schema will look like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CREATE TABLE [places] ( [location] TEXT, [latitude] FLOAT, [longitude] FLOAT ); .ft P .fi .UNINDENT .UNINDENT .sp The code function can also return \fBNone\fP, in which case its output will be ignored. You can drop the original column at the end of the operation by adding \fB\-\-drop\fP\&. .SS Creating tables .sp Most of the time creating tables by inserting example data is the quickest approach. If you need to create an empty table in advance of inserting data you can do so using the \fBcreate\-table\fP command: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils create\-table mydb.db mytable id integer name text \-\-pk=id .ft P .fi .UNINDENT .UNINDENT .sp This will create a table called \fBmytable\fP with two columns \- an integer \fBid\fP column and a text \fBname\fP column. It will set the \fBid\fP column to be the primary key. .sp You can pass as many column\-name column\-type pairs as you like. Valid types are \fBinteger\fP, \fBtext\fP, \fBfloat\fP and \fBblob\fP\&. .sp You can specify columns that should be NOT NULL using \fB\-\-not\-null colname\fP\&. You can specify default values for columns using \fB\-\-default colname defaultvalue\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils create\-table mydb.db mytable \e id integer \e name text \e age integer \e is_good integer \e \-\-not\-null name \e \-\-not\-null age \e \-\-default is_good 1 \e \-\-pk=id $ sqlite\-utils tables mydb.db \-\-schema \-t table schema \-\-\-\-\-\-\- \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- mytable CREATE TABLE [mytable] ( [id] INTEGER PRIMARY KEY, [name] TEXT NOT NULL, [age] INTEGER NOT NULL, [is_good] INTEGER DEFAULT \(aq1\(aq ) .ft P .fi .UNINDENT .UNINDENT .sp You can specify foreign key relationships between the tables you are creating using \fB\-\-fk colname othertable othercolumn\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils create\-table books.db authors \e id integer \e name text \e \-\-pk=id $ sqlite\-utils create\-table books.db books \e id integer \e title text \e author_id integer \e \-\-pk=id \e \-\-fk author_id authors id $ sqlite\-utils tables books.db \-\-schema \-t table schema \-\-\-\-\-\-\- \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- authors CREATE TABLE [authors] ( [id] INTEGER PRIMARY KEY, [name] TEXT ) books CREATE TABLE [books] ( [id] INTEGER PRIMARY KEY, [title] TEXT, [author_id] INTEGER REFERENCES [authors]([id]) ) .ft P .fi .UNINDENT .UNINDENT .sp If a table with the same name already exists, you will get an error. You can choose to silently ignore this error with \fB\-\-ignore\fP, or you can replace the existing table with a new, empty table using \fB\-\-replace\fP\&. .sp You can also pass \fB\-\-transform\fP to transform the existing table to match the new schema. See \fI\%Explicitly creating a table\fP in the Python library documentation for details of how this option works. .SS Duplicating tables .sp The \fBduplicate\fP command duplicates a table \- creating a new table with the same schema and a copy of all of the rows: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils duplicate books.db authors authors_copy .ft P .fi .UNINDENT .UNINDENT .SS Dropping tables .sp You can drop a table using the \fBdrop\-table\fP command: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils drop\-table mydb.db mytable .ft P .fi .UNINDENT .UNINDENT .sp Use \fB\-\-ignore\fP to ignore the error if the table does not exist. .SS Transforming tables .sp The \fBtransform\fP command allows you to apply complex transformations to a table that cannot be implemented using a regular SQLite \fBALTER TABLE\fP command. See \fI\%Transforming a table\fP for details of how this works. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils transform mydb.db mytable \e \-\-drop column1 \e \-\-rename column2 column_renamed .ft P .fi .UNINDENT .UNINDENT .sp Every option for this table (with the exception of \fB\-\-pk\-none\fP) can be specified multiple times. The options are as follows: .INDENT 0.0 .TP .B \fB\-\-type column\-name new\-type\fP Change the type of the specified column. Valid types are \fBinteger\fP, \fBtext\fP, \fBfloat\fP, \fBblob\fP\&. .TP .B \fB\-\-drop column\-name\fP Drop the specified column. .TP .B \fB\-\-rename column\-name new\-name\fP Rename this column to a new name. .TP .B \fB\-\-column\-order column\fP Use this multiple times to specify a new order for your columns. \fB\-o\fP shortcut is also available. .TP .B \fB\-\-not\-null column\-name\fP Set this column as \fBNOT NULL\fP\&. .TP .B \fB\-\-not\-null\-false column\-name\fP For a column that is currently set as \fBNOT NULL\fP, remove the \fBNOT NULL\fP\&. .TP .B \fB\-\-pk column\-name\fP Change the primary key column for this table. Pass \fB\-\-pk\fP multiple times if you want to create a compound primary key. .TP .B \fB\-\-pk\-none\fP Remove the primary key from this table, turning it into a \fBrowid\fP table. .TP .B \fB\-\-default column\-name value\fP Set the default value of this column. .TP .B \fB\-\-default\-none column\fP Remove the default value for this column. .TP .B \fB\-\-drop\-foreign\-key column\fP Drop the specified foreign key. .UNINDENT .sp If you want to see the SQL that will be executed to make the change without actually executing it, add the \fB\-\-sql\fP flag. For example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils transform fixtures.db roadside_attractions \e \-\-rename pk id \e \-\-default name Untitled \e \-\-column\-order id \e \-\-column\-order longitude \e \-\-column\-order latitude \e \-\-drop address \e \-\-sql CREATE TABLE [roadside_attractions_new_4033a60276b9] ( [id] INTEGER PRIMARY KEY, [longitude] FLOAT, [latitude] FLOAT, [name] TEXT DEFAULT \(aqUntitled\(aq ); INSERT INTO [roadside_attractions_new_4033a60276b9] ([longitude], [latitude], [id], [name]) SELECT [longitude], [latitude], [pk], [name] FROM [roadside_attractions]; DROP TABLE [roadside_attractions]; ALTER TABLE [roadside_attractions_new_4033a60276b9] RENAME TO [roadside_attractions]; .ft P .fi .UNINDENT .UNINDENT .SS Adding a primary key to a rowid table .sp SQLite tables that are created without an explicit primary key are created as \fI\%rowid tables\fP\&. They still have a numeric primary key which is available in the \fBrowid\fP column, but that column is not included in the output of \fBselect *\fP\&. Here\(aqs an example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C % echo \(aq[{"name": "Azi"}, {"name": "Suna"}]\(aq | \e sqlite\-utils insert chickens.db chickens \- % sqlite\-utils schema chickens.db CREATE TABLE [chickens] ( [name] TEXT ); % sqlite\-utils chickens.db \(aqselect * from chickens\(aq [{"name": "Azi"}, {"name": "Suna"}] % sqlite\-utils chickens.db \(aqselect rowid, * from chickens\(aq [{"rowid": 1, "name": "Azi"}, {"rowid": 2, "name": "Suna"}] .ft P .fi .UNINDENT .UNINDENT .sp You can use \fBsqlite\-utils transform ... \-\-pk id\fP to add a primary key column called \fBid\fP to the table. The primary key will be created as an \fBINTEGER PRIMARY KEY\fP and the existing \fBrowid\fP values will be copied across to it. It will automatically increment as new rows are added to the table: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C % sqlite\-utils transform chickens.db chickens \-\-pk id % sqlite\-utils schema chickens.db CREATE TABLE "chickens" ( [id] INTEGER PRIMARY KEY, [name] TEXT ); % sqlite\-utils chickens.db \(aqselect * from chickens\(aq [{"id": 1, "name": "Azi"}, {"id": 2, "name": "Suna"}] % echo \(aq{"name": "Cardi"}\(aq | sqlite\-utils insert chickens.db chickens \- % sqlite\-utils chickens.db \(aqselect * from chickens\(aq [{"id": 1, "name": "Azi"}, {"id": 2, "name": "Suna"}, {"id": 3, "name": "Cardi"}] .ft P .fi .UNINDENT .UNINDENT .SS Extracting columns into a separate table .sp The \fBsqlite\-utils extract\fP command can be used to extract specified columns into a separate table. .sp Take a look at the Python API documentation for \fI\%Extracting columns into a separate table\fP for a detailed description of how this works, including examples of table schemas before and after running an extraction operation. .sp The command takes a database, table and one or more columns that should be extracted. To extract the \fBspecies\fP column from the \fBtrees\fP table you would run: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils extract my.db trees species .ft P .fi .UNINDENT .UNINDENT .sp This would produce the following schema: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CREATE TABLE "trees" ( [id] INTEGER PRIMARY KEY, [TreeAddress] TEXT, [species_id] INTEGER, FOREIGN KEY(species_id) REFERENCES species(id) ); CREATE TABLE [species] ( [id] INTEGER PRIMARY KEY, [species] TEXT ); CREATE UNIQUE INDEX [idx_species_species] ON [species] ([species]); .ft P .fi .UNINDENT .UNINDENT .sp The command takes the following options: .INDENT 0.0 .TP .B \fB\-\-table TEXT\fP The name of the lookup to extract columns to. This defaults to using the name of the columns that are being extracted. .TP .B \fB\-\-fk\-column TEXT\fP The name of the foreign key column to add to the table. Defaults to \fBcolumnname_id\fP\&. .TP .B \fB\-\-rename \fP Use this option to rename the columns created in the new lookup table. .TP .B \fB\-\-silent\fP Don\(aqt display the progress bar. .UNINDENT .sp Here\(aqs a more complex example that makes use of these options. It converts \fI\%this CSV file\fP full of global power plants into SQLite, then extracts the \fBcountry\fP and \fBcountry_long\fP columns into a separate \fBcountries\fP table: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C wget \(aqhttps://github.com/wri/global\-power\-plant\-database/blob/232a6666/output_database/global_power_plant_database.csv?raw=true\(aq sqlite\-utils insert global.db power_plants \e \(aqglobal_power_plant_database.csv?raw=true\(aq \-\-csv # Extract those columns: sqlite\-utils extract global.db power_plants country country_long \e \-\-table countries \e \-\-fk\-column country_id \e \-\-rename country_long name .ft P .fi .UNINDENT .UNINDENT .sp After running the above, the command \fBsqlite\-utils schema global.db\fP reveals the following schema: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CREATE TABLE [countries] ( [id] INTEGER PRIMARY KEY, [country] TEXT, [name] TEXT ); CREATE TABLE "power_plants" ( [country_id] INTEGER, [name] TEXT, [gppd_idnr] TEXT, [capacity_mw] TEXT, [latitude] TEXT, [longitude] TEXT, [primary_fuel] TEXT, [other_fuel1] TEXT, [other_fuel2] TEXT, [other_fuel3] TEXT, [commissioning_year] TEXT, [owner] TEXT, [source] TEXT, [url] TEXT, [geolocation_source] TEXT, [wepp_id] TEXT, [year_of_capacity_data] TEXT, [generation_gwh_2013] TEXT, [generation_gwh_2014] TEXT, [generation_gwh_2015] TEXT, [generation_gwh_2016] TEXT, [generation_gwh_2017] TEXT, [generation_data_source] TEXT, [estimated_generation_gwh] TEXT, FOREIGN KEY([country_id]) REFERENCES [countries]([id]) ); CREATE UNIQUE INDEX [idx_countries_country_name] ON [countries] ([country], [name]); .ft P .fi .UNINDENT .UNINDENT .SS Creating views .sp You can create a view using the \fBcreate\-view\fP command: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils create\-view mydb.db version "select sqlite_version()" $ sqlite\-utils mydb.db "select * from version" [{"sqlite_version()": "3.31.1"}] .ft P .fi .UNINDENT .UNINDENT .sp Use \fB\-\-replace\fP to replace an existing view of the same name, and \fB\-\-ignore\fP to do nothing if a view already exists. .SS Dropping views .sp You can drop a view using the \fBdrop\-view\fP command: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils drop\-view myview .ft P .fi .UNINDENT .UNINDENT .sp Use \fB\-\-ignore\fP to ignore the error if the view does not exist. .SS Adding columns .sp You can add a column using the \fBadd\-column\fP command: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils add\-column mydb.db mytable nameofcolumn text .ft P .fi .UNINDENT .UNINDENT .sp The last argument here is the type of the column to be created. You can use one of \fBtext\fP, \fBinteger\fP, \fBfloat\fP or \fBblob\fP\&. If you leave it off, \fBtext\fP will be used. .sp You can add a column that is a foreign key reference to another table using the \fB\-\-fk\fP option: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils add\-column mydb.db dogs species_id \-\-fk species .ft P .fi .UNINDENT .UNINDENT .sp This will automatically detect the name of the primary key on the species table and use that (and its type) for the new column. .sp You can explicitly specify the column you wish to reference using \fB\-\-fk\-col\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils add\-column mydb.db dogs species_id \-\-fk species \-\-fk\-col ref .ft P .fi .UNINDENT .UNINDENT .sp You can set a \fBNOT NULL DEFAULT \(aqx\(aq\fP constraint on the new column using \fB\-\-not\-null\-default\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils add\-column mydb.db dogs friends_count integer \-\-not\-null\-default 0 .ft P .fi .UNINDENT .UNINDENT .SS Adding columns automatically on insert/update .sp You can use the \fB\-\-alter\fP option to automatically add new columns if the data you are inserting or upserting is of a different shape: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils insert dogs.db dogs new\-dogs.json \-\-pk=id \-\-alter .ft P .fi .UNINDENT .UNINDENT .SS Adding foreign key constraints .sp The \fBadd\-foreign\-key\fP command can be used to add new foreign key references to an existing table \- something which SQLite\(aqs \fBALTER TABLE\fP command does not support. .sp To add a foreign key constraint pointing the \fBbooks.author_id\fP column to \fBauthors.id\fP in another table, do this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils add\-foreign\-key books.db books author_id authors id .ft P .fi .UNINDENT .UNINDENT .sp If you omit the other table and other column references \fBsqlite\-utils\fP will attempt to guess them \- so the above example could instead look like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils add\-foreign\-key books.db books author_id .ft P .fi .UNINDENT .UNINDENT .sp Add \fB\-\-ignore\fP to ignore an existing foreign key (as opposed to returning an error): .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils add\-foreign\-key books.db books author_id \-\-ignore .ft P .fi .UNINDENT .UNINDENT .sp See \fI\%Adding foreign key constraints\fP in the Python API documentation for further details, including how the automatic table guessing mechanism works. .SS Adding multiple foreign keys at once .sp Adding a foreign key requires a \fBVACUUM\fP\&. On large databases this can be an expensive operation, so if you are adding multiple foreign keys you can combine them into one operation (and hence one \fBVACUUM\fP) using \fBadd\-foreign\-keys\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils add\-foreign\-keys books.db \e books author_id authors id \e authors country_id countries id .ft P .fi .UNINDENT .UNINDENT .sp When you are using this command each foreign key needs to be defined in full, as four arguments \- the table, column, other table and other column. .SS Adding indexes for all foreign keys .sp If you want to ensure that every foreign key column in your database has a corresponding index, you can do so like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils index\-foreign\-keys books.db .ft P .fi .UNINDENT .UNINDENT .SS Setting defaults and not null constraints .sp You can use the \fB\-\-not\-null\fP and \fB\-\-default\fP options (to both \fBinsert\fP and \fBupsert\fP) to specify columns that should be \fBNOT NULL\fP or to set database defaults for one or more specific columns: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils insert dogs.db dogs_with_scores dogs\-with\-scores.json \e \-\-not\-null=age \e \-\-not\-null=name \e \-\-default age 2 \e \-\-default score 5 .ft P .fi .UNINDENT .UNINDENT .SS Creating indexes .sp You can add an index to an existing table using the \fBcreate\-index\fP command: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils create\-index mydb.db mytable col1 [col2...] .ft P .fi .UNINDENT .UNINDENT .sp This can be used to create indexes against a single column or multiple columns. .sp The name of the index will be automatically derived from the table and columns. To specify a different name, use \fB\-\-name=name_of_index\fP\&. .sp Use the \fB\-\-unique\fP option to create a unique index. .sp Use \fB\-\-if\-not\-exists\fP to avoid attempting to create the index if one with that name already exists. .sp To add an index on a column in descending order, prefix the column with a hyphen. Since this can be confused for a command\-line option you need to construct that like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils create\-index mydb.db mytable \-\- col1 \-col2 col3 .ft P .fi .UNINDENT .UNINDENT .sp This will create an index on that table on \fB(col1, col2 desc, col3)\fP\&. .sp If your column names are already prefixed with a hyphen you\(aqll need to manually execute a \fBCREATE INDEX\fP SQL statement to add indexes to them rather than using this tool. .sp Add the \fB\-\-analyze\fP option to run \fBANALYZE\fP against the index after it has been created. .SS Configuring full\-text search .sp You can enable SQLite full\-text search on a table and a set of columns like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils enable\-fts mydb.db documents title summary .ft P .fi .UNINDENT .UNINDENT .sp This will use SQLite\(aqs FTS5 module by default. Use \fB\-\-fts4\fP if you want to use FTS4: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils enable\-fts mydb.db documents title summary \-\-fts4 .ft P .fi .UNINDENT .UNINDENT .sp The \fBenable\-fts\fP command will populate the new index with all existing documents. If you later add more documents you will need to use \fBpopulate\-fts\fP to cause them to be indexed as well: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils populate\-fts mydb.db documents title summary .ft P .fi .UNINDENT .UNINDENT .sp A better solution here is to use database triggers. You can set up database triggers to automatically update the full\-text index using the \fB\-\-create\-triggers\fP option when you first run \fBenable\-fts\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils enable\-fts mydb.db documents title summary \-\-create\-triggers .ft P .fi .UNINDENT .UNINDENT .sp To set a custom FTS tokenizer, e.g. to enable Porter stemming, use \fB\-\-tokenize=\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils populate\-fts mydb.db documents title summary \-\-tokenize=porter .ft P .fi .UNINDENT .UNINDENT .sp To remove the FTS tables and triggers you created, use \fBdisable\-fts\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils disable\-fts mydb.db documents .ft P .fi .UNINDENT .UNINDENT .sp To rebuild one or more FTS tables (see \fI\%Rebuilding a full\-text search table\fP), use \fBrebuild\-fts\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils rebuild\-fts mydb.db documents .ft P .fi .UNINDENT .UNINDENT .sp You can rebuild every FTS table by running \fBrebuild\-fts\fP without passing any table names: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils rebuild\-fts mydb.db .ft P .fi .UNINDENT .UNINDENT .SS Executing searches .sp Once you have configured full\-text search for a table, you can search it using \fBsqlite\-utils search\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils search mydb.db documents searchterm .ft P .fi .UNINDENT .UNINDENT .sp This command accepts the same output options as \fBsqlite\-utils query\fP: \fB\-\-table\fP, \fB\-\-csv\fP, \fB\-\-tsv\fP, \fB\-\-nl\fP etc. .sp By default it shows the most relevant matches first. You can specify a different sort order using the \fB\-o\fP option, which can take a column or a column followed by \fBdesc\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # Sort by rowid $ sqlite\-utils search mydb.db documents searchterm \-o rowid # Sort by created in descending order $ sqlite\-utils search mydb.db documents searchterm \-o \(aqcreated desc\(aq .ft P .fi .UNINDENT .UNINDENT .sp SQLite \fI\%advanced search syntax\fP is enabled by default. To run a search with automatic quoting applied to the terms to avoid them being potentially interpreted as advanced search syntax use the \fB\-\-quote\fP option. .sp You can specify a subset of columns to be returned using the \fB\-c\fP option one or more times: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils search mydb.db documents searchterm \-c title \-c created .ft P .fi .UNINDENT .UNINDENT .sp By default all search results will be returned. You can use \fB\-\-limit 20\fP to return just the first 20 results. .sp Use the \fB\-\-sql\fP option to output the SQL that would be executed, rather than running the query: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils search mydb.db documents searchterm \-\-sql with original as ( select rowid, * from [documents] ) select [original].* from [original] join [documents_fts] on [original].rowid = [documents_fts].rowid where [documents_fts] match :query order by [documents_fts].rank .ft P .fi .UNINDENT .UNINDENT .SS Enabling cached counts .sp \fBselect count(*)\fP queries can take a long time against large tables. \fBsqlite\-utils\fP can speed these up by adding triggers to maintain a \fB_counts\fP table, see \fI\%Cached table counts using triggers\fP for details. .sp The \fBsqlite\-utils enable\-counts\fP command can be used to configure these triggers, either for every table in the database or for specific tables. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # Configure triggers for every table in the database $ sqlite\-utils enable\-counts mydb.db # Configure triggers just for specific tables $ sqlite\-utils enable\-counts mydb.db table1 table2 .ft P .fi .UNINDENT .UNINDENT .sp If the \fB_counts\fP table ever becomes out\-of\-sync with the actual table counts you can repair it using the \fBreset\-counts\fP command: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils reset\-counts mydb.db .ft P .fi .UNINDENT .UNINDENT .SS Optimizing index usage with ANALYZE .sp The \fI\%SQLite ANALYZE command\fP builds a table of statistics which the query planner can use to make better decisions about which indexes to use for a given query. .sp You should run \fBANALYZE\fP if your database is large and you do not think your indexes are being efficiently used. .sp To run \fBANALYZE\fP against every index in a database, use this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils analyze mydb.db .ft P .fi .UNINDENT .UNINDENT .sp You can run it against specific tables, or against specific named indexes, by passing them as optional arguments: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils analyze mydb.db mytable idx_mytable_name .ft P .fi .UNINDENT .UNINDENT .sp You can also run \fBANALYZE\fP as part of another command using the \fB\-\-analyze\fP option. This is supported by the \fBcreate\-index\fP, \fBinsert\fP and \fBupsert\fP commands. .SS Vacuum .sp You can run VACUUM to optimize your database like so: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils vacuum mydb.db .ft P .fi .UNINDENT .UNINDENT .SS Optimize .sp The optimize command can dramatically reduce the size of your database if you are using SQLite full\-text search. It runs OPTIMIZE against all of your FTS4 and FTS5 tables, then runs VACUUM. .sp If you just want to run OPTIMIZE without the VACUUM, use the \fB\-\-no\-vacuum\fP flag. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # Optimize all FTS tables and then VACUUM $ sqlite\-utils optimize mydb.db # Optimize but skip the VACUUM $ sqlite\-utils optimize \-\-no\-vacuum mydb.db .ft P .fi .UNINDENT .UNINDENT .sp To optimize specific tables rather than every FTS table, pass those tables as extra arguments: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils optimize mydb.db table_1 table_2 .ft P .fi .UNINDENT .UNINDENT .SS WAL mode .sp You can enable \fI\%Write\-Ahead Logging\fP for a database file using the \fBenable\-wal\fP command: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils enable\-wal mydb.db .ft P .fi .UNINDENT .UNINDENT .sp You can disable WAL mode using \fBdisable\-wal\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils disable\-wal mydb.db .ft P .fi .UNINDENT .UNINDENT .sp Both of these commands accept one or more database files as arguments. .SS Dumping the database to SQL .sp The \fBdump\fP command outputs a SQL dump of the schema and full contents of the specified database file: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils dump mydb.db BEGIN TRANSACTION; CREATE TABLE ... \&... COMMIT; .ft P .fi .UNINDENT .UNINDENT .SS Loading SQLite extensions .sp Many of these commands have the ability to load additional SQLite extensions using the \fB\-\-load\-extension=/path/to/extension\fP option \- use \fB\-\-help\fP to check for support, e.g. \fBsqlite\-utils rows \-\-help\fP\&. .sp This option can be applied multiple times to load multiple extensions. .sp Since \fI\%SpatiaLite\fP is commonly used with SQLite, the value \fBspatialite\fP is special: it will search for SpatiaLite in the most common installation locations, saving you from needing to remember exactly where that module is located: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils memory "select spatialite_version()" \-\-load\-extension=spatialite [{"spatialite_version()": "4.3.0a"}] .ft P .fi .UNINDENT .UNINDENT .SS SpatiaLite helpers .sp \fI\%SpatiaLite\fP adds geographic capability to SQLite (similar to how PostGIS builds on PostgreSQL). The \fI\%SpatiaLite cookbook\fP is a good resource for learning what\(aqs possible with it. .sp You can convert an existing table to a geographic table by adding a geometry column, use the \fBsqlite\-utils add\-geometry\-column\fP command: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils add\-geometry\-column spatial.db locations geometry \-\-type POLYGON \-\-srid 4326 .ft P .fi .UNINDENT .UNINDENT .sp The table (\fBlocations\fP in the example above) must already exist before adding a geometry column. Use \fBsqlite\-utils create\-table\fP first, then \fBadd\-geometry\-column\fP\&. .sp Use the \fB\-\-type\fP option to specify a geometry type. By default, \fBadd\-geometry\-column\fP uses a generic \fBGEOMETRY\fP, which will work with any type, though it may not be supported by some desktop GIS applications. .sp Eight (case\-insensitive) types are allowed: .INDENT 0.0 .IP \(bu 2 POINT .IP \(bu 2 LINESTRING .IP \(bu 2 POLYGON .IP \(bu 2 MULTIPOINT .IP \(bu 2 MULTILINESTRING .IP \(bu 2 MULTIPOLYGON .IP \(bu 2 GEOMETRYCOLLECTION .IP \(bu 2 GEOMETRY .UNINDENT .SS Adding spatial indexes .sp Once you have a geometry column, you can speed up bounding box queries by adding a spatial index: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils create\-spatial\-index spatial.db locations geometry .ft P .fi .UNINDENT .UNINDENT .sp See this \fI\%SpatiaLite Cookbook recipe\fP for examples of how to use a spatial index. .SS Installing packages .sp The \fI\%convert command\fP and the \fI\%insert \-\e\-convert\fP and \fI\%query \-\e\-functions\fP options can be provided with a Python script that imports additional modules from the \fBsqlite\-utils\fP environment. .sp You can install packages from PyPI directly into the correct environment using \fBsqlite\-utils install \fP\&. This is a wrapper around \fBpip install\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils install beautifulsoup4 .ft P .fi .UNINDENT .UNINDENT .sp Use \fB\-U\fP to upgrade an existing package. .SS Uninstalling packages .sp You can uninstall packages that were installed using \fBsqlite\-utils install\fP with \fBsqlite\-utils uninstall \fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils uninstall beautifulsoup4 .ft P .fi .UNINDENT .UNINDENT .sp Use \fB\-y\fP to skip the request for confirmation. .SS sqlite_utils Python library .INDENT 0.0 .IP \(bu 2 \fI\%Getting started\fP .IP \(bu 2 \fI\%Connecting to or creating a database\fP .INDENT 2.0 .IP \(bu 2 \fI\%Attaching additional databases\fP .IP \(bu 2 \fI\%Tracing queries\fP .UNINDENT .IP \(bu 2 \fI\%Executing queries\fP .INDENT 2.0 .IP \(bu 2 \fI\%db.query(sql, params)\fP .IP \(bu 2 \fI\%db.execute(sql, params)\fP .IP \(bu 2 \fI\%Passing parameters\fP .UNINDENT .IP \(bu 2 \fI\%Accessing tables\fP .IP \(bu 2 \fI\%Listing tables\fP .IP \(bu 2 \fI\%Listing views\fP .IP \(bu 2 \fI\%Listing rows\fP .INDENT 2.0 .IP \(bu 2 \fI\%Counting rows\fP .UNINDENT .IP \(bu 2 \fI\%Listing rows with their primary keys\fP .IP \(bu 2 \fI\%Retrieving a specific record\fP .IP \(bu 2 \fI\%Showing the schema\fP .IP \(bu 2 \fI\%Creating tables\fP .INDENT 2.0 .IP \(bu 2 \fI\%Custom column order and column types\fP .IP \(bu 2 \fI\%Explicitly creating a table\fP .IP \(bu 2 \fI\%Compound primary keys\fP .IP \(bu 2 \fI\%Specifying foreign keys\fP .UNINDENT .IP \(bu 2 \fI\%Table configuration options\fP .IP \(bu 2 \fI\%Setting defaults and not null constraints\fP .IP \(bu 2 \fI\%Duplicating tables\fP .IP \(bu 2 \fI\%Bulk inserts\fP .IP \(bu 2 \fI\%Insert\-replacing data\fP .IP \(bu 2 \fI\%Updating a specific record\fP .IP \(bu 2 \fI\%Deleting a specific record\fP .IP \(bu 2 \fI\%Deleting multiple records\fP .IP \(bu 2 \fI\%Upserting data\fP .IP \(bu 2 \fI\%Converting data in columns\fP .IP \(bu 2 \fI\%Working with lookup tables\fP .INDENT 2.0 .IP \(bu 2 \fI\%Creating lookup tables explicitly\fP .IP \(bu 2 \fI\%Populating lookup tables automatically during insert/upsert\fP .UNINDENT .IP \(bu 2 \fI\%Working with many\-to\-many relationships\fP .INDENT 2.0 .IP \(bu 2 \fI\%Using m2m and lookup tables together\fP .UNINDENT .IP \(bu 2 \fI\%Analyzing a column\fP .IP \(bu 2 \fI\%Adding columns\fP .IP \(bu 2 \fI\%Adding columns automatically on insert/update\fP .IP \(bu 2 \fI\%Adding foreign key constraints\fP .INDENT 2.0 .IP \(bu 2 \fI\%Adding multiple foreign key constraints at once\fP .IP \(bu 2 \fI\%Adding indexes for all foreign keys\fP .UNINDENT .IP \(bu 2 \fI\%Dropping a table or view\fP .IP \(bu 2 \fI\%Transforming a table\fP .INDENT 2.0 .IP \(bu 2 \fI\%Altering column types\fP .IP \(bu 2 \fI\%Renaming columns\fP .IP \(bu 2 \fI\%Dropping columns\fP .IP \(bu 2 \fI\%Changing primary keys\fP .IP \(bu 2 \fI\%Changing not null status\fP .IP \(bu 2 \fI\%Altering column defaults\fP .IP \(bu 2 \fI\%Changing column order\fP .IP \(bu 2 \fI\%Dropping foreign key constraints\fP .IP \(bu 2 \fI\%Custom transformations with .transform_sql()\fP .UNINDENT .IP \(bu 2 \fI\%Extracting columns into a separate table\fP .IP \(bu 2 \fI\%Setting an ID based on the hash of the row contents\fP .IP \(bu 2 \fI\%Creating views\fP .IP \(bu 2 \fI\%Storing JSON\fP .IP \(bu 2 \fI\%Converting column values using SQL functions\fP .IP \(bu 2 \fI\%Checking the SQLite version\fP .IP \(bu 2 \fI\%Introspecting tables and views\fP .INDENT 2.0 .IP \(bu 2 \fI\%\&.exists()\fP .IP \(bu 2 \fI\%\&.count\fP .IP \(bu 2 \fI\%\&.columns\fP .IP \(bu 2 \fI\%\&.columns_dict\fP .IP \(bu 2 \fI\%\&.default_values\fP .IP \(bu 2 \fI\%\&.pks\fP .IP \(bu 2 \fI\%\&.use_rowid\fP .IP \(bu 2 \fI\%\&.foreign_keys\fP .IP \(bu 2 \fI\%\&.schema\fP .IP \(bu 2 \fI\%\&.strict\fP .IP \(bu 2 \fI\%\&.indexes\fP .IP \(bu 2 \fI\%\&.xindexes\fP .IP \(bu 2 \fI\%\&.triggers\fP .IP \(bu 2 \fI\%\&.triggers_dict\fP .IP \(bu 2 \fI\%\&.detect_fts()\fP .IP \(bu 2 \fI\%\&.virtual_table_using\fP .IP \(bu 2 \fI\%\&.has_counts_triggers\fP .UNINDENT .IP \(bu 2 \fI\%Full\-text search\fP .INDENT 2.0 .IP \(bu 2 \fI\%Enabling full\-text search for a table\fP .IP \(bu 2 \fI\%Quoting characters for use in search\fP .IP \(bu 2 \fI\%Searching with table.search()\fP .IP \(bu 2 \fI\%Building SQL queries with table.search_sql()\fP .UNINDENT .IP \(bu 2 \fI\%Rebuilding a full\-text search table\fP .IP \(bu 2 \fI\%Optimizing a full\-text search table\fP .IP \(bu 2 \fI\%Cached table counts using triggers\fP .IP \(bu 2 \fI\%Creating indexes\fP .IP \(bu 2 \fI\%Optimizing index usage with ANALYZE\fP .IP \(bu 2 \fI\%Vacuum\fP .IP \(bu 2 \fI\%WAL mode\fP .IP \(bu 2 \fI\%Suggesting column types\fP .IP \(bu 2 \fI\%Registering custom SQL functions\fP .IP \(bu 2 \fI\%Quoting strings for use in SQL\fP .IP \(bu 2 \fI\%Reading rows from a file\fP .IP \(bu 2 \fI\%Setting the maximum CSV field size limit\fP .IP \(bu 2 \fI\%Detecting column types using TypeTracker\fP .IP \(bu 2 \fI\%SpatiaLite helpers\fP .INDENT 2.0 .IP \(bu 2 \fI\%Initialize SpatiaLite\fP .IP \(bu 2 \fI\%Finding SpatiaLite\fP .IP \(bu 2 \fI\%Adding geometry columns\fP .IP \(bu 2 \fI\%Creating a spatial index\fP .UNINDENT .UNINDENT .SS Getting started .sp Here\(aqs how to create a new SQLite database file containing a new \fBchickens\fP table, populated with four records: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from sqlite_utils import Database db = Database("chickens.db") db["chickens"].insert_all([{ "name": "Azi", "color": "blue", }, { "name": "Lila", "color": "blue", }, { "name": "Suna", "color": "gold", }, { "name": "Cardi", "color": "black", }]) .ft P .fi .UNINDENT .UNINDENT .sp You can loop through those rows like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C for row in db["chickens"].rows: print(row) .ft P .fi .UNINDENT .UNINDENT .sp Which outputs the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C {\(aqname\(aq: \(aqAzi\(aq, \(aqcolor\(aq: \(aqblue\(aq} {\(aqname\(aq: \(aqLila\(aq, \(aqcolor\(aq: \(aqblue\(aq} {\(aqname\(aq: \(aqSuna\(aq, \(aqcolor\(aq: \(aqgold\(aq} {\(aqname\(aq: \(aqCardi\(aq, \(aqcolor\(aq: \(aqblack\(aq} .ft P .fi .UNINDENT .UNINDENT .sp To run a SQL query, use \fI\%db.query()\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C for row in db.query(""" select color, count(*) from chickens group by color order by count(*) desc """): print(row) .ft P .fi .UNINDENT .UNINDENT .sp Which outputs: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C {\(aqcolor\(aq: \(aqblue\(aq, \(aqcount(*)\(aq: 2} {\(aqcolor\(aq: \(aqgold\(aq, \(aqcount(*)\(aq: 1} {\(aqcolor\(aq: \(aqblack\(aq, \(aqcount(*)\(aq: 1} .ft P .fi .UNINDENT .UNINDENT .SS Connecting to or creating a database .sp Database objects are constructed by passing in either a path to a file on disk or an existing SQLite3 database connection: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from sqlite_utils import Database db = Database("my_database.db") .ft P .fi .UNINDENT .UNINDENT .sp This will create \fBmy_database.db\fP if it does not already exist. .sp If you want to recreate a database from scratch (first removing the existing file from disk if it already exists) you can use the \fBrecreate=True\fP argument: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db = Database("my_database.db", recreate=True) .ft P .fi .UNINDENT .UNINDENT .sp Instead of a file path you can pass in an existing SQLite connection: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import sqlite3 db = Database(sqlite3.connect("my_database.db")) .ft P .fi .UNINDENT .UNINDENT .sp If you want to create an in\-memory database, you can do so like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db = Database(memory=True) .ft P .fi .UNINDENT .UNINDENT .sp You can also create a named in\-memory database. Unlike regular memory databases these can be accessed by multiple threads, provided at least one reference to the database still exists. \fIdel db\fP will clear the database from memory. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db = Database(memory_name="my_shared_database") .ft P .fi .UNINDENT .UNINDENT .sp Connections use \fBPRAGMA recursive_triggers=on\fP by default. If you don\(aqt want to use \fI\%recursive triggers\fP you can turn them off using: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db = Database(memory=True, recursive_triggers=False) .ft P .fi .UNINDENT .UNINDENT .SS Attaching additional databases .sp SQLite supports cross\-database SQL queries, which can join data from tables in more than one database file. .sp You can attach an additional database using the \fB\&.attach()\fP method, providing an alias to use for that database and the path to the SQLite file on disk. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db = Database("first.db") db.attach("second", "second.db") # Now you can run queries like this one: print(db.query(""" select * from table_in_first union all select * from second.table_in_second """)) .ft P .fi .UNINDENT .UNINDENT .sp You can reference tables in the attached database using the alias value you passed to \fBdb.attach(alias, filepath)\fP as a prefix, for example the \fBsecond.table_in_second\fP reference in the SQL query above. .SS Tracing queries .sp You can use the \fBtracer\fP mechanism to see SQL queries that are being executed by SQLite. A tracer is a function that you provide which will be called with \fBsql\fP and \fBparams\fP arguments every time SQL is executed, for example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C def tracer(sql, params): print("SQL: {} \- params: {}".format(sql, params)) .ft P .fi .UNINDENT .UNINDENT .sp You can pass this function to the \fBDatabase()\fP constructor like so: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db = Database(memory=True, tracer=tracer) .ft P .fi .UNINDENT .UNINDENT .sp You can also turn on a tracer function temporarily for a block of code using the \fBwith db.tracer(...)\fP context manager: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db = Database(memory=True) # ... later with db.tracer(print): db["dogs"].insert({"name": "Cleo"}) .ft P .fi .UNINDENT .UNINDENT .sp This example will print queries only for the duration of the \fBwith\fP block. .SS Executing queries .sp The \fBDatabase\fP class offers several methods for directly executing SQL queries. .SS db.query(sql, params) .sp The \fBdb.query(sql)\fP function executes a SQL query and returns an iterator over Python dictionaries representing the resulting rows: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db = Database(memory=True) db["dogs"].insert_all([{"name": "Cleo"}, {"name": "Pancakes"}]) for row in db.query("select * from dogs"): print(row) # Outputs: # {\(aqname\(aq: \(aqCleo\(aq} # {\(aqname\(aq: \(aqPancakes\(aq} .ft P .fi .UNINDENT .UNINDENT .SS db.execute(sql, params) .sp The \fBdb.execute()\fP and \fBdb.executescript()\fP methods provide wrappers around \fB\&.execute()\fP and \fB\&.executescript()\fP on the underlying SQLite connection. These wrappers log to the \fI\%tracer function\fP if one has been registered. .sp \fBdb.execute(sql)\fP returns a \fI\%sqlite3.Cursor\fP that was used to execute the SQL. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db = Database(memory=True) db["dogs"].insert({"name": "Cleo"}) cursor = db.execute("update dogs set name = \(aqCleopaws\(aq") print(cursor.rowcount) # Outputs the number of rows affected by the update # In this case 2 .ft P .fi .UNINDENT .UNINDENT .sp Other cursor methods such as \fB\&.fetchone()\fP and \fB\&.fetchall()\fP are also available, see the \fI\%standard library documentation\fP\&. .SS Passing parameters .sp Both \fBdb.query()\fP and \fBdb.execute()\fP accept an optional second argument for parameters to be passed to the SQL query. .sp This can take the form of either a tuple/list or a dictionary, depending on the type of parameters used in the query. Values passed in this way will be correctly quoted and escaped, helping avoid SQL injection vulnerabilities. .sp \fB?\fP parameters in the SQL query can be filled in using a list: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db.execute("update dogs set name = ?", ["Cleopaws"]) # This will rename ALL dogs to be called "Cleopaws" .ft P .fi .UNINDENT .UNINDENT .sp Named parameters using \fB:name\fP can be filled using a dictionary: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C dog = next(db.query( "select rowid, name from dogs where name = :name", {"name": "Cleopaws"} )) # dog is now {\(aqrowid\(aq: 1, \(aqname\(aq: \(aqCleopaws\(aq} .ft P .fi .UNINDENT .UNINDENT .sp In this example \fBnext()\fP is used to retrieve the first result in the iterator returned by the \fBdb.query()\fP method. .SS Accessing tables .sp Tables are accessed using the indexing operator, like so: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C table = db["my_table"] .ft P .fi .UNINDENT .UNINDENT .sp If the table does not yet exist, it will be created the first time you attempt to insert or upsert data into it. .sp You can also access tables using the \fB\&.table()\fP method like so: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C table = db.table("my_table") .ft P .fi .UNINDENT .UNINDENT .sp Using this factory function allows you to set \fI\%Table configuration options\fP\&. .SS Listing tables .sp You can list the names of tables in a database using the \fB\&.table_names()\fP method: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db.table_names() [\(aqdogs\(aq] .ft P .fi .UNINDENT .UNINDENT .sp To see just the FTS4 tables, use \fB\&.table_names(fts4=True)\fP\&. For FTS5, use \fB\&.table_names(fts5=True)\fP\&. .sp You can also iterate through the table objects themselves using the \fB\&.tables\fP property: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db.tables [] .ft P .fi .UNINDENT .UNINDENT .SS Listing views .sp \fB\&.view_names()\fP shows you a list of views in the database: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db.view_names() [\(aqgood_dogs\(aq] .ft P .fi .UNINDENT .UNINDENT .sp You can iterate through view objects using the \fB\&.views\fP property: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db.views [] .ft P .fi .UNINDENT .UNINDENT .sp View objects are similar to Table objects, except that any attempts to insert or update data will throw an error. The full list of methods and properties available on a view object is as follows: .INDENT 0.0 .IP \(bu 2 \fBcolumns\fP .IP \(bu 2 \fBcolumns_dict\fP .IP \(bu 2 \fBcount\fP .IP \(bu 2 \fBschema\fP .IP \(bu 2 \fBrows\fP .IP \(bu 2 \fBrows_where(where, where_args, order_by, select)\fP .IP \(bu 2 \fBdrop()\fP .UNINDENT .SS Listing rows .sp To iterate through dictionaries for each of the rows in a table, use \fB\&.rows\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db = sqlite_utils.Database("dogs.db") >>> for row in db["dogs"].rows: \&... print(row) {\(aqid\(aq: 1, \(aqage\(aq: 4, \(aqname\(aq: \(aqCleo\(aq} {\(aqid\(aq: 2, \(aqage\(aq: 2, \(aqname\(aq: \(aqPancakes\(aq} .ft P .fi .UNINDENT .UNINDENT .sp You can filter rows by a WHERE clause using \fB\&.rows_where(where, where_args)\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db = sqlite_utils.Database("dogs.db") >>> for row in db["dogs"].rows_where("age > ?", [3]): \&... print(row) {\(aqid\(aq: 1, \(aqage\(aq: 4, \(aqname\(aq: \(aqCleo\(aq} .ft P .fi .UNINDENT .UNINDENT .sp The first argument is a fragment of SQL. The second, optional argument is values to be passed to that fragment \- you can use \fB?\fP placeholders and pass an array, or you can use \fB:named\fP parameters and pass a dictionary, like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> for row in db["dogs"].rows_where("age > :age", {"age": 3}): \&... print(row) {\(aqid\(aq: 1, \(aqage\(aq: 4, \(aqname\(aq: \(aqCleo\(aq} .ft P .fi .UNINDENT .UNINDENT .sp To return custom columns (instead of the default that uses \fBselect *\fP) pass \fBselect="column1, column2"\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db = sqlite_utils.Database("dogs.db") >>> for row in db["dogs"].rows_where(select=\(aqname, age\(aq): \&... print(row) {\(aqname\(aq: \(aqCleo\(aq, \(aqage\(aq: 4} .ft P .fi .UNINDENT .UNINDENT .sp To specify an order, use the \fBorder_by=\fP argument: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> for row in db["dogs"].rows_where("age > 1", order_by="age"): \&... print(row) {\(aqid\(aq: 2, \(aqage\(aq: 2, \(aqname\(aq: \(aqPancakes\(aq} {\(aqid\(aq: 1, \(aqage\(aq: 4, \(aqname\(aq: \(aqCleo\(aq} .ft P .fi .UNINDENT .UNINDENT .sp You can use \fBorder_by="age desc"\fP for descending order. .sp You can order all records in the table by excluding the \fBwhere\fP argument: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> for row in db["dogs"].rows_where(order_by="age desc"): \&... print(row) {\(aqid\(aq: 1, \(aqage\(aq: 4, \(aqname\(aq: \(aqCleo\(aq} {\(aqid\(aq: 2, \(aqage\(aq: 2, \(aqname\(aq: \(aqPancakes\(aq} .ft P .fi .UNINDENT .UNINDENT .sp This method also accepts \fBoffset=\fP and \fBlimit=\fP arguments, for specifying an OFFSET and a LIMIT for the SQL query: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> for row in db["dogs"].rows_where(order_by="age desc", limit=1): \&... print(row) {\(aqid\(aq: 1, \(aqage\(aq: 4, \(aqname\(aq: \(aqCleo\(aq} .ft P .fi .UNINDENT .UNINDENT .SS Counting rows .sp To count the number of rows that would be returned by a where filter, use \fB\&.count_where(where, where_args)\fP: .sp .nf .ft C >>> db["dogs"].count_where("age > ?", [1]) 2 .ft P .fi .SS Listing rows with their primary keys .sp Sometimes it can be useful to retrieve the primary key along with each row, in order to pass that key (or primary key tuple) to the \fB\&.get()\fP or \fB\&.update()\fP methods. .sp The \fB\&.pks_and_rows_where()\fP method takes the same signature as \fB\&.rows_where()\fP (with the exception of the \fBselect=\fP parameter) but returns a generator that yields pairs of \fB(primary key, row dictionary)\fP\&. .sp The primary key value will usually be a single value but can also be a tuple if the table has a compound primary key. .sp If the table is a \fBrowid\fP table (with no explicit primary key column) then that ID will be returned. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db = sqlite_utils.Database(memory=True) >>> db["dogs"].insert({"name": "Cleo"}) >>> for pk, row in db["dogs"].pks_and_rows_where(): \&... print(pk, row) 1 {\(aqrowid\(aq: 1, \(aqname\(aq: \(aqCleo\(aq} >>> db["dogs_with_pk"].insert({"id": 5, "name": "Cleo"}, pk="id") >>> for pk, row in db["dogs_with_pk"].pks_and_rows_where(): \&... print(pk, row) 5 {\(aqid\(aq: 5, \(aqname\(aq: \(aqCleo\(aq} >>> db["dogs_with_compound_pk"].insert( \&... {"species": "dog", "id": 3, "name": "Cleo"}, \&... pk=("species", "id") \&... ) >>> for pk, row in db["dogs_with_compound_pk"].pks_and_rows_where(): \&... print(pk, row) (\(aqdog\(aq, 3) {\(aqspecies\(aq: \(aqdog\(aq, \(aqid\(aq: 3, \(aqname\(aq: \(aqCleo\(aq} .ft P .fi .UNINDENT .UNINDENT .SS Retrieving a specific record .sp You can retrieve a record by its primary key using \fBtable.get()\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db = sqlite_utils.Database("dogs.db") >>> print(db["dogs"].get(1)) {\(aqid\(aq: 1, \(aqage\(aq: 4, \(aqname\(aq: \(aqCleo\(aq} .ft P .fi .UNINDENT .UNINDENT .sp If the table has a compound primary key you can pass in the primary key values as a tuple: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db["compound_dogs"].get(("mixed", 3)) .ft P .fi .UNINDENT .UNINDENT .sp If the record does not exist a \fBNotFoundError\fP will be raised: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from sqlite_utils.db import NotFoundError try: row = db["dogs"].get(5) except NotFoundError: print("Dog not found") .ft P .fi .UNINDENT .UNINDENT .SS Showing the schema .sp The \fBdb.schema\fP property returns the full SQL schema for the database as a string: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db = sqlite_utils.Database("dogs.db") >>> print(db.schema) CREATE TABLE "dogs" ( [id] INTEGER PRIMARY KEY, [name] TEXT ); .ft P .fi .UNINDENT .UNINDENT .SS Creating tables .sp The easiest way to create a new table is to insert a record into it: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from sqlite_utils import Database import sqlite3 db = Database("dogs.db") dogs = db["dogs"] dogs.insert({ "name": "Cleo", "twitter": "cleopaws", "age": 3, "is_good_dog": True, }) .ft P .fi .UNINDENT .UNINDENT .sp This will automatically create a new table called "dogs" with the following schema: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CREATE TABLE dogs ( name TEXT, twitter TEXT, age INTEGER, is_good_dog INTEGER ) .ft P .fi .UNINDENT .UNINDENT .sp You can also specify a primary key by passing the \fBpk=\fP parameter to the \fB\&.insert()\fP call. This will only be obeyed if the record being inserted causes the table to be created: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C dogs.insert({ "id": 1, "name": "Cleo", "twitter": "cleopaws", "age": 3, "is_good_dog": True, }, pk="id") .ft P .fi .UNINDENT .UNINDENT .sp After inserting a row like this, the \fBdogs.last_rowid\fP property will return the SQLite \fBrowid\fP assigned to the most recently inserted record. .sp The \fBdogs.last_pk\fP property will return the last inserted primary key value, if you specified one. This can be very useful when writing code that creates foreign keys or many\-to\-many relationships. .SS Custom column order and column types .sp The order of the columns in the table will be derived from the order of the keys in the dictionary, provided you are using Python 3.6 or later. .sp If you want to explicitly set the order of the columns you can do so using the \fBcolumn_order=\fP parameter: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].insert({ "id": 1, "name": "Cleo", "twitter": "cleopaws", "age": 3, "is_good_dog": True, }, pk="id", column_order=("id", "twitter", "name")) .ft P .fi .UNINDENT .UNINDENT .sp You don\(aqt need to pass all of the columns to the \fBcolumn_order\fP parameter. If you only pass a subset of the columns the remaining columns will be ordered based on the key order of the dictionary. .sp Column types are detected based on the example data provided. Sometimes you may find you need to over\-ride these detected types \- to create an integer column for data that was provided as a string for example, or to ensure that a table where the first example was \fBNone\fP is created as an \fBINTEGER\fP rather than a \fBTEXT\fP column. You can do this using the \fBcolumns=\fP parameter: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].insert({ "id": 1, "name": "Cleo", "age": "5", }, pk="id", columns={"age": int, "weight": float}) .ft P .fi .UNINDENT .UNINDENT .sp This will create a table with the following schema: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CREATE TABLE [dogs] ( [id] INTEGER PRIMARY KEY, [name] TEXT, [age] INTEGER, [weight] FLOAT ) .ft P .fi .UNINDENT .UNINDENT .SS Explicitly creating a table .sp You can directly create a new table without inserting any data into it using the \fB\&.create()\fP method: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["cats"].create({ "id": int, "name": str, "weight": float, }, pk="id") .ft P .fi .UNINDENT .UNINDENT .sp The first argument here is a dictionary specifying the columns you would like to create. Each column is paired with a Python type indicating the type of column. See \fI\%Adding columns\fP for full details on how these types work. .sp This method takes optional arguments \fBpk=\fP, \fBcolumn_order=\fP, \fBforeign_keys=\fP, \fBnot_null=set()\fP and \fBdefaults=dict()\fP \- explained below. .sp A \fBsqlite_utils.utils.sqlite3.OperationalError\fP will be raised if a table of that name already exists. .sp To do nothing if the table already exists, add \fBif_not_exists=True\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["cats"].create({ "id": int, "name": str, }, pk="id", if_not_exists=True) .ft P .fi .UNINDENT .UNINDENT .sp You can also pass \fBtransform=True\fP to have any existing tables \fI\%transformed\fP to match your new table specification. This is a \fBdangerous operation\fP as it will drop columns that are no longer listed in your call to \fB\&.create()\fP, so be careful when running this. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["cats"].create({ "id": int, "name": str, "weight": float, }, pk="id", transform=True) .ft P .fi .UNINDENT .UNINDENT .sp The \fBtransform=True\fP option will update the table schema if any of the following have changed: .INDENT 0.0 .IP \(bu 2 The specified columns or their types .IP \(bu 2 The specified primary key .IP \(bu 2 The order of the columns, defined using \fBcolumn_order=\fP .IP \(bu 2 The \fBnot_null=\fP or \fBdefaults=\fP arguments .UNINDENT .sp Changes to \fBforeign_keys=\fP are not currently detected and applied by \fBtransform=True\fP\&. .SS Compound primary keys .sp If you want to create a table with a compound primary key that spans multiple columns, you can do so by passing a tuple of column names to any of the methods that accept a \fBpk=\fP parameter. For example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["cats"].create({ "id": int, "breed": str, "name": str, "weight": float, }, pk=("breed", "id")) .ft P .fi .UNINDENT .UNINDENT .sp This also works for the \fB\&.insert()\fP, \fB\&.insert_all()\fP, \fB\&.upsert()\fP and \fB\&.upsert_all()\fP methods. .SS Specifying foreign keys .sp Any operation that can create a table (\fB\&.create()\fP, \fB\&.insert()\fP, \fB\&.insert_all()\fP, \fB\&.upsert()\fP and \fB\&.upsert_all()\fP) accepts an optional \fBforeign_keys=\fP argument which can be used to set up foreign key constraints for the table that is being created. .sp If you are using your database with \fI\%Datasette\fP, Datasette will detect these constraints and use them to generate hyperlinks to associated records. .sp The \fBforeign_keys\fP argument takes a list that indicates which foreign keys should be created. The list can take several forms. The simplest is a list of columns: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C foreign_keys=["author_id"] .ft P .fi .UNINDENT .UNINDENT .sp The library will guess which tables you wish to reference based on the column names using the rules described in \fI\%Adding foreign key constraints\fP\&. .sp You can also be more explicit, by passing in a list of tuples: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C foreign_keys=[ ("author_id", "authors", "id") ] .ft P .fi .UNINDENT .UNINDENT .sp This means that the \fBauthor_id\fP column should be a foreign key that references the \fBid\fP column in the \fBauthors\fP table. .sp You can leave off the third item in the tuple to have the referenced column automatically set to the primary key of that table. A full example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["authors"].insert_all([ {"id": 1, "name": "Sally"}, {"id": 2, "name": "Asheesh"} ], pk="id") db["books"].insert_all([ {"title": "Hedgehogs of the world", "author_id": 1}, {"title": "How to train your wolf", "author_id": 2}, ], foreign_keys=[ ("author_id", "authors") ]) .ft P .fi .UNINDENT .UNINDENT .SS Table configuration options .sp The \fB\&.insert()\fP, \fB\&.upsert()\fP, \fB\&.insert_all()\fP and \fB\&.upsert_all()\fP methods each take a number of keyword arguments, some of which influence what happens should they cause a table to be created and some of which affect the behavior of those methods. .sp You can set default values for these methods by accessing the table through the \fBdb.table(...)\fP method (instead of using \fBdb["table_name"]\fP), like so: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C table = db.table( "authors", pk="id", not_null={"name", "score"}, column_order=("id", "name", "score", "url") ) # Now you can call .insert() like so: table.insert({"id": 1, "name": "Tracy", "score": 5}) .ft P .fi .UNINDENT .UNINDENT .sp The configuration options that can be specified in this way are \fBpk\fP, \fBforeign_keys\fP, \fBcolumn_order\fP, \fBnot_null\fP, \fBdefaults\fP, \fBbatch_size\fP, \fBhash_id\fP, \fBhash_id_columns\fP, \fBalter\fP, \fBignore\fP, \fBreplace\fP, \fBextracts\fP, \fBconversions\fP, \fBcolumns\fP\&. These are all documented below. .SS Setting defaults and not null constraints .sp Each of the methods that can cause a table to be created take optional arguments \fBnot_null=set()\fP and \fBdefaults=dict()\fP\&. The methods that take these optional arguments are: .INDENT 0.0 .IP \(bu 2 \fBdb.create_table(...)\fP .IP \(bu 2 \fBtable.create(...)\fP .IP \(bu 2 \fBtable.insert(...)\fP .IP \(bu 2 \fBtable.insert_all(...)\fP .IP \(bu 2 \fBtable.upsert(...)\fP .IP \(bu 2 \fBtable.upsert_all(...)\fP .UNINDENT .sp You can use \fBnot_null=\fP to pass a set of column names that should have a \fBNOT NULL\fP constraint set on them when they are created. .sp You can use \fBdefaults=\fP to pass a dictionary mapping columns to the default value that should be specified in the \fBCREATE TABLE\fP statement. .sp Here\(aqs an example that uses these features: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["authors"].insert_all( [{"id": 1, "name": "Sally", "score": 2}], pk="id", not_null={"name", "score"}, defaults={"score": 1}, ) db["authors"].insert({"name": "Dharma"}) list(db["authors"].rows) # Outputs: # [{\(aqid\(aq: 1, \(aqname\(aq: \(aqSally\(aq, \(aqscore\(aq: 2}, # {\(aqid\(aq: 3, \(aqname\(aq: \(aqDharma\(aq, \(aqscore\(aq: 1}] print(db["authors"].schema) # Outputs: # CREATE TABLE [authors] ( # [id] INTEGER PRIMARY KEY, # [name] TEXT NOT NULL, # [score] INTEGER NOT NULL DEFAULT 1 # ) .ft P .fi .UNINDENT .UNINDENT .SS Duplicating tables .sp The \fBtable.duplicate()\fP method creates a copy of the table, copying both the table schema and all of the rows in that table: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["authors"].duplicate("authors_copy") .ft P .fi .UNINDENT .UNINDENT .sp The new \fBauthors_copy\fP table will now contain a duplicate copy of the data from \fBauthors\fP\&. .sp This method raises \fBsqlite_utils.db.NoTable\fP if the table does not exist. .SS Bulk inserts .sp If you have more than one record to insert, the \fBinsert_all()\fP method is a much more efficient way of inserting them. Just like \fBinsert()\fP it will automatically detect the columns that should be created, but it will inspect the first batch of 100 items to help decide what those column types should be. .sp Use it like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].insert_all([{ "id": 1, "name": "Cleo", "twitter": "cleopaws", "age": 3, "is_good_dog": True, }, { "id": 2, "name": "Marnie", "twitter": "MarnieTheDog", "age": 16, "is_good_dog": True, }], pk="id", column_order=("id", "twitter", "name")) .ft P .fi .UNINDENT .UNINDENT .sp The column types used in the \fBCREATE TABLE\fP statement are automatically derived from the types of data in that first batch of rows. Any additional columns in subsequent batches will cause a \fBsqlite3.OperationalError\fP exception to be raised unless the \fBalter=True\fP argument is supplied, in which case the new columns will be created. .sp The function can accept an iterator or generator of rows and will commit them according to the batch size. The default batch size is 100, but you can specify a different size using the \fBbatch_size\fP parameter: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["big_table"].insert_all(({ "id": 1, "name": "Name {}".format(i), } for i in range(10000)), batch_size=1000) .ft P .fi .UNINDENT .UNINDENT .sp You can skip inserting any records that have a primary key that already exists using \fBignore=True\fP\&. This works with both \fB\&.insert({...}, ignore=True)\fP and \fB\&.insert_all([...], ignore=True)\fP\&. .sp You can delete all the existing rows in the table before inserting the new records using \fBtruncate=True\fP\&. This is useful if you want to replace the data in the table. .sp Pass \fBanalyze=True\fP to run \fBANALYZE\fP against the table after inserting the new records. .SS Insert\-replacing data .sp If you try to insert data using a primary key that already exists, the \fB\&.insert()\fP or \fB\&.insert_all()\fP method will raise a \fBsqlite3.IntegrityError\fP exception. .sp This example that catches that exception: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from sqlite_utils.utils import sqlite3 try: db["dogs"].insert({"id": 1, "name": "Cleo"}, pk="id") except sqlite3.IntegrityError: print("Record already exists with that primary key") .ft P .fi .UNINDENT .UNINDENT .sp Importing from \fBsqlite_utils.utils.sqlite3\fP ensures your code continues to work even if you are using the \fBpysqlite3\fP library instead of the Python standard library \fBsqlite3\fP module. .sp Use the \fBignore=True\fP parameter to ignore this error: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # This fails silently if a record with id=1 already exists db["dogs"].insert({"id": 1, "name": "Cleo"}, pk="id", ignore=True) .ft P .fi .UNINDENT .UNINDENT .sp To replace any existing records that have a matching primary key, use the \fBreplace=True\fP parameter to \fB\&.insert()\fP or \fB\&.insert_all()\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].insert_all([{ "id": 1, "name": "Cleo", "twitter": "cleopaws", "age": 3, "is_good_dog": True, }, { "id": 2, "name": "Marnie", "twitter": "MarnieTheDog", "age": 16, "is_good_dog": True, }], pk="id", replace=True) .ft P .fi .UNINDENT .UNINDENT .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 Prior to sqlite\-utils 2.0 the \fB\&.upsert()\fP and \fB\&.upsert_all()\fP methods worked the same way as \fB\&.insert(replace=True)\fP does today. See \fI\%Upserting data\fP for the new behaviour of those methods introduced in 2.0. .UNINDENT .UNINDENT .SS Updating a specific record .sp You can update a record by its primary key using \fBtable.update()\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db = sqlite_utils.Database("dogs.db") >>> print(db["dogs"].get(1)) {\(aqid\(aq: 1, \(aqage\(aq: 4, \(aqname\(aq: \(aqCleo\(aq} >>> db["dogs"].update(1, {"age": 5}) >>> print(db["dogs"].get(1)) {\(aqid\(aq: 1, \(aqage\(aq: 5, \(aqname\(aq: \(aqCleo\(aq} .ft P .fi .UNINDENT .UNINDENT .sp The first argument to \fBupdate()\fP is the primary key. This can be a single value, or a tuple if that table has a compound primary key: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db["compound_dogs"].update((5, 3), {"name": "Updated"}) .ft P .fi .UNINDENT .UNINDENT .sp The second argument is a dictionary of columns that should be updated, along with their new values. .sp You can cause any missing columns to be added automatically using \fBalter=True\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db["dogs"].update(1, {"breed": "Mutt"}, alter=True) .ft P .fi .UNINDENT .UNINDENT .SS Deleting a specific record .sp You can delete a record using \fBtable.delete()\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db = sqlite_utils.Database("dogs.db") >>> db["dogs"].delete(1) .ft P .fi .UNINDENT .UNINDENT .sp The \fBdelete()\fP method takes the primary key of the record. This can be a tuple of values if the row has a compound primary key: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db["compound_dogs"].delete((5, 3)) .ft P .fi .UNINDENT .UNINDENT .SS Deleting multiple records .sp You can delete all records in a table that match a specific WHERE statement using \fBtable.delete_where()\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db = sqlite_utils.Database("dogs.db") >>> # Delete every dog with age less than 3 >>> db["dogs"].delete_where("age < ?", [3]) .ft P .fi .UNINDENT .UNINDENT .sp Calling \fBtable.delete_where()\fP with no other arguments will delete every row in the table. .sp Pass \fBanalyze=True\fP to run \fBANALYZE\fP against the table after deleting the rows. .SS Upserting data .sp Upserting allows you to insert records if they do not exist and update them if they DO exist, based on matching against their primary key. .sp For example, given the dogs database you could upsert the record for Cleo like so: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].upsert({ "id": 1, "name": "Cleo", "twitter": "cleopaws", "age": 4, "is_good_dog": True, }, pk="id", column_order=("id", "twitter", "name")) .ft P .fi .UNINDENT .UNINDENT .sp If a record exists with id=1, it will be updated to match those fields. If it does not exist it will be created. .sp Any existing columns that are not referenced in the dictionary passed to \fB\&.upsert()\fP will be unchanged. If you want to replace a record entirely, use \fB\&.insert(doc, replace=True)\fP instead. .sp Note that the \fBpk\fP and \fBcolumn_order\fP parameters here are optional if you are certain that the table has already been created. You should pass them if the table may not exist at the time the first upsert is performed. .sp An \fBupsert_all()\fP method is also available, which behaves like \fBinsert_all()\fP but performs upserts instead. .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 \fB\&.upsert()\fP and \fB\&.upsert_all()\fP in sqlite\-utils 1.x worked like \fB\&.insert(..., replace=True)\fP and \fB\&.insert_all(..., replace=True)\fP do in 2.x. See \fI\%issue #66\fP for details of this change. .UNINDENT .UNINDENT .SS Converting data in columns .sp The \fBtable.convert(...)\fP method can be used to apply a conversion function to the values in a column, either to update that column or to populate new columns. It is the Python library equivalent of the \fI\%sqlite\-utils convert\fP command. .sp This feature works by registering a custom SQLite function that applies a Python transformation, then running a SQL query equivalent to \fBUPDATE table SET column = convert_value(column);\fP .sp To transform a specific column to uppercase, you would use the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].convert("name", lambda value: value.upper()) .ft P .fi .UNINDENT .UNINDENT .sp You can pass a list of columns, in which case the transformation will be applied to each one: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].convert(["name", "twitter"], lambda value: value.upper()) .ft P .fi .UNINDENT .UNINDENT .sp To save the output to of the transformation to a different column, use the \fBoutput=\fP parameter: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].convert("name", lambda value: value.upper(), output="name_upper") .ft P .fi .UNINDENT .UNINDENT .sp This will add the new column, if it does not already exist. You can pass \fBoutput_type=int\fP or some other type to control the type of the new column \- otherwise it will default to text. .sp If you want to drop the original column after saving the results in a separate output column, pass \fBdrop=True\fP\&. .sp You can create multiple new columns from a single input column by passing \fBmulti=True\fP and a conversion function that returns a Python dictionary. This example creates new \fBupper\fP and \fBlower\fP columns populated from the single \fBtitle\fP column: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C table.convert( "title", lambda v: {"upper": v.upper(), "lower": v.lower()}, multi=True ) .ft P .fi .UNINDENT .UNINDENT .sp The \fB\&.convert()\fP method accepts optional \fBwhere=\fP and \fBwhere_args=\fP parameters which can be used to apply the conversion to a subset of rows specified by a where clause. Here\(aqs how to apply the conversion only to rows with an \fBid\fP that is higher than 20: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C table.convert("title", lambda v: v.upper(), where="id > :id", where_args={"id": 20}) .ft P .fi .UNINDENT .UNINDENT .sp These behave the same as the corresponding parameters to the \fI\%\&.rows_where()\fP method, so you can use \fB?\fP placeholders and a list of values instead of \fB:named\fP placeholders with a dictionary. .SS Working with lookup tables .sp A useful pattern when populating large tables in to break common values out into lookup tables. Consider a table of \fBTrees\fP, where each tree has a species. Ideally these species would be split out into a separate \fBSpecies\fP table, with each one assigned an integer primary key that can be referenced from the \fBTrees\fP table \fBspecies_id\fP column. .SS Creating lookup tables explicitly .sp Calling \fBdb["Species"].lookup({"name": "Palm"})\fP creates a table called \fBSpecies\fP (if one does not already exist) with two columns: \fBid\fP and \fBname\fP\&. It sets up a unique constraint on the \fBname\fP column to guarantee it will not contain duplicate rows. It then inserts a new row with the \fBname\fP set to \fBPalm\fP and returns the new integer primary key value. .sp If the \fBSpecies\fP table already exists, it will insert the new row and return the primary key. If a row with that \fBname\fP already exists, it will return the corresponding primary key value directly. .sp If you call \fB\&.lookup()\fP against an existing table without the unique constraint it will attempt to add the constraint, raising an \fBIntegrityError\fP if the constraint cannot be created. .sp If you pass in a dictionary with multiple values, both values will be used to insert or retrieve the corresponding ID and any unique constraint that is created will cover all of those columns, for example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["Trees"].insert({ "latitude": 49.1265976, "longitude": 2.5496218, "species": db["Species"].lookup({ "common_name": "Common Juniper", "latin_name": "Juniperus communis" }) }) .ft P .fi .UNINDENT .UNINDENT .sp The \fB\&.lookup()\fP method has an optional second argument which can be used to populate other columns in the table but only if the row does not exist yet. These columns will not be included in the unique index. .sp To create a species record with a note on when it was first seen, you can use this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["Species"].lookup({"name": "Palm"}, {"first_seen": "2021\-03\-04"}) .ft P .fi .UNINDENT .UNINDENT .sp The first time this is called the record will be created for \fBname="Palm"\fP\&. Any subsequent calls with that name will ignore the second argument, even if it includes different values. .sp \fB\&.lookup()\fP also accepts keyword arguments, which are passed through to the \fI\%insert() method\fP and can be used to influence the shape of the created table. Supported parameters are: .INDENT 0.0 .IP \(bu 2 \fBpk\fP \- which defaults to \fBid\fP .IP \(bu 2 \fBforeign_keys\fP .IP \(bu 2 \fBcolumn_order\fP .IP \(bu 2 \fBnot_null\fP .IP \(bu 2 \fBdefaults\fP .IP \(bu 2 \fBextracts\fP .IP \(bu 2 \fBconversions\fP .IP \(bu 2 \fBcolumns\fP .UNINDENT .SS Populating lookup tables automatically during insert/upsert .sp A more efficient way to work with lookup tables is to define them using the \fBextracts=\fP parameter, which is accepted by \fB\&.insert()\fP, \fB\&.upsert()\fP, \fB\&.insert_all()\fP, \fB\&.upsert_all()\fP and by the \fB\&.table(...)\fP factory function. .sp \fBextracts=\fP specifies columns which should be "extracted" out into a separate lookup table during the data insertion. .sp It can be either a list of column names, in which case the extracted table names will match the column names exactly, or it can be a dictionary mapping column names to the desired name of the extracted table. .sp To extract the \fBspecies\fP column out to a separate \fBSpecies\fP table, you can do this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # Using the table factory trees = db.table("Trees", extracts={"species": "Species"}) trees.insert({ "latitude": 49.1265976, "longitude": 2.5496218, "species": "Common Juniper" }) # If you want the table to be called \(aqspecies\(aq, you can do this: trees = db.table("Trees", extracts=["species"]) # Using .insert() directly db["Trees"].insert({ "latitude": 49.1265976, "longitude": 2.5496218, "species": "Common Juniper" }, extracts={"species": "Species"}) .ft P .fi .UNINDENT .UNINDENT .SS Working with many\-to\-many relationships .sp \fBsqlite\-utils\fP includes a shortcut for creating records using many\-to\-many relationships in the form of the \fBtable.m2m(...)\fP method. .sp Here\(aqs how to create two new records and connect them via a many\-to\-many table in a single line of code: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].insert({"id": 1, "name": "Cleo"}, pk="id").m2m( "humans", {"id": 1, "name": "Natalie"}, pk="id" ) .ft P .fi .UNINDENT .UNINDENT .sp Running this example actually creates three tables: \fBdogs\fP, \fBhumans\fP and a many\-to\-many \fBdogs_humans\fP table. It will insert a record into each of those tables. .sp The \fB\&.m2m()\fP method executes against the last record that was affected by \fB\&.insert()\fP or \fB\&.update()\fP \- the record identified by the \fBtable.last_pk\fP property. To execute \fB\&.m2m()\fP against a specific record you can first select it by passing its primary key to \fB\&.update()\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].update(1).m2m( "humans", {"id": 2, "name": "Simon"}, pk="id" ) .ft P .fi .UNINDENT .UNINDENT .sp The first argument to \fB\&.m2m()\fP can be either the name of a table as a string or it can be the table object itself. .sp The second argument can be a single dictionary record or a list of dictionaries. These dictionaries will be passed to \fB\&.upsert()\fP against the specified table. .sp Here\(aqs alternative code that creates the dog record and adds two people to it: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db = Database(memory=True) dogs = db.table("dogs", pk="id") humans = db.table("humans", pk="id") dogs.insert({"id": 1, "name": "Cleo"}).m2m( humans, [ {"id": 1, "name": "Natalie"}, {"id": 2, "name": "Simon"} ] ) .ft P .fi .UNINDENT .UNINDENT .sp The method will attempt to find an existing many\-to\-many table by looking for a table that has foreign key relationships against both of the tables in the relationship. .sp If it cannot find such a table, it will create a new one using the names of the two tables \- \fBdogs_humans\fP in this example. You can customize the name of this table using the \fBm2m_table=\fP argument to \fB\&.m2m()\fP\&. .sp It it finds multiple candidate tables with foreign keys to both of the specified tables it will raise a \fBsqlite_utils.db.NoObviousTable\fP exception. You can avoid this error by specifying the correct table using \fBm2m_table=\fP\&. .sp The \fB\&.m2m()\fP method also takes an optional \fBpk=\fP argument to specify the primary key that should be used if the table is created, and an optional \fBalter=True\fP argument to specify that any missing columns of an existing table should be added if they are needed. .SS Using m2m and lookup tables together .sp You can work with (or create) lookup tables as part of a call to \fB\&.m2m()\fP using the \fBlookup=\fP parameter. This accepts the same argument as \fBtable.lookup()\fP does \- a dictionary of values that should be used to lookup or create a row in the lookup table. .sp This example creates a dogs table, populates it, creates a characteristics table, populates that and sets up a many\-to\-many relationship between the two. It chains \fB\&.m2m()\fP twice to create two associated characteristics: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db = Database(memory=True) dogs = db.table("dogs", pk="id") dogs.insert({"id": 1, "name": "Cleo"}).m2m( "characteristics", lookup={ "name": "Playful" } ).m2m( "characteristics", lookup={ "name": "Opinionated" } ) .ft P .fi .UNINDENT .UNINDENT .sp You can inspect the database to see the results like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db.table_names() [\(aqdogs\(aq, \(aqcharacteristics\(aq, \(aqcharacteristics_dogs\(aq] >>> list(db["dogs"].rows) [{\(aqid\(aq: 1, \(aqname\(aq: \(aqCleo\(aq}] >>> list(db["characteristics"].rows) [{\(aqid\(aq: 1, \(aqname\(aq: \(aqPlayful\(aq}, {\(aqid\(aq: 2, \(aqname\(aq: \(aqOpinionated\(aq}] >>> list(db["characteristics_dogs"].rows) [{\(aqcharacteristics_id\(aq: 1, \(aqdogs_id\(aq: 1}, {\(aqcharacteristics_id\(aq: 2, \(aqdogs_id\(aq: 1}] >>> print(db["characteristics_dogs"].schema) CREATE TABLE [characteristics_dogs] ( [characteristics_id] INTEGER REFERENCES [characteristics]([id]), [dogs_id] INTEGER REFERENCES [dogs]([id]), PRIMARY KEY ([characteristics_id], [dogs_id]) ) .ft P .fi .UNINDENT .UNINDENT .SS Analyzing a column .sp The \fBtable.analyze_column(column, common_limit=10, value_truncate=None)\fP method is used by the \fI\%analyze\-tables\fP CLI command. It returns a \fBColumnDetails\fP named tuple with the following fields: .INDENT 0.0 .TP .B \fBtable\fP The name of the table .TP .B \fBcolumn\fP The name of the column .TP .B \fBtotal_rows\fP The total number of rows in the table .TP .B \fBnum_null\fP The number of rows for which this column is null .TP .B \fBnum_blank\fP The number of rows for which this column is blank (the empty string) .TP .B \fBnum_distinct\fP The number of distinct values in this column .TP .B \fBmost_common\fP The \fBN\fP most common values as a list of \fB(value, count)\fP tuples\(ga, or \fBNone\fP if the table consists entirely of distinct values .TP .B \fBleast_common\fP The \fBN\fP least common values as a list of \fB(value, count)\fP tuples\(ga, or \fBNone\fP if the table is entirely distinct or if the number of distinct values is less than N (since they will already have been returned in \fBmost_common\fP) .UNINDENT .sp \fBN\fP defaults to 10, or you can pass a custom \fBN\fP using the \fBcommon_limit\fP parameter. .sp You can use the \fBvalue_truncate\fP parameter to truncate values in the \fBmost_common\fP and \fBleast_common\fP lists to a specified number of characters. .SS Adding columns .sp You can add a new column to a table using the \fB\&.add_column(col_name, col_type)\fP method: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].add_column("instagram", str) db["dogs"].add_column("weight", float) db["dogs"].add_column("dob", datetime.date) db["dogs"].add_column("image", "BLOB") db["dogs"].add_column("website") # str by default .ft P .fi .UNINDENT .UNINDENT .sp You can specify the \fBcol_type\fP argument either using a SQLite type as a string, or by directly passing a Python type e.g. \fBstr\fP or \fBfloat\fP\&. .sp The \fBcol_type\fP is optional \- if you omit it the type of \fBTEXT\fP will be used. .sp SQLite types you can specify are \fB"TEXT"\fP, \fB"INTEGER"\fP, \fB"FLOAT"\fP or \fB"BLOB"\fP\&. .sp If you pass a Python type, it will be mapped to SQLite types as shown here: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C float: "FLOAT" int: "INTEGER" bool: "INTEGER" str: "TEXT" bytes: "BLOB" datetime.datetime: "TEXT" datetime.date: "TEXT" datetime.time: "TEXT" # If numpy is installed np.int8: "INTEGER" np.int16: "INTEGER" np.int32: "INTEGER" np.int64: "INTEGER" np.uint8: "INTEGER" np.uint16: "INTEGER" np.uint32: "INTEGER" np.uint64: "INTEGER" np.float16: "FLOAT" np.float32: "FLOAT" np.float64: "FLOAT" .ft P .fi .UNINDENT .UNINDENT .sp You can also add a column that is a foreign key reference to another table using the \fBfk\fP parameter: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].add_column("species_id", fk="species") .ft P .fi .UNINDENT .UNINDENT .sp This will automatically detect the name of the primary key on the species table and use that (and its type) for the new column. .sp You can explicitly specify the column you wish to reference using \fBfk_col\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].add_column("species_id", fk="species", fk_col="ref") .ft P .fi .UNINDENT .UNINDENT .sp You can set a \fBNOT NULL DEFAULT \(aqx\(aq\fP constraint on the new column using \fBnot_null_default\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].add_column("friends_count", int, not_null_default=0) .ft P .fi .UNINDENT .UNINDENT .SS Adding columns automatically on insert/update .sp You can insert or update data that includes new columns and have the table automatically altered to fit the new schema using the \fBalter=True\fP argument. This can be passed to all four of \fB\&.insert()\fP, \fB\&.upsert()\fP, \fB\&.insert_all()\fP and \fB\&.upsert_all()\fP, or it can be passed to \fBdb.table(table_name, alter=True)\fP to enable it by default for all method calls against that table instance. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["new_table"].insert({"name": "Gareth"}) # This will throw an exception: db["new_table"].insert({"name": "Gareth", "age": 32}) # This will succeed and add a new "age" integer column: db["new_table"].insert({"name": "Gareth", "age": 32}, alter=True) # You can see confirm the new column like so: print(db["new_table"].columns_dict) # Outputs this: # {\(aqname\(aq: , \(aqage\(aq: } # This works too: new_table = db.table("new_table", alter=True) new_table.insert({"name": "Gareth", "age": 32, "shoe_size": 11}) .ft P .fi .UNINDENT .UNINDENT .SS Adding foreign key constraints .sp The SQLite \fBALTER TABLE\fP statement doesn\(aqt have the ability to add foreign key references to an existing column. .sp It\(aqs possible to add these references through very careful manipulation of SQLite\(aqs \fBsqlite_master\fP table, using \fBPRAGMA writable_schema\fP\&. .sp \fBsqlite\-utils\fP can do this for you, though there is a significant risk of data corruption if something goes wrong so it is advisable to create a fresh copy of your database file before attempting this. .sp Here\(aqs an example of this mechanism in action: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["authors"].insert_all([ {"id": 1, "name": "Sally"}, {"id": 2, "name": "Asheesh"} ], pk="id") db["books"].insert_all([ {"title": "Hedgehogs of the world", "author_id": 1}, {"title": "How to train your wolf", "author_id": 2}, ]) db["books"].add_foreign_key("author_id", "authors", "id") .ft P .fi .UNINDENT .UNINDENT .sp The \fBtable.add_foreign_key(column, other_table, other_column)\fP method takes the name of the column, the table that is being referenced and the key column within that other table. If you omit the \fBother_column\fP argument the primary key from that table will be used automatically. If you omit the \fBother_table\fP argument the table will be guessed based on some simple rules: .INDENT 0.0 .IP \(bu 2 If the column is of format \fBauthor_id\fP, look for tables called \fBauthor\fP or \fBauthors\fP .IP \(bu 2 If the column does not end in \fB_id\fP, try looking for a table with the exact name of the column or that name with an added \fBs\fP .UNINDENT .sp This method first checks that the specified foreign key references tables and columns that exist and does not clash with an existing foreign key. It will raise a \fBsqlite_utils.db.AlterError\fP exception if these checks fail. .sp To ignore the case where the key already exists, use \fBignore=True\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["books"].add_foreign_key("author_id", "authors", "id", ignore=True) .ft P .fi .UNINDENT .UNINDENT .SS Adding multiple foreign key constraints at once .sp The final step in adding a new foreign key to a SQLite database is to run \fBVACUUM\fP, to ensure the new foreign key is available in future introspection queries. .sp \fBVACUUM\fP against a large (multi\-GB) database can take several minutes or longer. If you are adding multiple foreign keys using \fBtable.add_foreign_key(...)\fP these can quickly add up. .sp Instead, you can use \fBdb.add_foreign_keys(...)\fP to add multiple foreign keys within a single transaction. This method takes a list of four\-tuples, each one specifying a \fBtable\fP, \fBcolumn\fP, \fBother_table\fP and \fBother_column\fP\&. .sp Here\(aqs an example adding two foreign keys at once: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db.add_foreign_keys([ ("dogs", "breed_id", "breeds", "id"), ("dogs", "home_town_id", "towns", "id") ]) .ft P .fi .UNINDENT .UNINDENT .sp This method runs the same checks as \fB\&.add_foreign_keys()\fP and will raise \fBsqlite_utils.db.AlterError\fP if those checks fail. .SS Adding indexes for all foreign keys .sp If you want to ensure that every foreign key column in your database has a corresponding index, you can do so like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db.index_foreign_keys() .ft P .fi .UNINDENT .UNINDENT .SS Dropping a table or view .sp You can drop a table or view using the \fB\&.drop()\fP method: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["my_table"].drop() .ft P .fi .UNINDENT .UNINDENT .sp Pass \fBignore=True\fP if you want to ignore the error caused by the table or view not existing. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["my_table"].drop(ignore=True) .ft P .fi .UNINDENT .UNINDENT .SS Transforming a table .sp The SQLite \fBALTER TABLE\fP statement is limited. It can add and drop columns and rename tables, but it cannot change column types, change \fBNOT NULL\fP status or change the primary key for a table. .sp The \fBtable.transform()\fP method can do all of these things, by implementing a multi\-step pattern \fI\%described in the SQLite documentation\fP: .INDENT 0.0 .IP 1. 3 Start a transaction .IP 2. 3 \fBCREATE TABLE tablename_new_x123\fP with the required changes .IP 3. 3 Copy the old data into the new table using \fBINSERT INTO tablename_new_x123 SELECT * FROM tablename;\fP .IP 4. 3 \fBDROP TABLE tablename;\fP .IP 5. 3 \fBALTER TABLE tablename_new_x123 RENAME TO tablename;\fP .IP 6. 3 Commit the transaction .UNINDENT .sp The \fB\&.transform()\fP method takes a number of parameters, all of which are optional. .SS Altering column types .sp To alter the type of a column, use the \fBtypes=\fP argument: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # Convert the \(aqage\(aq column to an integer, and \(aqweight\(aq to a float table.transform(types={"age": int, "weight": float}) .ft P .fi .UNINDENT .UNINDENT .sp See \fI\%Adding columns\fP for a list of available types. .SS Renaming columns .sp The \fBrename=\fP parameter can rename columns: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # Rename \(aqage\(aq to \(aqinitial_age\(aq: table.transform(rename={"age": "initial_age"}) .ft P .fi .UNINDENT .UNINDENT .SS Dropping columns .sp To drop columns, pass them in the \fBdrop=\fP set: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # Drop the \(aqage\(aq column: table.transform(drop={"age"}) .ft P .fi .UNINDENT .UNINDENT .SS Changing primary keys .sp To change the primary key for a table, use \fBpk=\fP\&. This can be passed a single column for a regular primary key, or a tuple of columns to create a compound primary key. Passing \fBpk=None\fP will remove the primary key and convert the table into a \fBrowid\fP table. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # Make \(gauser_id\(ga the new primary key table.transform(pk="user_id") .ft P .fi .UNINDENT .UNINDENT .SS Changing not null status .sp You can change the \fBNOT NULL\fP status of columns by using \fBnot_null=\fP\&. You can pass this a set of columns to make those columns \fBNOT NULL\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # Make the \(aqage\(aq and \(aqweight\(aq columns NOT NULL table.transform(not_null={"age", "weight"}) .ft P .fi .UNINDENT .UNINDENT .sp If you want to take existing \fBNOT NULL\fP columns and change them to allow null values, you can do so by passing a dictionary of true/false values instead: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # \(aqage\(aq is NOT NULL but we want to allow NULL: table.transform(not_null={"age": False}) # Make age allow NULL and switch weight to being NOT NULL: table.transform(not_null={"age": False, "weight": True}) .ft P .fi .UNINDENT .UNINDENT .SS Altering column defaults .sp The \fBdefaults=\fP parameter can be used to set or change the defaults for different columns: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # Set default age to 1: table.transform(defaults={"age": 1}) # Now remove the default from that column: table.transform(defaults={"age": None}) .ft P .fi .UNINDENT .UNINDENT .SS Changing column order .sp The \fBcolumn_order=\fP parameter can be used to change the order of the columns. If you pass the names of a subset of the columns those will go first and columns you omitted will appear in their existing order after them. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # Change column order table.transform(column_order=("name", "age", "id") .ft P .fi .UNINDENT .UNINDENT .SS Dropping foreign key constraints .sp You can use \fB\&.transform()\fP to remove foreign key constraints from a table. .sp This example drops two foreign keys \- the one from \fBplaces.country\fP to \fBcountry.id\fP and the one from \fBplaces.continent\fP to \fBcontinent.id\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["places"].transform( drop_foreign_keys=("country", "continent") ) .ft P .fi .UNINDENT .UNINDENT .SS Custom transformations with .transform_sql() .sp The \fB\&.transform()\fP method can handle most cases, but it does not automatically upgrade indexes, views or triggers associated with the table that is being transformed. .sp If you want to do something more advanced, you can call the \fBtable.transform_sql(...)\fP method with the same arguments that you would have passed to \fBtable.transform(...)\fP\&. .sp This method will return a list of SQL statements that should be executed to implement the change. You can then make modifications to that SQL \- or add additional SQL statements \- before executing it yourself. .SS Extracting columns into a separate table .sp The \fBtable.extract()\fP method can be used to extract specified columns into a separate table. .sp Imagine a \fBTrees\fP table that looks like this: .TS center; |l|l|l|. _ T{ id T} T{ TreeAddress T} T{ Species T} _ T{ 1 T} T{ 52 Vine St T} T{ Palm T} _ T{ 2 T} T{ 12 Draft St T} T{ Oak T} _ T{ 3 T} T{ 51 Dark Ave T} T{ Palm T} _ T{ 4 T} T{ 1252 Left St T} T{ Palm T} _ .TE .sp The \fBSpecies\fP column contains duplicate values. This database could be improved by extracting that column out into a separate \fBSpecies\fP table and pointing to it using a foreign key column. .sp The schema of the above table is: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CREATE TABLE [Trees] ( [id] INTEGER PRIMARY KEY, [TreeAddress] TEXT, [Species] TEXT ) .ft P .fi .UNINDENT .UNINDENT .sp Here\(aqs how to extract the \fBSpecies\fP column using \fB\&.extract()\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["Trees"].extract("Species") .ft P .fi .UNINDENT .UNINDENT .sp After running this code the table schema now looks like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CREATE TABLE "Trees" ( [id] INTEGER PRIMARY KEY, [TreeAddress] TEXT, [Species_id] INTEGER, FOREIGN KEY(Species_id) REFERENCES Species(id) ) .ft P .fi .UNINDENT .UNINDENT .sp A new \fBSpecies\fP table will have been created with the following schema: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CREATE TABLE [Species] ( [id] INTEGER PRIMARY KEY, [Species] TEXT ) .ft P .fi .UNINDENT .UNINDENT .sp The \fB\&.extract()\fP method defaults to creating a table with the same name as the column that was extracted, and adding a foreign key column called \fBtablename_id\fP\&. .sp You can specify a custom table name using \fBtable=\fP, and a custom foreign key name using \fBfk_column=\fP\&. This example creates a table called \fBtree_species\fP and a foreign key column called \fBtree_species_id\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["Trees"].extract("Species", table="tree_species", fk_column="tree_species_id") .ft P .fi .UNINDENT .UNINDENT .sp The resulting schema looks like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CREATE TABLE "Trees" ( [id] INTEGER PRIMARY KEY, [TreeAddress] TEXT, [tree_species_id] INTEGER, FOREIGN KEY(tree_species_id) REFERENCES tree_species(id) ) CREATE TABLE [tree_species] ( [id] INTEGER PRIMARY KEY, [Species] TEXT ) .ft P .fi .UNINDENT .UNINDENT .sp You can also extract multiple columns into the same external table. Say for example you have a table like this: .TS center; |l|l|l|l|. _ T{ id T} T{ TreeAddress T} T{ CommonName T} T{ LatinName T} _ T{ 1 T} T{ 52 Vine St T} T{ Palm T} T{ Arecaceae T} _ T{ 2 T} T{ 12 Draft St T} T{ Oak T} T{ Quercus T} _ T{ 3 T} T{ 51 Dark Ave T} T{ Palm T} T{ Arecaceae T} _ T{ 4 T} T{ 1252 Left St T} T{ Palm T} T{ Arecaceae T} _ .TE .sp You can pass \fB["CommonName", "LatinName"]\fP to \fB\&.extract()\fP to extract both of those columns: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["Trees"].extract(["CommonName", "LatinName"]) .ft P .fi .UNINDENT .UNINDENT .sp This produces the following schema: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CREATE TABLE "Trees" ( [id] INTEGER PRIMARY KEY, [TreeAddress] TEXT, [CommonName_LatinName_id] INTEGER, FOREIGN KEY(CommonName_LatinName_id) REFERENCES CommonName_LatinName(id) ) CREATE TABLE [CommonName_LatinName] ( [id] INTEGER PRIMARY KEY, [CommonName] TEXT, [LatinName] TEXT ) .ft P .fi .UNINDENT .UNINDENT .sp The table name \fBCommonName_LatinName\fP is derived from the extract columns. You can use \fBtable=\fP and \fBfk_column=\fP to specify custom names like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["Trees"].extract(["CommonName", "LatinName"], table="Species", fk_column="species_id") .ft P .fi .UNINDENT .UNINDENT .sp This produces the following schema: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CREATE TABLE "Trees" ( [id] INTEGER PRIMARY KEY, [TreeAddress] TEXT, [species_id] INTEGER, FOREIGN KEY(species_id) REFERENCES Species(id) ) CREATE TABLE [Species] ( [id] INTEGER PRIMARY KEY, [CommonName] TEXT, [LatinName] TEXT ) .ft P .fi .UNINDENT .UNINDENT .sp You can use the \fBrename=\fP argument to rename columns in the lookup table. To create a \fBSpecies\fP table with columns called \fBname\fP and \fBlatin\fP you can do this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["Trees"].extract( ["CommonName", "LatinName"], table="Species", fk_column="species_id", rename={"CommonName": "name", "LatinName": "latin"} ) .ft P .fi .UNINDENT .UNINDENT .sp This produces a lookup table like so: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CREATE TABLE [Species] ( [id] INTEGER PRIMARY KEY, [name] TEXT, [latin] TEXT ) .ft P .fi .UNINDENT .UNINDENT .SS Setting an ID based on the hash of the row contents .sp Sometimes you will find yourself working with a dataset that includes rows that do not have a provided obvious ID, but where you would like to assign one so that you can later upsert into that table without creating duplicate records. .sp In these cases, a useful technique is to create an ID that is derived from the sha1 hash of the row contents. .sp \fBsqlite\-utils\fP can do this for you using the \fBhash_id=\fP option. For example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db = sqlite_utils.Database("dogs.db") db["dogs"].upsert({"name": "Cleo", "twitter": "cleopaws"}, hash_id="id") print(list(db["dogs])) .ft P .fi .UNINDENT .UNINDENT .sp Outputs: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C [{\(aqid\(aq: \(aqf501265970505d9825d8d9f590bfab3519fb20b1\(aq, \(aqname\(aq: \(aqCleo\(aq, \(aqtwitter\(aq: \(aqcleopaws\(aq}] .ft P .fi .UNINDENT .UNINDENT .sp If you are going to use that ID straight away, you can access it using \fBlast_pk\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C dog_id = db["dogs"].upsert({ "name": "Cleo", "twitter": "cleopaws" }, hash_id="id").last_pk # dog_id is now "f501265970505d9825d8d9f590bfab3519fb20b1" .ft P .fi .UNINDENT .UNINDENT .sp The hash will be created using all of the column values. To create a hash using a subset of the columns, pass the \fBhash_id_columns=\fP parameter: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].upsert( {"name": "Cleo", "twitter": "cleopaws", "age": 7}, hash_id_columns=("name", "twitter") ) .ft P .fi .UNINDENT .UNINDENT .sp The \fBhash_id=\fP parameter is optional if you specify \fBhash_id_columns=\fP \- it will default to putting the hash in a column called \fBid\fP\&. .sp You can manually calculate these hashes using the \fI\%hash_record(record, keys=...)\fP utility function. .SS Creating views .sp The \fB\&.create_view()\fP method on the database class can be used to create a view: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db.create_view("good_dogs", """ select * from dogs where is_good_dog = 1 """) .ft P .fi .UNINDENT .UNINDENT .sp This will raise a \fBsqlite_utils.utils.OperationalError\fP if a view with that name already exists. .sp You can pass \fBignore=True\fP to silently ignore an existing view and do nothing, or \fBreplace=True\fP to replace an existing view with a new definition if your select statement differs from the current view: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db.create_view("good_dogs", """ select * from dogs where is_good_dog = 1 """, replace=True) .ft P .fi .UNINDENT .UNINDENT .SS Storing JSON .sp SQLite has \fI\%excellent JSON support\fP, and \fBsqlite\-utils\fP can help you take advantage of this: if you attempt to insert a value that can be represented as a JSON list or dictionary, \fBsqlite\-utils\fP will create TEXT column and store your data as serialized JSON. This means you can quickly store even complex data structures in SQLite and query them using JSON features. .sp For example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["niche_museums"].insert({ "name": "The Bigfoot Discovery Museum", "url": "http://bigfootdiscoveryproject.com/" "hours": { "Monday": [11, 18], "Wednesday": [11, 18], "Thursday": [11, 18], "Friday": [11, 18], "Saturday": [11, 18], "Sunday": [11, 18] }, "address": { "streetAddress": "5497 Highway 9", "addressLocality": "Felton, CA", "postalCode": "95018" } }) db.execute(""" select json_extract(address, \(aq$.addressLocality\(aq) from niche_museums """).fetchall() # Returns [(\(aqFelton, CA\(aq,)] .ft P .fi .UNINDENT .UNINDENT .SS Converting column values using SQL functions .sp Sometimes it can be useful to run values through a SQL function prior to inserting them. A simple example might be converting a value to upper case while it is being inserted. .sp The \fBconversions={...}\fP parameter can be used to specify custom SQL to be used as part of a \fBINSERT\fP or \fBUPDATE\fP SQL statement. .sp You can specify an upper case conversion for a specific column like so: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["example"].insert({ "name": "The Bigfoot Discovery Museum" }, conversions={"name": "upper(?)"}) # list(db["example"].rows) now returns: # [{\(aqname\(aq: \(aqTHE BIGFOOT DISCOVERY MUSEUM\(aq}] .ft P .fi .UNINDENT .UNINDENT .sp The dictionary key is the column name to be converted. The value is the SQL fragment to use, with a \fB?\fP placeholder for the original value. .sp A more useful example: if you are working with \fI\%SpatiaLite\fP you may find yourself wanting to create geometry values from a WKT value. Code to do that could look like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import sqlite3 import sqlite_utils from shapely.geometry import shape import httpx db = sqlite_utils.Database("places.db") # Initialize SpatiaLite db.init_spatialite() # Use sqlite\-utils to create a places table places = db["places"].create({"id": int, "name": str}) # Add a SpatiaLite \(aqgeometry\(aq column places.add_geometry_column("geometry", "MULTIPOLYGON") # Fetch some GeoJSON from Who\(aqs On First: geojson = httpx.get( "https://raw.githubusercontent.com/whosonfirst\-data/" "whosonfirst\-data\-admin\-gb/master/data/404/227/475/404227475.geojson" ).json() # Convert to "Well Known Text" format using shapely wkt = shape(geojson["geometry"]).wkt # Insert the record, converting the WKT to a SpatiaLite geometry: db["places"].insert( {"name": "Wales", "geometry": wkt}, conversions={"geometry": "GeomFromText(?, 4326)"}, ) .ft P .fi .UNINDENT .UNINDENT .sp This example uses gographical data from [Who\(aqs On First](\fI\%https://whosonfirst.org/\fP) and depends on the [Shapely](\fI\%https://shapely.readthedocs.io/en/stable/manual.html\fP) and [HTTPX](\fI\%https://www.python\-httpx.org/\fP) Python libraries. .SS Checking the SQLite version .sp The \fBdb.sqlite_version\fP property returns a tuple of integers representing the version of SQLite used for that database object: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db.sqlite_version (3, 36, 0) .ft P .fi .UNINDENT .UNINDENT .SS Introspecting tables and views .sp If you have loaded an existing table or view, you can use introspection to find out more about it: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db["PlantType"]
.ft P .fi .UNINDENT .UNINDENT .SS \&.exists() .sp The \fB\&.exists()\fP method can be used to find out if a table exists or not: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db["PlantType"].exists() True >>> db["PlantType2"].exists() False .ft P .fi .UNINDENT .UNINDENT .SS \&.count .sp The \fB\&.count\fP property shows the current number of rows (\fBselect count(*) from table\fP): .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db["PlantType"].count 3 >>> db["Street_Tree_List"].count 189144 .ft P .fi .UNINDENT .UNINDENT .sp This property will take advantage of \fI\%Cached table counts using triggers\fP if the \fBuse_counts_table\fP property is set on the database. You can avoid that optimization entirely by calling \fBtable.count_where()\fP instead of accessing the property. .SS \&.columns .sp The \fB\&.columns\fP property shows the columns in the table or view. It returns a list of \fBColumn(cid, name, type, notnull, default_value, is_pk)\fP named tuples. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db["PlantType"].columns [Column(cid=0, name=\(aqid\(aq, type=\(aqINTEGER\(aq, notnull=0, default_value=None, is_pk=1), Column(cid=1, name=\(aqvalue\(aq, type=\(aqTEXT\(aq, notnull=0, default_value=None, is_pk=0)] .ft P .fi .UNINDENT .UNINDENT .SS \&.columns_dict .sp The \fB\&.columns_dict\fP property returns a dictionary version of the columns with just the names and Python types: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db["PlantType"].columns_dict {\(aqid\(aq: , \(aqvalue\(aq: } .ft P .fi .UNINDENT .UNINDENT .SS \&.default_values .sp The \fB\&.default_values\fP property returns a dictionary of default values for each column that has a default: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db["table_with_defaults"].default_values {\(aqscore\(aq: 5} .ft P .fi .UNINDENT .UNINDENT .SS \&.pks .sp The \fB\&.pks\fP property returns a list of strings naming the primary key columns for the table: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db["PlantType"].pks [\(aqid\(aq] .ft P .fi .UNINDENT .UNINDENT .sp If a table has no primary keys but is a \fI\%rowid table\fP, this property will return \fB[\(aqrowid\(aq]\fP\&. .SS \&.use_rowid .sp Almost all SQLite tables have a \fBrowid\fP column, but a table with no explicitly defined primary keys must use that \fBrowid\fP as the primary key for identifying individual rows. The \fB\&.use_rowid\fP property checks to see if a table needs to use the \fBrowid\fP in this way \- it returns \fBTrue\fP if the table has no explicitly defined primary keys and \fBFalse\fP otherwise. .sp .nf .ft C >>> db["PlantType"].use_rowid False .ft P .fi .SS \&.foreign_keys .sp The \fB\&.foreign_keys\fP property returns any foreign key relationships for the table, as a list of \fBForeignKey(table, column, other_table, other_column)\fP named tuples. It is not available on views. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db["Street_Tree_List"].foreign_keys [ForeignKey(table=\(aqStreet_Tree_List\(aq, column=\(aqqLegalStatus\(aq, other_table=\(aqqLegalStatus\(aq, other_column=\(aqid\(aq), ForeignKey(table=\(aqStreet_Tree_List\(aq, column=\(aqqCareAssistant\(aq, other_table=\(aqqCareAssistant\(aq, other_column=\(aqid\(aq), ForeignKey(table=\(aqStreet_Tree_List\(aq, column=\(aqqSiteInfo\(aq, other_table=\(aqqSiteInfo\(aq, other_column=\(aqid\(aq), ForeignKey(table=\(aqStreet_Tree_List\(aq, column=\(aqqSpecies\(aq, other_table=\(aqqSpecies\(aq, other_column=\(aqid\(aq), ForeignKey(table=\(aqStreet_Tree_List\(aq, column=\(aqqCaretaker\(aq, other_table=\(aqqCaretaker\(aq, other_column=\(aqid\(aq), ForeignKey(table=\(aqStreet_Tree_List\(aq, column=\(aqPlantType\(aq, other_table=\(aqPlantType\(aq, other_column=\(aqid\(aq)] .ft P .fi .UNINDENT .UNINDENT .SS \&.schema .sp The \fB\&.schema\fP property outputs the table\(aqs schema as a SQL string: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> print(db["Street_Tree_List"].schema) CREATE TABLE "Street_Tree_List" ( "TreeID" INTEGER, "qLegalStatus" INTEGER, "qSpecies" INTEGER, "qAddress" TEXT, "SiteOrder" INTEGER, "qSiteInfo" INTEGER, "PlantType" INTEGER, "qCaretaker" INTEGER, "qCareAssistant" INTEGER, "PlantDate" TEXT, "DBH" INTEGER, "PlotSize" TEXT, "PermitNotes" TEXT, "XCoord" REAL, "YCoord" REAL, "Latitude" REAL, "Longitude" REAL, "Location" TEXT , FOREIGN KEY ("PlantType") REFERENCES [PlantType](id), FOREIGN KEY ("qCaretaker") REFERENCES [qCaretaker](id), FOREIGN KEY ("qSpecies") REFERENCES [qSpecies](id), FOREIGN KEY ("qSiteInfo") REFERENCES [qSiteInfo](id), FOREIGN KEY ("qCareAssistant") REFERENCES [qCareAssistant](id), FOREIGN KEY ("qLegalStatus") REFERENCES [qLegalStatus](id)) .ft P .fi .UNINDENT .UNINDENT .SS \&.strict .sp The \fB\&.strict\fP property identifies if the table is a \fI\%SQLite STRICT table\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db["ny_times_us_counties"].strict False .ft P .fi .UNINDENT .UNINDENT .SS \&.indexes .sp The \fB\&.indexes\fP property returns all indexes created for a table, as a list of \fBIndex(seq, name, unique, origin, partial, columns)\fP named tuples. It is not available on views. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db["Street_Tree_List"].indexes [Index(seq=0, name=\(aq"Street_Tree_List_qLegalStatus"\(aq, unique=0, origin=\(aqc\(aq, partial=0, columns=[\(aqqLegalStatus\(aq]), Index(seq=1, name=\(aq"Street_Tree_List_qCareAssistant"\(aq, unique=0, origin=\(aqc\(aq, partial=0, columns=[\(aqqCareAssistant\(aq]), Index(seq=2, name=\(aq"Street_Tree_List_qSiteInfo"\(aq, unique=0, origin=\(aqc\(aq, partial=0, columns=[\(aqqSiteInfo\(aq]), Index(seq=3, name=\(aq"Street_Tree_List_qSpecies"\(aq, unique=0, origin=\(aqc\(aq, partial=0, columns=[\(aqqSpecies\(aq]), Index(seq=4, name=\(aq"Street_Tree_List_qCaretaker"\(aq, unique=0, origin=\(aqc\(aq, partial=0, columns=[\(aqqCaretaker\(aq]), Index(seq=5, name=\(aq"Street_Tree_List_PlantType"\(aq, unique=0, origin=\(aqc\(aq, partial=0, columns=[\(aqPlantType\(aq])] .ft P .fi .UNINDENT .UNINDENT .SS \&.xindexes .sp The \fB\&.xindexes\fP property returns more detailed information about the indexes on the table, using the SQLite \fI\%PRAGMA index_xinfo()\fP mechanism. It returns a list of \fBXIndex(name, columns)\fP named tuples, where \fBcolumns\fP is a list of \fBXIndexColumn(seqno, cid, name, desc, coll, key)\fP named tuples. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db["ny_times_us_counties"].xindexes [ XIndex( name=\(aqidx_ny_times_us_counties_date\(aq, columns=[ XIndexColumn(seqno=0, cid=0, name=\(aqdate\(aq, desc=1, coll=\(aqBINARY\(aq, key=1), XIndexColumn(seqno=1, cid=\-1, name=None, desc=0, coll=\(aqBINARY\(aq, key=0) ] ), XIndex( name=\(aqidx_ny_times_us_counties_fips\(aq, columns=[ XIndexColumn(seqno=0, cid=3, name=\(aqfips\(aq, desc=0, coll=\(aqBINARY\(aq, key=1), XIndexColumn(seqno=1, cid=\-1, name=None, desc=0, coll=\(aqBINARY\(aq, key=0) ] ) ] .ft P .fi .UNINDENT .UNINDENT .SS \&.triggers .sp The \fB\&.triggers\fP property lists database triggers. It can be used on both database and table objects. It returns a list of \fBTrigger(name, table, sql)\fP named tuples. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db["authors"].triggers [Trigger(name=\(aqauthors_ai\(aq, table=\(aqauthors\(aq, sql=\(aqCREATE TRIGGER [authors_ai] AFTER INSERT...\(aq), Trigger(name=\(aqauthors_ad\(aq, table=\(aqauthors\(aq, sql="CREATE TRIGGER [authors_ad] AFTER DELETE..."), Trigger(name=\(aqauthors_au\(aq, table=\(aqauthors\(aq, sql="CREATE TRIGGER [authors_au] AFTER UPDATE")] >>> db.triggers \&... similar output to db["authors"].triggers .ft P .fi .UNINDENT .UNINDENT .SS \&.triggers_dict .sp The \fB\&.triggers_dict\fP property returns the triggers for that table as a dictionary mapping their names to their SQL definitions. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db["authors"].triggers_dict {\(aqauthors_ai\(aq: \(aqCREATE TRIGGER [authors_ai] AFTER INSERT...\(aq, \(aqauthors_ad\(aq: \(aqCREATE TRIGGER [authors_ad] AFTER DELETE...\(aq, \(aqauthors_au\(aq: \(aqCREATE TRIGGER [authors_au] AFTER UPDATE\(aq} .ft P .fi .UNINDENT .UNINDENT .sp The same property exists on the database, and will return all triggers across all tables: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db.triggers_dict {\(aqauthors_ai\(aq: \(aqCREATE TRIGGER [authors_ai] AFTER INSERT...\(aq, \(aqauthors_ad\(aq: \(aqCREATE TRIGGER [authors_ad] AFTER DELETE...\(aq, \(aqauthors_au\(aq: \(aqCREATE TRIGGER [authors_au] AFTER UPDATE\(aq} .ft P .fi .UNINDENT .UNINDENT .SS \&.detect_fts() .sp The \fBdetect_fts()\fP method returns the associated SQLite FTS table name, if one exists for this table. If the table has not been configured for full\-text search it returns \fBNone\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db["authors"].detect_fts() "authors_fts" .ft P .fi .UNINDENT .UNINDENT .SS \&.virtual_table_using .sp The \fB\&.virtual_table_using\fP property reveals if a table is a virtual table. It returns \fBNone\fP for regular tables and the upper case version of the type of virtual table otherwise. For example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db["authors"].enable_fts(["name"]) >>> db["authors_fts"].virtual_table_using "FTS5" .ft P .fi .UNINDENT .UNINDENT .SS \&.has_counts_triggers .sp The \fB\&.has_counts_triggers\fP property shows if a table has been configured with triggers for updating a \fB_counts\fP table, as described in \fI\%Cached table counts using triggers\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db["authors"].has_counts_triggers False >>> db["authors"].enable_counts() >>> db["authors"].has_counts_triggers True .ft P .fi .UNINDENT .UNINDENT .SS Full\-text search .sp SQLite includes bundled extensions that implement \fI\%powerful full\-text search\fP\&. .SS Enabling full\-text search for a table .sp You can enable full\-text search on a table using \fB\&.enable_fts(columns)\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].enable_fts(["name", "twitter"]) .ft P .fi .UNINDENT .UNINDENT .sp You can then run searches using the \fB\&.search()\fP method: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C rows = list(db["dogs"].search("cleo")) .ft P .fi .UNINDENT .UNINDENT .sp This method returns a generator that can be looped over to get dictionaries for each row, similar to \fI\%Listing rows\fP\&. .sp If you insert additional records into the table you will need to refresh the search index using \fBpopulate_fts()\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].insert({ "id": 2, "name": "Marnie", "twitter": "MarnieTheDog", "age": 16, "is_good_dog": True, }, pk="id") db["dogs"].populate_fts(["name", "twitter"]) .ft P .fi .UNINDENT .UNINDENT .sp A better solution is to use database triggers. You can set up database triggers to automatically update the full\-text index using \fBcreate_triggers=True\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].enable_fts(["name", "twitter"], create_triggers=True) .ft P .fi .UNINDENT .UNINDENT .sp \fB\&.enable_fts()\fP defaults to using \fI\%FTS5\fP\&. If you wish to use \fI\%FTS4\fP instead, use the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].enable_fts(["name", "twitter"], fts_version="FTS4") .ft P .fi .UNINDENT .UNINDENT .sp You can customize the tokenizer configured for the table using the \fBtokenize=\fP parameter. For example, to enable Porter stemming, where English words like "running" will match stemmed alternatives such as "run", use \fBtokenize="porter"\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["articles"].enable_fts(["headline", "body"], tokenize="porter") .ft P .fi .UNINDENT .UNINDENT .sp The SQLite documentation has more on \fI\%FTS5 tokenizers\fP and \fI\%FTS4 tokenizers\fP\&. \fBporter\fP is a valid option for both. .sp If you attempt to configure a FTS table where one already exists, a \fBsqlite3.OperationalError\fP exception will be raised. .sp You can replace the existing table with a new configuration using \fBreplace=True\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["articles"].enable_fts(["headline"], tokenize="porter", replace=True) .ft P .fi .UNINDENT .UNINDENT .sp This will have no effect if the FTS table already exists, otherwise it will drop and recreate the table with the new settings. This takes into consideration the columns, the tokenizer, the FTS version used and whether or not the table has triggers. .sp To remove the FTS tables and triggers you created, use the \fBdisable_fts()\fP table method: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].disable_fts() .ft P .fi .UNINDENT .UNINDENT .SS Quoting characters for use in search .sp SQLite supports \fI\%advanced search query syntax\fP\&. In some situations you may wish to disable this, since characters such as \fB\&.\fP may have special meaning that causes errors when searching for strings provided by your users. .sp The \fBdb.quote_fts(query)\fP method returns the query with SQLite full\-text search quoting applied such that the query should be safe to use in a search: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db.quote_fts("Search term.") # Returns: \(aq"Search" "term."\(aq .ft P .fi .UNINDENT .UNINDENT .SS Searching with table.search() .sp The \fBtable.search(q)\fP method returns a generator over Python dictionaries representing rows that match the search phrase \fBq\fP, ordered by relevance with the most relevant results first. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C for article in db["articles"].search("jquery"): print(article) .ft P .fi .UNINDENT .UNINDENT .sp The \fB\&.search()\fP method also accepts the following optional parameters: .INDENT 0.0 .TP .B \fBorder_by\fP string The column to sort by. Defaults to relevance score. Can optionally include a \fBdesc\fP, e.g. \fBrowid desc\fP\&. .TP .B \fBcolumns\fP array of strings Columns to return. Defaults to all columns. .TP .B \fBlimit\fP integer Number of results to return. Defaults to all results. .TP .B \fBoffset\fP integer Offset to use along side the limit parameter. .TP .B \fBwhere\fP string Extra SQL fragment for the WHERE clause .TP .B \fBwhere_args\fP dictionary Arguments to use for \fB:param\fP placeholders in the extra WHERE clause .TP .B \fBquote\fP bool Apply \fI\%FTS quoting rules\fP to the search query, disabling advanced query syntax in a way that avoids surprising errors. .UNINDENT .sp To return just the title and published columns for three matches for \fB"dog"\fP where the \fBid\fP is greater than 10 ordered by \fBpublished\fP with the most recent first, use the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C for article in db["articles"].search( "dog", order_by="published desc", limit=3, where="id > :min_id", where_args={"min_id": 10}, columns=["title", "published"] ): print(article) .ft P .fi .UNINDENT .UNINDENT .SS Building SQL queries with table.search_sql() .sp You can generate the SQL query that would be used for a search using the \fBtable.search_sql()\fP method. It takes the same arguments as \fBtable.search()\fP, with the exception of the search query and the \fBwhere_args\fP parameter, since those should be provided when the returned SQL is executed. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C print(db["articles"].search_sql(columns=["title", "author"])) .ft P .fi .UNINDENT .UNINDENT .sp Outputs: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C with original as ( select rowid, [title], [author] from [articles] ) select [original].[title], [original].[author] from [original] join [articles_fts] on [original].rowid = [articles_fts].rowid where [articles_fts] match :query order by [articles_fts].rank .ft P .fi .UNINDENT .UNINDENT .sp This method detects if a SQLite table uses FTS4 or FTS5, and outputs the correct SQL for ordering by relevance depending on the search type. .sp The FTS4 output looks something like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C with original as ( select rowid, [title], [author] from [articles] ) select [original].[title], [original].[author] from [original] join [articles_fts] on [original].rowid = [articles_fts].rowid where [articles_fts] match :query order by rank_bm25(matchinfo([articles_fts], \(aqpcnalx\(aq)) .ft P .fi .UNINDENT .UNINDENT .sp This uses the \fBrank_bm25()\fP custom SQL function from \fI\%sqlite\-fts4\fP\&. You can register that custom function against a \fBDatabase\fP connection using this method: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db.register_fts4_bm25() .ft P .fi .UNINDENT .UNINDENT .SS Rebuilding a full\-text search table .sp You can rebuild a table using the \fBtable.rebuild_fts()\fP method. This is useful for if the table configuration changes or the indexed data has become corrupted in some way. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].rebuild_fts() .ft P .fi .UNINDENT .UNINDENT .sp This method can be called on a table that has been configured for full\-text search \- \fBdogs\fP in this instance \- or directly on a \fB_fts\fP table: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs_fts"].rebuild_fts() .ft P .fi .UNINDENT .UNINDENT .sp This runs the following SQL: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C INSERT INTO dogs_fts (dogs_fts) VALUES ("rebuild"); .ft P .fi .UNINDENT .UNINDENT .SS Optimizing a full\-text search table .sp Once you have populated a FTS table you can optimize it to dramatically reduce its size like so: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].optimize() .ft P .fi .UNINDENT .UNINDENT .sp This runs the following SQL: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C INSERT INTO dogs_fts (dogs_fts) VALUES ("optimize"); .ft P .fi .UNINDENT .UNINDENT .SS Cached table counts using triggers .sp The \fBselect count(*)\fP query in SQLite requires a full scan of the primary key index, and can take an increasingly long time as the table grows larger. .sp The \fBtable.enable_counts()\fP method can be used to configure triggers to continuously update a record in a \fB_counts\fP table. This value can then be used to quickly retrieve the count of rows in the associated table. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].enable_counts() .ft P .fi .UNINDENT .UNINDENT .sp This will create the \fB_counts\fP table if it does not already exist, with the following schema: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CREATE TABLE [_counts] ( [table] TEXT PRIMARY KEY, [count] INTEGER DEFAULT 0 ) .ft P .fi .UNINDENT .UNINDENT .sp You can enable cached counts for every table in a database (except for virtual tables and the \fB_counts\fP table itself) using the database \fBenable_counts()\fP method: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db.enable_counts() .ft P .fi .UNINDENT .UNINDENT .sp Once enabled, table counts will be stored in the \fB_counts\fP table. The count records will be automatically kept up\-to\-date by the triggers when rows are added or deleted to the table. .sp To access these counts you can query the \fB_counts\fP table directly or you can use the \fBdb.cached_counts()\fP method. This method returns a dictionary mapping tables to their counts: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db.cached_counts() {\(aqglobal\-power\-plants\(aq: 33643, \(aqglobal\-power\-plants_fts_data\(aq: 136, \(aqglobal\-power\-plants_fts_idx\(aq: 199, \(aqglobal\-power\-plants_fts_docsize\(aq: 33643, \(aqglobal\-power\-plants_fts_config\(aq: 1} .ft P .fi .UNINDENT .UNINDENT .sp You can pass a list of table names to this method to retrieve just those counts: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db.cached_counts(["global\-power\-plants"]) {\(aqglobal\-power\-plants\(aq: 33643} .ft P .fi .UNINDENT .UNINDENT .sp The \fBtable.count\fP property executes a \fBselect count(*)\fP query by default, unless the \fBdb.use_counts_table\fP property is set to \fBTrue\fP\&. .sp You can set \fBuse_counts_table\fP to \fBTrue\fP when you instantiate the database object: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db = Database("global\-power\-plants.db", use_counts_table=True) .ft P .fi .UNINDENT .UNINDENT .sp If the property is \fBTrue\fP any calls to the \fBtable.count\fP property will first attempt to find the cached count in the \fB_counts\fP table, and fall back on a \fBcount(*)\fP query if the value is not available or the table is missing. .sp Calling the \fB\&.enable_counts()\fP method on a database or table object will set \fBuse_counts_table\fP to \fBTrue\fP for the lifetime of that database object. .sp If the \fB_counts\fP table ever becomes out\-of\-sync with the actual table counts you can repair it using the \fB\&.reset_counts()\fP method: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db.reset_counts() .ft P .fi .UNINDENT .UNINDENT .SS Creating indexes .sp You can create an index on a table using the \fB\&.create_index(columns)\fP method. The method takes a list of columns: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].create_index(["is_good_dog"]) .ft P .fi .UNINDENT .UNINDENT .sp By default the index will be named \fBidx_{table\-name}_{columns}\fP\&. If you pass \fBfind_unique_name=True\fP and the automatically derived name already exists, an available name will be found by incrementing a suffix number, for example \fBidx_items_title_2\fP\&. .sp You can customize the name of the created index by passing the \fBindex_name\fP parameter: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].create_index( ["is_good_dog", "age"], index_name="good_dogs_by_age" ) .ft P .fi .UNINDENT .UNINDENT .sp To create an index in descending order for a column, wrap the column name in \fBdb.DescIndex()\fP like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from sqlite_utils.db import DescIndex db["dogs"].create_index( ["is_good_dog", DescIndex("age")], index_name="good_dogs_by_age" ) .ft P .fi .UNINDENT .UNINDENT .sp You can create a unique index by passing \fBunique=True\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].create_index(["name"], unique=True) .ft P .fi .UNINDENT .UNINDENT .sp Use \fBif_not_exists=True\fP to do nothing if an index with that name already exists. .sp Pass \fBanalyze=True\fP to run \fBANALYZE\fP against the new index after creating it. .SS Optimizing index usage with ANALYZE .sp The \fI\%SQLite ANALYZE command\fP builds a table of statistics which the query planner can use to make better decisions about which indexes to use for a given query. .sp You should run \fBANALYZE\fP if your database is large and you do not think your indexes are being efficiently used. .sp To run \fBANALYZE\fP against every index in a database, use this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db.analyze() .ft P .fi .UNINDENT .UNINDENT .sp To run it just against a specific named index, pass the name of the index to that method: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db.analyze("idx_countries_country_name") .ft P .fi .UNINDENT .UNINDENT .sp To run against all indexes attached to a specific table, you can either pass the table name to \fBdb.analyze(...)\fP or you can call the method directly on the table, like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["dogs"].analyze() .ft P .fi .UNINDENT .UNINDENT .SS Vacuum .sp You can optimize your database by running VACUUM against it like so: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Database("my_database.db").vacuum() .ft P .fi .UNINDENT .UNINDENT .SS WAL mode .sp You can enable \fI\%Write\-Ahead Logging\fP for a database with \fB\&.enable_wal()\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Database("my_database.db").enable_wal() .ft P .fi .UNINDENT .UNINDENT .sp You can disable WAL mode using \fB\&.disable_wal()\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Database("my_database.db").disable_wal() .ft P .fi .UNINDENT .UNINDENT .sp You can check the current journal mode for a database using the \fBjournal_mode\fP property: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C journal_mode = Database("my_database.db").journal_mode .ft P .fi .UNINDENT .UNINDENT .sp This will usually be \fBwal\fP or \fBdelete\fP (meaning WAL is disabled), but can have other values \- see the \fI\%PRAGMA journal_mode\fP documentation. .SS Suggesting column types .sp When you create a new table for a list of inserted or upserted Python dictionaries, those methods detect the correct types for the database columns based on the data you pass in. .sp In some situations you may need to intervene in this process, to customize the columns that are being created in some way \- see \fI\%Explicitly creating a table\fP\&. .sp That table \fB\&.create()\fP method takes a dictionary mapping column names to the Python type they should store: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["cats"].create({ "id": int, "name": str, "weight": float, }) .ft P .fi .UNINDENT .UNINDENT .sp You can use the \fBsuggest_column_types()\fP helper function to derive a dictionary of column names and types from a list of records, suitable to be passed to \fBtable.create()\fP\&. .sp For example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from sqlite_utils import Database, suggest_column_types cats = [{ "id": 1, "name": "Snowflake" }, { "id": 2, "name": "Crabtree", "age": 4 }] types = suggest_column_types(cats) # types now looks like this: # {"id": , # "name": , # "age": } # Manually add an extra field: types["thumbnail"] = bytes # types now looks like this: # {"id": , # "name": , # "age": , # "thumbnail": } # Create the table db = Database("cats.db") db["cats"].create(types, pk="id") # Insert the records db["cats"].insert_all(cats) # list(db["cats"].rows) now returns: # [{"id": 1, "name": "Snowflake", "age": None, "thumbnail": None} # {"id": 2, "name": "Crabtree", "age": 4, "thumbnail": None}] # The table schema looks like this: # print(db["cats"].schema) # CREATE TABLE [cats] ( # [id] INTEGER PRIMARY KEY, # [name] TEXT, # [age] INTEGER, # [thumbnail] BLOB # ) .ft P .fi .UNINDENT .UNINDENT .SS Registering custom SQL functions .sp SQLite supports registering custom SQL functions written in Python. The \fBdb.register_function()\fP method lets you register these functions, and keeps track of functions that have already been registered. .sp If you use it as a method it will automatically detect the name and number of arguments needed by the function: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from sqlite_utils import Database db = Database(memory=True) def reverse_string(s): return "".join(reversed(list(s))) db.register_function(reverse_string) print(db.execute(\(aqselect reverse_string("hello")\(aq).fetchone()[0]) # This prints "olleh" .ft P .fi .UNINDENT .UNINDENT .sp You can also use the method as a function decorator like so: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C @db.register_function def reverse_string(s): return "".join(reversed(list(s))) print(db.execute(\(aqselect reverse_string("hello")\(aq).fetchone()[0]) .ft P .fi .UNINDENT .UNINDENT .sp By default, the name of the Python function will be used as the name of the SQL function. You can customize this with the \fBname=\fP keyword argument: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C @db.register_function(name="rev") def reverse_string(s): return "".join(reversed(list(s))) print(db.execute(\(aqselect rev("hello")\(aq).fetchone()[0]) .ft P .fi .UNINDENT .UNINDENT .sp Python 3.8 added the ability to register \fI\%deterministic SQLite functions\fP, allowing you to indicate that a function will return the exact same result for any given inputs and hence allowing SQLite to apply some performance optimizations. You can mark a function as deterministic using \fBdeterministic=True\fP, like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C @db.register_function(deterministic=True) def reverse_string(s): return "".join(reversed(list(s))) .ft P .fi .UNINDENT .UNINDENT .sp If you run this on a version of Python prior to 3.8 your code will still work, but the \fBdeterministic=True\fP parameter will be ignored. .sp By default registering a function with the same name and number of arguments will have no effect \- the \fBDatabase\fP instance keeps track of functions that have already been registered and skips registering them if \fB@db.register_function\fP is called a second time. .sp If you want to deliberately replace the registered function with a new implementation, use the \fBreplace=True\fP argument: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C @db.register_function(deterministic=True, replace=True) def reverse_string(s): return s[::\-1] .ft P .fi .UNINDENT .UNINDENT .sp Exceptions that occur inside a user\-defined function default to returning the following error: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Unexpected error: user\-defined function raised exception .ft P .fi .UNINDENT .UNINDENT .sp You can cause \fBsqlite3\fP to return more useful errors, including the traceback from the custom function, by executing the following before your custom functions are executed: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from sqlite_utils.utils import sqlite3 sqlite3.enable_callback_tracebacks(True) .ft P .fi .UNINDENT .UNINDENT .SS Quoting strings for use in SQL .sp In almost all cases you should pass values to your SQL queries using the optional \fBparameters\fP argument to \fBdb.query()\fP, as described in \fI\%Passing parameters\fP\&. .sp If that option isn\(aqt relevant to your use\-case you can to quote a string for use with SQLite using the \fBdb.quote()\fP method, like so: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> db = Database(memory=True) >>> db.quote("hello") "\(aqhello\(aq" >>> db.quote("hello\(aqthis\(aqhas\(aqquotes") "\(aqhello\(aq\(aqthis\(aq\(aqhas\(aq\(aqquotes\(aq" .ft P .fi .UNINDENT .UNINDENT .SS Reading rows from a file .sp The \fBsqlite_utils.utils.rows_from_file()\fP helper function can read rows (a sequence of dictionaries) from CSV, TSV, JSON or newline\-delimited JSON files. .SS Setting the maximum CSV field size limit .sp Sometimes when working with CSV files that include extremely long fields you may see an error that looks like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C _csv.Error: field larger than field limit (131072) .ft P .fi .UNINDENT .UNINDENT .sp The Python standard library \fBcsv\fP module enforces a field size limit. You can increase that limit using the \fBcsv.field_size_limit(new_limit)\fP method (\fI\%documented here\fP) but if you don\(aqt want to pick a new level you may instead want to increase it to the maximum possible. .sp The maximum possible value for this is not documented, and varies between systems. .sp Calling \fBsqlite_utils.utils.maximize_csv_field_size_limit()\fP will set the value to the highest possible for the current system: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from sqlite_utils.utils import maximize_csv_field_size_limit maximize_csv_field_size_limit() .ft P .fi .UNINDENT .UNINDENT .sp If you need to reset to the original value after calling this function you can do so like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from sqlite_utils.utils import ORIGINAL_CSV_FIELD_SIZE_LIMIT import csv csv.field_size_limit(ORIGINAL_CSV_FIELD_SIZE_LIMIT) .ft P .fi .UNINDENT .UNINDENT .SS Detecting column types using TypeTracker .sp Sometimes you may find yourself working with data that lacks type information \- data from a CSV file for example. .sp The \fBTypeTracker\fP class can be used to try to automatically identify the most likely types for data that is initially represented as strings. .sp Consider this example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import csv, io csv_file = io.StringIO("id,name\en1,Cleo\en2,Cardi") rows = list(csv.DictReader(csv_file)) # rows is now this: # [{\(aqid\(aq: \(aq1\(aq, \(aqname\(aq: \(aqCleo\(aq}, {\(aqid\(aq: \(aq2\(aq, \(aqname\(aq: \(aqCardi\(aq}] .ft P .fi .UNINDENT .UNINDENT .sp If we insert this data directly into a table we will get a schema that is entirely \fBTEXT\fP columns: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from sqlite_utils import Database db = Database(memory=True) db["creatures"].insert_all(rows) print(db.schema) # Outputs: # CREATE TABLE [creatures] ( # [id] TEXT, # [name] TEXT # ); .ft P .fi .UNINDENT .UNINDENT .sp We can detect the best column types using a \fBTypeTracker\fP instance: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from sqlite_utils.utils import TypeTracker tracker = TypeTracker() db["creatures2"].insert_all(tracker.wrap(rows)) print(tracker.types) # Outputs {\(aqid\(aq: \(aqinteger\(aq, \(aqname\(aq: \(aqtext\(aq} .ft P .fi .UNINDENT .UNINDENT .sp We can then apply those types to our new table using the \fI\%table.transform()\fP method: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C db["creatures2"].transform(types=tracker.types) print(db["creatures2"].schema) # Outputs: # CREATE TABLE [creatures2] ( # [id] INTEGER, # [name] TEXT # ); .ft P .fi .UNINDENT .UNINDENT .SS SpatiaLite helpers .sp \fI\%SpatiaLite\fP is a geographic extension to SQLite (similar to PostgreSQL + PostGIS). Using requires finding, loading and initializing the extension, adding geometry columns to existing tables and optionally creating spatial indexes. The utilities here help streamline that setup. .SS Initialize SpatiaLite .SS Finding SpatiaLite .SS Adding geometry columns .SS Creating a spatial index .SS API reference .INDENT 0.0 .IP \(bu 2 \fI\%sqlite_utils.db.Database\fP .IP \(bu 2 \fI\%sqlite_utils.db.Queryable\fP .IP \(bu 2 \fI\%sqlite_utils.db.Table\fP .IP \(bu 2 \fI\%sqlite_utils.db.View\fP .IP \(bu 2 \fI\%Other\fP .INDENT 2.0 .IP \(bu 2 \fI\%sqlite_utils.db.Column\fP .IP \(bu 2 \fI\%sqlite_utils.db.ColumnDetails\fP .UNINDENT .IP \(bu 2 \fI\%sqlite_utils.utils\fP .INDENT 2.0 .IP \(bu 2 \fI\%sqlite_utils.utils.hash_record\fP .IP \(bu 2 \fI\%sqlite_utils.utils.rows_from_file\fP .IP \(bu 2 \fI\%sqlite_utils.utils.TypeTracker\fP .IP \(bu 2 \fI\%sqlite_utils.utils.chunks\fP .IP \(bu 2 \fI\%sqlite_utils.utils.flatten\fP .UNINDENT .UNINDENT .SS sqlite_utils.db.Database .SS sqlite_utils.db.Queryable .sp \fI\%Table\fP and \fI\%View\fP are both subclasses of \fBQueryable\fP, providing access to the following methods: .SS sqlite_utils.db.Table .SS sqlite_utils.db.View .SS Other .SS sqlite_utils.db.Column .SS sqlite_utils.db.ColumnDetails .SS sqlite_utils.utils .SS sqlite_utils.utils.hash_record .SS sqlite_utils.utils.rows_from_file .SS sqlite_utils.utils.TypeTracker .SS sqlite_utils.utils.chunks .SS sqlite_utils.utils.flatten .SS CLI reference .sp This page lists the \fB\-\-help\fP for every \fBsqlite\-utils\fP CLI sub\-command. .INDENT 0.0 .IP \(bu 2 \fI\%query\fP .IP \(bu 2 \fI\%memory\fP .IP \(bu 2 \fI\%insert\fP .IP \(bu 2 \fI\%upsert\fP .IP \(bu 2 \fI\%bulk\fP .IP \(bu 2 \fI\%search\fP .IP \(bu 2 \fI\%transform\fP .IP \(bu 2 \fI\%extract\fP .IP \(bu 2 \fI\%schema\fP .IP \(bu 2 \fI\%insert\-files\fP .IP \(bu 2 \fI\%analyze\-tables\fP .IP \(bu 2 \fI\%convert\fP .IP \(bu 2 \fI\%tables\fP .IP \(bu 2 \fI\%views\fP .IP \(bu 2 \fI\%rows\fP .IP \(bu 2 \fI\%triggers\fP .IP \(bu 2 \fI\%indexes\fP .IP \(bu 2 \fI\%create\-database\fP .IP \(bu 2 \fI\%create\-table\fP .IP \(bu 2 \fI\%create\-index\fP .IP \(bu 2 \fI\%enable\-fts\fP .IP \(bu 2 \fI\%populate\-fts\fP .IP \(bu 2 \fI\%rebuild\-fts\fP .IP \(bu 2 \fI\%disable\-fts\fP .IP \(bu 2 \fI\%optimize\fP .IP \(bu 2 \fI\%analyze\fP .IP \(bu 2 \fI\%vacuum\fP .IP \(bu 2 \fI\%dump\fP .IP \(bu 2 \fI\%add\-column\fP .IP \(bu 2 \fI\%add\-foreign\-key\fP .IP \(bu 2 \fI\%add\-foreign\-keys\fP .IP \(bu 2 \fI\%index\-foreign\-keys\fP .IP \(bu 2 \fI\%enable\-wal\fP .IP \(bu 2 \fI\%disable\-wal\fP .IP \(bu 2 \fI\%enable\-counts\fP .IP \(bu 2 \fI\%reset\-counts\fP .IP \(bu 2 \fI\%duplicate\fP .IP \(bu 2 \fI\%drop\-table\fP .IP \(bu 2 \fI\%create\-view\fP .IP \(bu 2 \fI\%drop\-view\fP .IP \(bu 2 \fI\%install\fP .IP \(bu 2 \fI\%uninstall\fP .IP \(bu 2 \fI\%add\-geometry\-column\fP .IP \(bu 2 \fI\%create\-spatial\-index\fP .UNINDENT .SS query .sp See \fI\%Running SQL queries\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils query [OPTIONS] PATH SQL Execute SQL query and return the results as JSON Example: sqlite\-utils data.db \e "select * from chickens where age > :age" \e \-p age 1 Options: \-\-attach ... Additional databases to attach \- specify alias and filepath \-\-nl Output newline\-delimited JSON \-\-arrays Output rows as arrays instead of objects \-\-csv Output CSV \-\-tsv Output TSV \-\-no\-headers Omit CSV headers \-t, \-\-table Output as a formatted table \-\-fmt TEXT Table format \- one of asciidoc, double_grid, double_outline, fancy_grid, fancy_outline, github, grid, heavy_grid, heavy_outline, html, jira, latex, latex_booktabs, latex_longtable, latex_raw, mediawiki, mixed_grid, mixed_outline, moinmoin, orgtbl, outline, pipe, plain, presto, pretty, psql, rounded_grid, rounded_outline, rst, simple, simple_grid, simple_outline, textile, tsv, unsafehtml, youtrack \-\-json\-cols Detect JSON cols and output them as JSON, not escaped strings \-r, \-\-raw Raw output, first column of first row \-p, \-\-param ... Named :parameters for SQL query \-\-functions TEXT Python code defining one or more custom SQL functions \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS memory .sp See \fI\%Querying data directly using an in\-memory database\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils memory [OPTIONS] [PATHS]... SQL Execute SQL query against an in\-memory database, optionally populated by imported data To import data from CSV, TSV or JSON files pass them on the command\-line: sqlite\-utils memory one.csv two.json \e "select * from one join two on one.two_id = two.id" For data piped into the tool from standard input, use "\-" or "stdin": cat animals.csv | sqlite\-utils memory \- \e "select * from stdin where species = \(aqdog\(aq" The format of the data will be automatically detected. You can specify the format explicitly using :json, :csv, :tsv or :nl (for newline\-delimited JSON) \- for example: cat animals.csv | sqlite\-utils memory stdin:csv places.dat:nl \e "select * from stdin where place_id in (select id from places)" Use \-\-schema to view the SQL schema of any imported files: sqlite\-utils memory animals.csv \-\-schema Options: \-\-functions TEXT Python code defining one or more custom SQL functions \-\-attach ... Additional databases to attach \- specify alias and filepath \-\-flatten Flatten nested JSON objects, so {"foo": {"bar": 1}} becomes {"foo_bar": 1} \-\-nl Output newline\-delimited JSON \-\-arrays Output rows as arrays instead of objects \-\-csv Output CSV \-\-tsv Output TSV \-\-no\-headers Omit CSV headers \-t, \-\-table Output as a formatted table \-\-fmt TEXT Table format \- one of asciidoc, double_grid, double_outline, fancy_grid, fancy_outline, github, grid, heavy_grid, heavy_outline, html, jira, latex, latex_booktabs, latex_longtable, latex_raw, mediawiki, mixed_grid, mixed_outline, moinmoin, orgtbl, outline, pipe, plain, presto, pretty, psql, rounded_grid, rounded_outline, rst, simple, simple_grid, simple_outline, textile, tsv, unsafehtml, youtrack \-\-json\-cols Detect JSON cols and output them as JSON, not escaped strings \-r, \-\-raw Raw output, first column of first row \-p, \-\-param ... Named :parameters for SQL query \-\-encoding TEXT Character encoding for CSV input, defaults to utf\-8 \-n, \-\-no\-detect\-types Treat all CSV/TSV columns as TEXT \-\-schema Show SQL schema for in\-memory database \-\-dump Dump SQL for in\-memory database \-\-save FILE Save in\-memory database to this file \-\-analyze Analyze resulting tables and output results \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS insert .sp See \fI\%Inserting JSON data\fP, \fI\%Inserting CSV or TSV data\fP, \fI\%Inserting unstructured data with \-\-lines and \-\-text\fP, \fI\%Applying conversions while inserting data\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils insert [OPTIONS] PATH TABLE FILE Insert records from FILE into a table, creating the table if it does not already exist. Example: echo \(aq{"name": "Lila"}\(aq | sqlite\-utils insert data.db chickens \- By default the input is expected to be a JSON object or array of objects. \- Use \-\-nl for newline\-delimited JSON objects \- Use \-\-csv or \-\-tsv for comma\-separated or tab\-separated input \- Use \-\-lines to write each incoming line to a column called "line" \- Use \-\-text to write the entire input to a column called "text" You can also use \-\-convert to pass a fragment of Python code that will be used to convert each input. Your Python code will be passed a "row" variable representing the imported row, and can return a modified row. This example uses just the name, latitude and longitude columns from a CSV file, converting name to upper case and latitude and longitude to floating point numbers: sqlite\-utils insert plants.db plants plants.csv \-\-csv \-\-convert \(aq return { "name": row["name"].upper(), "latitude": float(row["latitude"]), "longitude": float(row["longitude"]), }\(aq If you are using \-\-lines your code will be passed a "line" variable, and for \-\-text a "text" variable. When using \-\-text your function can return an iterator of rows to insert. This example inserts one record per word in the input: echo \(aqA bunch of words\(aq | sqlite\-utils insert words.db words \- \e \-\-text \-\-convert \(aq({"word": w} for w in text.split())\(aq Options: \-\-pk TEXT Columns to use as the primary key, e.g. id \-\-flatten Flatten nested JSON objects, so {"a": {"b": 1}} becomes {"a_b": 1} \-\-nl Expect newline\-delimited JSON \-c, \-\-csv Expect CSV input \-\-tsv Expect TSV input \-\-lines Treat each line as a single value called \(aqline\(aq \-\-text Treat input as a single value called \(aqtext\(aq \-\-convert TEXT Python code to convert each item \-\-import TEXT Python modules to import \-\-delimiter TEXT Delimiter to use for CSV files \-\-quotechar TEXT Quote character to use for CSV/TSV \-\-sniff Detect delimiter and quote character \-\-no\-headers CSV file has no header row \-\-encoding TEXT Character encoding for input, defaults to utf\-8 \-\-batch\-size INTEGER Commit every X records \-\-alter Alter existing table to add any missing columns \-\-not\-null TEXT Columns that should be created as NOT NULL \-\-default ... Default value that should be set for a column \-d, \-\-detect\-types Detect types for columns in CSV/TSV data \-\-analyze Run ANALYZE at the end of this operation \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-\-silent Do not show progress bar \-\-ignore Ignore records if pk already exists \-\-replace Replace records if pk already exists \-\-truncate Truncate table before inserting records, if table already exists \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS upsert .sp See \fI\%Upserting data\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils upsert [OPTIONS] PATH TABLE FILE Upsert records based on their primary key. Works like \(aqinsert\(aq but if an incoming record has a primary key that matches an existing record the existing record will be updated. Example: echo \(aq[ {"id": 1, "name": "Lila"}, {"id": 2, "name": "Suna"} ]\(aq | sqlite\-utils upsert data.db chickens \- \-\-pk id Options: \-\-pk TEXT Columns to use as the primary key, e.g. id [required] \-\-flatten Flatten nested JSON objects, so {"a": {"b": 1}} becomes {"a_b": 1} \-\-nl Expect newline\-delimited JSON \-c, \-\-csv Expect CSV input \-\-tsv Expect TSV input \-\-lines Treat each line as a single value called \(aqline\(aq \-\-text Treat input as a single value called \(aqtext\(aq \-\-convert TEXT Python code to convert each item \-\-import TEXT Python modules to import \-\-delimiter TEXT Delimiter to use for CSV files \-\-quotechar TEXT Quote character to use for CSV/TSV \-\-sniff Detect delimiter and quote character \-\-no\-headers CSV file has no header row \-\-encoding TEXT Character encoding for input, defaults to utf\-8 \-\-batch\-size INTEGER Commit every X records \-\-alter Alter existing table to add any missing columns \-\-not\-null TEXT Columns that should be created as NOT NULL \-\-default ... Default value that should be set for a column \-d, \-\-detect\-types Detect types for columns in CSV/TSV data \-\-analyze Run ANALYZE at the end of this operation \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-\-silent Do not show progress bar \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS bulk .sp See \fI\%Executing SQL in bulk\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils bulk [OPTIONS] PATH SQL FILE Execute parameterized SQL against the provided list of documents. Example: echo \(aq[ {"id": 1, "name": "Lila2"}, {"id": 2, "name": "Suna2"} ]\(aq | sqlite\-utils bulk data.db \(aq update chickens set name = :name where id = :id \(aq \- Options: \-\-batch\-size INTEGER Commit every X records \-\-functions TEXT Python code defining one or more custom SQL functions \-\-flatten Flatten nested JSON objects, so {"a": {"b": 1}} becomes {"a_b": 1} \-\-nl Expect newline\-delimited JSON \-c, \-\-csv Expect CSV input \-\-tsv Expect TSV input \-\-lines Treat each line as a single value called \(aqline\(aq \-\-text Treat input as a single value called \(aqtext\(aq \-\-convert TEXT Python code to convert each item \-\-import TEXT Python modules to import \-\-delimiter TEXT Delimiter to use for CSV files \-\-quotechar TEXT Quote character to use for CSV/TSV \-\-sniff Detect delimiter and quote character \-\-no\-headers CSV file has no header row \-\-encoding TEXT Character encoding for input, defaults to utf\-8 \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS search .sp See \fI\%Executing searches\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils search [OPTIONS] PATH DBTABLE Q Execute a full\-text search against this table Example: sqlite\-utils search data.db chickens lila Options: \-o, \-\-order TEXT Order by (\(aqcolumn\(aq or \(aqcolumn desc\(aq) \-c, \-\-column TEXT Columns to return \-\-limit INTEGER Number of rows to return \- defaults to everything \-\-sql Show SQL query that would be run \-\-quote Apply FTS quoting rules to search term \-\-nl Output newline\-delimited JSON \-\-arrays Output rows as arrays instead of objects \-\-csv Output CSV \-\-tsv Output TSV \-\-no\-headers Omit CSV headers \-t, \-\-table Output as a formatted table \-\-fmt TEXT Table format \- one of asciidoc, double_grid, double_outline, fancy_grid, fancy_outline, github, grid, heavy_grid, heavy_outline, html, jira, latex, latex_booktabs, latex_longtable, latex_raw, mediawiki, mixed_grid, mixed_outline, moinmoin, orgtbl, outline, pipe, plain, presto, pretty, psql, rounded_grid, rounded_outline, rst, simple, simple_grid, simple_outline, textile, tsv, unsafehtml, youtrack \-\-json\-cols Detect JSON cols and output them as JSON, not escaped strings \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS transform .sp See \fI\%Transforming tables\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils transform [OPTIONS] PATH TABLE Transform a table beyond the capabilities of ALTER TABLE Example: sqlite\-utils transform mydb.db mytable \e \-\-drop column1 \e \-\-rename column2 column_renamed Options: \-\-type ... Change column type to INTEGER, TEXT, FLOAT or BLOB \-\-drop TEXT Drop this column \-\-rename ... Rename this column to X \-o, \-\-column\-order TEXT Reorder columns \-\-not\-null TEXT Set this column to NOT NULL \-\-not\-null\-false TEXT Remove NOT NULL from this column \-\-pk TEXT Make this column the primary key \-\-pk\-none Remove primary key (convert to rowid table) \-\-default ... Set default value for this column \-\-default\-none TEXT Remove default from this column \-\-drop\-foreign\-key TEXT Drop foreign key constraint for this column \-\-sql Output SQL without executing it \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS extract .sp See \fI\%Extracting columns into a separate table\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils extract [OPTIONS] PATH TABLE COLUMNS... Extract one or more columns into a separate table Example: sqlite\-utils extract trees.db Street_Trees species Options: \-\-table TEXT Name of the other table to extract columns to \-\-fk\-column TEXT Name of the foreign key column to add to the table \-\-rename ... Rename this column in extracted table \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS schema .sp See \fI\%Showing the schema\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils schema [OPTIONS] PATH [TABLES]... Show full schema for this database or for specified tables Example: sqlite\-utils schema trees.db Options: \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS insert\-files .sp See \fI\%Inserting data from files\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils insert\-files [OPTIONS] PATH TABLE FILE_OR_DIR... Insert one or more files using BLOB columns in the specified table Example: sqlite\-utils insert\-files pics.db images *.gif \e \-c name:name \e \-c content:content \e \-c content_hash:sha256 \e \-c created:ctime_iso \e \-c modified:mtime_iso \e \-c size:size \e \-\-pk name Options: \-c, \-\-column TEXT Column definitions for the table \-\-pk TEXT Column to use as primary key \-\-alter Alter table to add missing columns \-\-replace Replace files with matching primary key \-\-upsert Upsert files with matching primary key \-\-name TEXT File name to use \-\-text Store file content as TEXT, not BLOB \-\-encoding TEXT Character encoding for input, defaults to utf\-8 \-s, \-\-silent Don\(aqt show a progress bar \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS analyze\-tables .sp See \fI\%Analyzing tables\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils analyze\-tables [OPTIONS] PATH [TABLES]... Analyze the columns in one or more tables Example: sqlite\-utils analyze\-tables data.db trees Options: \-c, \-\-column TEXT Specific columns to analyze \-\-save Save results to _analyze_tables table \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS convert .sp See \fI\%Converting data in columns\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils convert [OPTIONS] DB_PATH TABLE COLUMNS... CODE Convert columns using Python code you supply. For example: sqlite\-utils convert my.db mytable mycolumn \e \(aq"\en".join(textwrap.wrap(value, 10))\(aq \e \-\-import=textwrap "value" is a variable with the column value to be converted. Use "\-" for CODE to read Python code from standard input. The following common operations are available as recipe functions: r.jsonsplit(value, delimiter=\(aq,\(aq, type=) Convert a string like a,b,c into a JSON array ["a", "b", "c"] r.parsedate(value, dayfirst=False, yearfirst=False, errors=None) Parse a date and convert it to ISO date format: yyyy\-mm\-dd  \- dayfirst=True: treat xx as the day in xx/yy/zz \- yearfirst=True: treat xx as the year in xx/yy/zz \- errors=r.IGNORE to ignore values that cannot be parsed \- errors=r.SET_NULL to set values that cannot be parsed to null r.parsedatetime(value, dayfirst=False, yearfirst=False, errors=None) Parse a datetime and convert it to ISO datetime format: yyyy\-mm\-ddTHH:MM:SS  \- dayfirst=True: treat xx as the day in xx/yy/zz \- yearfirst=True: treat xx as the year in xx/yy/zz \- errors=r.IGNORE to ignore values that cannot be parsed \- errors=r.SET_NULL to set values that cannot be parsed to null You can use these recipes like so: sqlite\-utils convert my.db mytable mycolumn \e \(aqr.jsonsplit(value, delimiter=":")\(aq Options: \-\-import TEXT Python modules to import \-\-dry\-run Show results of running this against first 10 rows \-\-multi Populate columns for keys in returned dictionary \-\-where TEXT Optional where clause \-p, \-\-param ... Named :parameters for where clause \-\-output TEXT Optional separate column to populate with the output \-\-output\-type [integer|float|blob|text] Column type to use for the output column \-\-drop Drop original column afterwards \-s, \-\-silent Don\(aqt show a progress bar \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS tables .sp See \fI\%Listing tables\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils tables [OPTIONS] PATH List the tables in the database Example: sqlite\-utils tables trees.db Options: \-\-fts4 Just show FTS4 enabled tables \-\-fts5 Just show FTS5 enabled tables \-\-counts Include row counts per table \-\-nl Output newline\-delimited JSON \-\-arrays Output rows as arrays instead of objects \-\-csv Output CSV \-\-tsv Output TSV \-\-no\-headers Omit CSV headers \-t, \-\-table Output as a formatted table \-\-fmt TEXT Table format \- one of asciidoc, double_grid, double_outline, fancy_grid, fancy_outline, github, grid, heavy_grid, heavy_outline, html, jira, latex, latex_booktabs, latex_longtable, latex_raw, mediawiki, mixed_grid, mixed_outline, moinmoin, orgtbl, outline, pipe, plain, presto, pretty, psql, rounded_grid, rounded_outline, rst, simple, simple_grid, simple_outline, textile, tsv, unsafehtml, youtrack \-\-json\-cols Detect JSON cols and output them as JSON, not escaped strings \-\-columns Include list of columns for each table \-\-schema Include schema for each table \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS views .sp See \fI\%Listing views\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils views [OPTIONS] PATH List the views in the database Example: sqlite\-utils views trees.db Options: \-\-counts Include row counts per view \-\-nl Output newline\-delimited JSON \-\-arrays Output rows as arrays instead of objects \-\-csv Output CSV \-\-tsv Output TSV \-\-no\-headers Omit CSV headers \-t, \-\-table Output as a formatted table \-\-fmt TEXT Table format \- one of asciidoc, double_grid, double_outline, fancy_grid, fancy_outline, github, grid, heavy_grid, heavy_outline, html, jira, latex, latex_booktabs, latex_longtable, latex_raw, mediawiki, mixed_grid, mixed_outline, moinmoin, orgtbl, outline, pipe, plain, presto, pretty, psql, rounded_grid, rounded_outline, rst, simple, simple_grid, simple_outline, textile, tsv, unsafehtml, youtrack \-\-json\-cols Detect JSON cols and output them as JSON, not escaped strings \-\-columns Include list of columns for each view \-\-schema Include schema for each view \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS rows .sp See \fI\%Returning all rows in a table\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils rows [OPTIONS] PATH DBTABLE Output all rows in the specified table Example: sqlite\-utils rows trees.db Trees Options: \-c, \-\-column TEXT Columns to return \-\-where TEXT Optional where clause \-o, \-\-order TEXT Order by (\(aqcolumn\(aq or \(aqcolumn desc\(aq) \-p, \-\-param ... Named :parameters for where clause \-\-limit INTEGER Number of rows to return \- defaults to everything \-\-offset INTEGER SQL offset to use \-\-nl Output newline\-delimited JSON \-\-arrays Output rows as arrays instead of objects \-\-csv Output CSV \-\-tsv Output TSV \-\-no\-headers Omit CSV headers \-t, \-\-table Output as a formatted table \-\-fmt TEXT Table format \- one of asciidoc, double_grid, double_outline, fancy_grid, fancy_outline, github, grid, heavy_grid, heavy_outline, html, jira, latex, latex_booktabs, latex_longtable, latex_raw, mediawiki, mixed_grid, mixed_outline, moinmoin, orgtbl, outline, pipe, plain, presto, pretty, psql, rounded_grid, rounded_outline, rst, simple, simple_grid, simple_outline, textile, tsv, unsafehtml, youtrack \-\-json\-cols Detect JSON cols and output them as JSON, not escaped strings \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS triggers .sp See \fI\%Listing triggers\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils triggers [OPTIONS] PATH [TABLES]... Show triggers configured in this database Example: sqlite\-utils triggers trees.db Options: \-\-nl Output newline\-delimited JSON \-\-arrays Output rows as arrays instead of objects \-\-csv Output CSV \-\-tsv Output TSV \-\-no\-headers Omit CSV headers \-t, \-\-table Output as a formatted table \-\-fmt TEXT Table format \- one of asciidoc, double_grid, double_outline, fancy_grid, fancy_outline, github, grid, heavy_grid, heavy_outline, html, jira, latex, latex_booktabs, latex_longtable, latex_raw, mediawiki, mixed_grid, mixed_outline, moinmoin, orgtbl, outline, pipe, plain, presto, pretty, psql, rounded_grid, rounded_outline, rst, simple, simple_grid, simple_outline, textile, tsv, unsafehtml, youtrack \-\-json\-cols Detect JSON cols and output them as JSON, not escaped strings \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS indexes .sp See \fI\%Listing indexes\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils indexes [OPTIONS] PATH [TABLES]... Show indexes for the whole database or specific tables Example: sqlite\-utils indexes trees.db Trees Options: \-\-aux Include auxiliary columns \-\-nl Output newline\-delimited JSON \-\-arrays Output rows as arrays instead of objects \-\-csv Output CSV \-\-tsv Output TSV \-\-no\-headers Omit CSV headers \-t, \-\-table Output as a formatted table \-\-fmt TEXT Table format \- one of asciidoc, double_grid, double_outline, fancy_grid, fancy_outline, github, grid, heavy_grid, heavy_outline, html, jira, latex, latex_booktabs, latex_longtable, latex_raw, mediawiki, mixed_grid, mixed_outline, moinmoin, orgtbl, outline, pipe, plain, presto, pretty, psql, rounded_grid, rounded_outline, rst, simple, simple_grid, simple_outline, textile, tsv, unsafehtml, youtrack \-\-json\-cols Detect JSON cols and output them as JSON, not escaped strings \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS create\-database .sp See \fI\%Creating an empty database\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils create\-database [OPTIONS] PATH Create a new empty database file Example: sqlite\-utils create\-database trees.db Options: \-\-enable\-wal Enable WAL mode on the created database \-\-init\-spatialite Enable SpatiaLite on the created database \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS create\-table .sp See \fI\%Creating tables\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils create\-table [OPTIONS] PATH TABLE COLUMNS... Add a table with the specified columns. Columns should be specified using name, type pairs, for example: sqlite\-utils create\-table my.db people \e id integer \e name text \e height float \e photo blob \-\-pk id Options: \-\-pk TEXT Column to use as primary key \-\-not\-null TEXT Columns that should be created as NOT NULL \-\-default ... Default value that should be set for a column \-\-fk ... Column, other table, other column to set as a foreign key \-\-ignore If table already exists, do nothing \-\-replace If table already exists, replace it \-\-transform If table already exists, try to transform the schema \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS create\-index .sp See \fI\%Creating indexes\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils create\-index [OPTIONS] PATH TABLE COLUMN... Add an index to the specified table for the specified columns Example: sqlite\-utils create\-index chickens.db chickens name To create an index in descending order: sqlite\-utils create\-index chickens.db chickens \-\- \-name Options: \-\-name TEXT Explicit name for the new index \-\-unique Make this a unique index \-\-if\-not\-exists, \-\-ignore Ignore if index already exists \-\-analyze Run ANALYZE after creating the index \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS enable\-fts .sp See \fI\%Configuring full\-text search\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils enable\-fts [OPTIONS] PATH TABLE COLUMN... Enable full\-text search for specific table and columns" Example: sqlite\-utils enable\-fts chickens.db chickens name Options: \-\-fts4 Use FTS4 \-\-fts5 Use FTS5 \-\-tokenize TEXT Tokenizer to use, e.g. porter \-\-create\-triggers Create triggers to update the FTS tables when the parent table changes. \-\-replace Replace existing FTS configuration if it exists \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS populate\-fts .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils populate\-fts [OPTIONS] PATH TABLE COLUMN... Re\-populate full\-text search for specific table and columns Example: sqlite\-utils populate\-fts chickens.db chickens name Options: \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS rebuild\-fts .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils rebuild\-fts [OPTIONS] PATH [TABLES]... Rebuild all or specific full\-text search tables Example: sqlite\-utils rebuild\-fts chickens.db chickens Options: \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS disable\-fts .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils disable\-fts [OPTIONS] PATH TABLE Disable full\-text search for specific table Example: sqlite\-utils disable\-fts chickens.db chickens Options: \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS optimize .sp See \fI\%Optimize\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils optimize [OPTIONS] PATH [TABLES]... Optimize all full\-text search tables and then run VACUUM \- should shrink the database file Example: sqlite\-utils optimize chickens.db Options: \-\-no\-vacuum Don\(aqt run VACUUM \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS analyze .sp See \fI\%Optimizing index usage with ANALYZE\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils analyze [OPTIONS] PATH [NAMES]... Run ANALYZE against the whole database, or against specific named indexes and tables Example: sqlite\-utils analyze chickens.db Options: \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS vacuum .sp See \fI\%Vacuum\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils vacuum [OPTIONS] PATH Run VACUUM against the database Example: sqlite\-utils vacuum chickens.db Options: \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS dump .sp See \fI\%Dumping the database to SQL\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils dump [OPTIONS] PATH Output a SQL dump of the schema and full contents of the database Example: sqlite\-utils dump chickens.db Options: \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS add\-column .sp See \fI\%Adding columns\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils add\-column [OPTIONS] PATH TABLE COL_NAME [[integer|float|blob|text|INTEGER|FLOAT|BLOB|TEXT]] Add a column to the specified table Example: sqlite\-utils add\-column chickens.db chickens weight float Options: \-\-fk TEXT Table to reference as a foreign key \-\-fk\-col TEXT Referenced column on that foreign key table \- if omitted will automatically use the primary key \-\-not\-null\-default TEXT Add NOT NULL DEFAULT \(aqTEXT\(aq constraint \-\-ignore If column already exists, do nothing \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS add\-foreign\-key .sp See \fI\%Adding foreign key constraints\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils add\-foreign\-key [OPTIONS] PATH TABLE COLUMN [OTHER_TABLE] [OTHER_COLUMN] Add a new foreign key constraint to an existing table Example: sqlite\-utils add\-foreign\-key my.db books author_id authors id WARNING: Could corrupt your database! Back up your database file first. Options: \-\-ignore If foreign key already exists, do nothing \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS add\-foreign\-keys .sp See \fI\%Adding multiple foreign keys at once\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils add\-foreign\-keys [OPTIONS] PATH [FOREIGN_KEY]... Add multiple new foreign key constraints to a database Example: sqlite\-utils add\-foreign\-keys my.db \e books author_id authors id \e authors country_id countries id Options: \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS index\-foreign\-keys .sp See \fI\%Adding indexes for all foreign keys\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils index\-foreign\-keys [OPTIONS] PATH Ensure every foreign key column has an index on it Example: sqlite\-utils index\-foreign\-keys chickens.db Options: \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS enable\-wal .sp See \fI\%WAL mode\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils enable\-wal [OPTIONS] PATH... Enable WAL for database files Example: sqlite\-utils enable\-wal chickens.db Options: \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS disable\-wal .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils disable\-wal [OPTIONS] PATH... Disable WAL for database files Example: sqlite\-utils disable\-wal chickens.db Options: \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS enable\-counts .sp See \fI\%Enabling cached counts\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils enable\-counts [OPTIONS] PATH [TABLES]... Configure triggers to update a _counts table with row counts Example: sqlite\-utils enable\-counts chickens.db Options: \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS reset\-counts .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils reset\-counts [OPTIONS] PATH Reset calculated counts in the _counts table Example: sqlite\-utils reset\-counts chickens.db Options: \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS duplicate .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils duplicate [OPTIONS] PATH TABLE NEW_TABLE Create a duplicate of this table, copying across the schema and all row data. Options: \-\-ignore If table does not exist, do nothing \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS drop\-table .sp See \fI\%Dropping tables\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils drop\-table [OPTIONS] PATH TABLE Drop the specified table Example: sqlite\-utils drop\-table chickens.db chickens Options: \-\-ignore If table does not exist, do nothing \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS create\-view .sp See \fI\%Creating views\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils create\-view [OPTIONS] PATH VIEW SELECT Create a view for the provided SELECT query Example: sqlite\-utils create\-view chickens.db heavy_chickens \e \(aqselect * from chickens where weight > 3\(aq Options: \-\-ignore If view already exists, do nothing \-\-replace If view already exists, replace it \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS drop\-view .sp See \fI\%Dropping views\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils drop\-view [OPTIONS] PATH VIEW Drop the specified view Example: sqlite\-utils drop\-view chickens.db heavy_chickens Options: \-\-ignore If view does not exist, do nothing \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS install .sp See \fI\%Installing packages\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils install [OPTIONS] PACKAGES... Install packages from PyPI into the same environment as sqlite\-utils Options: \-U, \-\-upgrade Upgrade packages to latest version \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS uninstall .sp See \fI\%Uninstalling packages\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils uninstall [OPTIONS] PACKAGES... Uninstall Python packages from the sqlite\-utils environment Options: \-y, \-\-yes Don\(aqt ask for confirmation \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS add\-geometry\-column .sp See \fI\%SpatiaLite helpers\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils add\-geometry\-column [OPTIONS] DB_PATH TABLE COLUMN_NAME Add a SpatiaLite geometry column to an existing table. Requires SpatiaLite extension. By default, this command will try to load the SpatiaLite extension from usual paths. To load it from a specific path, use \-\-load\-extension. Options: \-t, \-\-type [POINT|LINESTRING|POLYGON|MULTIPOINT|MULTILINESTRING|MULTIPOLYGON|GEOMETRYCOLLECTION|GEOMETRY] Specify a geometry type for this column. [default: GEOMETRY] \-\-srid INTEGER Spatial Reference ID. See https://spatialreference.org for details on specific projections. [default: 4326] \-\-dimensions TEXT Coordinate dimensions. Use XYZ for three\- dimensional geometries. \-\-not\-null Add a NOT NULL constraint. \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS create\-spatial\-index .sp See \fI\%Adding spatial indexes\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Usage: sqlite\-utils create\-spatial\-index [OPTIONS] DB_PATH TABLE COLUMN_NAME Create a spatial index on a SpatiaLite geometry column. The table and geometry column must already exist before trying to add a spatial index. By default, this command will try to load the SpatiaLite extension from usual paths. To load it from a specific path, use \-\-load\-extension. Options: \-\-load\-extension TEXT Path to SQLite extension, with optional :entrypoint \-h, \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS Contributing .sp Development of \fBsqlite\-utils\fP takes place in the \fI\%sqlite\-utils GitHub repository\fP\&. .sp All improvements to the software should start with an issue. Read \fI\%How I build a feature\fP for a detailed description of the recommended process for building bug fixes or enhancements. .SS Obtaining the code .sp To work on this library locally, first checkout the code. Then create a new virtual environment: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C git clone git@github.com:simonw/sqlite\-utils cd sqlite\-utils python3 \-mvenv venv source venv/bin/activate .ft P .fi .UNINDENT .UNINDENT .sp Or if you are using \fBpipenv\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C pipenv shell .ft P .fi .UNINDENT .UNINDENT .sp Within the virtual environment running \fBsqlite\-utils\fP should run your locally editable version of the tool. You can use \fBwhich sqlite\-utils\fP to confirm that you are running the version that lives in your virtual environment. .SS Running the tests .sp To install the dependencies and test dependencies: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C pip install \-e \(aq.[test]\(aq .ft P .fi .UNINDENT .UNINDENT .sp To run the tests: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C pytest .ft P .fi .UNINDENT .UNINDENT .SS Building the documentation .sp To build the documentation, first install the documentation dependencies: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C pip install \-e \(aq.[docs]\(aq .ft P .fi .UNINDENT .UNINDENT .sp Then run \fBmake livehtml\fP from the \fBdocs/\fP directory to start a server on port 8000 that will serve the documentation and live\-reload any time you make an edit to a \fB\&.rst\fP file: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C cd docs make livehtml .ft P .fi .UNINDENT .UNINDENT .sp The \fI\%cog\fP tool is used to maintain portions of the documentation. You can run it like so: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C cog \-r docs/*.rst .ft P .fi .UNINDENT .UNINDENT .SS Linting and formatting .sp \fBsqlite\-utils\fP uses \fI\%Black\fP for code formatting, and \fI\%flake8\fP and \fI\%mypy\fP for linting and type checking. .sp Black is installed as part of \fBpip install \-e \(aq.[test]\(aq\fP \- you can then format your code by running it in the root of the project: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C black . .ft P .fi .UNINDENT .UNINDENT .sp To install \fBmypy\fP and \fBflake8\fP run the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C pip install \-e \(aq.[flake8,mypy]\(aq .ft P .fi .UNINDENT .UNINDENT .sp Both commands can then be run in the root of the project like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C flake8 mypy sqlite_utils .ft P .fi .UNINDENT .UNINDENT .sp All three of these tools are run by our CI mechanism against every commit and pull request. .SS Using Just and pipenv .sp If you install \fI\%Just\fP and \fI\%pipenv\fP you can use them to manage your local development environment. .sp To create a virtual environment and install all development dependencies, run: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C cd sqlite\-utils just init .ft P .fi .UNINDENT .UNINDENT .sp To run all of the tests and linters: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C just .ft P .fi .UNINDENT .UNINDENT .sp To run tests, or run a specific test module or test by name: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C just test # All tests just test tests/test_cli_memory.py # Just this module just test \-k test_memory_no_detect_types # Just this test .ft P .fi .UNINDENT .UNINDENT .sp To run just the linters: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C just lint .ft P .fi .UNINDENT .UNINDENT .sp To apply Black to your code: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C just black .ft P .fi .UNINDENT .UNINDENT .sp To update documentation using Cog: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C just cog .ft P .fi .UNINDENT .UNINDENT .sp To run the live documentation server (this will run Cog first): .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C just docs .ft P .fi .UNINDENT .UNINDENT .sp And to list all available commands: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C just \-l .ft P .fi .UNINDENT .UNINDENT .SS Release process .sp Releases are performed using tags. When a new release is published on GitHub, a \fI\%GitHub Actions workflow\fP will perform the following: .INDENT 0.0 .IP \(bu 2 Run the unit tests against all supported Python versions. If the tests pass... .IP \(bu 2 Build a wheel bundle of the underlying Python source code .IP \(bu 2 Push that new wheel up to PyPI: \fI\%https://pypi.org/project/sqlite\-utils/\fP .UNINDENT .sp To deploy new releases you will need to have push access to the GitHub repository. .sp \fBsqlite\-utils\fP follows \fI\%Semantic Versioning\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C major.minor.patch .ft P .fi .UNINDENT .UNINDENT .sp We increment \fBmajor\fP for backwards\-incompatible releases. .sp We increment \fBminor\fP for new features. .sp We increment \fBpatch\fP for bugfix releass. .sp To release a new version, first create a commit that updates the version number in \fBsetup.py\fP and the \fI\%the changelog\fP with highlights of the new version. An example \fI\%commit can be seen here\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # Update changelog git commit \-m " Release 3.29 Refs #423, #458, #467, #469, #470, #471, #472, #475" \-a git push .ft P .fi .UNINDENT .UNINDENT .sp Referencing the issues that are part of the release in the commit message ensures the name of the release shows up on those issue pages, e.g. \fI\%here\fP\&. .sp You can generate the list of issue references for a specific release by copying and pasting text from the release notes or GitHub changes\-since\-last\-release view into this \fI\%Extract issue numbers from pasted text\fP tool. .sp To create the tag for the release, create \fI\%a new release\fP on GitHub matching the new version number. You can convert the release notes to Markdown by copying and pasting the rendered HTML into this \fI\%Paste to Markdown tool\fP\&. .SS Changelog .SS 3.30 (2022\-10\-25) .INDENT 0.0 .IP \(bu 2 Now tested against Python 3.11. (\fI\%#502\fP) .IP \(bu 2 New \fBtable.search_sql(include_rank=True)\fP option, which adds a \fBrank\fP column to the generated SQL. Thanks, Jacob Chapman. (\fI\%#480\fP) .IP \(bu 2 Progress bars now display for newline\-delimited JSON files using the \fB\-\-nl\fP option. Thanks, Mischa Untaga. (\fI\%#485\fP) .IP \(bu 2 New \fBdb.close()\fP method. (\fI\%#504\fP) .IP \(bu 2 Conversion functions passed to \fI\%table.convert(...)\fP can now return lists or dictionaries, which will be inserted into the database as JSON strings. (\fI\%#495\fP) .IP \(bu 2 \fBsqlite\-utils install\fP and \fBsqlite\-utils uninstall\fP commands for installing packages into the same virtual environment as \fBsqlite\-utils\fP, \fI\%described here\fP\&. (\fI\%#483\fP) .IP \(bu 2 New \fI\%sqlite_utils.utils.flatten()\fP utility function. (\fI\%#500\fP) .IP \(bu 2 Documentation on \fI\%using Just\fP to run tests, linters and build documentation. .IP \(bu 2 Documentation now covers the \fI\%Release process\fP for this package. .UNINDENT .SS 3.29 (2022\-08\-27) .INDENT 0.0 .IP \(bu 2 The \fBsqlite\-utils query\fP, \fBmemory\fP and \fBbulk\fP commands now all accept a new \fB\-\-functions\fP option. This can be passed a string of Python code, and any callable objects defined in that code will be made available to SQL queries as custom SQL functions. See \fI\%Defining custom SQL functions\fP for details. (\fI\%#471\fP) .IP \(bu 2 \fBdb[table].create(...)\fP method now accepts a new \fBtransform=True\fP parameter. If the table already exists it will be \fI\%transformed\fP to match the schema configuration options passed to the function. This may result in columns being added or dropped, column types being changed, column order being updated or not null and default values for columns being set. (\fI\%#467\fP) .IP \(bu 2 Related to the above, the \fBsqlite\-utils create\-table\fP command now accepts a \fB\-\-transform\fP option. .IP \(bu 2 New introspection property: \fBtable.default_values\fP returns a dictionary mapping each column name with a default value to the configured default value. (\fI\%#475\fP) .IP \(bu 2 The \fB\-\-load\-extension\fP option can now be provided a path to a compiled SQLite extension module accompanied by the name of an entrypoint, separated by a colon \- for example \fB\-\-load\-extension ./lines0:sqlite3_lines0_noread_init\fP\&. This feature is modelled on code first \fI\%contributed to Datasette\fP by Alex Garcia. (\fI\%#470\fP) .IP \(bu 2 Functions registered using the \fI\%db.register_function()\fP method can now have a custom name specified using the new \fBdb.register_function(fn, name=...)\fP parameter. (\fI\%#458\fP) .IP \(bu 2 \fI\%sqlite\-utils rows\fP has a new \fB\-\-order\fP option for specifying the sort order for the returned rows. (\fI\%#469\fP) .IP \(bu 2 All of the CLI options that accept Python code blocks can now all be used to define functions that can access modules imported in that same block of code without needing to use the \fBglobal\fP keyword. (\fI\%#472\fP) .IP \(bu 2 Fixed bug where \fBtable.extract()\fP would not behave correctly for columns containing null values. Thanks, Forest Gregg. (\fI\%#423\fP) .IP \(bu 2 New tutorial: \fI\%Cleaning data with sqlite\-utils and Datasette\fP shows how to use \fBsqlite\-utils\fP to import and clean an example CSV file. .IP \(bu 2 Datasette and \fBsqlite\-utils\fP now have a Discord community. \fI\%Join the Discord here\fP\&. .UNINDENT .SS 3.28 (2022\-07\-15) .INDENT 0.0 .IP \(bu 2 New \fI\%table.duplicate(new_name)\fP method for creating a copy of a table with a matching schema and row contents. Thanks, \fI\%David\fP\&. (\fI\%#449\fP) .IP \(bu 2 New \fBsqlite\-utils duplicate data.db table_name new_name\fP CLI command for \fI\%Duplicating tables\fP\&. (\fI\%#454\fP) .IP \(bu 2 \fBsqlite_utils.utils.rows_from_file()\fP is now a \fI\%documented API\fP\&. It can be used to read a sequence of dictionaries from a file\-like object containing CSV, TSV, JSON or newline\-delimited JSON. It can be passed an explicit format or can attempt to detect the format automatically. (\fI\%#443\fP) .IP \(bu 2 \fBsqlite_utils.utils.TypeTracker\fP is now a documented API for detecting the likely column types for a sequence of string rows, see \fI\%Detecting column types using TypeTracker\fP\&. (\fI\%#445\fP) .IP \(bu 2 \fBsqlite_utils.utils.chunks()\fP is now a documented API for \fI\%splitting an iterator into chunks\fP\&. (\fI\%#451\fP) .IP \(bu 2 \fBsqlite\-utils enable\-fts\fP now has a \fB\-\-replace\fP option for replacing the existing FTS configuration for a table. (\fI\%#450\fP) .IP \(bu 2 The \fBcreate\-index\fP, \fBadd\-column\fP and \fBduplicate\fP commands all now take a \fB\-\-ignore\fP option for ignoring errors should the database not be in the right state for them to operate. (\fI\%#450\fP) .UNINDENT .SS 3.27 (2022\-06\-14) .sp See also \fI\%the annotated release notes\fP for this release. .INDENT 0.0 .IP \(bu 2 Documentation now uses the \fI\%Furo\fP Sphinx theme. (\fI\%#435\fP) .IP \(bu 2 Code examples in documentation now have a "copy to clipboard" button. (\fI\%#436\fP) .IP \(bu 2 \fBsqlite_utils.utils.utils.rows_from_file()\fP is now a documented API, see \fI\%Reading rows from a file\fP\&. (\fI\%#443\fP) .IP \(bu 2 \fBrows_from_file()\fP has two new parameters to help handle CSV files with rows that contain more values than are listed in that CSV file\(aqs headings: \fBignore_extras=True\fP and \fBextras_key="name\-of\-key"\fP\&. (\fI\%#440\fP) .IP \(bu 2 \fBsqlite_utils.utils.maximize_csv_field_size_limit()\fP helper function for increasing the field size limit for reading CSV files to its maximum, see \fI\%Setting the maximum CSV field size limit\fP\&. (\fI\%#442\fP) .IP \(bu 2 \fBtable.search(where=, where_args=)\fP parameters for adding additional \fBWHERE\fP clauses to a search query. The \fBwhere=\fP parameter is available on \fBtable.search_sql(...)\fP as well. See \fI\%Searching with table.search()\fP\&. (\fI\%#441\fP) .IP \(bu 2 Fixed bug where \fBtable.detect_fts()\fP and other search\-related functions could fail if two FTS\-enabled tables had names that were prefixes of each other. (\fI\%#434\fP) .UNINDENT .SS 3.26.1 (2022\-05\-02) .INDENT 0.0 .IP \(bu 2 Now depends on \fI\%click\-default\-group\-wheel\fP, a pure Python wheel package. This means you can install and use this package with \fI\%Pyodide\fP, which can run Python entirely in your browser using WebAssembly. (\fI\%#429\fP) .sp Try that out using the \fI\%Pyodide REPL\fP: .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C >>> import micropip >>> await micropip.install("sqlite\-utils") >>> import sqlite_utils >>> db = sqlite_utils.Database(memory=True) >>> list(db.query("select 3 * 5")) [{\(aq3 * 5\(aq: 15}] .ft P .fi .UNINDENT .UNINDENT .UNINDENT .SS 3.26 (2022\-04\-13) .INDENT 0.0 .IP \(bu 2 New \fBerrors=r.IGNORE/r.SET_NULL\fP parameter for the \fBr.parsedatetime()\fP and \fBr.parsedate()\fP \fI\%convert recipes\fP\&. (\fI\%#416\fP) .IP \(bu 2 Fixed a bug where \fB\-\-multi\fP could not be used in combination with \fB\-\-dry\-run\fP for the \fI\%convert\fP command. (\fI\%#415\fP) .IP \(bu 2 New documentation: \fI\%Using a convert() function to execute initialization\fP\&. (\fI\%#420\fP) .IP \(bu 2 More robust detection for whether or not \fBdeterministic=True\fP is supported. (\fI\%#425\fP) .UNINDENT .SS 3.25.1 (2022\-03\-11) .INDENT 0.0 .IP \(bu 2 Improved display of type information and parameters in the \fI\%API reference documentation\fP\&. (\fI\%#413\fP) .UNINDENT .SS 3.25 (2022\-03\-01) .INDENT 0.0 .IP \(bu 2 New \fBhash_id_columns=\fP parameter for creating a primary key that\(aqs a hash of the content of specific columns \- see \fI\%Setting an ID based on the hash of the row contents\fP for details. (\fI\%#343\fP) .IP \(bu 2 New \fI\%db.sqlite_version\fP property, returning a tuple of integers representing the version of SQLite, for example \fB(3, 38, 0)\fP\&. .IP \(bu 2 Fixed a bug where \fI\%register_function(deterministic=True)\fP caused errors on versions of SQLite prior to 3.8.3. (\fI\%#408\fP) .IP \(bu 2 New documented \fI\%hash_record(record, keys=...)\fP function. .UNINDENT .SS 3.24 (2022\-02\-15) .INDENT 0.0 .IP \(bu 2 SpatiaLite helpers for the \fBsqlite\-utils\fP command\-line tool \- thanks, Chris Amico. (\fI\%#398\fP) .INDENT 2.0 .IP \(bu 2 \fI\%sqlite\-utils create\-database\fP \fB\-\-init\-spatialite\fP option for initializing SpatiaLite on a newly created database. .IP \(bu 2 \fI\%sqlite\-utils add\-geometry\-column\fP command for adding geometry columns. .IP \(bu 2 \fI\%sqlite\-utils create\-spatial\-index\fP command for adding spatial indexes. .UNINDENT .IP \(bu 2 \fBdb[table].create(..., if_not_exists=True)\fP option for \fI\%creating a table\fP only if it does not already exist. (\fI\%#397\fP) .IP \(bu 2 \fBDatabase(memory_name="my_shared_database")\fP parameter for creating a \fI\%named in\-memory database\fP that can be shared between multiple connections. (\fI\%#405\fP) .IP \(bu 2 Documentation now describes \fI\%how to add a primary key to a rowid table\fP using \fBsqlite\-utils transform\fP\&. (\fI\%#403\fP) .UNINDENT .SS 3.23 (2022\-02\-03) .sp This release introduces four new utility methods for working with \fI\%SpatiaLite\fP\&. Thanks, Chris Amico. (\fI\%#385\fP) .INDENT 0.0 .IP \(bu 2 \fBsqlite_utils.utils.find_spatialite()\fP \fI\%finds the location of the SpatiaLite module\fP on disk. .IP \(bu 2 \fBdb.init_spatialite()\fP \fI\%initializes SpatiaLite\fP for the given database. .IP \(bu 2 \fBtable.add_geometry_column(...)\fP \fI\%adds a geometry column\fP to an existing table. .IP \(bu 2 \fBtable.create_spatial_index(...)\fP \fI\%creates a spatial index\fP for a column. .IP \(bu 2 \fBsqlite\-utils batch\fP now accepts a \fB\-\-batch\-size\fP option. (\fI\%#392\fP) .UNINDENT .SS 3.22.1 (2022\-01\-25) .INDENT 0.0 .IP \(bu 2 All commands now include example usage in their \fB\-\-help\fP \- see \fI\%CLI reference\fP\&. (\fI\%#384\fP) .IP \(bu 2 Python library documentation has a new \fI\%Getting started\fP section. (\fI\%#387\fP) .IP \(bu 2 Documentation now uses \fI\%Plausible analytics\fP\&. (\fI\%#389\fP) .UNINDENT .SS 3.22 (2022\-01\-11) .INDENT 0.0 .IP \(bu 2 New \fI\%CLI reference\fP documentation page, listing the output of \fB\-\-help\fP for every one of the CLI commands. (\fI\%#383\fP) .IP \(bu 2 \fBsqlite\-utils rows\fP now has \fB\-\-limit\fP and \fB\-\-offset\fP options for paginating through data. (\fI\%#381\fP) .IP \(bu 2 \fBsqlite\-utils rows\fP now has \fB\-\-where\fP and \fB\-p\fP options for filtering the table using a \fBWHERE\fP query, see \fI\%Returning all rows in a table\fP\&. (\fI\%#382\fP) .UNINDENT .SS 3.21 (2022\-01\-10) .sp CLI and Python library improvements to help run \fI\%ANALYZE\fP after creating indexes or inserting rows, to gain better performance from the SQLite query planner when it runs against indexes. .sp Three new CLI commands: \fBcreate\-database\fP, \fBanalyze\fP and \fBbulk\fP\&. .sp More details and examples can be found in \fI\%the annotated release notes\fP\&. .INDENT 0.0 .IP \(bu 2 New \fBsqlite\-utils create\-database\fP command for creating new empty database files. (\fI\%#348\fP) .IP \(bu 2 New Python methods for running \fBANALYZE\fP against a database, table or index: \fBdb.analyze()\fP and \fBtable.analyze()\fP, see \fI\%Optimizing index usage with ANALYZE\fP\&. (\fI\%#366\fP) .IP \(bu 2 New \fI\%sqlite\-utils analyze command\fP for running \fBANALYZE\fP using the CLI. (\fI\%#379\fP) .IP \(bu 2 The \fBcreate\-index\fP, \fBinsert\fP and \fBupsert\fP commands now have a new \fB\-\-analyze\fP option for running \fBANALYZE\fP after the command has completed. (\fI\%#379\fP) .IP \(bu 2 New \fI\%sqlite\-utils bulk command\fP which can import records in the same way as \fBsqlite\-utils insert\fP (from JSON, CSV or TSV) and use them to bulk execute a parametrized SQL query. (\fI\%#375\fP) .IP \(bu 2 The CLI tool can now also be run using \fBpython \-m sqlite_utils\fP\&. (\fI\%#368\fP) .IP \(bu 2 Using \fB\-\-fmt\fP now implies \fB\-\-table\fP, so you don\(aqt need to pass both options. (\fI\%#374\fP) .IP \(bu 2 The \fB\-\-convert\fP function applied to rows can now modify the row in place. (\fI\%#371\fP) .IP \(bu 2 The \fI\%insert\-files command\fP supports two new columns: \fBstem\fP and \fBsuffix\fP\&. (\fI\%#372\fP) .IP \(bu 2 The \fB\-\-nl\fP import option now ignores blank lines in the input. (\fI\%#376\fP) .IP \(bu 2 Fixed bug where streaming input to the \fBinsert\fP command with \fB\-\-batch\-size 1\fP would appear to only commit after several rows had been ingested, due to unnecessary input buffering. (\fI\%#364\fP) .UNINDENT .SS 3.20 (2022\-01\-05) .INDENT 0.0 .IP \(bu 2 \fBsqlite\-utils insert ... \-\-lines\fP to insert the lines from a file into a table with a single \fBline\fP column, see \fI\%Inserting unstructured data with \-\-lines and \-\-text\fP\&. .IP \(bu 2 \fBsqlite\-utils insert ... \-\-text\fP to insert the contents of the file into a table with a single \fBtext\fP column and a single row. .IP \(bu 2 \fBsqlite\-utils insert ... \-\-convert\fP allows a Python function to be provided that will be used to convert each row that is being inserted into the database. See \fI\%Applying conversions while inserting data\fP, including details on special behavior when combined with \fB\-\-lines\fP and \fB\-\-text\fP\&. (\fI\%#356\fP) .IP \(bu 2 \fBsqlite\-utils convert\fP now accepts a code value of \fB\-\fP to read code from standard input. (\fI\%#353\fP) .IP \(bu 2 \fBsqlite\-utils convert\fP also now accepts code that defines a named \fBconvert(value)\fP function, see \fI\%Converting data in columns\fP\&. .IP \(bu 2 \fBdb.supports_strict\fP property showing if the database connection supports \fI\%SQLite strict tables\fP\&. .IP \(bu 2 \fBtable.strict\fP property (see \fI\%\&.strict\fP) indicating if the table uses strict mode. (\fI\%#344\fP) .IP \(bu 2 Fixed bug where \fBsqlite\-utils upsert ... \-\-detect\-types\fP ignored the \fB\-\-detect\-types\fP option. (\fI\%#362\fP) .UNINDENT .SS 3.19 (2021\-11\-20) .INDENT 0.0 .IP \(bu 2 The \fI\%table.lookup() method\fP now accepts keyword arguments that match those on the underlying \fBtable.insert()\fP method: \fBforeign_keys=\fP, \fBcolumn_order=\fP, \fBnot_null=\fP, \fBdefaults=\fP, \fBextracts=\fP, \fBconversions=\fP and \fBcolumns=\fP\&. You can also now pass \fBpk=\fP to specify a different column name to use for the primary key. (\fI\%#342\fP) .UNINDENT .SS 3.18 (2021\-11\-14) .INDENT 0.0 .IP \(bu 2 The \fBtable.lookup()\fP method now has an optional second argument which can be used to populate columns only the first time the record is created, see \fI\%Working with lookup tables\fP\&. (\fI\%#339\fP) .IP \(bu 2 \fBsqlite\-utils memory\fP now has a \fB\-\-flatten\fP option for \fI\%flattening nested JSON objects\fP into separate columns, consistent with \fBsqlite\-utils insert\fP\&. (\fI\%#332\fP) .IP \(bu 2 \fBtable.create_index(..., find_unique_name=True)\fP parameter, which finds an available name for the created index even if the default name has already been taken. This means that \fBindex\-foreign\-keys\fP will work even if one of the indexes it tries to create clashes with an existing index name. (\fI\%#335\fP) .IP \(bu 2 Added \fBpy.typed\fP to the module, so \fI\%mypy\fP should now correctly pick up the type annotations. Thanks, Andreas Longo. (\fI\%#331\fP) .IP \(bu 2 Now depends on \fBpython\-dateutil\fP instead of depending on \fBdateutils\fP\&. Thanks, Denys Pavlov. (\fI\%#324\fP) .IP \(bu 2 \fBtable.create()\fP (see \fI\%Explicitly creating a table\fP) now handles \fBdict\fP, \fBlist\fP and \fBtuple\fP types, mapping them to \fBTEXT\fP columns in SQLite so that they can be stored encoded as JSON. (\fI\%#338\fP) .IP \(bu 2 Inserted data with square braces in the column names (for example a CSV file containing a \fBitem[price]\fP) column now have the braces converted to underscores: \fBitem_price_\fP\&. Previously such columns would be rejected with an error. (\fI\%#329\fP) .IP \(bu 2 Now also tested against Python 3.10. (\fI\%#330\fP) .UNINDENT .SS 3.17.1 (2021\-09\-22) .INDENT 0.0 .IP \(bu 2 \fI\%sqlite\-utils memory\fP now works if files passed to it share the same file name. (\fI\%#325\fP) .IP \(bu 2 \fI\%sqlite\-utils query\fP now returns \fB[]\fP in JSON mode if no rows are returned. (\fI\%#328\fP) .UNINDENT .SS 3.17 (2021\-08\-24) .INDENT 0.0 .IP \(bu 2 The \fI\%sqlite\-utils memory\fP command has a new \fB\-\-analyze\fP option, which runs the equivalent of the \fI\%analyze\-tables\fP command directly against the in\-memory database created from the incoming CSV or JSON data. (\fI\%#320\fP) .IP \(bu 2 \fI\%sqlite\-utils insert\-files\fP now has the ability to insert file contents in to \fBTEXT\fP columns in addition to the default \fBBLOB\fP\&. Pass the \fB\-\-text\fP option or use \fBcontent_text\fP as a column specifier. (\fI\%#319\fP) .UNINDENT .SS 3.16 (2021\-08\-18) .INDENT 0.0 .IP \(bu 2 Type signatures added to more methods, including \fBtable.resolve_foreign_keys()\fP, \fBdb.create_table_sql()\fP, \fBdb.create_table()\fP and \fBtable.create()\fP\&. (\fI\%#314\fP) .IP \(bu 2 New \fBdb.quote_fts(value)\fP method, see \fI\%Quoting characters for use in search\fP \- thanks, Mark Neumann. (\fI\%#246\fP) .IP \(bu 2 \fBtable.search()\fP now accepts an optional \fBquote=True\fP parameter. (\fI\%#296\fP) .IP \(bu 2 CLI command \fBsqlite\-utils search\fP now accepts a \fB\-\-quote\fP option. (\fI\%#296\fP) .IP \(bu 2 Fixed bug where \fB\-\-no\-headers\fP and \fB\-\-tsv\fP options to \fI\%sqlite\-utils insert\fP could not be used together. (\fI\%#295\fP) .IP \(bu 2 Various small improvements to \fI\%API reference\fP documentation. .UNINDENT .SS 3.15.1 (2021\-08\-10) .INDENT 0.0 .IP \(bu 2 Python library now includes type annotations on almost all of the methods, plus detailed docstrings describing each one. (\fI\%#311\fP) .IP \(bu 2 New \fI\%API reference\fP documentation page, powered by those docstrings. .IP \(bu 2 Fixed bug where \fB\&.add_foreign_keys()\fP failed to raise an error if called against a \fBView\fP\&. (\fI\%#313\fP) .IP \(bu 2 Fixed bug where \fB\&.delete_where()\fP returned a \fB[]\fP instead of returning \fBself\fP if called against a non\-existent table. (\fI\%#315\fP) .UNINDENT .SS 3.15 (2021\-08\-09) .INDENT 0.0 .IP \(bu 2 \fBsqlite\-utils insert \-\-flatten\fP option for \fI\%flattening nested JSON objects\fP to create tables with column names like \fBtopkey_nestedkey\fP\&. (\fI\%#310\fP) .IP \(bu 2 Fixed several spelling mistakes in the documentation, spotted \fI\%using codespell\fP\&. .IP \(bu 2 Errors that occur while using the \fBsqlite\-utils\fP CLI tool now show the responsible SQL and query parameters, if possible. (\fI\%#309\fP) .UNINDENT .SS 3.14 (2021\-08\-02) .sp This release introduces the new \fI\%sqlite\-utils convert command\fP (\fI\%#251\fP) and corresponding \fI\%table.convert(...)\fP Python method (\fI\%#302\fP). These tools can be used to apply a Python conversion function to one or more columns of a table, either updating the column in place or using transformed data from that column to populate one or more other columns. .sp This command\-line example uses the Python standard library \fI\%textwrap module\fP to wrap the content of the \fBcontent\fP column in the \fBarticles\fP table to 100 characters: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils convert content.db articles content \e \(aq"\en".join(textwrap.wrap(value, 100))\(aq \e \-\-import=textwrap .ft P .fi .UNINDENT .UNINDENT .sp The same operation in Python code looks like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import sqlite_utils, textwrap db = sqlite_utils.Database("content.db") db["articles"].convert("content", lambda v: "\en".join(textwrap.wrap(v, 100))) .ft P .fi .UNINDENT .UNINDENT .sp See the full documentation for the \fI\%sqlite\-utils convert command\fP and the \fI\%table.convert(...)\fP Python method for more details. .sp Also in this release: .INDENT 0.0 .IP \(bu 2 The new \fBtable.count_where(...)\fP method, for counting rows in a table that match a specific SQL \fBWHERE\fP clause. (\fI\%#305\fP) .IP \(bu 2 New \fB\-\-silent\fP option for the \fI\%sqlite\-utils insert\-files command\fP to hide the terminal progress bar, consistent with the \fB\-\-silent\fP option for \fBsqlite\-utils convert\fP\&. (\fI\%#301\fP) .UNINDENT .SS 3.13 (2021\-07\-24) .INDENT 0.0 .IP \(bu 2 \fBsqlite\-utils schema my.db table1 table2\fP command now accepts optional table names. (\fI\%#299\fP) .IP \(bu 2 \fBsqlite\-utils memory \-\-help\fP now describes the \fB\-\-schema\fP option. .UNINDENT .SS 3.12 (2021\-06\-25) .INDENT 0.0 .IP \(bu 2 New \fI\%db.query(sql, params)\fP method, which executes a SQL query and returns the results as an iterator over Python dictionaries. (\fI\%#290\fP) .IP \(bu 2 This project now uses \fBflake8\fP and has started to use \fBmypy\fP\&. (\fI\%#291\fP) .IP \(bu 2 New documentation on \fI\%contributing\fP to this project. (\fI\%#292\fP) .UNINDENT .SS 3.11 (2021\-06\-20) .INDENT 0.0 .IP \(bu 2 New \fBsqlite\-utils memory data.csv \-\-schema\fP option, for outputting the schema of the in\-memory database generated from one or more files. See \fI\%\-\-schema, \-\-analyze, \-\-dump and \-\-save\fP\&. (\fI\%#288\fP) .IP \(bu 2 Added \fI\%installation instructions\fP\&. (\fI\%#286\fP) .UNINDENT .SS 3.10 (2021\-06\-19) .sp This release introduces the \fBsqlite\-utils memory\fP command, which can be used to load CSV or JSON data into a temporary in\-memory database and run SQL queries (including joins across multiple files) directly against that data. .sp Also new: \fBsqlite\-utils insert \-\-detect\-types\fP, \fBsqlite\-utils dump\fP, \fBtable.use_rowid\fP plus some smaller fixes. .SS sqlite\-utils memory .sp This example of \fBsqlite\-utils memory\fP retrieves information about the all of the repositories in the \fI\%Dogsheep\fP organization on GitHub using \fI\%this JSON API\fP, sorts them by their number of stars and outputs a table of the top five (using \fB\-t\fP): .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ curl \-s \(aqhttps://api.github.com/users/dogsheep/repos\(aq \e | sqlite\-utils memory \- \(aq select full_name, forks_count, stargazers_count from stdin order by stargazers_count desc limit 5 \(aq \-t full_name forks_count stargazers_count \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- \-\-\-\-\-\-\-\-\-\-\-\-\- \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- dogsheep/twitter\-to\-sqlite 12 225 dogsheep/github\-to\-sqlite 14 139 dogsheep/dogsheep\-photos 5 116 dogsheep/dogsheep.github.io 7 90 dogsheep/healthkit\-to\-sqlite 4 85 .ft P .fi .UNINDENT .UNINDENT .sp The tool works against files on disk as well. This example joins data from two CSV files: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ cat creatures.csv species_id,name 1,Cleo 2,Bants 2,Dori 2,Azi $ cat species.csv id,species_name 1,Dog 2,Chicken $ sqlite\-utils memory species.csv creatures.csv \(aq select * from creatures join species on creatures.species_id = species.id \(aq [{"species_id": 1, "name": "Cleo", "id": 1, "species_name": "Dog"}, {"species_id": 2, "name": "Bants", "id": 2, "species_name": "Chicken"}, {"species_id": 2, "name": "Dori", "id": 2, "species_name": "Chicken"}, {"species_id": 2, "name": "Azi", "id": 2, "species_name": "Chicken"}] .ft P .fi .UNINDENT .UNINDENT .sp Here the \fBspecies.csv\fP file becomes the \fBspecies\fP table, the \fBcreatures.csv\fP file becomes the \fBcreatures\fP table and the output is JSON, the default output format. .sp You can also use the \fB\-\-attach\fP option to attach existing SQLite database files to the in\-memory database, in order to join data from CSV or JSON directly against your existing tables. .sp Full documentation of this new feature is available in \fI\%Querying data directly using an in\-memory database\fP\&. (\fI\%#272\fP) .SS sqlite\-utils insert \-\-detect\-types .sp The \fI\%sqlite\-utils insert\fP command can be used to insert data from JSON, CSV or TSV files into a SQLite database file. The new \fB\-\-detect\-types\fP option (shortcut \fB\-d\fP), when used in conjunction with a CSV or TSV import, will automatically detect if columns in the file are integers or floating point numbers as opposed to treating everything as a text column and create the new table with the corresponding schema. See \fI\%Inserting CSV or TSV data\fP for details. (\fI\%#282\fP) .SS Other changes .INDENT 0.0 .IP \(bu 2 \fBBug fix\fP: \fBtable.transform()\fP, when run against a table without explicit primary keys, would incorrectly create a new version of the table with an explicit primary key column called \fBrowid\fP\&. (\fI\%#284\fP) .IP \(bu 2 New \fBtable.use_rowid\fP introspection property, see \fI\%\&.use_rowid\fP\&. (\fI\%#285\fP) .IP \(bu 2 The new \fBsqlite\-utils dump file.db\fP command outputs a SQL dump that can be used to recreate a database. (\fI\%#274\fP) .IP \(bu 2 \fB\-h\fP now works as a shortcut for \fB\-\-help\fP, thanks Loren McIntyre. (\fI\%#276\fP) .IP \(bu 2 Now using \fI\%pytest\-cov\fP and \fI\%Codecov\fP to track test coverage \- currently at 96%. (\fI\%#275\fP) .IP \(bu 2 SQL errors that occur when using \fBsqlite\-utils query\fP are now displayed as CLI errors. .UNINDENT .SS 3.9.1 (2021\-06\-12) .INDENT 0.0 .IP \(bu 2 Fixed bug when using \fBtable.upsert_all()\fP to create a table with only a single column that is treated as the primary key. (\fI\%#271\fP) .UNINDENT .SS 3.9 (2021\-06\-11) .INDENT 0.0 .IP \(bu 2 New \fBsqlite\-utils schema\fP command showing the full SQL schema for a database, see \fI\%Showing the schema (CLI)\fP\&. (\fI\%#268\fP) .IP \(bu 2 \fBdb.schema\fP introspection property exposing the same feature to the Python library, see \fI\%Showing the schema (Python library)\fP\&. .UNINDENT .SS 3.8 (2021\-06\-02) .INDENT 0.0 .IP \(bu 2 New \fBsqlite\-utils indexes\fP command to list indexes in a database, see \fI\%Listing indexes\fP\&. (\fI\%#263\fP) .IP \(bu 2 \fBtable.xindexes\fP introspection property returning more details about that table\(aqs indexes, see \fI\%\&.xindexes\fP\&. (\fI\%#261\fP) .UNINDENT .SS 3.7 (2021\-05\-28) .INDENT 0.0 .IP \(bu 2 New \fBtable.pks_and_rows_where()\fP method returning \fB(primary_key, row_dictionary)\fP tuples \- see \fI\%Listing rows with their primary keys\fP\&. (\fI\%#240\fP) .IP \(bu 2 Fixed bug with \fBtable.add_foreign_key()\fP against columns containing spaces. (\fI\%#238\fP) .IP \(bu 2 \fBtable_or_view.drop(ignore=True)\fP option for avoiding errors if the table or view does not exist. (\fI\%#237\fP) .IP \(bu 2 \fBsqlite\-utils drop\-view \-\-ignore\fP and \fBsqlite\-utils drop\-table \-\-ignore\fP options. (\fI\%#237\fP) .IP \(bu 2 Fixed a bug with inserts of nested JSON containing non\-ascii strings \- thanks, Dylan Wu. (\fI\%#257\fP) .IP \(bu 2 Suggest \fB\-\-alter\fP if an error occurs caused by a missing column. (\fI\%#259\fP) .IP \(bu 2 Support creating indexes with columns in descending order, see \fI\%API documentation\fP and \fI\%CLI documentation\fP\&. (\fI\%#260\fP) .IP \(bu 2 Correctly handle CSV files that start with a UTF\-8 BOM. (\fI\%#250\fP) .UNINDENT .SS 3.6 (2021\-02\-18) .sp This release adds the ability to execute queries joining data from more than one database file \- similar to the cross database querying feature introduced in \fI\%Datasette 0.55\fP\&. .INDENT 0.0 .IP \(bu 2 The \fBdb.attach(alias, filepath)\fP Python method can be used to attach extra databases to the same connection, see \fI\%db.attach() in the Python API documentation\fP\&. (\fI\%#113\fP) .IP \(bu 2 The \fB\-\-attach\fP option attaches extra aliased databases to run SQL queries against directly on the command\-line, see \fI\%attaching additional databases in the CLI documentation\fP\&. (\fI\%#236\fP) .UNINDENT .SS 3.5 (2021\-02\-14) .INDENT 0.0 .IP \(bu 2 \fBsqlite\-utils insert \-\-sniff\fP option for detecting the delimiter and quote character used by a CSV file, see \fI\%Alternative delimiters and quote characters\fP\&. (\fI\%#230\fP) .IP \(bu 2 The \fBtable.rows_where()\fP, \fBtable.search()\fP and \fBtable.search_sql()\fP methods all now take optional \fBoffset=\fP and \fBlimit=\fP arguments. (\fI\%#231\fP) .IP \(bu 2 New \fB\-\-no\-headers\fP option for \fBsqlite\-utils insert \-\-csv\fP to handle CSV files that are missing the header row, see \fI\%CSV files without a header row\fP\&. (\fI\%#228\fP) .IP \(bu 2 Fixed bug where inserting data with extra columns in subsequent chunks would throw an error. Thanks \fI\%@nieuwenhoven\fP for the fix. (\fI\%#234\fP) .IP \(bu 2 Fixed bug importing CSV files with columns containing more than 128KB of data. (\fI\%#229\fP) .IP \(bu 2 Test suite now runs in CI against Ubuntu, macOS and Windows. Thanks \fI\%@nieuwenhoven\fP for the Windows test fixes. (\fI\%#232\fP) .UNINDENT .SS 3.4.1 (2021\-02\-05) .INDENT 0.0 .IP \(bu 2 Fixed a code import bug that slipped in to 3.4. (\fI\%#226\fP) .UNINDENT .SS 3.4 (2021\-02\-05) .INDENT 0.0 .IP \(bu 2 \fBsqlite\-utils insert \-\-csv\fP now accepts optional \fB\-\-delimiter\fP and \fB\-\-quotechar\fP options. See \fI\%Alternative delimiters and quote characters\fP\&. (\fI\%#223\fP) .UNINDENT .SS 3.3 (2021\-01\-17) .INDENT 0.0 .IP \(bu 2 The \fBtable.m2m()\fP method now accepts an optional \fBalter=True\fP argument to specify that any missing columns should be added to the referenced table. See \fI\%Working with many\-to\-many relationships\fP\&. (\fI\%#222\fP) .UNINDENT .SS 3.2.1 (2021\-01\-12) .INDENT 0.0 .IP \(bu 2 Fixed a bug where \fB\&.add_missing_columns()\fP failed to take case insensitive column names into account. (\fI\%#221\fP) .UNINDENT .SS 3.2 (2021\-01\-03) .sp This release introduces a new mechanism for speeding up \fBcount(*)\fP queries using cached table counts, stored in a \fB_counts\fP table and updated by triggers. This mechanism is described in \fI\%Cached table counts using triggers\fP, and can be enabled using Python API methods or the new \fBenable\-counts\fP CLI command. (\fI\%#212\fP) .INDENT 0.0 .IP \(bu 2 \fBtable.enable_counts()\fP method for enabling these triggers on a specific table. .IP \(bu 2 \fBdb.enable_counts()\fP method for enabling triggers on every table in the database. (\fI\%#213\fP) .IP \(bu 2 New \fBsqlite\-utils enable\-counts my.db\fP command for enabling counts on all or specific tables, see \fI\%Enabling cached counts\fP\&. (\fI\%#214\fP) .IP \(bu 2 New \fBsqlite\-utils triggers\fP command for listing the triggers defined for a database or specific tables, see \fI\%Listing triggers\fP\&. (\fI\%#218\fP) .IP \(bu 2 New \fBdb.use_counts_table\fP property which, if \fBTrue\fP, causes \fBtable.count\fP to read from the \fB_counts\fP table. (\fI\%#215\fP) .IP \(bu 2 \fBtable.has_counts_triggers\fP property revealing if a table has been configured with the new \fB_counts\fP database triggers. .IP \(bu 2 \fBdb.reset_counts()\fP method and \fBsqlite\-utils reset\-counts\fP command for resetting the values in the \fB_counts\fP table. (\fI\%#219\fP) .IP \(bu 2 The previously undocumented \fBdb.escape()\fP method has been renamed to \fBdb.quote()\fP and is now covered by the documentation: \fI\%Quoting strings for use in SQL\fP\&. (\fI\%#217\fP) .IP \(bu 2 New \fBtable.triggers_dict\fP and \fBdb.triggers_dict\fP introspection properties. (\fI\%#211\fP, \fI\%#216\fP) .IP \(bu 2 \fBsqlite\-utils insert\fP now shows a more useful error message for invalid JSON. (\fI\%#206\fP) .UNINDENT .SS 3.1.1 (2021\-01\-01) .INDENT 0.0 .IP \(bu 2 Fixed failing test caused by \fBoptimize\fP sometimes creating larger database files. (\fI\%#209\fP) .IP \(bu 2 Documentation now lives on \fI\%https://sqlite\-utils.datasette.io/\fP .IP \(bu 2 README now includes \fBbrew install sqlite\-utils\fP installation method. .UNINDENT .SS 3.1 (2020\-12\-12) .INDENT 0.0 .IP \(bu 2 New command: \fBsqlite\-utils analyze\-tables my.db\fP outputs useful information about the table columns in the database, such as the number of distinct values and how many rows are null. See \fI\%Analyzing tables\fP for documentation. (\fI\%#207\fP) .IP \(bu 2 New \fBtable.analyze_column(column)\fP Python method used by the \fBanalyze\-tables\fP command \- see \fI\%Analyzing a column\fP\&. .IP \(bu 2 The \fBtable.update()\fP method now correctly handles values that should be stored as JSON. Thanks, Andreas Madsack. (\fI\%#204\fP) .UNINDENT .SS 3.0 (2020\-11\-08) .sp This release introduces a new \fBsqlite\-utils search\fP command for searching tables, see \fI\%Executing searches\fP\&. (\fI\%#192\fP) .sp The \fBtable.search()\fP method has been redesigned, see \fI\%Searching with table.search()\fP\&. (\fI\%#197\fP) .sp The release includes minor backwards\-incompatible changes, hence the version bump to 3.0. Those changes, which should not affect most users, are: .INDENT 0.0 .IP \(bu 2 The \fB\-c\fP shortcut option for outputting CSV is no longer available. The full \fB\-\-csv\fP option is required instead. .IP \(bu 2 The \fB\-f\fP shortcut for \fB\-\-fmt\fP has also been removed \- use \fB\-\-fmt\fP\&. .IP \(bu 2 The \fBtable.search()\fP method now defaults to sorting by relevance, not sorting by \fBrowid\fP\&. (\fI\%#198\fP) .IP \(bu 2 The \fBtable.search()\fP method now returns a generator over a list of Python dictionaries. It previously returned a list of tuples. .UNINDENT .sp Also in this release: .INDENT 0.0 .IP \(bu 2 The \fBquery\fP, \fBtables\fP, \fBrows\fP and \fBsearch\fP CLI commands now accept a new \fB\-\-tsv\fP option which outputs the results in TSV. (\fI\%#193\fP) .IP \(bu 2 A new \fBtable.virtual_table_using\fP property reveals if a table is a virtual table, and returns the upper case type of virtual table (e.g. \fBFTS4\fP or \fBFTS5\fP) if it is. It returns \fBNone\fP if the table is not a virtual table. (\fI\%#196\fP) .IP \(bu 2 The new \fBtable.search_sql()\fP method returns the SQL for searching a table, see \fI\%Building SQL queries with table.search_sql()\fP\&. .IP \(bu 2 \fBsqlite\-utils rows\fP now accepts multiple optional \fB\-c\fP parameters specifying the columns to return. (\fI\%#200\fP) .UNINDENT .sp Changes since the 3.0a0 alpha release: .INDENT 0.0 .IP \(bu 2 The \fBsqlite\-utils search\fP command now defaults to returning every result, unless you add a \fB\-\-limit 20\fP option. .IP \(bu 2 The \fBsqlite\-utils search \-c\fP and \fBtable.search(columns=[])\fP options are now fully respected. (\fI\%#201\fP) .UNINDENT .SS 2.23 (2020\-10\-28) .INDENT 0.0 .IP \(bu 2 \fBtable.m2m(other_table, records)\fP method now takes any iterable, not just a list or tuple. Thanks, Adam Wolf. (\fI\%#189\fP) .IP \(bu 2 \fBsqlite\-utils insert\fP now displays a progress bar for CSV or TSV imports. (\fI\%#173\fP) .IP \(bu 2 New \fB@db.register_function(deterministic=True)\fP option for registering deterministic SQLite functions in Python 3.8 or higher. (\fI\%#191\fP) .UNINDENT .SS 2.22 (2020\-10\-16) .INDENT 0.0 .IP \(bu 2 New \fB\-\-encoding\fP option for processing CSV and TSV files that use a non\-utf\-8 encoding, for both the \fBinsert\fP and \fBupdate\fP commands. (\fI\%#182\fP) .IP \(bu 2 The \fB\-\-load\-extension\fP option is now available to many more commands. (\fI\%#137\fP) .IP \(bu 2 \fB\-\-load\-extension=spatialite\fP can be used to load SpatiaLite from common installation locations, if it is available. (\fI\%#136\fP) .IP \(bu 2 Tests now also run against Python 3.9. (\fI\%#184\fP) .IP \(bu 2 Passing \fBpk=["id"]\fP now has the same effect as passing \fBpk="id"\fP\&. (\fI\%#181\fP) .UNINDENT .SS 2.21 (2020\-09\-24) .INDENT 0.0 .IP \(bu 2 \fBtable.extract()\fP and \fBsqlite\-utils extract\fP now apply much, much faster \- one example operation reduced from twelve minutes to just four seconds! (\fI\%#172\fP) .IP \(bu 2 \fBsqlite\-utils extract\fP no longer shows a progress bar, because it\(aqs fast enough not to need one. .IP \(bu 2 New \fBcolumn_order=\fP option for \fBtable.transform()\fP which can be used to alter the order of columns in a table. (\fI\%#175\fP) .IP \(bu 2 \fBsqlite\-utils transform \-\-column\-order=\fP option (with a \fB\-o\fP shortcut) for changing column order. (\fI\%#176\fP) .IP \(bu 2 The \fBtable.transform(drop_foreign_keys=)\fP parameter and the \fBsqlite\-utils transform \-\-drop\-foreign\-key\fP option have changed. They now accept just the name of the column rather than requiring all three of the column, other table and other column. This is technically a backwards\-incompatible change but I chose not to bump the major version number because the transform feature is so new. (\fI\%#177\fP) .IP \(bu 2 The table \fB\&.disable_fts()\fP, \fB\&.rebuild_fts()\fP, \fB\&.delete()\fP, \fB\&.delete_where()\fP and \fB\&.add_missing_columns()\fP methods all now \fBreturn self\fP, which means they can be chained together with other table operations. .UNINDENT .SS 2.20 (2020\-09\-22) .sp This release introduces two key new capabilities: \fBtransform\fP (\fI\%#114\fP) and \fBextract\fP (\fI\%#42\fP). .SS Transform .sp SQLite\(aqs ALTER TABLE has \fI\%several documented limitations\fP\&. The \fBtable.transform()\fP Python method and \fBsqlite\-utils transform\fP CLI command work around these limitations using a pattern where a new table with the desired structure is created, data is copied over to it and the old table is then dropped and replaced by the new one. .sp You can use these tools to change column types, rename columns, drop columns, add and remove \fBNOT NULL\fP and defaults, remove foreign key constraints and more. See the \fI\%transforming tables (CLI)\fP and \fI\%transforming tables (Python library)\fP documentation for full details of how to use them. .SS Extract .sp Sometimes a database table \- especially one imported from a CSV file \- will contain duplicate data. A \fBTrees\fP table may include a \fBSpecies\fP column with only a few dozen unique values, when the table itself contains thousands of rows. .sp The \fBtable.extract()\fP method and \fBsqlite\-utils extract\fP commands can extract a column \- or multiple columns \- out into a separate lookup table, and set up a foreign key relationship from the original table. .sp The Python library \fI\%extract() documentation\fP describes how extraction works in detail, and \fI\%Extracting columns into a separate table\fP in the CLI documentation includes a detailed example. .SS Other changes .INDENT 0.0 .IP \(bu 2 The \fB@db.register_function\fP decorator can be used to quickly register Python functions as custom SQL functions, see \fI\%Registering custom SQL functions\fP\&. (\fI\%#162\fP) .IP \(bu 2 The \fBtable.rows_where()\fP method now accepts an optional \fBselect=\fP argument for specifying which columns should be selected, see \fI\%Listing rows\fP\&. .UNINDENT .SS 2.19 (2020\-09\-20) .INDENT 0.0 .IP \(bu 2 New \fBsqlite\-utils add\-foreign\-keys\fP command for \fI\%Adding multiple foreign keys at once\fP\&. (\fI\%#157\fP) .IP \(bu 2 New \fBtable.enable_fts(..., replace=True)\fP argument for replacing an existing FTS table with a new configuration. (\fI\%#160\fP) .IP \(bu 2 New \fBtable.add_foreign_key(..., ignore=True)\fP argument for ignoring a foreign key if it already exists. (\fI\%#112\fP) .UNINDENT .SS 2.18 (2020\-09\-08) .INDENT 0.0 .IP \(bu 2 \fBtable.rebuild_fts()\fP method for rebuilding a FTS index, see \fI\%Rebuilding a full\-text search table\fP\&. (\fI\%#155\fP) .IP \(bu 2 \fBsqlite\-utils rebuild\-fts data.db\fP command for rebuilding FTS indexes across all tables, or just specific tables. (\fI\%#155\fP) .IP \(bu 2 \fBtable.optimize()\fP method no longer deletes junk rows from the \fB*_fts_docsize\fP table. This was added in 2.17 but it turns out running \fBtable.rebuild_fts()\fP is a better solution to this problem. .IP \(bu 2 Fixed a bug where rows with additional columns that are inserted after the first batch of records could cause an error due to breaking SQLite\(aqs maximum number of parameters. Thanks, Simon Wiles. (\fI\%#145\fP) .UNINDENT .SS 2.17 (2020\-09\-07) .sp This release handles a bug where replacing rows in FTS tables could result in growing numbers of unnecessary rows in the associated \fB*_fts_docsize\fP table. (\fI\%#149\fP) .INDENT 0.0 .IP \(bu 2 \fBPRAGMA recursive_triggers=on\fP by default for all connections. You can turn it off with \fBDatabase(recursive_triggers=False)\fP\&. (\fI\%#152\fP) .IP \(bu 2 \fBtable.optimize()\fP method now deletes unnecessary rows from the \fB*_fts_docsize\fP table. (\fI\%#153\fP) .IP \(bu 2 New tracer method for tracking underlying SQL queries, see \fI\%Tracing queries\fP\&. (\fI\%#150\fP) .IP \(bu 2 Neater indentation for schema SQL. (\fI\%#148\fP) .IP \(bu 2 Documentation for \fBsqlite_utils.AlterError\fP exception thrown by in \fBadd_foreign_keys()\fP\&. .UNINDENT .SS 2.16.1 (2020\-08\-28) .INDENT 0.0 .IP \(bu 2 \fBinsert_all(..., alter=True)\fP now works for columns introduced after the first 100 records. Thanks, Simon Wiles! (\fI\%#139\fP) .IP \(bu 2 Continuous Integration is now powered by GitHub Actions. (\fI\%#143\fP) .UNINDENT .SS 2.16 (2020\-08\-21) .INDENT 0.0 .IP \(bu 2 \fB\-\-load\-extension\fP option for \fBsqlite\-utils query\fP for loading SQLite extensions. (\fI\%#134\fP) .IP \(bu 2 New \fBsqlite_utils.utils.find_spatialite()\fP function for finding SpatiaLite in common locations. (\fI\%#135\fP) .UNINDENT .SS 2.15.1 (2020\-08\-12) .INDENT 0.0 .IP \(bu 2 Now available as a \fBsdist\fP package on PyPI in addition to a wheel. (\fI\%#133\fP) .UNINDENT .SS 2.15 (2020\-08\-10) .INDENT 0.0 .IP \(bu 2 New \fBdb.enable_wal()\fP and \fBdb.disable_wal()\fP methods for enabling and disabling \fI\%Write\-Ahead Logging\fP for a database file \- see \fI\%WAL mode\fP in the Python API documentation. .IP \(bu 2 Also \fBsqlite\-utils enable\-wal file.db\fP and \fBsqlite\-utils disable\-wal file.db\fP commands for doing the same thing on the command\-line, see \fI\%WAL mode (CLI)\fP\&. (\fI\%#132\fP) .UNINDENT .SS 2.14.1 (2020\-08\-05) .INDENT 0.0 .IP \(bu 2 Documentation improvements. .UNINDENT .SS 2.14 (2020\-08\-01) .INDENT 0.0 .IP \(bu 2 The \fI\%insert\-files command\fP can now read from standard input: \fBcat dog.jpg | sqlite\-utils insert\-files dogs.db pics \- \-\-name=dog.jpg\fP\&. (\fI\%#127\fP) .IP \(bu 2 You can now specify a full\-text search tokenizer using the new \fBtokenize=\fP parameter to \fI\%enable_fts()\fP\&. This means you can enable Porter stemming on a table by running \fBdb["articles"].enable_fts(["headline", "body"], tokenize="porter")\fP\&. (\fI\%#130\fP) .IP \(bu 2 You can also set a custom tokenizer using the \fI\%sqlite\-utils enable\-fts\fP CLI command, via the new \fB\-\-tokenize\fP option. .UNINDENT .SS 2.13 (2020\-07\-29) .INDENT 0.0 .IP \(bu 2 \fBmemoryview\fP and \fBuuid.UUID\fP objects are now supported. \fBmemoryview\fP objects will be stored using \fBBLOB\fP and \fBuuid.UUID\fP objects will be stored using \fBTEXT\fP\&. (\fI\%#128\fP) .UNINDENT .SS 2.12 (2020\-07\-27) .sp The theme of this release is better tools for working with binary data. The new \fBinsert\-files\fP command can be used to insert binary files directly into a database table, and other commands have been improved with better support for BLOB columns. .INDENT 0.0 .IP \(bu 2 \fBsqlite\-utils insert\-files my.db gifs *.gif\fP can now insert the contents of files into a specified table. The columns in the table can be customized to include different pieces of metadata derived from the files. See \fI\%Inserting data from files\fP\&. (\fI\%#122\fP) .IP \(bu 2 \fB\-\-raw\fP option to \fBsqlite\-utils query\fP \- for outputting just a single raw column value \- see \fI\%Returning raw data, such as binary content\fP\&. (\fI\%#123\fP) .IP \(bu 2 JSON output now encodes BLOB values as special base64 objects \- see \fI\%Returning JSON\fP\&. (\fI\%#125\fP) .IP \(bu 2 The same format of JSON base64 objects can now be used to insert binary data \- see \fI\%Inserting JSON data\fP\&. (\fI\%#126\fP) .IP \(bu 2 The \fBsqlite\-utils query\fP command can now accept named parameters, e.g. \fBsqlite\-utils :memory: "select :num * :num2" \-p num 5 \-p num2 6\fP \- see \fI\%Returning JSON\fP\&. (\fI\%#124\fP) .UNINDENT .SS 2.11 (2020\-07\-08) .INDENT 0.0 .IP \(bu 2 New \fB\-\-truncate\fP option to \fBsqlite\-utils insert\fP, and \fBtruncate=True\fP argument to \fB\&.insert_all()\fP\&. Thanks, Thomas Sibley. (\fI\%#118\fP) .IP \(bu 2 The \fBsqlite\-utils query\fP command now runs updates in a transaction. Thanks, Thomas Sibley. (\fI\%#120\fP) .UNINDENT .SS 2.10.1 (2020\-06\-23) .INDENT 0.0 .IP \(bu 2 Added documentation for the \fBtable.pks\fP introspection property. (\fI\%#116\fP) .UNINDENT .SS 2.10 (2020\-06\-12) .INDENT 0.0 .IP \(bu 2 The \fBsqlite\-utils\fP command now supports UPDATE/INSERT/DELETE in addition to SELECT. (\fI\%#115\fP) .UNINDENT .SS 2.9.1 (2020\-05\-11) .INDENT 0.0 .IP \(bu 2 Added custom project links to the \fI\%PyPI listing\fP\&. .UNINDENT .SS 2.9 (2020\-05\-10) .INDENT 0.0 .IP \(bu 2 New \fBsqlite\-utils drop\-table\fP command, see \fI\%Dropping tables\fP\&. (\fI\%#111\fP) .IP \(bu 2 New \fBsqlite\-utils drop\-view\fP command, see \fI\%Dropping views\fP\&. .IP \(bu 2 Python \fBdecimal.Decimal\fP objects are now stored as \fBFLOAT\fP\&. (\fI\%#110\fP) .UNINDENT .SS 2.8 (2020\-05\-03) .INDENT 0.0 .IP \(bu 2 New \fBsqlite\-utils create\-table\fP command, see \fI\%Creating tables\fP\&. (\fI\%#27\fP) .IP \(bu 2 New \fBsqlite\-utils create\-view\fP command, see \fI\%Creating views\fP\&. (\fI\%#107\fP) .UNINDENT .SS 2.7.2 (2020\-05\-02) .INDENT 0.0 .IP \(bu 2 \fBdb.create_view(...)\fP now has additional parameters \fBignore=True\fP or \fBreplace=True\fP, see \fI\%Creating views\fP\&. (\fI\%#106\fP) .UNINDENT .SS 2.7.1 (2020\-05\-01) .INDENT 0.0 .IP \(bu 2 New \fBsqlite\-utils views my.db\fP command for listing views in a database, see \fI\%Listing views\fP\&. (\fI\%#105\fP) .IP \(bu 2 \fBsqlite\-utils tables\fP (and \fBviews\fP) has a new \fB\-\-schema\fP option which outputs the table/view schema, see \fI\%Listing tables\fP\&. (\fI\%#104\fP) .IP \(bu 2 Nested structures containing invalid JSON values (e.g. Python bytestrings) are now serialized using \fBrepr()\fP instead of throwing an error. (\fI\%#102\fP) .UNINDENT .SS 2.7 (2020\-04\-17) .INDENT 0.0 .IP \(bu 2 New \fBcolumns=\fP argument for the \fB\&.insert()\fP, \fB\&.insert_all()\fP, \fB\&.upsert()\fP and \fB\&.upsert_all()\fP methods, for over\-riding the auto\-detected types for columns and specifying additional columns that should be added when the table is created. See \fI\%Custom column order and column types\fP\&. (\fI\%#100\fP) .UNINDENT .SS 2.6 (2020\-04\-15) .INDENT 0.0 .IP \(bu 2 New \fBtable.rows_where(..., order_by="age desc")\fP argument, see \fI\%Listing rows\fP\&. (\fI\%#76\fP) .UNINDENT .SS 2.5 (2020\-04\-12) .INDENT 0.0 .IP \(bu 2 Panda\(aqs Timestamp is now stored as a SQLite TEXT column. Thanks, b0b5h4rp13! (\fI\%#96\fP) .IP \(bu 2 \fBtable.last_pk\fP is now only available for inserts or upserts of a single record. (\fI\%#98\fP) .IP \(bu 2 New \fBDatabase(filepath, recreate=True)\fP parameter for deleting and recreating the database. (\fI\%#97\fP) .UNINDENT .SS 2.4.4 (2020\-03\-23) .INDENT 0.0 .IP \(bu 2 Fixed bug where columns with only null values were not correctly created. (\fI\%#95\fP) .UNINDENT .SS 2.4.3 (2020\-03\-23) .INDENT 0.0 .IP \(bu 2 Column type suggestion code is no longer confused by null values. (\fI\%#94\fP) .UNINDENT .SS 2.4.2 (2020\-03\-14) .INDENT 0.0 .IP \(bu 2 \fBtable.column_dicts\fP now works with all column types \- previously it would throw errors on types other than \fBTEXT\fP, \fBBLOB\fP, \fBINTEGER\fP or \fBFLOAT\fP\&. (\fI\%#92\fP) .IP \(bu 2 Documentation for \fBNotFoundError\fP thrown by \fBtable.get(pk)\fP \- see \fI\%Retrieving a specific record\fP\&. .UNINDENT .SS 2.4.1 (2020\-03\-01) .INDENT 0.0 .IP \(bu 2 \fBtable.enable_fts()\fP now works with columns that contain spaces. (\fI\%#90\fP) .UNINDENT .SS 2.4 (2020\-02\-26) .INDENT 0.0 .IP \(bu 2 \fBtable.disable_fts()\fP can now be used to remove FTS tables and triggers that were created using \fBtable.enable_fts(...)\fP\&. (\fI\%#88\fP) .IP \(bu 2 The \fBsqlite\-utils disable\-fts\fP command can be used to remove FTS tables and triggers from the command\-line. (\fI\%#88\fP) .IP \(bu 2 Trying to create table columns with square braces ([ or ]) in the name now raises an error. (\fI\%#86\fP) .IP \(bu 2 Subclasses of \fBdict\fP, \fBlist\fP and \fBtuple\fP are now detected as needing a JSON column. (\fI\%#87\fP) .UNINDENT .SS 2.3.1 (2020\-02\-10) .sp \fBtable.create_index()\fP now works for columns that contain spaces. (\fI\%#85\fP) .SS 2.3 (2020\-02\-08) .sp \fBtable.exists()\fP is now a method, not a property. This was not a documented part of the API before so I\(aqm considering this a non\-breaking change. (\fI\%#83\fP) .SS 2.2.1 (2020\-02\-06) .sp Fixed a bug where \fB\&.upsert(..., hash_id="pk")\fP threw an error (\fI\%#84\fP). .SS 2.2 (2020\-02\-01) .sp New feature: \fBsqlite_utils.suggest_column_types([records])\fP returns the suggested column types for a list of records. See \fI\%Suggesting column types\fP\&. (\fI\%#81\fP). .sp This replaces the undocumented \fBtable.detect_column_types()\fP method. .SS 2.1 (2020\-01\-30) .sp New feature: \fBconversions={...}\fP can be passed to the \fB\&.insert()\fP family of functions to specify SQL conversions that should be applied to values that are being inserted or updated. See \fI\%Converting column values using SQL functions\fP . (\fI\%#77\fP). .SS 2.0.1 (2020\-01\-05) .sp The \fB\&.upsert()\fP and \fB\&.upsert_all()\fP methods now raise a \fBsqlite_utils.db.PrimaryKeyRequired\fP exception if you call them without specifying the primary key column using \fBpk=\fP (\fI\%#73\fP). .SS 2.0 (2019\-12\-29) .sp This release changes the behaviour of \fBupsert\fP\&. It\(aqs a breaking change, hence \fB2.0\fP\&. .sp The \fBupsert\fP command\-line utility and the \fB\&.upsert()\fP and \fB\&.upsert_all()\fP Python API methods have had their behaviour altered. They used to completely replace the affected records: now, they update the specified values on existing records but leave other columns unaffected. .sp See \fI\%Upserting data using the Python API\fP and \fI\%Upserting data using the CLI\fP for full details. .sp If you want the old behaviour \- where records were completely replaced \- you can use \fB$ sqlite\-utils insert ... \-\-replace\fP on the command\-line and \fB\&.insert(..., replace=True)\fP and \fB\&.insert_all(..., replace=True)\fP in the Python API. See \fI\%Insert\-replacing data using the Python API\fP and \fI\%Insert\-replacing data using the CLI\fP for more. .sp For full background on this change, see \fI\%issue #66\fP\&. .SS 1.12.1 (2019\-11\-06) .INDENT 0.0 .IP \(bu 2 Fixed error thrown when \fB\&.insert_all()\fP and \fB\&.upsert_all()\fP were called with empty lists (\fI\%#52\fP) .UNINDENT .SS 1.12 (2019\-11\-04) .sp Python library utilities for deleting records (\fI\%#62\fP) .INDENT 0.0 .IP \(bu 2 \fBdb["tablename"].delete(4)\fP to delete by primary key, see \fI\%Deleting a specific record\fP .IP \(bu 2 \fBdb["tablename"].delete_where("id > ?", [3])\fP to delete by a where clause, see \fI\%Deleting multiple records\fP .UNINDENT .SS 1.11 (2019\-09\-02) .sp Option to create triggers to automatically keep FTS tables up\-to\-date with newly inserted, updated and deleted records. Thanks, Amjith Ramanujam! (\fI\%#57\fP) .INDENT 0.0 .IP \(bu 2 \fBsqlite\-utils enable\-fts ... \-\-create\-triggers\fP \- see \fI\%Configuring full\-text search using the CLI\fP .IP \(bu 2 \fBdb["tablename"].enable_fts(..., create_triggers=True)\fP \- see \fI\%Configuring full\-text search using the Python library\fP .IP \(bu 2 Support for introspecting triggers for a database or table \- see \fI\%Introspecting tables and views\fP (\fI\%#59\fP) .UNINDENT .SS 1.10 (2019\-08\-23) .sp Ability to introspect and run queries against views (\fI\%#54\fP) .INDENT 0.0 .IP \(bu 2 \fBdb.view_names()\fP method and and \fBdb.views\fP property .IP \(bu 2 Separate \fBView\fP and \fBTable\fP classes, both subclassing new \fBQueryable\fP class .IP \(bu 2 \fBview.drop()\fP method .UNINDENT .sp See \fI\%Listing views\fP\&. .SS 1.9 (2019\-08\-04) .INDENT 0.0 .IP \(bu 2 \fBtable.m2m(...)\fP method for creating many\-to\-many relationships: \fI\%Working with many\-to\-many relationships\fP (\fI\%#23\fP) .UNINDENT .SS 1.8 (2019\-07\-28) .INDENT 0.0 .IP \(bu 2 \fBtable.update(pk, values)\fP method: \fI\%Updating a specific record\fP (\fI\%#35\fP) .UNINDENT .SS 1.7.1 (2019\-07\-28) .INDENT 0.0 .IP \(bu 2 Fixed bug where inserting records with 11 columns in a batch of 100 triggered a "too many SQL variables" error (\fI\%#50\fP) .IP \(bu 2 Documentation and tests for \fBtable.drop()\fP method: \fI\%Dropping a table or view\fP .UNINDENT .SS 1.7 (2019\-07\-24) .sp Support for lookup tables. .INDENT 0.0 .IP \(bu 2 New \fBtable.lookup({...})\fP utility method for building and querying lookup tables \- see \fI\%Working with lookup tables\fP (\fI\%#44\fP) .IP \(bu 2 New \fBextracts=\fP table configuration option, see \fI\%Populating lookup tables automatically during insert/upsert\fP (\fI\%#46\fP) .IP \(bu 2 Use \fI\%pysqlite3\fP if it is available, otherwise use \fBsqlite3\fP from the standard library .IP \(bu 2 Table options can now be passed to the new \fBdb.table(name, **options)\fP factory function in addition to being passed to \fBinsert_all(records, **options)\fP and friends \- see \fI\%Table configuration options\fP .IP \(bu 2 In\-memory databases can now be created using \fBdb = Database(memory=True)\fP .UNINDENT .SS 1.6 (2019\-07\-18) .INDENT 0.0 .IP \(bu 2 \fBsqlite\-utils insert\fP can now accept TSV data via the new \fB\-\-tsv\fP option (\fI\%#41\fP) .UNINDENT .SS 1.5 (2019\-07\-14) .INDENT 0.0 .IP \(bu 2 Support for compound primary keys (\fI\%#36\fP) .INDENT 2.0 .IP \(bu 2 Configure these using the CLI tool by passing \fB\-\-pk\fP multiple times .IP \(bu 2 In Python, pass a tuple of columns to the \fBpk=(..., ...)\fP argument: \fI\%Compound primary keys\fP .UNINDENT .IP \(bu 2 New \fBtable.get()\fP method for retrieving a record by its primary key: \fI\%Retrieving a specific record\fP (\fI\%#39\fP) .UNINDENT .SS 1.4.1 (2019\-07\-14) .INDENT 0.0 .IP \(bu 2 Assorted minor documentation fixes: \fI\%changes since 1.4\fP .UNINDENT .SS 1.4 (2019\-06\-30) .INDENT 0.0 .IP \(bu 2 Added \fBsqlite\-utils index\-foreign\-keys\fP command (\fI\%docs\fP) and \fBdb.index_foreign_keys()\fP method (\fI\%docs\fP) (\fI\%#33\fP) .UNINDENT .SS 1.3 (2019\-06\-28) .INDENT 0.0 .IP \(bu 2 New mechanism for adding multiple foreign key constraints at once: \fI\%db.add_foreign_keys() documentation\fP (\fI\%#31\fP) .UNINDENT .SS 1.2.2 (2019\-06\-25) .INDENT 0.0 .IP \(bu 2 Fixed bug where \fBdatetime.time\fP was not being handled correctly .UNINDENT .SS 1.2.1 (2019\-06\-20) .INDENT 0.0 .IP \(bu 2 Check the column exists before attempting to add a foreign key (\fI\%#29\fP) .UNINDENT .SS 1.2 (2019\-06\-12) .INDENT 0.0 .IP \(bu 2 Improved foreign key definitions: you no longer need to specify the \fBcolumn\fP, \fBother_table\fP AND \fBother_column\fP to define a foreign key \- if you omit the \fBother_table\fP or \fBother_column\fP the script will attempt to guess the correct values by introspecting the database. See \fI\%Adding foreign key constraints\fP for details. (\fI\%#25\fP) .IP \(bu 2 Ability to set \fBNOT NULL\fP constraints and \fBDEFAULT\fP values when creating tables (\fI\%#24\fP). Documentation: \fI\%Setting defaults and not null constraints (Python API)\fP, \fI\%Setting defaults and not null constraints (CLI)\fP .IP \(bu 2 Support for \fBnot_null_default=X\fP / \fB\-\-not\-null\-default\fP for setting a \fBNOT NULL DEFAULT \(aqx\(aq\fP when adding a new column. Documentation: \fI\%Adding columns (Python API)\fP, \fI\%Adding columns (CLI)\fP .UNINDENT .SS 1.1 (2019\-05\-28) .INDENT 0.0 .IP \(bu 2 Support for \fBignore=True\fP / \fB\-\-ignore\fP for ignoring inserted records if the primary key already exists (\fI\%#21\fP) \- documentation: \fI\%Inserting data (Python API)\fP, \fI\%Inserting data (CLI)\fP .IP \(bu 2 Ability to add a column that is a foreign key reference using \fBfk=...\fP / \fB\-\-fk\fP (\fI\%#16\fP) \- documentation: \fI\%Adding columns (Python API)\fP, \fI\%Adding columns (CLI)\fP .UNINDENT .SS 1.0.1 (2019\-05\-27) .INDENT 0.0 .IP \(bu 2 \fBsqlite\-utils rows data.db table \-\-json\-cols\fP \- fixed bug where \fB\-\-json\-cols\fP was not obeyed .UNINDENT .SS 1.0 (2019\-05\-24) .INDENT 0.0 .IP \(bu 2 .INDENT 2.0 .TP .B Option to automatically add new columns if you attempt to insert or upsert data with extra fields: \fBsqlite\-utils insert ... \-\-alter\fP \- see \fI\%Adding columns automatically with the sqlite\-utils CLI\fP .sp \fBdb["tablename"].insert(record, alter=True)\fP \- see \fI\%Adding columns automatically using the Python API\fP .UNINDENT .IP \(bu 2 New \fB\-\-json\-cols\fP option for outputting nested JSON, see \fI\%Nested JSON values\fP .UNINDENT .SS 0.14 (2019\-02\-24) .INDENT 0.0 .IP \(bu 2 Ability to create unique indexes: \fBdb["mytable"].create_index(["name"], unique=True)\fP .IP \(bu 2 \fBdb["mytable"].create_index(["name"], if_not_exists=True)\fP .IP \(bu 2 \fB$ sqlite\-utils create\-index mydb.db mytable col1 [col2...]\fP, see \fI\%Creating indexes\fP .IP \(bu 2 \fBtable.add_column(name, type)\fP method, see \fI\%Adding columns\fP .IP \(bu 2 \fB$ sqlite\-utils add\-column mydb.db mytable nameofcolumn\fP, see \fI\%Adding columns\fP (CLI) .IP \(bu 2 \fBdb["books"].add_foreign_key("author_id", "authors", "id")\fP, see \fI\%Adding foreign key constraints\fP .IP \(bu 2 \fB$ sqlite\-utils add\-foreign\-key books.db books author_id authors id\fP, see \fI\%Adding foreign key constraints\fP (CLI) .IP \(bu 2 Improved (but backwards\-incompatible) \fBforeign_keys=\fP argument to various methods, see \fI\%Specifying foreign keys\fP .UNINDENT .SS 0.13 (2019\-02\-23) .INDENT 0.0 .IP \(bu 2 New \fB\-\-table\fP and \fB\-\-fmt\fP options can be used to output query results in a variety of visual table formats, see \fI\%Table\-formatted output\fP .IP \(bu 2 New \fBhash_id=\fP argument can now be used for \fI\%Setting an ID based on the hash of the row contents\fP .IP \(bu 2 Can now derive correct column types for numpy int, uint and float values .IP \(bu 2 \fBtable.last_id\fP has been renamed to \fBtable.last_rowid\fP .IP \(bu 2 \fBtable.last_pk\fP now contains the last inserted primary key, if \fBpk=\fP was specified .IP \(bu 2 Prettier indentation in the \fBCREATE TABLE\fP generated schemas .UNINDENT .SS 0.12 (2019\-02\-22) .INDENT 0.0 .IP \(bu 2 Added \fBdb[table].rows\fP iterator \- see \fI\%Listing rows\fP .IP \(bu 2 Replaced \fBsqlite\-utils json\fP and \fBsqlite\-utils csv\fP with a new default subcommand called \fBsqlite\-utils query\fP which defaults to JSON and takes formatting options \fB\-\-nl\fP, \fB\-\-csv\fP and \fB\-\-no\-headers\fP \- see \fI\%Returning JSON\fP and \fI\%Returning CSV or TSV\fP .IP \(bu 2 New \fBsqlite\-utils rows data.db name\-of\-table\fP command, see \fI\%Returning all rows in a table\fP .IP \(bu 2 \fBsqlite\-utils table\fP command now takes options \fB\-\-counts\fP and \fB\-\-columns\fP plus the standard output format options, see \fI\%Listing tables\fP .UNINDENT .SS 0.11 (2019\-02\-07) .sp New commands for enabling FTS against a table and columns: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C sqlite\-utils enable\-fts db.db mytable col1 col2 .ft P .fi .UNINDENT .UNINDENT .sp See \fI\%Configuring full\-text search\fP\&. .SS 0.10 (2019\-02\-06) .sp Handle \fBdatetime.date\fP and \fBdatetime.time\fP values. .sp New option for efficiently inserting rows from a CSV: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C sqlite\-utils insert db.db foo \- \-\-csv .ft P .fi .UNINDENT .UNINDENT .SS 0.9 (2019\-01\-27) .sp Improved support for newline\-delimited JSON. .sp \fBsqlite\-utils insert\fP has two new command\-line options: .INDENT 0.0 .IP \(bu 2 \fB\-\-nl\fP means "expect newline\-delimited JSON". This is an extremely efficient way of loading in large amounts of data, especially if you pipe it into standard input. .IP \(bu 2 \fB\-\-batch\-size=1000\fP lets you increase the batch size (default is 100). A commit will be issued every X records. This also control how many initial records are considered when detecting the desired SQL table schema for the data. .UNINDENT .sp In the Python API, the \fBtable.insert_all(...)\fP method can now accept a generator as well as a list of objects. This will be efficiently used to populate the table no matter how many records are produced by the generator. .sp The \fBDatabase()\fP constructor can now accept a \fBpathlib.Path\fP object in addition to a string or an existing SQLite connection object. .SS 0.8 (2019\-01\-25) .sp Two new commands: \fBsqlite\-utils csv\fP and \fBsqlite\-utils json\fP .sp These commands execute a SQL query and return the results as CSV or JSON. See \fI\%Returning CSV or TSV\fP and \fI\%Returning JSON\fP for more details. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ sqlite\-utils json \-\-help Usage: sqlite\-utils json [OPTIONS] PATH SQL Execute SQL query and return the results as JSON Options: \-\-nl Output newline\-delimited JSON \-\-arrays Output rows as arrays instead of objects \-\-help Show this message and exit. $ sqlite\-utils csv \-\-help Usage: sqlite\-utils csv [OPTIONS] PATH SQL Execute SQL query and return the results as CSV Options: \-\-no\-headers Exclude headers from CSV output \-\-help Show this message and exit. .ft P .fi .UNINDENT .UNINDENT .SS 0.7 (2019\-01\-24) .sp This release implements the \fBsqlite\-utils\fP command\-line tool with a number of useful subcommands. .INDENT 0.0 .IP \(bu 2 \fBsqlite\-utils tables demo.db\fP lists the tables in the database .IP \(bu 2 \fBsqlite\-utils tables demo.db \-\-fts4\fP shows just the FTS4 tables .IP \(bu 2 \fBsqlite\-utils tables demo.db \-\-fts5\fP shows just the FTS5 tables .IP \(bu 2 \fBsqlite\-utils vacuum demo.db\fP runs VACUUM against the database .IP \(bu 2 \fBsqlite\-utils optimize demo.db\fP runs OPTIMIZE against all FTS tables, then VACUUM .IP \(bu 2 \fBsqlite\-utils optimize demo.db \-\-no\-vacuum\fP runs OPTIMIZE but skips VACUUM .UNINDENT .sp The two most useful subcommands are \fBupsert\fP and \fBinsert\fP, which allow you to ingest JSON files with one or more records in them, creating the corresponding table with the correct columns if it does not already exist. See \fI\%Inserting JSON data\fP for more details. .INDENT 0.0 .IP \(bu 2 \fBsqlite\-utils insert demo.db dogs dogs.json \-\-pk=id\fP inserts new records from \fBdogs.json\fP into the \fBdogs\fP table .IP \(bu 2 \fBsqlite\-utils upsert demo.db dogs dogs.json \-\-pk=id\fP upserts records, replacing any records with duplicate primary keys .UNINDENT .sp One backwards incompatible change: the \fBdb["table"].table_names\fP property is now a method: .INDENT 0.0 .IP \(bu 2 \fBdb["table"].table_names()\fP returns a list of table names .IP \(bu 2 \fBdb["table"].table_names(fts4=True)\fP returns a list of just the FTS4 tables .IP \(bu 2 \fBdb["table"].table_names(fts5=True)\fP returns a list of just the FTS5 tables .UNINDENT .sp A few other changes: .INDENT 0.0 .IP \(bu 2 Plenty of updated documentation, including full coverage of the new command\-line tool .IP \(bu 2 Allow column names to be reserved words (use correct SQL escaping) .IP \(bu 2 Added automatic column support for bytes and datetime.datetime .UNINDENT .SS 0.6 (2018\-08\-12) .INDENT 0.0 .IP \(bu 2 \fB\&.enable_fts()\fP now takes optional argument \fBfts_version\fP, defaults to \fBFTS5\fP\&. Use \fBFTS4\fP if the version of SQLite bundled with your Python does not support FTS5 .IP \(bu 2 New optional \fBcolumn_order=\fP argument to \fB\&.insert()\fP and friends for providing a partial or full desired order of the columns when a database table is created .IP \(bu 2 \fI\%New documentation\fP for \fB\&.insert_all()\fP and \fB\&.upsert()\fP and \fB\&.upsert_all()\fP .UNINDENT .SS 0.5 (2018\-08\-05) .INDENT 0.0 .IP \(bu 2 \fBdb.tables\fP and \fBdb.table_names\fP introspection properties .IP \(bu 2 \fBdb.indexes\fP property for introspecting indexes .IP \(bu 2 \fBtable.create_index(columns, index_name)\fP method .IP \(bu 2 \fBdb.create_view(name, sql)\fP method .IP \(bu 2 Table methods can now be chained, plus added \fBtable.last_id\fP for accessing the last inserted row ID .UNINDENT .SS 0.4 (2018\-07\-31) .INDENT 0.0 .IP \(bu 2 \fBenable_fts()\fP, \fBpopulate_fts()\fP and \fBsearch()\fP table methods .UNINDENT .SH AUTHOR Simon Willison .SH COPYRIGHT 2018-2022, Simon Willison .\" Generated by docutils manpage writer. .