GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||||||||
GeezerVison is showing sqlite-utils.datasette.io — sqlite-utils command-line tool - sqlite-utils sqlite-utils command-line tool¶The Once installed the tool should be available as Running SQL queries¶The sqlite-utils query dogs.db "select * from dogs" sqlite-utils dogs.db "select * from dogs" Note In Python: db.query() CLI reference: sqlite-utils query Pass echo "select * from dogs" | sqlite-utils query dogs.db - sqlite-utils query dogs.db - < query.sql Returning JSON¶The default format returned for queries is JSON: sqlite-utils dogs.db "select * from dogs" [{"id": 1, "age": 4, "name": "Cleo"}, {"id": 2, "age": 2, "name": "Pancakes"}] If the query returns more than one column with the same name, later occurrences are renamed with a numeric suffix - Newline-delimited JSON¶Use sqlite-utils dogs.db "select * from dogs" --nl {"id": 1, "age": 4, "name": "Cleo"} {"id": 2, "age": 2, "name": "Pancakes"} JSON arrays¶You can use sqlite-utils dogs.db "select * from dogs" --arrays [[1, 4, "Cleo"], [2, 2, "Pancakes"]] You can also combine sqlite-utils dogs.db "select * from dogs" --arrays --nl [1, 4, "Cleo"] [2, 2, "Pancakes"] If you want to pretty-print the output further, you can pipe it through sqlite-utils dogs.db "select * from dogs" | python -mjson.tool [ { "id": 1, "age": 4, "name": "Cleo" }, { "id": 2, "age": 2, "name": "Pancakes" } ] Unicode characters in JSON¶JSON output includes unicode characters directly, without escaping them: sqlite-utils dogs.db "select '日本語' as text" [{"text": "日本語"}]
Use sqlite-utils dogs.db "select '日本語' as text" --ascii [{"text": "\u65e5\u672c\u8a9e"}]
The Binary data in JSON¶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: sqlite-utils dogs.db "select name, content from images" | python -mjson.tool [ { "name": "transparent.gif", "content": { "$base64": true, "encoded": "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" } } ] Nested JSON values¶If one of your columns contains JSON, by default it will be returned as an escaped string: sqlite-utils dogs.db "select * from dogs" | python -mjson.tool [ { "id": 1, "name": "Cleo", "friends": "[{\"name\": \"Pancakes\"}, {\"name\": \"Bailey\"}]" } ] You can use the sqlite-utils dogs.db "select * from dogs" --json-cols | python -mjson.tool [ { "id": 1, "name": "Cleo", "friends": [ { "name": "Pancakes" }, { "name": "Bailey" } ] } ] Returning CSV or TSV¶You can use the sqlite-utils dogs.db "select * from dogs" --csv id,age,name 1,4,Cleo 2,2,Pancakes This will default to including the column names as a header row. To exclude the headers, use sqlite-utils dogs.db "select * from dogs" --csv --no-headers 1,4,Cleo 2,2,Pancakes Use sqlite-utils dogs.db "select * from dogs" --tsv id age name 1 4 Cleo 2 2 Pancakes Table-formatted output¶You can use the sqlite-utils dogs.db "select * from dogs" --table id age name ---- ----- -------- 1 4 Cleo 2 2 Pancakes You can use the sqlite-utils dogs.db "select * from dogs" --fmt rst ==== ===== ======== id age name ==== ===== ======== 1 4 Cleo 2 2 Pancakes ==== ===== ======== Available
This list can also be found by running Returning raw data, such as binary content¶If your table contains binary data in a For example, to retrieve a binary image from a sqlite-utils photos.db "select contents from photos where id=1" --raw > myphoto.jpg To return the first column of each result as raw data, separated by newlines, use sqlite-utils photos.db "select caption from photos" --raw-lines > captions.txt Using named parameters¶You can pass named parameters to the query using sqlite-utils query dogs.db "select :num * :num2" -p num 5 -p num2 6 [{":num * :num2": 30}]
These will be correctly quoted and escaped in the SQL query, providing a safe way to combine other values with SQL. UPDATE, INSERT and DELETE¶If you execute an sqlite-utils dogs.db "update dogs set age = 5 where name = 'Cleo'" [{"rows_affected": 1}]
Defining custom SQL functions¶You can use the This example defines a function which extracts the domain from a URL: sqlite-utils query sites.db "select url, domain(url) from urls" --functions ' from urllib.parse import urlparse def domain(url): return urlparse(url).netloc ' 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. You can also pass the path to a Python file containing function definitions: sqlite-utils query sites.db "select url, domain(url) from urls" --functions functions.py The sqlite-utils query sites.db "select url, domain(url), extract_path(url) from urls" \ --functions domain_funcs.py \ --functions 'def extract_path(url): from urllib.parse import urlparse return urlparse(url).path' Note In Python: db.register_function() SQLite extensions¶You can load SQLite extension modules using the sqlite-utils dogs.db "select spatialite_version()" --load-extension=spatialite [{"spatialite_version()": "4.3.0a"}]
Attaching additional databases¶SQLite supports cross-database SQL queries, which can join data from tables in more than one database file. You can attach one or more additional databases using the This example attaches the sqlite-utils dogs.db --attach books books.db \ 'select * from sqlite_master union all select * from books.sqlite_master' Note In Python: db.attach() Querying data directly using an in-memory database¶The 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. Without any extra arguments, this command executes SQL against the in-memory database directly: sqlite-utils memory 'select sqlite_version()' [{"sqlite_version()": "3.35.5"}]
It takes all of the same output formatting options as sqlite-utils query: sqlite-utils memory 'select sqlite_version()' --csv sqlite_version() 3.35.5 sqlite-utils memory 'select sqlite_version()' --fmt grid +--------------------+ | sqlite_version() | +====================+ | 3.35.5 | +--------------------+ Running queries directly against CSV or JSON¶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 sqlite-utils memory data.csv "select * from data" You can pass multiple files to the command if you want to run joins between data from different files: sqlite-utils memory one.csv two.json \ "select * from one join two on one.id = two.other_id" If your data is JSON it should be the same format supported by the sqlite-utils insert command - so either a single JSON object (treated as a single row) or a list of JSON objects. CSV data can be comma- or tab- delimited. 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 sqlite-utils memory example.csv "select * from t" If two files have the same name they will be assigned a numeric suffix: sqlite-utils memory foo/data.csv bar/data.csv "select * from data_2" To read from standard input, use either cat example.csv | sqlite-utils memory - "select * from stdin" Incoming CSV data will be assumed to use cat example.csv | sqlite-utils memory - "select * from stdin" --encoding=latin-1 If you are joining across multiple CSV files they must all use the same encoding. Column types will be automatically detected in CSV or TSV data, as described in Inserting CSV or TSV data. You can pass the Explicitly specifying the format¶By default, You can instead specify an explicit format by adding a sqlite-utils memory one.dat:csv two.dat:nl \ "select * from one union select * from two" Here the contents of To explicitly specify the format for data piped into the tool on standard input, use cat one.dat | sqlite-utils memory stdin:csv "select * from stdin" Joining in-memory data against existing databases using --attach¶The attach option 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: echo "id\n1\n3\n5" | sqlite-utils memory - --attach trees trees.db \ "select * from trees.trees where rowid in (select id from stdin)" Here the
The CSV data that was piped into the script is available in the --schema, --analyze, --dump and --save¶To see the in-memory database schema that would be used for a file or for multiple files, use 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"; You can run the equivalent of the analyze-tables command using 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 You can output SQL that will both create the tables and insert the full data used to populate the in-memory database using sqlite-utils memory dogs.csv --dump BEGIN TRANSACTION; CREATE TABLE "dogs" ( "id" INTEGER, "age" INTEGER, "name" TEXT ); INSERT INTO "dogs" VALUES('1','4','Cleo'); INSERT INTO "dogs" VALUES('2','2','Pancakes'); CREATE VIEW "t1" AS select * from "dogs"; CREATE VIEW "t" AS select * from "dogs"; COMMIT; Passing sqlite-utils memory dogs.csv --save dogs.db 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 Inserting JSON data and Inserting CSV or TSV data. Returning all rows in a table¶You can return every row in a specified table using the sqlite-utils rows dogs.db dogs [{"id": 1, "age": 4, "name": "Cleo"}, {"id": 2, "age": 2, "name": "Pancakes"}] This command accepts the same output options as You can use the sqlite-utils rows dogs.db dogs -c age -c name [{"age": 4, "name": "Cleo"}, {"age": 2, "name": "Pancakes"}] You can filter rows using a where clause with the sqlite-utils rows dogs.db dogs -c name --where 'name = "Cleo"' [{"name": "Cleo"}]
Or pass named parameters using sqlite-utils rows dogs.db dogs -c name --where 'name = :name' -p name Cleo [{"name": "Cleo"}]
You can define a sort order using Use Note In Python: table.rows CLI reference: sqlite-utils rows Listing tables¶You can list the names of tables in a database using the sqlite-utils tables mydb.db [{"table": "dogs"}, {"table": "cats"}, {"table": "chickens"}] You can output this list in CSV using the sqlite-utils tables mydb.db --csv --no-headers dogs cats chickens If you just want to see the FTS4 tables, you can use sqlite-utils tables docs.db --fts4 [{"table": "docs_fts"}]
Use sqlite-utils tables mydb.db --counts [{"table": "dogs", "count": 12}, {"table": "cats", "count": 332}, {"table": "chickens", "count": 9}] Use 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"]}] Use 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) The Note In Python: db.tables or db.table_names() CLI reference: sqlite-utils tables Listing views¶The sqlite-utils views sf-trees.db --table --counts --columns --schema view count columns schema --------- ------- -------------------- -------------------------------------------------------------- demo_view 189144 ['qSpecies'] CREATE VIEW demo_view AS select qSpecies from Street_Tree_List hello 1 ['sqlite_version()'] CREATE VIEW hello as select sqlite_version() It takes the same options as the
Note In Python: db.views or db.view_names() CLI reference: sqlite-utils views Listing indexes¶The 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 It shows indexes across all tables. To see indexes for specific tables, list those after the database: sqlite-utils indexes covid.db johns_hopkins_csse_daily_reports --table The command defaults to only showing the columns that are explicitly part of the index. To also include auxiliary columns use the The command takes the same format options as the Note In Python: table.indexes CLI reference: sqlite-utils indexes Listing triggers¶The 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 ( 'plants', COALESCE( (SELECT count FROM "_counts" WHERE "table" = 'plants'), 0 ) + 1 ); END It defaults to showing triggers for all tables. To see triggers for one or more specific tables pass their names as arguments: sqlite-utils triggers global-power-plants.db plants The command takes the same format options as the Note In Python: table.triggers or db.triggers CLI reference: sqlite-utils triggers Showing the schema¶The sqlite-utils schema dogs.db CREATE TABLE "dogs" ( "id" INTEGER PRIMARY KEY, "name" TEXT ); 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: sqlite-utils schema dogs.db dogs chickens Note In Python: table.schema or db.schema CLI reference: sqlite-utils schema Analyzing tables¶When working with a new database it can be useful to get an idea of the shape of the data. The To inspect the 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 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. If you do not specify any tables every table in the database will be analyzed: sqlite-utils analyze-tables github.db If you wish to analyze one or more specific columns, use the sqlite-utils analyze-tables github.db tags -c sha To show more than 10 common values, use sqlite-utils analyze-tables github.db tags --common-limit 20 --no-least Note In Python: table.analyze_column() CLI reference: sqlite-utils analyze-tables Saving the analyzed table details¶
sqlite-utils analyze-tables github.db --save The 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") ); The [ ["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] ] Creating an empty database¶You can create a new empty database file using the sqlite-utils create-database empty.db To enable WAL mode on the newly created database add the sqlite-utils create-database empty.db --enable-wal To enable SpatiaLite metadata on a newly created database, add the sqlite-utils create-database empty.db --init-spatialite That will look for SpatiaLite in a set of predictable locations. To load it from somewhere else, use the sqlite-utils create-database empty.db --init-spatialite --load-extension /path/to/spatialite.so Running migrations¶The sqlite-utils migrate creatures.db path/to/migrations.py If you omit the migration path it will search the current directory and subdirectories for files called sqlite-utils migrate creatures.db Use sqlite-utils migrate creatures.db --list Use sqlite-utils migrate creatures.db path/to/migrations.py \ --stop-before creatures:add_weight \ --stop-before sales:drop_index Inserting JSON data¶If you have data as JSON, you can use 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 Here’s the simplest possible example: echo '{"name": "Cleo", "age": 4}' | sqlite-utils insert dogs.db dogs - To specify a column as the primary key, use To create a compound primary key across more than one column, use If you feed it a JSON list it will insert multiple records. For example, if [ { "id": 1, "name": "Cleo", "age": 4 }, { "id": 2, "name": "Pancakes", "age": 2 }, { "id": 3, "name": "Toby", "age": 6 } ] You can import all three records into an automatically created sqlite-utils insert dogs.db dogs dogs.json --pk=id Pass You can skip inserting any records that have a primary key that already exists using sqlite-utils insert dogs.db dogs dogs.json --pk=id --ignore You can delete all the existing rows in the table before inserting the new records using sqlite-utils insert dogs.db dogs dogs.json --truncate You can add the Note In Python: table.insert_all() CLI reference: sqlite-utils insert Inserting binary data¶You can insert binary data into a BLOB column by first encoding it using base64 and then structuring it like this: [ { "name": "transparent.gif", "content": { "$base64": true, "encoded": "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" } } ] Inserting newline-delimited JSON¶You can also import newline-delimited JSON (see JSON Lines) using the echo '{"id": 1, "name": "Cleo"} {"id": 2, "name": "Suna"}' | sqlite-utils insert creatures.db creatures - --nl Newline-delimited JSON consists of full JSON objects separated by newlines. If you are processing data using Since Datasette can export newline-delimited JSON, you can combine the Datasette and curl -L "https://latest.datasette.io/fixtures/facetable.json?_shape=array&_nl=on" \ | sqlite-utils insert nl-demo.db facetable - --pk=id --nl You can also pipe sqlite-utils sf-trees.db \ "select TreeID, qAddress, Latitude, Longitude from Street_Tree_List" --nl \ | sqlite-utils insert saved.db trees - --nl 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 Flattening nested JSON objects¶
If your data is nested you can use the Consider this example document, in a file called { "httpRequest": { "latency": "0.112114537s", "requestMethod": "GET", "requestSize": "534", "status": 200 }, "insertId": "6111722f000b5b4c4d4071e2", "labels": { "service": "datasette-io" } } Inserting this into a table using CREATE TABLE "logs" ( "httpRequest" TEXT, "insertId" TEXT, "labels" TEXT ); With the CREATE TABLE "logs" ( "httpRequest_latency" TEXT, "httpRequest_requestMethod" TEXT, "httpRequest_requestSize" TEXT, "httpRequest_status" INTEGER, "insertId" TEXT, "labels_service" TEXT ); Inserting CSV or TSV data¶If your data is in CSV format, you can insert it using the sqlite-utils insert dogs.db dogs dogs.csv --csv For tab-delimited data, use sqlite-utils insert dogs.db dogs dogs.tsv --tsv Data is expected to be encoded as Unicode UTF-8. If your data is an another character encoding you can specify it using the sqlite-utils insert dogs.db dogs dogs.tsv --tsv --encoding=latin-1 To stop inserting after a specified number of records - useful for getting a faster preview of a large file - use the sqlite-utils insert dogs.db dogs dogs.csv --csv --stop-after=10 A progress bar is displayed when inserting data from a file. You can hide the progress bar using the By default, column types are automatically detected for CSV or TSV files - resulting in a mix of Detected types are only applied when the table is created by the command. Inserting CSV or TSV data into a table that already exists leaves the existing column types unchanged - values are inserted using the table’s existing schema. For example, given a name,age,weight Cleo,6,45.5 Dori,1,3.5 The following command: sqlite-utils insert creatures.db creatures creatures.csv --csv Will produce this schema with automatically detected types: sqlite-utils schema creatures.db CREATE TABLE "creatures" ( "name" TEXT, "age" INTEGER, "weight" REAL ); Overriding column types¶Use sqlite-utils insert places.db places places.csv --csv \ --type zipcode text \ --type score real This is useful for values such as ZIP codes, which may look like integers but should be stored as The column type should be one of
sqlite-utils insert events.db events events.csv --csv --strict \ --type payload any As with detected column types, To disable type detection and treat all columns as TEXT, use sqlite-utils insert creatures.db creatures creatures.csv --csv --no-detect-types If a CSV or TSV file includes empty cells, like this one: name,age,weight Cleo,6, Dori,,3.5 They will be imported into SQLite as empty string values, To import them as sqlite-utils insert creatures.db creatures creatures.csv --csv --empty-null Alternative delimiters and quote characters¶If your file uses a delimiter other than The sqlite-utils insert dogs.db dogs dogs.csv --sniff Alternatively, you can specify them using the Here’s a CSV file that uses name;description Cleo;|Very fine; a friendly dog| Pancakes;A local corgi You can import that using: sqlite-utils insert dogs.db dogs dogs.csv --delimiter=";" --quotechar="|" Passing CSV files without a header row¶The first row of any CSV or TSV file is expected to contain the names of the columns in that file. If your file does not include this row, you can use the If you do this, the table will be created with column names called Inserting unstructured data with --lines and --text¶If you have an unstructured file you can insert its contents into a table with a single sqlite-utils insert logs.db loglines logfile.log --lines This will produce the following schema: CREATE TABLE "loglines" ( "line" TEXT ); You can also insert the entire contents of the file into a single column called sqlite-utils insert content.db content file.txt --text The schema here will be: CREATE TABLE "content" ( "text" TEXT ); Applying conversions while inserting data¶The Your Python function will be passed a dictionary called Given a JSON file called [ {"id": 1, "name": "Cleo"}, {"id": 2, "name": "Pancakes"} ] The following command will insert that data and add an sqlite-utils insert dogs.db dogs dogs.json --convert 'row["is_good"] = 1' The As with You can also pass code that runs some initialization steps and defines a --convert with --lines¶Things work slightly differently when combined with the With 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 You could convert it into structured data like so: sqlite-utils insert logs.db loglines access.log --convert ' type, source, _, verb, path, _, status, _ = line.split() return { "type": type, "source": source, "verb": verb, "path": path, "status": status, }' --lines The resulting table would look like this:
--convert with --text¶With 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. Here’s how to use echo 'A bunch of words' | sqlite-utils insert words.db words - \ --text --convert '({"word": w} for w in text.split())' The result looks like this: sqlite-utils dump words.db BEGIN TRANSACTION; CREATE TABLE "words" ( "word" TEXT ); INSERT INTO "words" VALUES('A'); INSERT INTO "words" VALUES('bunch'); INSERT INTO "words" VALUES('of'); INSERT INTO "words" VALUES('words'); COMMIT; Inserting rows generated by Python code¶Instead of providing a Your code should define either a sqlite-utils insert data.db creatures --code ' def rows(): yield {"id": 1, "name": "Cleo"} yield {"id": 2, "name": "Suna"} ' --pk id
The Insert-replacing data¶The To replace a dog with in ID of 2 with a new record, run the following: echo '{"id": 2, "name": "Pancakes", "age": 3}' | \ sqlite-utils insert dogs.db dogs - --pk=id --replace Note In Python: table.insert(…, replace=True) CLI reference: sqlite-utils insert Upserting data¶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. Unlike For example: echo '{"id": 2, "age": 4}' | \ sqlite-utils upsert dogs.db dogs - --pk=id 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. If the table already exists and has a primary key, you can omit the The command will fail if you reference columns that do not exist on the table. To automatically create missing columns, use the Note
Note In Python: table.upsert() CLI reference: sqlite-utils upsert Executing SQL in bulk¶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 The command takes the database file, the SQL to be executed and the file containing records to be used when evaluating the SQL query. The SQL query should include For example, given a id,name 1,Blue 2,Snowy 3,Azi 4,Lila 5,Suna 6,Cardi You could insert those rows into a pre-created sqlite-utils bulk chickens.db \ 'insert into chickens (id, name) values (:id, :name)' \ chickens.csv --csv This command takes the same options as the By default all of the SQL queries will be executed in a single transaction. To commit every 20 records, use Inserting data from files¶The Here’s an example that inserts all of the GIF files in the current directory into a sqlite-utils insert-files gifs.db images *.gif You can also pass one or more directories, in which case every file in those directories will be added recursively: sqlite-utils insert-files gifs.db images path/to/my-gifs By default this command will create a table with the following schema: CREATE TABLE "images" ( "path" TEXT PRIMARY KEY, "content" BLOB, "size" INTEGER ); Content will be treated as binary by default and stored in a You can customize the schema using one or more sqlite-utils insert-files gifs.db images *.gif -c path -c md5 -c mtime --pk=path This will result in the following schema: CREATE TABLE "images" ( "path" TEXT PRIMARY KEY, "md5" TEXT, "mtime" REAL ); Note that there’s no You can change the name of one of these columns using a sqlite-utils insert-files gifs.db images *.gif \ -c path -c md5 -c last_modified:mtime --pk=path You can pass The full list of column definitions you can use is as follows:
You can insert data piped from standard input like this: cat dog.jpg | sqlite-utils insert-files dogs.db pics - --name=dog.jpg The When inserting data from standard input only the following column definitions are supported: Converting data in columns¶The 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 sqlite-utils convert content.db articles headline 'value.upper()' The Python code is passed as a string. Within that Python code the The code you provide will be compiled into a function that takes sqlite-utils convert content.db articles headline ' value = str(value) return value.upper()' Your code will be automatically wrapped in a function, but you can also define a function called sqlite-utils convert content.db articles headline ' def convert(value): return value.upper()' Use a cat mycode.py | sqlite-utils convert content.db articles headline - Where def convert(value): return value.upper() The conversion will be applied to every row in the specified table. You can limit that to just rows that match a sqlite-utils convert content.db articles headline 'value.upper()' \ --where "headline like '%cat%'" You can include named parameters in your where clause and populate them using one or more sqlite-utils convert content.db articles headline 'value.upper()' \ --where "headline like :query" \ --param query '%cat%' The Note In Python: table.convert() CLI reference: sqlite-utils convert Importing additional modules¶You can specify Python modules that should be imported and made available to your code using one or more sqlite-utils convert content.db articles content \ '"\n".join(textwrap.wrap(value, 100))' \ --import=textwrap This supports nested imports as well, for example to use ElementTree: sqlite-utils convert content.db articles content \ 'xml.etree.ElementTree.fromstring(value).attrib["title"]' \ --import=xml.etree.ElementTree Using the debugger¶If an error occurs while running your conversion operation you may see a message like this: user-defined function raised exception Add the Here’s an example debugging session. First, create a echo '{"content": "This is not XML"}' | sqlite-utils insert content.db articles - Now run the conversion with the sqlite-utils convert content.db articles content \ 'xml.etree.ElementTree.fromstring(value).attrib["title"]' \ --import=xml.etree.ElementTree \ --pdb When the error occurs the debugger will open: Exception raised, dropping into pdb...: syntax error: line 1, column 0 > .../python3.11/xml/etree/ElementTree.py(1338)XML() -> parser.feed(text) (Pdb) args text = 'This is not XML' parser = <xml.etree.ElementTree.XMLParser object at 0x102c405e0> (Pdb) q
Defining a convert() function¶Instead of providing a single line of code to be executed against each value, you can define a function called This mechanism can be used to execute one-off initialization code that runs once at the start of the conversion run. The following example adds a new sqlite-utils add-column content.db articles score float --not-null-default 1.0 sqlite-utils convert content.db articles score ' import random random.seed(10) def convert(value): return random.random() ' sqlite-utils convert recipes¶Various built-in recipe functions are available for common operations. These are:
These recipes can be used in the code passed to sqlite-utils convert my.db mytable mycolumn \ 'r.jsonsplit(value)' You can also pass the recipe function directly without the sqlite-utils convert my.db mytable mycolumn r.parsedate This shorter syntax works for any callable, including functions from imported modules: sqlite-utils convert my.db mytable mycolumn json.loads --import json To use any of the documented parameters, use the full function call syntax: sqlite-utils convert my.db mytable mycolumn \ 'r.jsonsplit(value, delimiter=":")' Saving the result to a different column¶The sqlite-utils convert content.db articles headline 'value.upper()' \ --output headline_upper The type of the created column defaults to sqlite-utils convert content.db articles id 'float(value) + 0.5' \ --output id_as_a_float \ --output-type float You can drop the original column at the end of the operation by adding Converting a column into multiple columns¶Sometimes you may wish to convert a single column into multiple derived columns. For example, you may have a You can achieve this using the For the sqlite-utils convert demo.db places location \ 'bits = value.split(",") return { "latitude": float(bits[0]), "longitude": float(bits[1]), }' --multi 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: CREATE TABLE "places" ( "location" TEXT, "latitude" REAL, "longitude" REAL ); The code function can also return Creating tables¶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 sqlite-utils create-table mydb.db mytable id integer name text --pk=id This will create a table called You can pass as many column-name column-type pairs as you like. Valid types are Pass You can specify columns that should be NOT NULL using sqlite-utils create-table mydb.db mytable \ id integer \ name text \ age integer \ is_good integer \ --not-null name \ --not-null age \ --default is_good 1 \ --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 '1' ) You can specify foreign key relationships between the tables you are creating using sqlite-utils create-table books.db authors \ id integer \ name text \ --pk=id sqlite-utils create-table books.db books \ id integer \ title text \ author_id integer \ --pk=id \ --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") ) You can create a table in SQLite STRICT mode using sqlite-utils create-table mydb.db mytable id integer name text --strict Use the sqlite-utils create-table events.db events id integer payload any --strict sqlite-utils tables mydb.db --schema -t table schema ------- ------------------------ mytable CREATE TABLE "mytable" ( "id" INTEGER, "name" TEXT ) STRICT If a table with the same name already exists, you will get an error. You can choose to silently ignore this error with You can also pass Note In Python: table.create() CLI reference: sqlite-utils create-table Renaming a table¶Yo ucan rename a table using the sqlite-utils rename-table mydb.db oldname newname Pass Note In Python: db.rename_table() CLI reference: sqlite-utils rename-table Duplicating tables¶The sqlite-utils duplicate books.db authors authors_copy Note In Python: table.duplicate() CLI reference: sqlite-utils duplicate Dropping tables¶You can drop a table using the sqlite-utils drop-table mydb.db mytable Use Note In Python: table.drop() CLI reference: sqlite-utils drop-table Transforming tables¶The sqlite-utils transform mydb.db mytable \ --drop column1 \ --rename column2 column_renamed Every option for this table (with the exception of
If you want to see the SQL that will be executed to make the change without actually executing it, add the sqlite-utils transform fixtures.db roadside_attractions \ --rename pk id \ --default name Untitled \ --column-order id \ --column-order longitude \ --column-order latitude \ --drop address \ --sql CREATE TABLE "roadside_attractions_new_4033a60276b9" ( "id" INTEGER PRIMARY KEY, "longitude" FLOAT, "latitude" FLOAT, "name" TEXT DEFAULT 'Untitled' ); INSERT INTO "roadside_attractions_new_4033a60276b9" ("longitude", "latitude", "id", "name") SELECT "longitude", "latitude", "pk", "name" FROM "roadside_attractions"; DROP TABLE "roadside_attractions"; PRAGMA legacy_alter_table=ON; ALTER TABLE "roadside_attractions_new_4033a60276b9" RENAME TO "roadside_attractions"; PRAGMA legacy_alter_table=OFF; Tables that are referenced by views can be transformed - the view definitions are left unchanged, see Tables referenced by views for details. Note In Python: table.transform() CLI reference: sqlite-utils transform Adding a primary key to a rowid table¶SQLite tables that are created without an explicit primary key are created as rowid tables. They still have a numeric primary key which is available in the echo '[{"name": "Azi"}, {"name": "Suna"}]' | \ sqlite-utils insert chickens.db chickens - sqlite-utils schema chickens.db CREATE TABLE "chickens" ( "name" TEXT ); sqlite-utils chickens.db 'select * from chickens' [{"name": "Azi"}, {"name": "Suna"}] sqlite-utils chickens.db 'select rowid, * from chickens' [{"rowid": 1, "name": "Azi"}, {"rowid": 2, "name": "Suna"}] You can use 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 'select * from chickens' [{"id": 1, "name": "Azi"}, {"id": 2, "name": "Suna"}] echo '{"name": "Cardi"}' | sqlite-utils insert chickens.db chickens - sqlite-utils chickens.db 'select * from chickens' [{"id": 1, "name": "Azi"}, {"id": 2, "name": "Suna"}, {"id": 3, "name": "Cardi"}] Extracting columns into a separate table¶The Take a look at the Python API documentation for Extracting columns into a separate table for a detailed description of how this works, including examples of table schemas before and after running an extraction operation. Rows where every extracted column is The command takes a database, table and one or more columns that should be extracted. To extract the sqlite-utils extract my.db trees species This would produce the following schema: 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"); The command takes the following options:
Here’s a more complex example that makes use of these options. It converts this CSV file full of global power plants into SQLite, then extracts the wget 'https://github.com/wri/global-power-plant-database/blob/232a6666/output_database/global_power_plant_database.csv?raw=true' sqlite-utils insert global.db power_plants \ 'global_power_plant_database.csv?raw=true' --csv # Extract those columns: sqlite-utils extract global.db power_plants country country_long \ --table countries \ --fk-column country_id \ --rename country_long name After running the above, the command 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"); Note In Python: table.extract() CLI reference: sqlite-utils extract Creating views¶You can create a view using the sqlite-utils create-view mydb.db version "select sqlite_version()" sqlite-utils mydb.db "select * from version" [{"sqlite_version()": "3.31.1"}]
Use Note In Python: db.create_view() CLI reference: sqlite-utils create-view Dropping views¶You can drop a view using the sqlite-utils drop-view myview Use Note In Python: view.drop() CLI reference: sqlite-utils drop-view Adding columns¶You can add a column using the sqlite-utils add-column mydb.db mytable nameofcolumn text The last argument here is the type of the column to be created. This can be one of:
This argument is optional and defaults to You can add a column that is a foreign key reference to another table using the sqlite-utils add-column mydb.db dogs species_id --fk species This will automatically detect the name of the primary key on the species table and use that (and its type) for the new column. You can explicitly specify the column you wish to reference using sqlite-utils add-column mydb.db dogs species_id --fk species --fk-col ref You can set a sqlite-utils add-column mydb.db dogs friends_count integer --not-null-default 0 Note In Python: table.add_column() CLI reference: sqlite-utils add-column Adding columns automatically on insert/update¶You can use the sqlite-utils insert dogs.db dogs new-dogs.json --pk=id --alter Note In Python: table.insert(…, alter=True) Adding foreign key constraints¶The To add a foreign key constraint pointing the sqlite-utils add-foreign-key books.db books author_id authors id If you omit the other table and other column references sqlite-utils add-foreign-key books.db books author_id Add sqlite-utils add-foreign-key books.db books author_id --ignore See Adding foreign key constraints in the Python API documentation for further details, including how the automatic table guessing mechanism works. Note In Python: table.add_foreign_key() CLI reference: sqlite-utils add-foreign-key Adding multiple foreign keys at once¶Adding a foreign key requires a sqlite-utils add-foreign-keys books.db \ books author_id authors id \ authors country_id countries id 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. Note In Python: db.add_foreign_keys() CLI reference: sqlite-utils add-foreign-keys Adding indexes for all foreign keys¶If you want to ensure that every foreign key column in your database has a corresponding index, you can do so like this: sqlite-utils index-foreign-keys books.db Note In Python: db.index_foreign_keys() CLI reference: sqlite-utils index-foreign-keys Setting defaults and not null constraints¶You can use the sqlite-utils insert dogs.db dogs_with_scores dogs-with-scores.json \ --not-null=age \ --not-null=name \ --default age 2 \ --default score 5 Note In Python: not_null= and defaults= arguments Creating indexes¶You can add an index to an existing table using the sqlite-utils create-index mydb.db mytable col1 [col2...] This can be used to create indexes against a single column or multiple columns. The name of the index will be automatically derived from the table and columns. To specify a different name, use Use the Use 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: sqlite-utils create-index mydb.db mytable -- col1 -col2 col3 This will create an index on that table on If your column names are already prefixed with a hyphen you’ll need to manually execute a Add the Note In Python: table.create_index() CLI reference: sqlite-utils create-index Dropping indexes¶You can drop an index from an existing table using the sqlite-utils drop-index mydb.db mytable idx_mytable_col1 Use Note In Python: table.drop_index() CLI reference: sqlite-utils drop-index Configuring full-text search¶You can enable SQLite full-text search on a table and a set of columns like this: sqlite-utils enable-fts mydb.db documents title summary This will use SQLite’s FTS5 module by default. Use sqlite-utils enable-fts mydb.db documents title summary --fts4 The sqlite-utils populate-fts mydb.db documents title summary A better solution here is to use database triggers. You can set up database triggers to automatically update the full-text index using the sqlite-utils enable-fts mydb.db documents title summary --create-triggers To set a custom FTS tokenizer, e.g. to enable Porter stemming, use sqlite-utils populate-fts mydb.db documents title summary --tokenize=porter To remove the FTS tables and triggers you created, use sqlite-utils disable-fts mydb.db documents To rebuild one or more FTS tables (see Rebuilding a full-text search table), use sqlite-utils rebuild-fts mydb.db documents You can rebuild every FTS table by running sqlite-utils rebuild-fts mydb.db Note In Python: table.enable_fts() CLI reference: sqlite-utils enable-fts Executing searches¶Once you have configured full-text search for a table, you can search it using sqlite-utils search mydb.db documents searchterm This command accepts the same output options as By default it shows the most relevant matches first. You can specify a different sort order using the # 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 'created desc' SQLite advanced search syntax 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 You can specify a subset of columns to be returned using the sqlite-utils search mydb.db documents searchterm -c title -c created By default all search results will be returned. You can use Use the 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 Note In Python: table.search() CLI reference: sqlite-utils search Enabling cached counts¶
The # 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 If the sqlite-utils reset-counts mydb.db Note In Python: table.enable_counts() CLI reference: sqlite-utils enable-counts Optimizing index usage with ANALYZE¶The SQLite ANALYZE command builds a table of statistics which the query planner can use to make better decisions about which indexes to use for a given query. You should run To run sqlite-utils analyze mydb.db You can run it against specific tables, or against specific named indexes, by passing them as optional arguments: sqlite-utils analyze mydb.db mytable idx_mytable_name You can also run Note In Python: db.analyze() CLI reference: sqlite-utils analyze Vacuum¶You can run VACUUM to optimize your database like so: sqlite-utils vacuum mydb.db Note In Python: db.vacuum() CLI reference: sqlite-utils vacuum Optimize¶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. If you just want to run OPTIMIZE without the VACUUM, use the # Optimize all FTS tables and then VACUUM sqlite-utils optimize mydb.db # Optimize but skip the VACUUM sqlite-utils optimize --no-vacuum mydb.db To optimize specific tables rather than every FTS table, pass those tables as extra arguments: sqlite-utils optimize mydb.db table_1 table_2 Note In Python: table.optimize() CLI reference: sqlite-utils optimize WAL mode¶You can enable Write-Ahead Logging for a database file using the sqlite-utils enable-wal mydb.db You can disable WAL mode using sqlite-utils disable-wal mydb.db Both of these commands accept one or more database files as arguments. Note In Python: db.enable_wal() and db.disable_wal() CLI reference: sqlite-utils enable-wal Dumping the database to SQL¶The sqlite-utils dump mydb.db BEGIN TRANSACTION; CREATE TABLE ... ... COMMIT; Note In Python: db.iterdump() CLI reference: sqlite-utils dump Loading SQLite extensions¶Many of these commands have the ability to load additional SQLite extensions using the This option can be applied multiple times to load multiple extensions. Since SpatiaLite is commonly used with SQLite, the value sqlite-utils memory "select spatialite_version()" --load-extension=spatialite [{"spatialite_version()": "4.3.0a"}]
SpatiaLite helpers¶SpatiaLite adds geographic capability to SQLite (similar to how PostGIS builds on PostgreSQL). The SpatiaLite cookbook is a good resource for learning what’s possible with it. You can convert an existing table to a geographic table by adding a geometry column, use the sqlite-utils add-geometry-column spatial.db locations geometry --type POLYGON --srid 4326 The table ( Use the Eight (case-insensitive) types are allowed:
Note In Python: table.add_geometry_column() CLI reference: sqlite-utils add-geometry-column Adding spatial indexes¶Once you have a geometry column, you can speed up bounding box queries by adding a spatial index: sqlite-utils create-spatial-index spatial.db locations geometry See this SpatiaLite Cookbook recipe for examples of how to use a spatial index. Note In Python: table.create_spatial_index() CLI reference: sqlite-utils create-spatial-index Installing packages¶The convert command and the insert –convert and query –functions options can be provided with a Python script that imports additional modules from the You can install packages from PyPI directly into the correct environment using sqlite-utils install beautifulsoup4 Use Uninstalling packages¶You can uninstall packages that were installed using sqlite-utils uninstall beautifulsoup4 Use | |||||||||||||||
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |