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 Python library - sqlite-utils sqlite_utils Python library¶Getting started¶Here’s how to create a new SQLite database file containing a new from sqlite_utils import Database db = Database("chickens.db") db.table("chickens").insert_all([{ "name": "Azi", "color": "blue", }, { "name": "Lila", "color": "blue", }, { "name": "Suna", "color": "gold", }, { "name": "Cardi", "color": "black", }]) The inserted rows are saved to the database file straight away - methods like You can loop through those rows like this: for row in db.table("chickens").rows: print(row) Which outputs the following: {'name': 'Azi', 'color': 'blue'}
{'name': 'Lila', 'color': 'blue'}
{'name': 'Suna', 'color': 'gold'}
{'name': 'Cardi', 'color': 'black'}
To run a SQL query, use db.query(): for row in db.query(""" select color, count(*) from chickens group by color order by count(*) desc """): print(row) Which outputs: {'color': 'blue', 'count(*)': 2}
{'color': 'gold', 'count(*)': 1}
{'color': 'black', 'count(*)': 1}
Connecting to or creating a database¶Database objects are constructed by passing in either a path to a file on disk or an existing SQLite3 database connection: from sqlite_utils import Database db = Database("my_database.db") This will create If you want to recreate a database from scratch (first removing the existing file from disk if it already exists) you can use the db = Database("my_database.db", recreate=True) Instead of a file path you can pass in an existing SQLite connection: import sqlite3 db = Database(sqlite3.connect("my_database.db")) The connection must use Python’s default transaction handling. Connections created with the Python 3.12+ If you want to create an in-memory database, you can do so like this: db = Database(memory=True) 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. del db will clear the database from memory. db = Database(memory_name="my_shared_database") After creating a db = Database(memory_name="shared") db.memory # True db.memory_name # "shared" Connections use db = Database(memory=True, recursive_triggers=False) By default, any sqlite-utils plugins that implement the prepare_connection(conn) hook will be executed against the connection when you create the db = Database(memory=True, execute_plugins=False) You can pass db = Database("my_database.db", strict=True) Closing a database¶Database objects maintain a connection to the underlying SQLite database. You can explicitly close this connection using the db = Database("my_database.db") # ... use the database ... db.close() The with Database("my_database.db") as db: db["my_table"].insert({"name": "Example"}) # Connection is automatically closed here Exiting the block is equivalent to calling This rarely matters in practice. Everything that writes to the database - including raw Note this differs from the Attaching additional databases¶SQLite supports cross-database SQL queries, which can join data from tables in more than one database file. You can attach an additional database using the 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 """)) You can reference tables in the attached database using the alias value you passed to Note In the CLI: sqlite-utils –attach Tracing queries¶You can use the def tracer(sql, params): print("SQL: {} - params: {}".format(sql, params)) You can pass this function to the db = Database(memory=True, tracer=tracer) You can also turn on a tracer function temporarily for a block of code using the db = Database(memory=True) # ... later with db.tracer(print): db.table("dogs").insert({"name": "Cleo"}) This example will print queries only for the duration of the Executing queries¶The db.query(sql, params)¶The db = Database(memory=True) db.table("dogs").insert_all([{"name": "Cleo"}, {"name": "Pancakes"}]) for row in db.query("select * from dogs"): print(row) # Outputs: # {'name': 'Cleo'} # {'name': 'Pancakes'} The SQL query is executed as soon as
There is one exception to the rolled-back guarantee: a If a query returns more than one column with the same name - a join between two tables that share column names, for example - later occurrences are renamed with a numeric suffix, so every value is included in the dictionary: row = next(db.query("select 1 as id, 2 as id, 3 as id")) print(row) # Outputs: # {'id': 1, 'id_2': 2, 'id_3': 3} A suffix that would collide with another column in the query is skipped - Note In the CLI: sqlite-utils query db.execute(sql, params)¶The
db = Database(memory=True) db.table("dogs").insert({"name": "Cleo"}) cursor = db.execute("update dogs set name = 'Cleopaws'") print(cursor.rowcount) # Outputs the number of rows affected by the update # In this case 2 Other cursor methods such as Note Write statements executed this way are committed automatically, unless a transaction is already open in which case they become part of it - see Raw SQL writes with db.execute(). Passing parameters¶Both 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.
db.execute("update dogs set name = ?", ["Cleopaws"]) # This will rename ALL dogs to be called "Cleopaws" Named parameters using dog = next(db.query( "select rowid, name from dogs where name = :name", {"name": "Cleopaws"} )) # dog is now {'rowid': 1, 'name': 'Cleopaws'} In this example Transactions and saving your changes¶Every method in this library that writes to the database - db = Database("data.db") db.table("news").insert({"headline": "Dog wins award"}) # The new row is already saved - no commit() required The same applies to raw SQL executed with db.execute() - a write statement is committed as soon as it has run. Another way to think about this is that each sqlite-utils method call is its own unit of work. If several method calls must either all succeed or all fail, use You never need to call
Grouping changes with db.atomic()¶Use with db.atomic(): db.table("dogs").insert({"id": 1, "name": "Cleo"}, pk="id") db.table("dogs").insert({"id": 2, "name": "Pancakes"}) The transaction commits when the block exits. If an exception is raised, changes made inside the block will be rolled back. This matters when several operations represent a single logical change. Without # These are two separate transactions db.table("accounts").update(1, {"balance": 90}) db.table("accounts").update(2, {"balance": 110}) # These updates either both succeed or both fail with db.atomic(): db.table("accounts").update(1, {"balance": 90}) db.table("accounts").update(2, {"balance": 110}) Transactions can also improve performance. Calling with db.atomic(): for row in rows: db.table("events").insert(row)
with db.atomic(): db.table("dogs").insert({"id": 1, "name": "Cleo"}, pk="id") try: with db.atomic(): db.table("dogs").insert({"id": 2, "name": "Pancakes"}) raise ValueError("skip this one") except ValueError: pass db.table("dogs").insert({"id": 3, "name": "Marnie"}) The transaction is opened with a deferred Raw SQL writes with db.execute()¶Write statements executed with db.execute() follow the same rule as everything else: they are committed automatically as soon as they have run. db.execute("insert into news (headline) values (?)", ["Dog wins award"]) # Already committed
If a transaction is open - because the call happens inside a with db.atomic(): db.execute("insert into news (headline) values (?)", ["Dog wins award"]) db.execute("insert into news (headline) values (?)", ["Cat unimpressed"]) # Both rows committed together One corner case: a row-returning write such as Managing transactions yourself¶You can take full manual control using the db.begin() db.table("news").insert({"headline": "Dog wins award"}) if all_looks_good: db.commit() else: db.rollback()
The library will never commit a transaction you opened. If you call write methods such as Prefer Some related safeguards to be aware of:
Supported connection modes¶
Connections using Connections using Accessing tables¶Tables are accessed using the table = db.table("my_table") Using this factory function allows you to set Table configuration options. Additional keyword arguments to The You can also access tables or views using dictionary-style syntax, like this: table_or_view = db["my_table_or_view_name"] If a table accessed using either of these methods does not yet exist, it will be created the first time you attempt to insert or upsert data into it. Accessing views¶SQL views can be accessed using the view = db.view("my_view") This will return a sqlite_utils.db.View instance, or raise a Listing tables¶You can list the names of tables in a database using the >>> db.table_names() ['dogs'] To see just the FTS4 tables, use You can also iterate through the table objects themselves using the >>> db.tables [<Table dogs>] Note In the CLI: sqlite-utils tables Listing views¶
>>> db.view_names() ['good_dogs'] You can iterate through view objects using the >>> db.views [<View good_dogs>] 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:
Note In the CLI: sqlite-utils views Listing rows¶To iterate through dictionaries for each of the rows in a table, use >>> db = sqlite_utils.Database("dogs.db")
>>> for row in db.table("dogs").rows:
... print(row)
{'id': 1, 'age': 4, 'name': 'Cleo'}
{'id': 2, 'age': 2, 'name': 'Pancakes'}
You can filter rows by a WHERE clause using >>> db = sqlite_utils.Database("dogs.db")
>>> for row in db.table("dogs").rows_where("age > ?", [3]):
... print(row)
{'id': 1, 'age': 4, 'name': 'Cleo'}
The first argument is a fragment of SQL. The second, optional argument is values to be passed to that fragment - you can use >>> for row in db.table("dogs").rows_where("age > :age", {"age": 3}):
... print(row)
{'id': 1, 'age': 4, 'name': 'Cleo'}
To return custom columns (instead of the default that uses >>> db = sqlite_utils.Database("dogs.db")
>>> for row in db.table("dogs").rows_where(select='name, age'):
... print(row)
{'name': 'Cleo', 'age': 4}
To specify an order, use the >>> for row in db.table("dogs").rows_where("age > 1", order_by="age"):
... print(row)
{'id': 2, 'age': 2, 'name': 'Pancakes'}
{'id': 1, 'age': 4, 'name': 'Cleo'}
You can use You can order all records in the table by excluding the >>> for row in db.table("dogs").rows_where(order_by="age desc"):
... print(row)
{'id': 1, 'age': 4, 'name': 'Cleo'}
{'id': 2, 'age': 2, 'name': 'Pancakes'}
This method also accepts >>> for row in db.table("dogs").rows_where(order_by="age desc", limit=1):
... print(row)
{'id': 1, 'age': 4, 'name': 'Cleo'}
Note In the CLI: sqlite-utils rows Counting rows¶To count the number of rows that would be returned by a where filter, use >>> db.table("dogs").count_where("age > ?", [1]) 2 Listing rows with their primary keys¶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 The The primary key value will usually be a single value but can also be a tuple if the table has a compound primary key. If the table is a >>> db = sqlite_utils.Database(memory=True)
>>> db.table("dogs").insert({"name": "Cleo"})
>>> for pk, row in db.table("dogs").pks_and_rows_where():
... print(pk, row)
1 {'rowid': 1, 'name': 'Cleo'}
>>> db.table("dogs_with_pk").insert({"id": 5, "name": "Cleo"}, pk="id")
>>> for pk, row in db.table("dogs_with_pk").pks_and_rows_where():
... print(pk, row)
5 {'id': 5, 'name': 'Cleo'}
>>> db.table("dogs_with_compound_pk").insert(
... {"species": "dog", "id": 3, "name": "Cleo"},
... pk=("species", "id")
... )
>>> for pk, row in db.table("dogs_with_compound_pk").pks_and_rows_where():
... print(pk, row)
('dog', 3) {'species': 'dog', 'id': 3, 'name': 'Cleo'}
Retrieving a specific record¶You can retrieve a record by its primary key using >>> db = sqlite_utils.Database("dogs.db")
>>> print(db.table("dogs").get(1))
{'id': 1, 'age': 4, 'name': 'Cleo'}
If the table has a compound primary key you can pass in the primary key values as a tuple: >>> db.table("compound_dogs").get(("mixed", 3))
If the record does not exist a from sqlite_utils.db import NotFoundError try: row = db.table("dogs").get(5) except NotFoundError: print("Dog not found") Showing the schema¶The >>> db = sqlite_utils.Database("dogs.db")
>>> print(db.schema)
CREATE TABLE "dogs" (
"id" INTEGER PRIMARY KEY,
"name" TEXT
);
Note In the CLI: sqlite-utils schema Creating tables¶The easiest way to create a new table is to insert a record into it: from sqlite_utils import Database import sqlite3 db = Database("dogs.db") dogs = db.table("dogs") dogs.insert({ "name": "Cleo", "twitter": "cleopaws", "age": 3, "is_good_dog": True, }) This will automatically create a new table called “dogs” with the following schema: CREATE TABLE dogs (
name TEXT,
twitter TEXT,
age INTEGER,
is_good_dog INTEGER
)
You can also specify a primary key by passing the dogs.insert({ "id": 1, "name": "Cleo", "twitter": "cleopaws", "age": 3, "is_good_dog": True, }, pk="id") After inserting a row like this, the The Custom column order and column types¶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. If you want to explicitly set the order of the columns you can do so using the db.table("dogs").insert({ "id": 1, "name": "Cleo", "twitter": "cleopaws", "age": 3, "is_good_dog": True, }, pk="id", column_order=("id", "twitter", "name")) You don’t need to pass all of the columns to the 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 db.table("dogs").insert({ "id": 1, "name": "Cleo", "age": "5", }, pk="id", columns={"age": int, "weight": float}) This will create a table with the following schema: CREATE TABLE "dogs" ( "id" INTEGER PRIMARY KEY, "name" TEXT, "age" INTEGER, "weight" REAL ) Explicitly creating a table¶You can directly create a new table without inserting any data into it using the db.table("cats").create({ "id": int, "name": str, "weight": float, }, pk="id") 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 Adding columns for full details on how these types work. This method takes optional arguments A You can pass db.table("cats").create({ "id": int, "name": str, }, pk="id", if_not_exists=True) To drop and replace any existing table of that name, pass You can also pass db.table("cats").create({ "id": int, "name": str, "weight": float, }, pk="id", transform=True) The
Changes to You can pass db.table("cats").create({ "id": int, "name": str, }, strict=True) SQLite import sqlite_utils db.table("events").create({ "id": int, "payload": sqlite_utils.ANY, }, pk="id", strict=True) An Note In the CLI: sqlite-utils create-table Compound primary keys¶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 db.table("cats").create({ "id": int, "breed": str, "name": str, "weight": float, }, pk=("breed", "id")) This also works for the Specifying foreign keys¶Any operation that can create a table ( If you are using your database with Datasette, Datasette will detect these constraints and use them to generate hyperlinks to associated records. The foreign_keys=["author_id"] The library will guess which tables you wish to reference based on the column names using the rules described in Adding foreign key constraints. You can also be more explicit, by passing in a list of tuples: foreign_keys=[ ("author_id", "authors", "id") ] This means that the 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: db.table("authors").insert_all([ {"id": 1, "name": "Sally"}, {"id": 2, "name": "Asheesh"} ], pk="id") db.table("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") ]) Compound foreign keys¶To create a compound (multi-column) foreign key, use tuples of column names in place of the single column names: db.table("courses").create({ "course_code": str, "campus_name": str, "dept_code": str, }, pk="course_code", foreign_keys=[ (("campus_name", "dept_code"), "departments", ("campus_name", "dept_code")) ]) This creates a table-level constraint: CREATE TABLE "courses" ( "course_code" TEXT PRIMARY KEY, "campus_name" TEXT, "dept_code" TEXT, FOREIGN KEY ("campus_name", "dept_code") REFERENCES "departments"("campus_name", "dept_code") ) As with single columns, you can leave off the tuple of other columns to reference the compound primary key of the other table: foreign_keys=[ (("campus_name", "dept_code"), "departments") ] To specify from sqlite_utils.db import ForeignKey db.table("books").create({ "id": int, "author_id": int, }, pk="id", foreign_keys=[ ForeignKey( table="books", column="author_id", other_table="authors", other_column="id", on_delete="CASCADE", ) ]) Foreign key actions are preserved by table.transform() - prior to sqlite-utils 4.0 they were silently dropped when a table was transformed. Table configuration options¶The You can set default values for these methods by accessing the table through the 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}) The configuration options that can be specified in this way are Setting defaults and not null constraints¶Each of the methods that can cause a table to be created take optional arguments
You can use You can use Here’s an example that uses these features: db.table("authors").insert_all( [{"id": 1, "name": "Sally", "score": 2}], pk="id", not_null={"name", "score"}, defaults={"score": 1}, ) db.table("authors").insert({"name": "Dharma"}) list(db.table("authors").rows) # Outputs: # [{'id': 1, 'name': 'Sally', 'score': 2}, # {'id': 3, 'name': 'Dharma', 'score': 1}] print(db.table("authors").schema) # Outputs: # CREATE TABLE "authors" ( # "id" INTEGER PRIMARY KEY, # "name" TEXT NOT NULL, # "score" INTEGER NOT NULL DEFAULT 1 # ) Note In the CLI: sqlite-utils insert –not-null and –default Renaming a table¶The db.rename_table("my_table", "new_name_for_my_table") This executes the following SQL: ALTER TABLE [my_table] RENAME TO [new_name_for_my_table] Note In the CLI: sqlite-utils rename-table Duplicating tables¶The db.table("authors").duplicate("authors_copy") The new This method raises Note In the CLI: sqlite-utils duplicate Bulk inserts¶If you have more than one record to insert, the Use it like this: db.table("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")) The column types used in the 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 db.table("big_table").insert_all(({ "id": 1, "name": "Name {}".format(i), } for i in range(10000)), batch_size=1000) You can skip inserting any records that have a primary key that already exists using You can delete all the existing rows in the table before inserting the new records using Pass Note In the CLI: sqlite-utils insert Inserting data from a list or tuple iterator¶As an alternative to passing an iterator of dictionaries, you can pass an iterator of lists or tuples. The first item yielded by the iterator must be a list or tuple of string column names, and subsequent items should be lists or tuples of values: db["creatures"].insert_all([ ["name", "species"], ["Cleo", "dog"], ["Lila", "chicken"], ["Bants", "chicken"], ]) This also works with generators: def creatures(): yield "id", "name", "city" yield 1, "Cleo", "San Francisco" yield 2, "Lila", "Los Angeles" db["creatures"].insert_all(creatures()) Tuples and lists are both supported. Insert-replacing data¶If you try to insert data using a primary key that already exists, the This example that catches that exception: from sqlite_utils.utils import sqlite3 try: db.table("dogs").insert({"id": 1, "name": "Cleo"}, pk="id") except sqlite3.IntegrityError: print("Record already exists with that primary key") Importing from Use the # This fails silently if a record with id=1 already exists db.table("dogs").insert({"id": 1, "name": "Cleo"}, pk="id", ignore=True) To replace any existing records that have a matching primary key, use the db.table("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) Note Prior to sqlite-utils 2.0 the Note In the CLI: sqlite-utils insert –replace Updating a specific record¶You can update a record by its primary key using >>> db = sqlite_utils.Database("dogs.db")
>>> print(db.table("dogs").get(1))
{'id': 1, 'age': 4, 'name': 'Cleo'}
>>> db.table("dogs").update(1, {"age": 5})
>>> print(db.table("dogs").get(1))
{'id': 1, 'age': 5, 'name': 'Cleo'}
The first argument to >>> db.table("compound_dogs").update((5, 3), {"name": "Updated"})
The second argument is a dictionary of columns that should be updated, along with their new values. You can cause any missing columns to be added automatically using >>> db.table("dogs").update(1, {"breed": "Mutt"}, alter=True)
Deleting a specific record¶You can delete a record using >>> db = sqlite_utils.Database("dogs.db")
>>> db.table("dogs").delete(1)
The >>> db.table("compound_dogs").delete((5, 3))
Deleting multiple records¶You can delete all records in a table that match a specific WHERE statement using >>> db = sqlite_utils.Database("dogs.db")
>>> # Delete every dog with age less than 3
>>> db.table("dogs").delete_where("age < ?", [3])
Calling Pass Upserting data¶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. For example, given the dogs database you could upsert the record for Cleo like so: db.table("dogs").upsert({ "id": 1, "name": "Cleo", "twitter": "cleopaws", "age": 4, "is_good_dog": True, }, pk="id", column_order=("id", "twitter", "name")) If a record exists with id=1, it will be updated to match those fields. If it does not exist it will be created. Any existing columns that are not referenced in the dictionary passed to Note that the An Every record passed to Note
Note In the CLI: sqlite-utils upsert Alternative upserts using INSERT OR IGNORE¶Upserts use Converting data in columns¶The This feature works by registering a custom SQLite function that applies a Python transformation, then running a SQL query equivalent to To transform a specific column to uppercase, you would use the following: db.table("dogs").convert("name", lambda value: value.upper()) You can pass a list of columns, in which case the transformation will be applied to each one: db.table("dogs").convert(["name", "twitter"], lambda value: value.upper()) To save the output to of the transformation to a different column, use the db.table("dogs").convert("name", lambda value: value.upper(), output="name_upper") This will add the new column, if it does not already exist. You can pass If you want to drop the original column after saving the results in a separate output column, pass You can create multiple new columns from a single input column by passing table.convert( "title", lambda v: {"upper": v.upper(), "lower": v.lower()}, multi=True ) The table.convert("title", lambda v: v.upper(), where="id > :id", where_args={"id": 20}) These behave the same as the corresponding parameters to the .rows_where() method, so you can use Working with lookup tables¶A useful pattern when populating large tables in to break common values out into lookup tables. Consider a table of Creating lookup tables explicitly¶Calling If the If you call 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: db.table("Trees").insert({ "latitude": 49.1265976, "longitude": 2.5496218, "species": db.table("Species").lookup({ "common_name": "Common Juniper", "latin_name": "Juniperus communis" }) }) The To create a species record with a note on when it was first seen, you can use this: db.table("Species").lookup({"name": "Palm"}, {"first_seen": "2021-03-04"}) The first time this is called the record will be created for
Populating lookup tables automatically during insert/upsert¶A more efficient way to work with lookup tables is to define them using the
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. To extract the # 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 'species', you can do this: trees = db.table("Trees", extracts=["species"]) # Using .insert() directly db.table("Trees").insert({ "latitude": 49.1265976, "longitude": 2.5496218, "species": "Common Juniper" }, extracts={"species": "Species"})
Working with many-to-many relationships¶
Here’s how to create two new records and connect them via a many-to-many table in a single line of code: db.table("dogs").insert({"id": 1, "name": "Cleo"}, pk="id").m2m( "humans", {"id": 1, "name": "Natalie"}, pk="id" ) Running this example actually creates three tables: The db.table("dogs").update(1).m2m( "humans", {"id": 2, "name": "Simon"}, pk="id" ) The first argument to The second argument can be a single dictionary record or a list of dictionaries. These dictionaries will be passed to Here’s alternative code that creates the dog record and adds two people to it: 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"} ] ) 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. If it cannot find such a table, it will create a new one using the names of the two tables - It it finds multiple candidate tables with foreign keys to both of the specified tables it will raise a The Using m2m and lookup tables together¶You can work with (or create) lookup tables as part of a call to 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 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" } ) You can inspect the database to see the results like this: >>> db.table_names()
['dogs', 'characteristics', 'characteristics_dogs']
>>> list(db.table("dogs").rows)
[{'id': 1, 'name': 'Cleo'}]
>>> list(db.table("characteristics").rows)
[{'id': 1, 'name': 'Playful'}, {'id': 2, 'name': 'Opinionated'}]
>>> list(db.table("characteristics_dogs").rows)
[{'characteristics_id': 1, 'dogs_id': 1}, {'characteristics_id': 2, 'dogs_id': 1}]
>>> print(db.table("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")
)
Analyzing a column¶The It takes the following arguments and options:
And returns a
Adding columns¶You can add a new column to a table using the db.table("dogs").add_column("instagram", str) db.table("dogs").add_column("weight", float) db.table("dogs").add_column("dob", datetime.date) db.table("dogs").add_column("image", "BLOB") db.table("dogs").add_column("website") # str by default You can specify the The SQLite types you can specify are If you pass a Python type, it will be mapped to SQLite types as shown here: float: "REAL" int: "INTEGER" bool: "INTEGER" str: "TEXT" bytes: "BLOB" datetime.datetime: "TEXT" datetime.date: "TEXT" datetime.time: "TEXT" datetime.timedelta: "TEXT" sqlite_utils.ANY: "ANY" # 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: "REAL" np.float32: "REAL" np.float64: "REAL" You can also add a column that is a foreign key reference to another table using the db.table("dogs").add_column("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 db.table("dogs").add_column("species_id", fk="species", fk_col="ref") You can set a db.table("dogs").add_column("friends_count", int, not_null_default=0) Note In the CLI: sqlite-utils add-column Adding columns automatically on insert/update¶You can insert or update data that includes new columns and have the table automatically altered to fit the new schema using the db.table("new_table").insert({"name": "Gareth"}) # This will throw an exception: db.table("new_table").insert({"name": "Gareth", "age": 32}) # This will succeed and add a new "age" integer column: db.table("new_table").insert({"name": "Gareth", "age": 32}, alter=True) # You can see confirm the new column like so: print(db.table("new_table").columns_dict) # Outputs this: # {'name': <class 'str'>, 'age': <class 'int'>} # This works too: new_table = db.table("new_table", alter=True) new_table.insert({"name": "Gareth", "age": 32, "shoe_size": 11}) Note In the CLI: sqlite-utils insert –alter Adding foreign key constraints¶The SQLite The It’s also possible to add foreign keys by directly updating the sqlite_master table. The sqlite-utils-fast-fks plugin implements this pattern, using code that was included with Here’s an example of this mechanism in action: db.table("authors").insert_all([ {"id": 1, "name": "Sally"}, {"id": 2, "name": "Asheesh"} ], pk="id") db.table("books").insert_all([ {"title": "Hedgehogs of the world", "author_id": 1}, {"title": "How to train your wolf", "author_id": 2}, ]) db.table("books").add_foreign_key("author_id", "authors", "id") The
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 To ignore the case where the key already exists, use db.table("books").add_foreign_key("author_id", "authors", "id", ignore=True) To add a compound foreign key, pass tuples of columns: db.table("courses").add_foreign_key( ("campus_name", "dept_code"), "departments", ("campus_name", "dept_code") ) As with single columns, omitting the other columns will use the compound primary key of the other table. Use db.table("books").add_foreign_key( "author_id", "authors", "id", on_delete="CASCADE" ) This creates a foreign key with an Note In the CLI: sqlite-utils add-foreign-key Adding multiple foreign key constraints at once¶You can use Here’s an example adding two foreign keys at once: db.add_foreign_keys([ ("dogs", "breed_id", "breeds", "id"), ("dogs", "home_town_id", "towns", "id") ]) This method runs the same checks as Foreign keys that already exist are silently skipped, so repeated calls are idempotent - but only if they match exactly. Requesting a foreign key that exists with different Note In the CLI: 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: db.index_foreign_keys() Compound foreign keys get a single composite index across their columns. Note In the CLI: sqlite-utils index-foreign-keys Dropping a table or view¶You can drop a table or view using the db.table("my_table").drop() # Or for a view: db.view("my_view").drop() # Or for either: db["table_or_view_name"].drop() Pass db.table("my_table").drop(ignore=True) Note In the CLI: sqlite-utils drop-table and sqlite-utils drop-view Transforming a table¶The SQLite The
The As a bonus, calling To keep the original table around instead of dropping it, pass the table.transform(types={"age": int}, keep_table="original_table") This method raises a Note In the CLI: sqlite-utils transform Altering column types¶To alter the type of a column, use the # Convert the 'age' column to an integer, and 'weight' to a float table.transform(types={"age": int, "weight": float}) When a See Adding columns for a list of available types. Changing strict mode¶The optional table.transform(strict=True) Pass table.transform(strict=False) If the table has The default is Passing Converting to a strict table validates all existing rows as they are copied into the replacement table. If a value is incompatible with its declared column type, SQLite raises Renaming columns¶The # Rename 'age' to 'initial_age': table.transform(rename={"age": "initial_age"}) Dropping columns¶To drop columns, pass them in the # Drop the 'age' column: table.transform(drop={"age"}) Changing primary keys¶To change the primary key for a table, use # Make `user_id` the new primary key table.transform(pk="user_id") Changing not null status¶You can change the # Make the 'age' and 'weight' columns NOT NULL table.transform(not_null={"age", "weight"}) If you want to take existing # 'age' 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}) Altering column defaults¶The # Set default age to 1: table.transform(defaults={"age": 1}) # Now remove the default from that column: table.transform(defaults={"age": None}) Changing column order¶The # Change column order table.transform(column_order=("name", "age", "id") Adding foreign key constraints¶You can add one or more foreign key constraints to a table using the db.table("places").transform( add_foreign_keys=( ("country", "country", "id"), ("continent", "continent", "id") ) ) This accepts the same arguments described in specifying foreign keys - so you can specify them as a full tuple of db.table("places").transform( add_foreign_keys=(("country", "continent")) ) Replacing foreign key constraints¶The db.table("places").transform( foreign_keys=( ("continent", "continent", "id"), ) ) Dropping foreign key constraints¶You can use This example drops two foreign keys - the one from db.table("places").transform( drop_foreign_keys=("country", "continent") ) A bare column name drops any foreign key that column participates in, including compound foreign keys. To target a compound foreign key precisely, pass a tuple of its columns: db.table("courses").transform( drop_foreign_keys=[("campus_name", "dept_code")] ) Renaming a column with CHECK constraints¶
A column-level check is removed if its owning column is dropped. Dropping a column referenced by any remaining check raises Comments immediately before or after a column definition are preserved too. They move with that column if it is renamed or reordered, and are removed if the column is dropped. A comment between two column definitions is treated as belonging to the following column. Tables referenced by views¶Tables that are referenced by views can be safely transformed - the view definitions are left byte-for-byte unchanged, and views continue to read from the live table even when A view that references a column which the transform renamed or dropped will remain defined but will raise a To achieve this, the SQL produced by Custom transformations with .transform_sql()¶The If you want to do something more advanced, you can call the 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. Foreign keys and transactions¶Because
from sqlite_utils.db import TransactionError try: with db.atomic(): db["authors"].transform(types={"id": str}) except TransactionError as ex: print("Could not transform in transaction:", ex) To transform such a table either call db.execute("PRAGMA foreign_keys = off") with db.atomic(): db["authors"].transform(types={"id": str}) db.execute("PRAGMA foreign_keys = on") Tables referenced by foreign keys without a destructive action (the default Extracting columns into a separate table¶The Imagine a
The The schema of the above table is: CREATE TABLE "Trees" ( "id" INTEGER PRIMARY KEY, "TreeAddress" TEXT, "Species" TEXT ) Here’s how to extract the db.table("Trees").extract("Species") After running this code the table schema now looks like this: CREATE TABLE "Trees" ( "id" INTEGER PRIMARY KEY, "TreeAddress" TEXT, "Species_id" INTEGER, FOREIGN KEY(Species_id) REFERENCES Species(id) ) A new CREATE TABLE "Species" ( "id" INTEGER PRIMARY KEY, "Species" TEXT ) The You can specify a custom table name using db.table("Trees").extract("Species", table="tree_species", fk_column="tree_species_id") The resulting schema looks like this: 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 ) You can also extract multiple columns into the same external table. Say for example you have a table like this:
You can pass db.table("Trees").extract(["CommonName", "LatinName"]) This produces the following schema: 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 ) The table name db.table("Trees").extract(["CommonName", "LatinName"], table="Species", fk_column="species_id") This produces 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, "CommonName" TEXT, "LatinName" TEXT ) You can use the db.table("Trees").extract( ["CommonName", "LatinName"], table="Species", fk_column="species_id", rename={"CommonName": "name", "LatinName": "latin"} ) This produces a lookup table like so: CREATE TABLE "Species" ( "id" INTEGER PRIMARY KEY, "name" TEXT, "latin" TEXT ) Rows where every extracted column is Note In the CLI: sqlite-utils extract Setting an ID based on the hash of the row contents¶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. In these cases, a useful technique is to create an ID that is derived from the sha1 hash of the row contents.
db = sqlite_utils.Database("dogs.db")
db.table("dogs").upsert({"name": "Cleo", "twitter": "cleopaws"}, hash_id="id")
print(list(db["dogs]))
Outputs: [{'id': 'f501265970505d9825d8d9f590bfab3519fb20b1', 'name': 'Cleo', 'twitter': 'cleopaws'}]
If you are going to use that ID straight away, you can access it using dog_id = db.table("dogs").upsert({
"name": "Cleo",
"twitter": "cleopaws"
}, hash_id="id").last_pk
# dog_id is now "f501265970505d9825d8d9f590bfab3519fb20b1"
The hash will be created using all of the column values. To create a hash using a subset of the columns, pass the db.table("dogs").upsert(
{"name": "Cleo", "twitter": "cleopaws", "age": 7},
hash_id_columns=("name", "twitter")
)
The You can manually calculate these hashes using the hash_record(record, keys=…) utility function. Creating views¶The db.create_view("good_dogs", """ select * from dogs where is_good_dog = 1 """) This will raise a You can pass db.create_view("good_dogs", """ select * from dogs where is_good_dog = 1 """, replace=True) Note In the CLI: sqlite-utils create-view Storing JSON¶SQLite has excellent JSON support, and For example: db.table("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, '$.addressLocality') from niche_museums """).fetchall() # Returns [('Felton, CA',)] Converting column values using SQL functions¶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. The You can specify an upper case conversion for a specific column like so: db.table("example").insert({ "name": "The Bigfoot Discovery Museum" }, conversions={"name": "upper(?)"}) # list(db.table("example").rows) now returns: # [{'name': 'THE BIGFOOT DISCOVERY MUSEUM'}] The dictionary key is the column name to be converted. The value is the SQL fragment to use, with a A more useful example: if you are working with SpatiaLite you may find yourself wanting to create geometry values from a WKT value. Code to do that could look like this: 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.table("places").create({"id": int, "name": str}) # Add a SpatiaLite 'geometry' column places.add_geometry_column("geometry", "MULTIPOLYGON") # Fetch some GeoJSON from Who's 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.table("places").insert( {"name": "Wales", "geometry": wkt}, conversions={"geometry": "GeomFromText(?, 4326)"}, ) This example uses gographical data from Who’s On First and depends on the Shapely and HTTPX Python libraries. Checking the SQLite version¶The >>> db.sqlite_version (3, 36, 0) Dumping the database to SQL¶The full_sql = "".join(db.iterdump()) This uses the sqlite3.Connection.iterdump() method. If you are using pip install sqlite-dump Note In the CLI: sqlite-utils dump Introspecting tables and views¶If you have loaded an existing table or view, you can use introspection to find out more about it: >>> db.table("PlantType")
<Table PlantType (id, value)>
### db.view("NameOfView")
<View NameOfView (id, value)>
.exists()¶The >>> db.table("PlantType").exists()
True
>>> db.table("PlantType2").exists()
False
>>> db["table_or_view_name"].exists()
False
.count¶The >>> db.table("PlantType").count
3
>>> db.table("Street_Tree_List").count
189144
This property will take advantage of Cached table counts using triggers if the .columns¶The >>> db.table("PlantType").columns
[Column(cid=0, name='id', type='INTEGER', notnull=0, default_value=None, is_pk=1),
Column(cid=1, name='value', type='TEXT', notnull=0, default_value=None, is_pk=0)]
.columns_dict¶The >>> db.table("PlantType").columns_dict
{'id': <class 'int'>, 'value': <class 'str'>}
SQLite >>> db.table("events").columns_dict
{'id': <class 'int'>, 'payload': <class 'sqlite_utils.utils.ANY'>}
.default_values¶The >>> db.table("table_with_defaults").default_values
{'score': 5}
.pks¶The >>> db.table("PlantType").pks
['id']
If a table has no primary keys but is a rowid table, this property will return .use_rowid¶Almost all SQLite tables have a >>> db.table("PlantType").use_rowid False .checks¶The >>> db["scores"].checks [Check(check='score > 0', name='positive', column='score', options=None), Check(check='score <= maximum', name='within_maximum', column='', options=None)] .column_checks¶The >>> db["scores"].column_checks {'score': [Check(check='score > 0', name='positive', column='score', options=None)]} .table_checks¶The >>> db["scores"].table_checks [Check(check='score <= maximum', name='within_maximum', column='', options=None)] .foreign_keys¶The Each
>>> db.table("Street_Tree_List").foreign_keys
[ForeignKey(table='Street_Tree_List', column='qLegalStatus', other_table='qLegalStatus', other_column='id', columns=('qLegalStatus',), other_columns=('id',), is_compound=False, on_delete='NO ACTION', on_update='NO ACTION'),
ForeignKey(table='Street_Tree_List', column='qCareAssistant', other_table='qCareAssistant', other_column='id', columns=('qCareAssistant',), other_columns=('id',), is_compound=False, on_delete='NO ACTION', on_update='NO ACTION'),
...]
Compound foreign keys - defined with .schema¶The >>> print(db.table("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))
.strict¶The >>> db.table("ny_times_us_counties").strict
False
.indexes¶The >>> db.table("Street_Tree_List").indexes
[Index(seq=0, name='"Street_Tree_List_qLegalStatus"', unique=0, origin='c', partial=0, columns=['qLegalStatus']),
Index(seq=1, name='"Street_Tree_List_qCareAssistant"', unique=0, origin='c', partial=0, columns=['qCareAssistant']),
Index(seq=2, name='"Street_Tree_List_qSiteInfo"', unique=0, origin='c', partial=0, columns=['qSiteInfo']),
Index(seq=3, name='"Street_Tree_List_qSpecies"', unique=0, origin='c', partial=0, columns=['qSpecies']),
Index(seq=4, name='"Street_Tree_List_qCaretaker"', unique=0, origin='c', partial=0, columns=['qCaretaker']),
Index(seq=5, name='"Street_Tree_List_PlantType"', unique=0, origin='c', partial=0, columns=['PlantType'])]
Note In the CLI: sqlite-utils indexes .xindexes¶The >>> db.table("ny_times_us_counties").xindexes
[
XIndex(
name='idx_ny_times_us_counties_date',
columns=[
XIndexColumn(seqno=0, cid=0, name='date', desc=1, coll='BINARY', key=1),
XIndexColumn(seqno=1, cid=-1, name=None, desc=0, coll='BINARY', key=0)
]
),
XIndex(
name='idx_ny_times_us_counties_fips',
columns=[
XIndexColumn(seqno=0, cid=3, name='fips', desc=0, coll='BINARY', key=1),
XIndexColumn(seqno=1, cid=-1, name=None, desc=0, coll='BINARY', key=0)
]
)
]
.triggers¶The >>> db.table("authors").triggers
[Trigger(name='authors_ai', table='authors', sql='CREATE TRIGGER [authors_ai] AFTER INSERT...'),
Trigger(name='authors_ad', table='authors', sql="CREATE TRIGGER [authors_ad] AFTER DELETE..."),
Trigger(name='authors_au', table='authors', sql="CREATE TRIGGER [authors_au] AFTER UPDATE")]
>>> db.triggers
... similar output to db.table("authors").triggers
Note In the CLI: sqlite-utils triggers .triggers_dict¶The >>> db.table("authors").triggers_dict
{'authors_ai': 'CREATE TRIGGER [authors_ai] AFTER INSERT...',
'authors_ad': 'CREATE TRIGGER [authors_ad] AFTER DELETE...',
'authors_au': 'CREATE TRIGGER [authors_au] AFTER UPDATE'}
The same property exists on the database, and will return all triggers across all tables: >>> db.triggers_dict
{'authors_ai': 'CREATE TRIGGER [authors_ai] AFTER INSERT...',
'authors_ad': 'CREATE TRIGGER [authors_ad] AFTER DELETE...',
'authors_au': 'CREATE TRIGGER [authors_au] AFTER UPDATE'}
.detect_fts()¶The >>> db.table("authors").detect_fts()
"authors_fts"
.virtual_table_using¶The >>> db.table("authors").enable_fts(["name"])
>>> db.table("authors_fts").virtual_table_using
"FTS5"
.has_counts_triggers¶The >>> db.table("authors").has_counts_triggers
False
>>> db.table("authors").enable_counts()
>>> db.table("authors").has_counts_triggers
True
db.supports_strict¶This property on the database object returns >>> db.supports_strict True Full-text search¶SQLite includes bundled extensions that implement powerful full-text search. Enabling full-text search for a table¶You can enable full-text search on a table using db.table("dogs").enable_fts(["name", "twitter"]) You can then run searches using the rows = list(db.table("dogs").search("cleo")) This method returns a generator that can be looped over to get dictionaries for each row, similar to Listing rows. If you insert additional records into the table you will need to refresh the search index using db.table("dogs").insert({ "id": 2, "name": "Marnie", "twitter": "MarnieTheDog", "age": 16, "is_good_dog": True, }, pk="id") db.table("dogs").populate_fts(["name", "twitter"]) A better solution is to use database triggers. You can set up database triggers to automatically update the full-text index using db.table("dogs").enable_fts(["name", "twitter"], create_triggers=True)
db.table("dogs").enable_fts(["name", "twitter"], fts_version="FTS4") You can customize the tokenizer configured for the table using the db.table("articles").enable_fts(["headline", "body"], tokenize="porter") The SQLite documentation has more on FTS5 tokenizers and FTS4 tokenizers. If you attempt to configure a FTS table where one already exists, a You can replace the existing table with a new configuration using db.table("articles").enable_fts(["headline"], tokenize="porter", replace=True) 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. To remove the FTS tables and triggers you created, use the db.table("dogs").disable_fts() Note In the CLI: sqlite-utils enable-fts Quoting characters for use in search¶SQLite supports advanced search query syntax. In some situations you may wish to disable this, since characters such as The db.quote_fts("Search term.")
# Returns: '"Search" "term."'
Searching with table.search()¶The for article in db.table("articles").search("jquery"): print(article) The
To return just the title and published columns for three matches for for article in db.table("articles").search( "dog", order_by="published desc", limit=3, where="id > :min_id", where_args={"min_id": 10}, columns=["title", "published"] ): print(article) Note In the CLI: sqlite-utils search Building SQL queries with table.search_sql()¶You can generate the SQL query that would be used for a search using the print(db.table("articles").search_sql(columns=["title", "author"])) Outputs: 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 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. The FTS4 output looks something like this: 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], 'pcnalx')) This uses the db.register_fts4_bm25() Rebuilding a full-text search table¶You can rebuild a table using the db.table("dogs").rebuild_fts() This method can be called on a table that has been configured for full-text search - db.table("dogs_fts").rebuild_fts() This runs the following SQL: INSERT INTO dogs_fts (dogs_fts) VALUES ("rebuild");
Note In the CLI: sqlite-utils rebuild-fts Optimizing a full-text search table¶Once you have populated a FTS table you can optimize it to dramatically reduce its size like so: db.table("dogs").optimize() This runs the following SQL: INSERT INTO dogs_fts (dogs_fts) VALUES ("optimize");
Note In the CLI: sqlite-utils optimize Cached table counts using triggers¶The The db.table("dogs").enable_counts() This will create the CREATE TABLE "_counts" ( "table" TEXT PRIMARY KEY, "count" INTEGER DEFAULT 0 ) You can enable cached counts for every table in a database (except for virtual tables and the db.enable_counts() Once enabled, table counts will be stored in the To access these counts you can query the >>> db.cached_counts()
{'global-power-plants': 33643,
'global-power-plants_fts_data': 136,
'global-power-plants_fts_idx': 199,
'global-power-plants_fts_docsize': 33643,
'global-power-plants_fts_config': 1}
You can pass a list of table names to this method to retrieve just those counts: >>> db.cached_counts(["global-power-plants"])
{'global-power-plants': 33643}
The You can set db = Database("global-power-plants.db", use_counts_table=True) If the property is Calling the If the db.reset_counts() Note In the CLI: sqlite-utils enable-counts Creating indexes¶You can create an index on a table using the db.table("dogs").create_index(["is_good_dog"]) By default the index will be named You can customize the name of the created index by passing the db.table("dogs").create_index( ["is_good_dog", "age"], index_name="good_dogs_by_age" ) To create an index in descending order for a column, wrap the column name in from sqlite_utils.db import DescIndex db.table("dogs").create_index( ["is_good_dog", DescIndex("age")], index_name="good_dogs_by_age" ) You can create a unique index by passing db.table("dogs").create_index(["name"], unique=True) Use Pass You can drop an index from a table using db.table("dogs").drop_index("idx_dogs_name") Use Note In the CLI: sqlite-utils create-index and sqlite-utils drop-index 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 db.analyze() To run it just against a specific named index, pass the name of the index to that method: db.analyze("idx_countries_country_name") To run against all indexes attached to a specific table, you can either pass the table name to db.table("dogs").analyze() Note In the CLI: sqlite-utils analyze Vacuum¶You can optimize your database by running VACUUM against it like so: Database("my_database.db").vacuum() Note In the CLI: sqlite-utils vacuum WAL mode¶You can enable Write-Ahead Logging for a database with Database("my_database.db").enable_wal() You can disable WAL mode using Database("my_database.db").disable_wal() The journal mode can only be changed outside of a transaction. Calling either method while a transaction is open - inside a You can check the current journal mode for a database using the journal_mode = Database("my_database.db").journal_mode This will usually be Note In the CLI: sqlite-utils enable-wal and disable-wal Suggesting column types¶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. In some situations you may need to intervene in this process, to customize the columns that are being created in some way - see Explicitly creating a table. That table db.table("cats").create({ "id": int, "name": str, "weight": float, }) You can use the For example: 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": <class 'int'>, # "name": <class 'str'>, # "age": <class 'int'>} # Manually add an extra field: types["thumbnail"] = bytes # types now looks like this: # {"id": <class 'int'>, # "name": <class 'str'>, # "age": <class 'int'>, # "thumbnail": <class 'bytes'>} # Create the table db = Database("cats.db") db.table("cats").create(types, pk="id") # Insert the records db.table("cats").insert_all(cats) # list(db.table("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.table("cats").schema) # CREATE TABLE "cats" ( # "id" INTEGER PRIMARY KEY, # "name" TEXT, # "age" INTEGER, # "thumbnail" BLOB # ) Registering custom SQL functions¶SQLite supports registering custom SQL functions written in Python. The If you use it as a method it will automatically detect the name and number of arguments needed by the function: 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('select reverse_string("hello")').fetchone()[0]) # This prints "olleh" You can also use the method as a function decorator like so: @db.register_function def reverse_string(s): return "".join(reversed(list(s))) print(db.execute('select reverse_string("hello")').fetchone()[0]) By default, the name of the Python function will be used as the name of the SQL function. You can customize this with the @db.register_function(name="rev") def reverse_string(s): return "".join(reversed(list(s))) print(db.execute('select rev("hello")').fetchone()[0]) If a function will return the exact same result for any given inputs you can register it as a deterministic SQLite function allowing SQLite to apply some performance optimizations: @db.register_function(deterministic=True) def reverse_string(s): return "".join(reversed(list(s))) By default registering a function with the same name and number of arguments will have no effect - the If you want to deliberately replace the registered function with a new implementation, use the @db.register_function(deterministic=True, replace=True) def reverse_string(s): return s[::-1] Exceptions that occur inside a user-defined function default to returning the following error: Unexpected error: user-defined function raised exception You can cause from sqlite_utils.utils import sqlite3 sqlite3.enable_callback_tracebacks(True) Note In the CLI: sqlite-utils query –functions Quoting strings for use in SQL¶In almost all cases you should pass values to your SQL queries using the optional If that option isn’t relevant to your use-case you can to quote a string for use with SQLite using the >>> db = Database(memory=True)
>>> db.quote("hello")
"'hello'"
>>> db.quote("hello'this'has'quotes")
"'hello''this''has''quotes'"
Reading rows from a file¶The
Setting the maximum CSV field size limit¶Sometimes when working with CSV files that include extremely long fields you may see an error that looks like this: _csv.Error: field larger than field limit (131072) The Python standard library The maximum possible value for this is not documented, and varies between systems. Calling from sqlite_utils.utils import maximize_csv_field_size_limit maximize_csv_field_size_limit() If you need to reset to the original value after calling this function you can do so like this: from sqlite_utils.utils import ORIGINAL_CSV_FIELD_SIZE_LIMIT import csv csv.field_size_limit(ORIGINAL_CSV_FIELD_SIZE_LIMIT) Detecting column types using TypeTracker¶Sometimes you may find yourself working with data that lacks type information - data from a CSV file for example. The Consider this example: import csv, io csv_file = io.StringIO("id,name\n1,Cleo\n2,Cardi") rows = list(csv.DictReader(csv_file)) # rows is now this: # [{'id': '1', 'name': 'Cleo'}, {'id': '2', 'name': 'Cardi'}] If we insert this data directly into a table we will get a schema that is entirely from sqlite_utils import Database db = Database(memory=True) db.table("creatures").insert_all(rows) print(db.schema) # Outputs: # CREATE TABLE "creatures" ( # "id" TEXT, # "name" TEXT # ); We can detect the best column types using a from sqlite_utils.utils import TypeTracker tracker = TypeTracker() db.table("creatures2").insert_all(tracker.wrap(rows)) print(tracker.types) # Outputs {'id': 'integer', 'name': 'text'} We can then apply those types to our new table using the table.transform() method: db.table("creatures2").transform(types=tracker.types) print(db.table("creatures2").schema) # Outputs: # CREATE TABLE "creatures2" ( # "id" INTEGER, # "name" TEXT # ); SpatiaLite helpers¶SpatiaLite 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. Initialize SpatiaLite¶
Note In the CLI: sqlite-utils create-database –init-spatialite Finding SpatiaLite¶
Adding geometry columns¶
Note In the CLI: sqlite-utils add-geometry-column Creating a spatial index¶
Note In the CLI: sqlite-utils create-spatial-index | |||||||||||||||||||||||||||||||||||
| 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. |