---
title: Database and tables
description: Minimal `sqlite3` database, table, and view API forked from `sqlite-utils`
  without CLI dependencies.
order: 1
---
Provides [`Database`](db.md#database), [`Table`](db.md#table), [`View`](db.md#view), and [`Queryable`](db.md#queryable) over Python's `sqlite3` (or `pysqlite3`/`sqlean` when installed). See the README for usage examples.

## Database

```python
def Database(
    filename_or_conn:Union[str, pathlib._local.Path, sqlite3.Connection, NoneType]=None, memory:bool=False,
    memory_name:Optional[str]=None, recreate:bool=False, recursive_triggers:bool=True,
    tracer:Optional[Callable]=None, use_counts_table:bool=False, strict:bool=False
):
```

*Wrapper for a SQLite database connection that adds a variety of useful utility methods.*

To create an instance::

```
# create data.db file, or open existing:
db = Database("data.db")
# Create an in-memory database:
dB = Database(memory=True)
```

:param filename\_or\_conn: String path to a file, or a `pathlib.Path` object, or a `sqlite3` connection :param memory: set to `True` to create an in-memory database :param memory\_name: creates a named in-memory database that can be shared across multiple connections :param recreate: set to `True` to delete and recreate a file database (**dangerous**) :param recursive\_triggers: defaults to `True`, which sets `PRAGMA recursive_triggers=on;` - set to `False` to avoid setting this pragma :param tracer: set a tracer function (`print` works for this) which will be called with `sql, parameters` every time a SQL query is executed :param use\_counts\_table: set to `True` to use a cached counts table, if available. See :ref:`python_api_cached_table_counts` :param strict: Apply STRICT mode to all created tables (unless overridden)

### Database.close

```python
def close():
```

*Close the SQLite connection, and the underlying database file*

### Database.get\_last\_rowid

```python
def get_last_rowid():
```

### Database.ensure\_autocommit\_off

```python
def ensure_autocommit_off():
```

*Ensure autocommit is off for this database connection.*

Example usage::

```
with db.ensure_autocommit_off():
    # do stuff here
```

This will reset to the previous autocommit state at the end of the block.

### Database.tracer

```python
def tracer(
    tracer:Optional[Callable]=None
):
```

*Context manager to temporarily set a tracer function - all executed SQL queries will be passed to this.*

The tracer function should accept two arguments: `sql` and `parameters`

Example usage::

```
with db.tracer(print):
    db["creatures"].insert({"name": "Cleo"})
```

See :ref:`python_api_tracing`.

:param tracer: Callable accepting `sql` and `parameters` arguments

### Database.register\_function

```python
def register_function(
    fn:Optional[Callable]=None, deterministic:bool=False, replace:bool=False, name:Optional[str]=None
):
```

*`fn` will be made available as a function within SQL, with the same name and number of arguments. Can be used as a decorator::*

```
@db.register_function
def upper(value):
    return str(value).upper()
```

The decorator can take arguments::

```
@db.register_function(deterministic=True, replace=True)
def upper(value):
    return str(value).upper()
```

See :ref:`python_api_register_function`.

:param fn: Function to register :param deterministic: set `True` for functions that always returns the same output for a given input :param replace: set `True` to replace an existing function with the same name - otherwise throw an error :param name: name of the SQLite function - if not specified, the Python function name will be used

### Database.attach

```python
def attach(
    alias:str, filepath:Union[str, pathlib._local.Path]
):
```

*Attach another SQLite database file to this connection with the specified alias, equivalent to::*

```
ATTACH DATABASE 'filepath.db' AS alias
```

:param alias: Alias name to use :param filepath: Path to SQLite database file on disk

### Database.fetchone

```python
def fetchone(
    sql:str, where_args:Union[Iterable, dict, NoneType]=None
):
```

*Execute `sql` and return a single row result*

### Database.query

```python
def query(
    sql:str, params:Union[Iterable, dict, NoneType]=None
)->Generator[dict, NoneType, NoneType]:
```

*Execute `sql` and return an iterable of dictionaries representing each row.*

:param sql: SQL query to execute :param params: Parameters to use in that query - an iterable for `where id = ?` parameters, or a dictionary for `where id = :id`

### Database.execute

```python
def execute(
    sql:str, parameters:Union[Iterable, dict, NoneType]=None
)->sqlite3.Cursor:
```

*Execute SQL query and return a `sqlite3.Cursor`.*

:param sql: SQL query to execute :param parameters: Parameters to use in that query - an iterable for `where id = ?` parameters, or a dictionary for `where id = :id`

### Database.executescript

```python
def executescript(
    sql:str
)->sqlite3.Cursor:
```

*Execute multiple SQL statements separated by ; and return the `sqlite3.Cursor`.*

:param sql: SQL to execute

### Database.convert\_lists\_to\_tuples

```python
def convert_lists_to_tuples(
    function
):
```

*functool module cache decorator doesn't work with lists, sets, or dicts, so this decorator converts them to tuples before calling the function, and then converts any lists in the result back to tuples.*

### Database.convert\_lists\_to\_tuples.\<locals\>.wrapper

```python
def wrapper(
    *args, **kwargs
):
```

### Database.quote

```python
def quote(
    value:str
)->str:
```

*Apply SQLite string quoting to a value, including wrapping it in single quotes.*

:param value: String to quote

### Database.quote\_fts

```python
def quote_fts(
    query:str
)->str:
```

*Escape special characters in a SQLite full-text search query.*

This works by surrounding each token within the query with double quotes, in order to avoid words like `NOT` and `OR` having special meaning as defined by the FTS query syntax here:

[https://www.sqlite.org/fts5.html\#full\_text\_query\_syntax](https://www.sqlite.org/fts5.html#full_text_query_syntax)

If the query has unbalanced `"` characters, adds one at end.

:param query: String to escape

### Database.quote\_default\_value

```python
def quote_default_value(
    value:str
)->str:
```

### Database.table\_names

```python
def table_names(
    fts5:bool=False
)->List[str]:
```

*List of string table names in this database.*

:param fts5: Only return tables that are part of FTS5 indexes

### Database.begin

```python
def begin():
```

*Begin a transaction*

### Database.commit

```python
def commit():
```

*Commit a transaction*

### Database.rollback

```python
def rollback():
```

*Roll back a transaction*

### Database.view\_names

```python
def view_names()->List[str]:
```

*List of string view names in this database.*

### Database.tables

```python
def tables()->List[ForwardRef('Table')]:
```

*List of Table objects in this database.*

### Database.views

```python
def views()->List[ForwardRef('View')]:
```

*List of View objects in this database.*

### Database.triggers

```python
def triggers()->List[sqlite_minutils.db.Trigger]:
```

*List of `(name, table_name, sql)` tuples representing triggers in this database.*

### Database.triggers\_dict

```python
def triggers_dict()->Dict[str, str]:
```

*A `{trigger_name: sql}` dictionary of triggers in this database.*

### Database.schema

```python
def schema()->str:
```

*SQL schema for this database.*

### Database.supports\_strict

```python
def supports_strict()->bool:
```

*Does this database support STRICT mode?*

### Database.sqlite\_version

```python
def sqlite_version()->Tuple[int, ...]:
```

*Version of SQLite, as a tuple of integers for example `(3, 36, 0)`.*

### Database.journal\_mode

```python
def journal_mode()->str:
```

*Current `journal_mode` of this database.*

[https://www.sqlite.org/pragma.html\#pragma\_journal\_mode](https://www.sqlite.org/pragma.html#pragma_journal_mode)

### Database.enable\_wal

```python
def enable_wal():
```

*Sets `journal_mode` to `'wal'` to enable Write-Ahead Log mode.*

### Database.disable\_wal

```python
def disable_wal():
```

*Sets `journal_mode` back to `'delete'` to disable Write-Ahead Log mode.*

### Database.enable\_counts

```python
def enable_counts():
```

*Enable trigger-based count caching for every table in the database, see* :ref:`python_api_cached_table_counts`.

### Database.cached\_counts

```python
def cached_counts(
    tables:Optional[Iterable[str]]=None
)->Dict[str, int]:
```

*Return `{table_name: count}` dictionary of cached counts for specified tables, or all tables if `tables` not provided.*

:param tables: Subset list of tables to return counts for.

### Database.reset\_counts

```python
def reset_counts():
```

*Re-calculate cached counts for tables.*

### Database.execute\_returning\_dicts

```python
def execute_returning_dicts(
    sql:str, params:Union[Iterable, dict, NoneType]=None
)->List[dict]:
```

### Database.resolve\_foreign\_keys

```python
def resolve_foreign_keys(
    name:str,
    foreign_keys:Union[Iterable[Union[str, sqlite_minutils.db.ForeignKey, Tuple[str, str], Tuple[str, str, str], Tuple[str, str, str, str]]], List[Union[str, sqlite_minutils.db.ForeignKey, Tuple[str, str], Tuple[str, str, str], Tuple[str, str, str, str]]]]
)->List[sqlite_minutils.db.ForeignKey]:
```

*Given a list of differing foreign\_keys definitions, return a list of fully resolved ForeignKey() named tuples.*

:param name: Name of table that foreign keys are being defined for :param foreign\_keys: List of foreign keys, each of which can be a string, a ForeignKey() named tuple, a tuple of (column, other\_table), or a tuple of (column, other\_table, other\_column), or a tuple of (table, column, other\_table, other\_column)

### Database.create\_table\_sql

```python
def create_table_sql(
    name:str, columns:Dict[str, Any], pk:Optional[Any]=None,
    foreign_keys:Union[Iterable[Union[str, sqlite_minutils.db.ForeignKey, Tuple[str, str], Tuple[str, str, str], Tuple[str, str, str, str]]], List[Union[str, sqlite_minutils.db.ForeignKey, Tuple[str, str], Tuple[str, str, str], Tuple[str, str, str, str]]], NoneType]=None,
    column_order:Optional[List[str]]=None, not_null:Optional[Iterable[str]]=None,
    defaults:Optional[Dict[str, Any]]=None, hash_id:Optional[str]=None, hash_id_columns:Optional[Iterable[str]]=None,
    extracts:Union[Dict[str, str], List[str], NoneType]=None, if_not_exists:bool=False, strict:bool=False
)->str:
```

*Returns the SQL `CREATE TABLE` statement for creating the specified table.*

:param name: Name of table :param columns: Dictionary mapping column names to their types, for example `{"name": str, "age": int}` :param pk: String name of column to use as a primary key, or a tuple of strings for a compound primary key covering multiple columns :param foreign\_keys: List of foreign key definitions for this table :param column\_order: List specifying which columns should come first :param not\_null: List of columns that should be created as `NOT NULL` :param defaults: Dictionary specifying default values for columns :param hash\_id: Name of column to be used as a primary key containing a hash of the other columns :param hash\_id\_columns: List of columns to be used when calculating the hash ID for a row :param extracts: List or dictionary of columns to be extracted during inserts, see :ref:`python_api_extracts` :param if\_not\_exists: Use `CREATE TABLE IF NOT EXISTS` :param strict: Apply STRICT mode to table

### Database.create\_table

```python
def create_table(
    name:str, columns:Dict[str, Any], pk:Optional[Any]=None,
    foreign_keys:Union[Iterable[Union[str, sqlite_minutils.db.ForeignKey, Tuple[str, str], Tuple[str, str, str], Tuple[str, str, str, str]]], List[Union[str, sqlite_minutils.db.ForeignKey, Tuple[str, str], Tuple[str, str, str], Tuple[str, str, str, str]]], NoneType]=None,
    column_order:Optional[List[str]]=None, not_null:Optional[Iterable[str]]=None,
    defaults:Optional[Dict[str, Any]]=None, hash_id:Optional[str]=None, hash_id_columns:Optional[Iterable[str]]=None,
    extracts:Union[Dict[str, str], List[str], NoneType]=None, if_not_exists:bool=False, replace:bool=False,
    ignore:bool=False, transform:bool=False, strict:bool=False
)->Table:
```

*Create a table with the specified name and the specified `{column_name: type}` columns.*

See :ref:`python_api_explicit_create`.

:param name: Name of table :param columns: Dictionary mapping column names to their types, for example `{"name": str, "age": int}` :param pk: String name of column to use as a primary key, or a tuple of strings for a compound primary key covering multiple columns :param foreign\_keys: List of foreign key definitions for this table :param column\_order: List specifying which columns should come first :param not\_null: List of columns that should be created as `NOT NULL` :param defaults: Dictionary specifying default values for columns :param hash\_id: Name of column to be used as a primary key containing a hash of the other columns :param hash\_id\_columns: List of columns to be used when calculating the hash ID for a row :param extracts: List or dictionary of columns to be extracted during inserts, see :ref:`python_api_extracts` :param if\_not\_exists: Use `CREATE TABLE IF NOT EXISTS` :param replace: Drop and replace table if it already exists :param ignore: Silently do nothing if table already exists :param transform: If table already exists transform it to fit the specified schema :param strict: Apply STRICT mode to table

### Database.rename\_table

```python
def rename_table(
    name:str, new_name:str
):
```

*Rename a table.*

:param name: Current table name :param new\_name: Name to rename it to

### Database.create\_view

```python
def create_view(
    name:str, sql:str, ignore:bool=False, replace:bool=False
):
```

*Create a new SQL view with the specified name - `sql` should start with `SELECT ...`.*

:param name: Name of the view :param sql: SQL `SELECT` query to use for this view. :param ignore: Set to `True` to do nothing if a view with this name already exists :param replace: Set to `True` to replace the view if one with this name already exists

### Database.m2m\_table\_candidates

```python
def m2m_table_candidates(
    table:str, other_table:str
)->List[str]:
```

*Given two table names returns the name of tables that could define a many-to-many relationship between those two tables, based on having foreign keys to both of the provided tables.*

:param table: Table name :param other\_table: Other table name

### Database.add\_foreign\_keys

```python
def add_foreign_keys(
    foreign_keys:Iterable[Tuple[str, str, str, str]]
):
```

*See :ref:`python_api_add_foreign_keys`.*

:param foreign\_keys: A list of  `(table, column, other_table, other_column)` tuples

### Database.index\_foreign\_keys

```python
def index_foreign_keys():
```

*Create indexes for every foreign key column on every table in the database.*

### Database.vacuum

```python
def vacuum():
```

*Run a SQLite `VACUUM` against the database.*

### Database.analyze

```python
def analyze(
    name=None
):
```

*Run `ANALYZE` against the entire database or a named table or index.*

:param name: Run `ANALYZE` against this specific named table or index

### Database.iterdump

```python
def iterdump()->Generator[str, NoneType, NoneType]:
```

*A sequence of strings representing a SQL dump of the database*

### Database.init\_spatialite

```python
def init_spatialite(
    path:Optional[str]=None
)->bool:
```

*The `init_spatialite` method will load and initialize the SpatiaLite extension. The `path` argument should be an absolute path to the compiled extension, which can be found using `[`find\_spatialite`](/api/utils.html#find_spatialite)`.*

Returns `True` if SpatiaLite was successfully initialized.

.. code-block:: python

```
from fastlite.db import Database
from fastlite.utils import find_spatialite

db = Database("mydb.db")
db.init_spatialite(find_spatialite())
```

If you've installed SpatiaLite somewhere unexpected (for testing an alternate version, for example) you can pass in an absolute path:

.. code-block:: python

```
from fastlite.db import Database
from fastlite.utils import find_spatialite

db = Database("mydb.db")
db.init_spatialite("./local/mod_spatialite.dylib")
```

:param path: Path to SpatiaLite module on disk

## Queryable

```python
def Queryable(
    db, name
):
```

### Queryable.exists

```python
def exists()->bool:
```

*Does this table or view exist yet?*

### Queryable.count\_where

```python
def count_where(
    where:Optional[str]=None, where_args:Union[Iterable, dict, NoneType]=None
)->int:
```

*Executes `SELECT count(*) FROM table WHERE ...` and returns a count.*

:param where: SQL where fragment to use, for example `id > ?` :param where\_args: Parameters to use with that fragment - an iterable for `id > ?` parameters, or a dictionary for `id > :id`

### Queryable.execute\_count

```python
def execute_count():
```

### Queryable.count

```python
def count()->int:
```

*A count of the rows in this table or view.*

### Queryable.rows

```python
def rows()->Generator[dict, NoneType, NoneType]:
```

*Iterate over every dictionaries for each row in this table or view.*

### Queryable.rows\_where

```python
def rows_where(
    where:Optional[str]=None, where_args:Union[Iterable, dict, NoneType]=None, order_by:Optional[str]=None,
    select:str='*', limit:Optional[int]=None, offset:Optional[int]=None
)->Generator[dict, NoneType, NoneType]:
```

*Iterate over every row in this table or view that matches the specified where clause.*

Returns each row as a dictionary. See :ref:`python_api_rows` for more details.

:param where: SQL where fragment to use, for example `id > ?` :param where\_args: Parameters to use with that fragment - an iterable for `id > ?` parameters, or a dictionary for `id > :id` :param order\_by: Column or fragment of SQL to order by :param select: Comma-separated list of columns to select - defaults to `*` :param limit: Integer number of rows to limit to :param offset: Integer for SQL offset

### Queryable.pks\_and\_rows\_where

```python
def pks_and_rows_where(
    where:Optional[str]=None, where_args:Union[Iterable, dict, NoneType]=None, order_by:Optional[str]=None,
    limit:Optional[int]=None, offset:Optional[int]=None, select:str='*'
)->Generator[Tuple[Any, Dict], NoneType, NoneType]:
```

*Like `.rows_where()` but returns `(pk, row)` pairs - `pk` can be a single value or tuple.*

:param where: SQL where fragment to use, for example `id > ?` :param where\_args: Parameters to use with that fragment - an iterable for `id > ?` parameters, or a dictionary for `id > :id` :param order\_by: Column or fragment of SQL to order by :param select: Comma-separated list of columns to select - defaults to `*` :param limit: Integer number of rows to limit to :param offset: Integer for SQL offset

### Queryable.columns

```python
def columns()->List[ForwardRef('Column')]:
```

*List of :ref:`Columns <reference_db_other_column>` representing the columns in this table or view.*

### Queryable.columns\_dict

```python
def columns_dict()->Dict[str, Any]:
```

*`{column_name: python-type}` dictionary representing columns in this table or view.*

### Queryable.schema

```python
def schema()->str:
```

*SQL schema for this table or view.*

## Table

```python
def Table(
    db:sqlite_minutils.db.Database, name:str, pk:Optional[Any]=None,
    foreign_keys:Union[Iterable[Union[str, sqlite_minutils.db.ForeignKey, Tuple[str, str], Tuple[str, str, str], Tuple[str, str, str, str]]], List[Union[str, sqlite_minutils.db.ForeignKey, Tuple[str, str], Tuple[str, str, str], Tuple[str, str, str, str]]], NoneType]=None,
    column_order:Optional[List[str]]=None, not_null:Optional[Iterable[str]]=None,
    defaults:Optional[Dict[str, Any]]=None, batch_size:int=100, hash_id:Optional[str]=None,
    hash_id_columns:Optional[Iterable[str]]=None, alter:bool=False, ignore:bool=False, replace:bool=False,
    extracts:Union[Dict[str, str], List[str], NoneType]=None, conversions:Optional[dict]=None,
    columns:Optional[Dict[str, Any]]=None, strict:bool=False
):
```

*A Table class instance represents a sqlite3 table that may or may not exist in the database. The Table class instance may or may not represent some of the rows of the database table. After some mutations (INSERT/UPDATE/UPSERT) the changed records the Table class instance can be iterated over, returning during each iteration providing a `dict` representation of the current record.*

Tables should usually be initialized using the `db.table(table_name)` or `db[table_name]` methods.

The following optional parameters can be passed to `db.table(table_name, ...)`:

:param db: Provided by `db.table(table_name)` :param name: Provided by `db.table(table_name)` :param pk: Name of the primary key column, or tuple of columns :param foreign\_keys: List of foreign key definitions :param column\_order: List of column names in the order they should be in the table :param not\_null: List of columns that cannot be null :param defaults: Dictionary of column names and default values :param batch\_size: Integer number of rows to insert at a time :param hash\_id: If True, use a hash of the row values as the primary key :param hash\_id\_columns: List of columns to use for the hash\_id :param alter: If True, automatically alter the table if it doesn't match the schema :param ignore: If True, ignore rows that already exist when inserting :param replace: If True, replace rows that already exist when inserting :param extracts: Dictionary or list of column names to extract into a separate table on inserts :param conversions: Dictionary of column names and conversion functions :param columns: Dictionary of column names to column types :param strict: If True, apply STRICT mode to table

### Table.count

```python
def count()->int:
```

*Count of the rows in this table - optionally from the table count cache, if configured.*

### Table.exists

```python
def exists()->bool:
```

*Does this table or view exist yet?*

### Table.pks

```python
def pks()->List[str]:
```

*Primary key columns for this table.*

### Table.use\_rowid

```python
def use_rowid()->bool:
```

*Does this table use `rowid` for its primary key (no other primary keys are specified)?*

### Table.get

```python
def get(
    pk_values:Union[list, tuple, str, int]
)->dict:
```

*Return row (as dictionary) for the specified primary key.*

Raises `fastlite.db.NotFoundError` if a matching row cannot be found.

:param pk\_values: A single value, or a tuple of values for tables that have a compound primary key

### Table.foreign\_keys

```python
def foreign_keys()->List[ForwardRef('ForeignKey')]:
```

*List of foreign keys defined on this table.*

### Table.virtual\_table\_using

```python
def virtual_table_using()->Optional[str]:
```

*Type of virtual table, or `None` if this is not a virtual table.*

### Table.indexes

```python
def indexes()->List[sqlite_minutils.db.Index]:
```

*List of indexes defined on this table.*

### Table.xindexes

```python
def xindexes()->List[sqlite_minutils.db.XIndex]:
```

*List of indexes defined on this table using the more detailed `XIndex` format.*

### Table.triggers

```python
def triggers()->List[sqlite_minutils.db.Trigger]:
```

*List of triggers defined on this table.*

### Table.triggers\_dict

```python
def triggers_dict()->Dict[str, str]:
```

*`{trigger_name: sql}` dictionary of triggers defined on this table.*

### Table.default\_values

```python
def default_values()->Dict[str, Any]:
```

*`{column_name: default_value}` dictionary of default values for columns in this table.*

### Table.strict

```python
def strict()->bool:
```

*Is this a STRICT table?*

### Table.create

```python
def create(
    columns:Dict[str, Any], pk:Optional[Any]=None,
    foreign_keys:Union[Iterable[Union[str, sqlite_minutils.db.ForeignKey, Tuple[str, str], Tuple[str, str, str], Tuple[str, str, str, str]]], List[Union[str, sqlite_minutils.db.ForeignKey, Tuple[str, str], Tuple[str, str, str], Tuple[str, str, str, str]]], NoneType]=None,
    column_order:Optional[List[str]]=None, not_null:Optional[Iterable[str]]=None,
    defaults:Optional[Dict[str, Any]]=None, hash_id:Optional[str]=None, hash_id_columns:Optional[Iterable[str]]=None,
    extracts:Union[Dict[str, str], List[str], NoneType]=None, if_not_exists:bool=False, replace:bool=False,
    ignore:bool=False, transform:bool=False, strict:bool=False
)->Table:
```

*Create a table with the specified columns.*

See :ref:`python_api_explicit_create` for full details.

:param columns: Dictionary mapping column names to their types, for example `{"name": str, "age": int}` :param pk: String name of column to use as a primary key, or a tuple of strings for a compound primary key covering multiple columns :param foreign\_keys: List of foreign key definitions for this table :param column\_order: List specifying which columns should come first :param not\_null: List of columns that should be created as `NOT NULL` :param defaults: Dictionary specifying default values for columns :param hash\_id: Name of column to be used as a primary key containing a hash of the other columns :param hash\_id\_columns: List of columns to be used when calculating the hash ID for a row :param extracts: List or dictionary of columns to be extracted during inserts, see :ref:`python_api_extracts` :param if\_not\_exists: Use `CREATE TABLE IF NOT EXISTS` :param replace: Drop and replace table if it already exists :param ignore: Silently do nothing if table already exists :param transform: If table already exists transform it to fit the specified schema :param strict: Apply STRICT mode to table

### Table.duplicate

```python
def duplicate(
    new_name:str
)->Table:
```

*Create a duplicate of this table, copying across the schema and all row data.*

:param new\_name: Name of the new table

### Table.transform

```python
def transform(
    *, types:Optional[dict]=None, rename:Optional[dict]=None, drop:Optional[Iterable]=None,
    pk:Optional[Any]=<sqlite_minutils.db.Default object at 0x77e647427a10>, not_null:Optional[Iterable[str]]=None,
    defaults:Optional[Dict[str, Any]]=None, drop_foreign_keys:Optional[Iterable[str]]=None,
    add_foreign_keys:Union[Iterable[Union[str, sqlite_minutils.db.ForeignKey, Tuple[str, str], Tuple[str, str, str], Tuple[str, str, str, str]]], List[Union[str, sqlite_minutils.db.ForeignKey, Tuple[str, str], Tuple[str, str, str], Tuple[str, str, str, str]]], NoneType]=None,
    foreign_keys:Union[Iterable[Union[str, sqlite_minutils.db.ForeignKey, Tuple[str, str], Tuple[str, str, str], Tuple[str, str, str, str]]], List[Union[str, sqlite_minutils.db.ForeignKey, Tuple[str, str], Tuple[str, str, str], Tuple[str, str, str, str]]], NoneType]=None,
    column_order:Optional[List[str]]=None, keep_table:Optional[str]=None
)->Table:
```

*Apply an advanced alter table, including operations that are not supported by `ALTER TABLE` in SQLite itself.*

See :ref:`python_api_transform` for full details.

:param types: Columns that should have their type changed, for example `{"weight": float}` :param rename: Columns to rename, for example `{"headline": "title"}` :param drop: Columns to drop :param pk: New primary key for the table :param not\_null: Columns to set as `NOT NULL` :param defaults: Default values for columns :param drop\_foreign\_keys: Names of columns that should have their foreign key constraints removed :param add\_foreign\_keys: List of foreign keys to add to the table :param foreign\_keys: List of foreign keys to set for the table, replacing any existing foreign keys :param column\_order: List of strings specifying a full or partial column order to use when creating the table :param keep\_table: If specified, the existing table will be renamed to this and will not be dropped

### Table.transform\_sql

```python
def transform_sql(
    *, types:Optional[dict]=None, rename:Optional[dict]=None, drop:Optional[Iterable]=None,
    pk:Optional[Any]=<sqlite_minutils.db.Default object at 0x77e647427a10>, not_null:Optional[Iterable[str]]=None,
    defaults:Optional[Dict[str, Any]]=None, drop_foreign_keys:Optional[Iterable]=None,
    add_foreign_keys:Union[Iterable[Union[str, sqlite_minutils.db.ForeignKey, Tuple[str, str], Tuple[str, str, str], Tuple[str, str, str, str]]], List[Union[str, sqlite_minutils.db.ForeignKey, Tuple[str, str], Tuple[str, str, str], Tuple[str, str, str, str]]], NoneType]=None,
    foreign_keys:Union[Iterable[Union[str, sqlite_minutils.db.ForeignKey, Tuple[str, str], Tuple[str, str, str], Tuple[str, str, str, str]]], List[Union[str, sqlite_minutils.db.ForeignKey, Tuple[str, str], Tuple[str, str, str], Tuple[str, str, str, str]]], NoneType]=None,
    column_order:Optional[List[str]]=None, tmp_suffix:Optional[str]=None, keep_table:Optional[str]=None
)->List[str]:
```

*Return a list of SQL statements that should be executed in order to apply this transformation.*

:param types: Columns that should have their type changed, for example `{"weight": float}` :param rename: Columns to rename, for example `{"headline": "title"}` :param drop: Columns to drop :param pk: New primary key for the table :param not\_null: Columns to set as `NOT NULL` :param defaults: Default values for columns :param drop\_foreign\_keys: Names of columns that should have their foreign key constraints removed :param add\_foreign\_keys: List of foreign keys to add to the table :param foreign\_keys: List of foreign keys to set for the table, replacing any existing foreign keys :param column\_order: List of strings specifying a full or partial column order to use when creating the table :param tmp\_suffix: Suffix to use for the temporary table name :param keep\_table: If specified, the existing table will be renamed to this and will not be dropped

### Table.extract

```python
def extract(
    columns:Union[str, Iterable[str]], table:Optional[str]=None, fk_column:Optional[str]=None,
    rename:Optional[Dict[str, str]]=None
)->Table:
```

*Extract specified columns into a separate table.*

See :ref:`python_api_extract` for details.

:param columns: Single column or list of columns that should be extracted :param table: Name of table in which the new records should be created :param fk\_column: Name of the foreign key column to populate in the original table :param rename: Dictionary of columns that should be renamed when populating the new table

### Table.create\_index

```python
def create_index(
    columns:Iterable[Union[str, sqlite_minutils.db.DescIndex]], index_name:Optional[str]=None, unique:bool=False,
    if_not_exists:bool=False, find_unique_name:bool=False, analyze:bool=False
):
```

*Create an index on this table.*

:param columns: A single columns or list of columns to index. These can be strings or, to create an index using the column in descending order, `db.DescIndex(column_name)` objects. :param index\_name: The name to use for the new index. Defaults to the column names joined on `_`. :param unique: Should the index be marked as unique, forcing unique values? :param if\_not\_exists: Only create the index if one with that name does not already exist. :param find\_unique\_name: If `index_name` is not provided and the automatically derived name already exists, keep incrementing a suffix number to find an available name. :param analyze: Run `ANALYZE` against this index after creating it.

See :ref:`python_api_create_index`.

### Table.drop\_column

```python
def drop_column(
    col_name:str
):
```

*Drop a column from this table.*

:param col\_name: Name of the new column

### Table.add\_column

```python
def add_column(
    col_name:str, col_type:Optional[Any]=None, fk:Optional[str]=None, fk_col:Optional[str]=None,
    not_null_default:Optional[Any]=None
):
```

*Add a column to this table. See :ref:`python_api_add_column`.*

:param col\_name: Name of the new column :param col\_type: Column type - a Python type such as `str` or a SQLite type string such as `"BLOB"` :param fk: Name of a table that this column should be a foreign key reference to :param fk\_col: Column in the foreign key table that this should reference :param not\_null\_default: Set this column to `not null` and give it this default value

### Table.drop

```python
def drop(
    ignore:bool=False
):
```

*Drop this table.*

:param ignore: Set to `True` to ignore the error if the table does not exist

### Table.guess\_foreign\_table

```python
def guess_foreign_table(
    column:str
)->str:
```

*For a given column, suggest another table that might be referenced by this column should it be used as a foreign key.*

For example, a column called `tag_id` or `tag` or `tags` might suggest a `tag` table, if one exists.

If no candidates can be found, raises a `NoObviousTable` exception.

:param column: Name of column

### Table.guess\_foreign\_column

```python
def guess_foreign_column(
    other_table:str
):
```

### Table.add\_foreign\_key

```python
def add_foreign_key(
    column:str, other_table:Optional[str]=None, other_column:Optional[str]=None, ignore:bool=False
):
```

*Alter the schema to mark the specified column as a foreign key to another table.*

:param column: The column to mark as a foreign key. :param other\_table: The table it refers to - if omitted, will be guessed based on the column name. :param other\_column: The column on the other table it - if omitted, will be guessed. :param ignore: Set this to `True` to ignore an existing foreign key - otherwise a `AlterError` will be raised.

### Table.enable\_counts

```python
def enable_counts():
```

*Set up triggers to update a cache of the count of rows in this table.*

See :ref:`python_api_cached_table_counts` for details.

### Table.has\_counts\_triggers

```python
def has_counts_triggers()->bool:
```

*Does this table have triggers setup to update cached counts?*

### Table.enable\_fts

```python
def enable_fts(
    columns:Iterable[str], fts_version:str='FTS5', create_triggers:bool=False, tokenize:Optional[str]=None,
    replace:bool=False
):
```

*Enable SQLite full-text search against the specified columns.*

See :ref:`python_api_fts` for more details.

:param columns: List of column names to include in the search index. :param fts\_version: FTS version to use - defaults to `FTS5` but you may want `FTS4` for older SQLite versions. :param create\_triggers: Should triggers be created to keep the search index up-to-date? Defaults to `False`. :param tokenize: Custom SQLite tokenizer to use, for example `"porter"` to enable Porter stemming. :param replace: Should any existing FTS index for this table be replaced by the new one?

### Table.populate\_fts

```python
def populate_fts(
    columns:Iterable[str]
)->Table:
```

*Update the associated SQLite full-text search index with the latest data from the table for the specified columns.*

:param columns: Columns to populate the data for

### Table.disable\_fts

```python
def disable_fts()->Table:
```

*Remove any full-text search index and related triggers configured for this table.*

### Table.rebuild\_fts

```python
def rebuild_fts():
```

*Run the `rebuild` operation against the associated full-text search index table.*

### Table.detect\_fts

```python
def detect_fts()->Optional[str]:
```

*Detect if table has a corresponding FTS virtual table and return it*

### Table.optimize

```python
def optimize()->Table:
```

*Run the `optimize` operation against the associated full-text search index table.*

### Table.search\_sql

```python
def search_sql(
    columns:Optional[Iterable[str]]=None, order_by:Optional[str]=None, limit:Optional[int]=None,
    offset:Optional[int]=None, where:Optional[str]=None, include_rank:bool=False
)->str:
```

*" Return SQL string that can be used to execute searches against this table.*

:param columns: Columns to search against :param order\_by: Column or SQL expression to sort by :param limit: SQL limit :param offset: SQL offset :param where: Extra SQL fragment for the WHERE clause :param include\_rank: Select the search rank column in the final query

### Table.search

```python
def search(
    q:str, order_by:Optional[str]=None, columns:Optional[Iterable[str]]=None, limit:Optional[int]=None,
    offset:Optional[int]=None, where:Optional[str]=None, where_args:Union[Iterable, dict, NoneType]=None,
    quote:bool=False
)->Generator[dict, NoneType, NoneType]:
```

*Execute a search against this table using SQLite full-text search, returning a sequence of dictionaries for each row.*

:param q: Terms to search for :param order\_by: Defaults to order by rank, or specify a column here. :param columns: List of columns to return, defaults to all columns. :param limit: Optional integer limit for returned rows. :param offset: Optional integer SQL offset. :param where: Extra SQL fragment for the WHERE clause :param where\_args: Arguments to use for :param placeholders in the extra WHERE clause :param quote: Apply quoting to disable any special characters in the search query

See :ref:`python_api_fts_search`.

### Table.value\_or\_default

```python
def value_or_default(
    key, value
):
```

### Table.delete

```python
def delete(
    pk_values:Union[list, tuple, str, int, float]
)->Table:
```

*Delete row matching the specified primary key.*

:param pk\_values: A single value, or a tuple of values for tables that have a compound primary key

### Table.delete\_where

```python
def delete_where(
    where:Optional[str]=None, where_args:Union[Iterable, dict, NoneType]=None, analyze:bool=False
)->Table:
```

*Delete rows matching the specified where clause, or delete all rows in the table.*

See :ref:`python_api_delete_where`.

:param where: SQL where fragment to use, for example `id > ?` :param where\_args: Parameters to use with that fragment - an iterable for `id > ?` parameters, or a dictionary for `id > :id` :param analyze: Set to `True` to run `ANALYZE` after the rows have been deleted.

### Table.update

```python
def update(
    pk_values:Union[list, tuple, str, int, float], updates:Optional[dict]=None, alter:bool=False,
    conversions:Optional[dict]=None
)->Table:
```

*Execute a SQL `UPDATE` against the specified row.*

See :ref:`python_api_update`.

:param pk\_values: The primary key of an individual record - can be a tuple if the table has a compound primary key. :param updates: A dictionary mapping columns to their updated values. :param alter: Set to `True` to add any missing columns. :param conversions: Optional dictionary of SQL functions to apply during the update, for example `{"mycolumn": "upper(?)"}`.

### Table.build\_insert\_queries\_and\_params

```python
def build_insert_queries_and_params(
    extracts, chunk, all_columns, hash_id, hash_id_columns, upsert, pk, not_null, conversions, num_records_processed,
    replace, ignore
):
```

### Table.insert\_chunk

```python
def insert_chunk(
    alter, extracts, chunk, all_columns, hash_id, hash_id_columns, upsert, pk, not_null, conversions,
    num_records_processed, replace, ignore
)->List[Dict]:
```

### Table.insert

```python
def insert(
    record:Dict[str, Any], pk:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    foreign_keys:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    column_order:Union[List[str], sqlite_minutils.db.Default, NoneType]=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    not_null:Union[Iterable[str], sqlite_minutils.db.Default, NoneType]=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    defaults:Union[Dict[str, Any], sqlite_minutils.db.Default, NoneType]=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    hash_id:Union[str, sqlite_minutils.db.Default, NoneType]=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    hash_id_columns:Union[Iterable[str], sqlite_minutils.db.Default, NoneType]=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    alter:Union[bool, sqlite_minutils.db.Default, NoneType]=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    ignore:Union[bool, sqlite_minutils.db.Default, NoneType]=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    replace:Union[bool, sqlite_minutils.db.Default, NoneType]=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    extracts:Union[Dict[str, str], List[str], sqlite_minutils.db.Default, NoneType]=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    conversions:Union[Dict[str, str], sqlite_minutils.db.Default, NoneType]=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    columns:Union[Dict[str, Any], sqlite_minutils.db.Default, NoneType]=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    strict:Union[bool, sqlite_minutils.db.Default, NoneType]=<sqlite_minutils.db.Default object at 0x77e647427a10>
)->Table:
```

*Insert a single record into the table. The table will be created with a schema that matches the inserted record if it does not already exist, see :ref:`python_api_creating_tables`.*

- `record` - required: a dictionary representing the record to be inserted.

The other parameters are optional, and mostly influence how the new table will be created if that table does not exist yet.

Each of them defaults to `DEFAULT`, which indicates that the default setting for the current `[`Table`](/api/db.html#table)` object (specified in the table constructor) should be used.

:param record: Dictionary record to be inserted :param pk: If creating the table, which column should be the primary key. :param foreign\_keys: See :ref:`python_api_foreign_keys`. :param column\_order: List of strings specifying a full or partial column order to use when creating the table. :param not\_null: Set of strings specifying columns that should be `NOT NULL`. :param defaults: Dictionary specifying default values for specific columns. :param hash\_id: Name of a column to create and use as a primary key, where the value of thet primary key will be derived as a SHA1 hash of the other column values in the record. `hash_id="id"` is a common column name used for this. :param alter: Boolean, should any missing columns be added automatically? :param ignore: Boolean, if a record already exists with this primary key, ignore this insert. :param replace: Boolean, if a record already exists with this primary key, replace it with this new record. :param extracts: A list of columns to extract to other tables, or a dictionary that maps `{column_name: other_table_name}`. See :ref:`python_api_extracts`. :param conversions: Dictionary specifying SQL conversion functions to be applied to the data while it is being inserted, for example `{"name": "upper(?)"}`. See :ref:`python_api_conversions`. :param columns: Dictionary over-riding the detected types used for the columns, for example `{"age": int, "weight": float}`. :param strict: Boolean, apply STRICT mode if creating the table.

### Table.insert\_all

```python
def insert_all(
    records, pk:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    foreign_keys:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    column_order:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    not_null:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    defaults:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    batch_size:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    hash_id:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    hash_id_columns:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    alter:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    ignore:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    replace:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>, truncate:bool=False,
    extracts:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    conversions:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    columns:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>, upsert:bool=False,
    analyze:bool=False, strict:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>
)->Table:
```

*Like `.insert()` but takes a list of records and ensures that the table that it creates (if table does not exist) has columns for ALL of that data.*

Use `analyze=True` to run `ANALYZE` after the insert has completed.

### Table.upsert

```python
def upsert(
    record, pk:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    foreign_keys:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    column_order:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    not_null:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    defaults:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    hash_id:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    hash_id_columns:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    alter:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    extracts:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    conversions:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    columns:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    strict:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>
)->Table:
```

*Like `.insert()` but performs an `UPSERT`, where records are inserted if they do not exist and updated if they DO exist, based on matching against their primary key.*

See :ref:`python_api_upsert`.

### Table.upsert\_all

```python
def upsert_all(
    records, pk:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    foreign_keys:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    column_order:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    not_null:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    defaults:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    batch_size:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    hash_id:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    hash_id_columns:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    alter:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    extracts:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    conversions:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    columns:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>, analyze:bool=False,
    strict:sqlite_minutils.db.Default=<sqlite_minutils.db.Default object at 0x77e647427a10>
)->Table:
```

*Like `.upsert()` but can be applied to a list of records.*

### Table.add\_missing\_columns

```python
def add_missing_columns(
    records:Iterable[Dict[str, Any]]
)->Table:
```

### Table.lookup

```python
def lookup(
    lookup_values:Dict[str, Any], extra_values:Optional[Dict[str, Any]]=None, pk:Optional[str]='id',
    foreign_keys:Union[Iterable[Union[str, sqlite_minutils.db.ForeignKey, Tuple[str, str], Tuple[str, str, str], Tuple[str, str, str, str]]], List[Union[str, sqlite_minutils.db.ForeignKey, Tuple[str, str], Tuple[str, str, str], Tuple[str, str, str, str]]], NoneType]=None,
    column_order:Optional[List[str]]=None, not_null:Optional[Iterable[str]]=None,
    defaults:Optional[Dict[str, Any]]=None, extracts:Union[Dict[str, str], List[str], NoneType]=None,
    conversions:Optional[Dict[str, str]]=None, columns:Optional[Dict[str, Any]]=None, strict:Optional[bool]=False
):
```

*Create or populate a lookup table with the specified values.*

`db["Species"].lookup({"name": "Palm"})` will create a table called `Species` (if one does not already exist) with two columns: `id` and `name`. It will set up a unique constraint on the `name` column to guarantee it will not contain duplicate rows.

It will then insert a new row with the `name` set to `Palm` and return the new integer primary key value.

An optional second argument can be provided with more `name: value` pairs to be included only if the record is being created for the first time. These will be ignored on subsequent lookup calls for records that already exist.

All other keyword arguments are passed through to `.insert()`.

See :ref:`python_api_lookup_tables` for more details.

:param lookup\_values: Dictionary specifying column names and values to use for the lookup :param extra\_values: Additional column values to be used only if creating a new record :param strict: Boolean, apply STRICT mode if creating the table.

### Table.m2m

```python
def m2m(
    other_table:Union[str, ForwardRef('Table')],
    record_or_iterable:Union[Iterable[Dict[str, Any]], Dict[str, Any], NoneType]=None,
    pk:Union[Any, sqlite_minutils.db.Default, NoneType]=<sqlite_minutils.db.Default object at 0x77e647427a10>,
    lookup:Optional[Dict[str, Any]]=None, m2m_table:Optional[str]=None, alter:bool=False
):
```

*After inserting a record in a table, create one or more records in some other table and then create many-to-many records linking the original record and the newly created records together.*

For example::

```
db["dogs"].insert({"id": 1, "name": "Cleo"}, pk="id").m2m(
    "humans", {"id": 1, "name": "Natalie"}, pk="id"
)
```

See :ref:`python_api_m2m` for details.

:param other\_table: The name of the table to insert the new records into. :param record\_or\_iterable: A single dictionary record to insert, or a list of records. :param pk: The primary key to use if creating `other_table`. :param lookup: Same dictionary as for `.lookup()`, to create a many-to-many lookup table. :param m2m\_table: The string name to use for the many-to-many table, defaults to creating this automatically based on the names of the two tables. :param alter: Set to `True` to add any missing columns on `other_table` if that table already exists.

### Table.analyze

```python
def analyze():
```

*Run ANALYZE against this table*

### Table.analyze\_column

```python
def analyze_column(
    column:str, common_limit:int=10, value_truncate=None, total_rows=None, most_common:bool=True,
    least_common:bool=True
)->ColumnDetails:
```

*Return statistics about the specified column.*

See :ref:`python_api_analyze_column`.

:param column: Column to analyze :param common\_limit: Show this many column values :param value\_truncate: Truncate display of common values to this many characters :param total\_rows: Optimization - pass the total number of rows in the table to save running a fresh `count(*)` query :param most\_common: If `True`, calculate the most common values :param least\_common: If `True`, calculate the least common values

### Table.add\_geometry\_column

```python
def add_geometry_column(
    column_name:str, geometry_type:str, srid:int=4326, coord_dimension:str='XY', not_null:bool=False
)->bool:
```

*In SpatiaLite, a geometry column can only be added to an existing table. To do so, use `table.add_geometry_column`, passing in a geometry type.*

By default, this will add a nullable column using `SRID 4326 <https://spatialreference.org/ref/epsg/wgs-84/>`\_\_. This can be customized using the `column_name`, `srid` and `not_null` arguments.

Returns `True` if the column was successfully added, `False` if not.

.. code-block:: python

```
from fastlite.db import Database
from fastlite.utils import find_spatialite

db = Database("mydb.db")
db.init_spatialite(find_spatialite())

# the table must exist before adding a geometry column
table = db["locations"].create({"name": str})
table.add_geometry_column("geometry", "POINT")
```

:param column\_name: Name of column to add :param geometry\_type: Type of geometry column, for example `"GEOMETRY"` or ` "POINT" or  `"POLYGON"`:param srid: Integer SRID, defaults to 4326 for WGS84 :param coord_dimension: Dimensions to use, defaults to`"XY"`- set to`"XYZ"`to work in three dimensions :param not_null: Should the column be`NOT NULL\`\`

### Table.create\_spatial\_index

```python
def create_spatial_index(
    column_name
)->bool:
```

*A spatial index allows for significantly faster bounding box queries. To create one, use `create_spatial_index` with the name of an existing geometry column.*

Returns `True` if the index was successfully created, `False` if not. Calling this function if an index already exists is a no-op.

.. code-block:: python

```
# assuming SpatiaLite is loaded, create the table, add the column
table = db["locations"].create({"name": str})
table.add_geometry_column("geometry", "POINT")

# now we can index it
table.create_spatial_index("geometry")

# the spatial index is a virtual table, which we can inspect
print(db["idx_locations_geometry"].schema)
# outputs:
# CREATE VIRTUAL TABLE "idx_locations_geometry" USING rtree(pkid, xmin, xmax, ymin, ymax)
```

:param column\_name: Geometry column to create the spatial index against

## View

```python
def View(
    db, name
):
```

### View.exists

```python
def exists():
```

*Does this table or view exist yet?*

### View.drop

```python
def drop(
    ignore:bool=False
):
```

*Drop this view.*

:param ignore: Set to `True` to ignore the error if the view does not exist

### View.enable\_fts

```python
def enable_fts(
    *args, **kwargs
):
```

*`enable_fts()` is supported on tables but not on views.*
