SqlDaf overview¶
SqlDaf ¶
Bases: Daf
A Daf whose rows live in a SQLite table.
Use it for a table too large to hold in memory. The rows stay on disk in a SQLite database
file, and SQL does the work. When the rows you need are few, pull them into an ordinary Daf
with to_daf(), and work on them there.
A SqlDaf is a Daf, so isinstance(sdaf, Daf) is True. But it has only the methods
written for SQL. Every other Daf method raises NotImplementedError, which names it. So
nothing quietly loads a large table into memory. For anything not covered yet, sql()
runs a SQL statement of your own.
The database is the file named by the class setting SqlDaf.db_path. Set it once, for
example once for each job, and every SqlDaf opens that file. A db_path given to the
constructor overrides it for that table. With neither, the constructor raises ValueError.
The class setting engine is 'sqlite', the only engine so far.
It needs SQLite 3.48 or later. See the guide page on SqlDaf for how to get it.
Make a table with the constructor, as a Daf is made: give its name, its columns and its
rows. Open a table that is already in the file by its name alone. Its keyfield and dtypes
come back as they were, from the metadata that SqlDaf keeps in the table daf_tables of the
same file. A table made by other code has no such record, so give them to the constructor.
SqlDaf.from_csv() and SqlDaf.from_daf() load a file or a Daf into a new table.
A join, concat() and keys with a table in another database file bring it in themselves, as a
TEMP copy. SqlDaf.from_db() copies a table in as a permanent one.
A SqlDaf is a parent or a child.
- A parent holds its rows, in a table of its own: one made by the constructor, a loader or
copy(), or one already in the file. - A child is a selection. It holds references to rows of its parent, in order, as a
selection of a Daf holds the same row lists.
select_where(),select_by_dict(),select_where_sql()and indexing, as insdaf[2:5]orsdaf['b2'], each make one. A child of a child is a child of the same parent.is_childtells them apart, andparent_sdafis the parent of a child.
Making a child does not read its rows. Some methods run a query at once for their
arguments: select_krows() checks the keys, select_by_dict() with expectmax finds
its rows to count them, and groupby() finds the groups. The rows of a child are fixed the first time
it is read whole: by to_daf(), len(), bool(), to_dict(), to_list() or
to_value(). After that, it always means the same rows, as a selection of a Daf does.
select_record() and iloc() read one row and fix nothing, unless iloc() is given a
negative position, which needs len(). A change to the values in those
rows shows in it, since it refers to them. copy(inplace=True) gives it rows of its own.
A child made from a child not read yet carries that child's query inside its own. So a chain
of selections, each made from the last before any is read, nests one query per step. SQLite
stops at about 400 levels, 413 with SQLite 3.53, with OperationalError "Recursion limit". It
raises at once, and does not hang. A child that has been read starts a fresh query, so read
one, as with len(), every so often in a loop that selects from its own last result. A chain
of 2,000 selections, each read as it was made, ran in 1.7 s.
Every SqlDaf on one file shares one connection, which it holds in its attributes. So any two
of them can be joined, and a child of one can be used with another. They also share its
transactions: see transaction(). SqlDaf.close() closes the file, for every SqlDaf on it.
Otherwise it stays open until the program ends. Each statement is committed when it
finishes. So committed changes to permanent tables remain, whether the file is closed or the
program ends. delete() deletes a table from the file.
A table made by copy(), or by reading a join, is a TEMP table. It belongs to the
connection, and is removed when the connection closes. save() makes it a permanent table in the
file, under a name, to be opened again later.
Do not delete rows from a parent that has children. len() of a child counts its
references, so it would still count a deleted row, though to_daf() leaves it out. Worse,
SQLite gives the daf_rid of a deleted last row to the next row added. A child made before
the delete then shows that new row, which it never selected. Leave rows out with a selection
instead, as in a Daf.
A parent that has had rows deleted cannot be read by position. Positions in a parent are
looked up by daf_rid, and a delete leaves a gap there. So iloc(), iloc_exists() and
sdaf[n] or sdaf[n:m] on it raise ValueError. Read positions from copy(), which numbers
the rows again, or select the rows you want. A selection numbers its own rows, so positions
in it always work.
To read one row, use select_record() by key or iloc() by position. Each is one query,
returns a dict, and makes no selection.
The methods, by what they do:
- Size:
len(),bool(),num_rows(),num_cols(),shape()andcolumns(). - Looping, in batches:
for row in sdaf,iter_dict(),iter_klist()anditer_list(). - One row:
select_record()by key, andiloc()by position. - Columns:
col(),col_to_la(),icol(),icol_to_la()andcols_to_dol(). - Selecting:
select_where(),select_by_dict(),select_where_sql(),split_where(),select_cols()and indexing. - By key:
key in sdaf,keys(),select_records(),select_krows(),get_existing_keys()anddelete_records(). - The first match:
select_first_row_by_dict(). - Groups and counts:
groupby(),groupby_cols(),group_where(),groupsum_daf(),sum(),daf_valuecount(),value_counts_daf()and thevaluecounts_for_*methods. - Functions over rows:
apply()andreduce(). - Adding rows:
append(),record_append(),extend(),assign_record()andconcat(). - Changing values:
sdaf[key, col] = v,sdaf[key] = row,sdaf[:, col] = values,update_record_krow(),update_by_keylist(),assign_col(),apply_to_col()andapply_in_place(). - Columns and layout:
insert_col(),drop_cols(),rename_cols(),set_cols(),set_dtypes(),attach_schema()andclone_empty(). - Repeated keys:
remove_dups(). Sorting:sort_by_colname()andsort_by_colnames(). - Joining:
join(). Choosing columns:calc_cols(). - Into memory:
to_daf(),to_dict(),to_list(),to_value(),to_lod(),to_dod()andto_json(). - Display and files:
to_md(),to_md_cols(),to_csv_buff()andto_csv_file(). - Tables:
from_csv(),from_daf(),from_db(),copy(),save(),delete()andtable_exists(). - The database:
close(),transaction()andsql(), which runs any SQL statement. - Keys and types:
set_keyfield(),ensure_key_index()andapply_dtypes().
Work with large tables in whole statements. One query costs about 12 to 24 us, against under 1 us for a lookup in memory, because each one passes through sqlite3. Many rows in one statement are far cheaper per row.
There are two kinds of NULL. Python NULL is daffodil's missing value: the empty string '',
which daffodil names NULL, as in from daffodil.daf import NULL. SQL NULL is the database's.
A Python None written to a SqlDaf is stored as SQL NULL too, so it reads back as Python NULL. SqlDaf writes Python NULL as SQL NULL, and reads SQL NULL back as
Python NULL. A table written by other code may hold the text '' instead, which also reads as
Python NULL. So the methods that group, count or select by value treat SQL NULL and '' as the
same value, as a Daf does. In Python, test a value with val is NULL. This works because
CPython keeps one shared empty string, and it is faster than val == ''. In your own SQL,
test for both, as (col IS NULL OR col = '').
Avoid a Python NULL key, the empty string in the keyfield. If you allow one, the results of
SqlDaf are undefined. The key methods compare keys with = in SQL, and SQL NULL equals
nothing, so such a row is not found by key, select_records(), delete_records() or
join(). The unique index also lets several SQL NULL keys in. A Daf treats a Python NULL key
as a key like any other, so the two differ. Give every row a real key. Making the key index
raises ValueError on a Python NULL key, and so does concat() of one.
Until apply_dtypes() converts them, values loaded from a CSV file are text, in SQL too.
Text is never less than a number in SQLite, so WHERE n < 5 finds nothing on a text
column, and MAX() gives the last in text order.
The name is the name of the table in the database. A child gets a generated name, such as
daf_tmp_people_v3, which names its reference table once its rows are found.
Examples:
Create a small SqlDaf table of people. It is stored on disk, so its size is not limited by memory. One age is not known:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'name', 'age'], keyfield='id', lol=[
... ['p1', 'Ana Lopez', 34], ['p2', 'Ben Okafor', '']])
>>> people_sdaf
| id | name | age |
| -: | ---------: | --: |
| p1 | Ana Lopez | 34 |
| p2 | Ben Okafor | |
%% sdaf rows=2; cols=3; keyfield='id'; name='people'
Find the people whose age is not known, with SQL. A Python NULL is stored as SQL NULL:
>>> people_sdaf.sql('SELECT id FROM people WHERE age IS NULL').to_list()
['p2']
Open the table again by its name. Its keyfield was recorded when it was made:
>>> SqlDaf('people').keyfield
'id'
Constructor¶
__init__ ¶
__init__(
name,
cols=None,
lol=None,
keyfield="",
dtypes=None,
db_path="",
read_only=False,
)
Make a new table, or open one that is in the database file.
With cols, a new table is made in the file, with the rows of lol, read one at a
time, so an iterator of any length works. The table, its rows and its metadata are made
in one transaction: if any row fails, nothing is made. A Python NULL cell is stored
as SQL NULL. The table gets a hidden first column, daf_rid, an INTEGER PRIMARY KEY, which
numbers the rows in order. It is not one of the columns(). The columns are declared
with no SQL type, so an int stays an int, and text stays text. A cell that holds a dict
or a list is stored as its text, as Daf.to_csv_file() writes it, and is read back as
that text. to_daf().apply_dtypes() decodes it, with the column's dtype dict or list, as
for a table loaded from a CSV file.
Without cols, the table of that name is opened. Its keyfield and dtypes are those
recorded when it was made, unless they are given here. Nothing is read yet.
The keyfield is only recorded. Its unique index is made when a key is first used, as a Daf builds its key index.
With read_only=True, the table's data cannot be changed: writing a cell, adding or
removing rows or columns, renaming a column and dropping the table raise ReadOnlyTableError.
Selections, copies, sorts, joins, indexes and the keyfield still work, since they leave the
data as it is. To change it, copy() the table and change the copy. A Daf changes only
memory until it is written out. A SqlDaf writes to its file at once, and nothing in the
file shows it later. SQLite enforces it, so no method can slip past it, sql() included.
Read-only holds for this SqlDaf and its selections only. Another SqlDaf opened on the same
table without read_only can change it, and this one then reads the changed rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the table. |
required |
cols
|
T_ls | None
|
The column names of a new table, in order. None to open a table that is there. |
None
|
lol
|
Iterable[Iterable[Any]] | None
|
The rows of a new table, each the values in the order of |
None
|
keyfield
|
str
|
The column that holds the key of each row. For a table that is opened, the recorded one if empty. |
''
|
dtypes
|
T_dtype_dict | None
|
The types of the columns, kept for |
None
|
db_path
|
str
|
The database file. The class setting |
''
|
read_only
|
bool
|
If True, a change to the table's data raises ReadOnlyTableError. |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
There is no database path, a new table's name is taken, a column is named daf_rid, or |
KeyError
|
There is no table of that name to open, or the keyfield is not a column. |
FileNotFoundError
|
A table is to be opened, and the database file is not there. |
NotImplementedError
|
The class setting |
Examples:
Choose the database file for the tables made after this:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
Create a new table, with cols. The rows may come from any iterable, read one at a time:
>>> people_sdaf = SqlDaf('people', cols=['id', 'name', 'age'], lol=(['p1', 'Ana Lopez', 34], ['p2', 'Ben Okafor', 52]),
... keyfield='id', dtypes={'id': str, 'name': str, 'age': int})
>>> people_sdaf
| id | name | age |
| -: | ---------: | --: |
| p1 | Ana Lopez | 34 |
| p2 | Ben Okafor | 52 |
%% sdaf rows=2; cols=3; keyfield='id'; name='people'
Open the table again by its name, with no cols. Its keyfield and dtypes are those recorded:
>>> again_sdaf = SqlDaf('people')
>>> again_sdaf.keyfield, again_sdaf.dtypes
('id', {'id': <class 'str'>, 'name': <class 'str'>, 'age': <class 'int'>})
Put a table in another file, with db_path:
>>> other_path = tempfile.mkdtemp() + '/other.db'
>>> SqlDaf('notes', cols=['id', 'text'], lol=[['n1', 'Call back on Monday']], db_path=other_path)
| id | text |
| -: | ------------------: |
| n1 | Call back on Monday |
%% sdaf rows=1; cols=2; keyfield=''; name='notes'
Open a table read-only, with read_only=True. Its data cannot be changed, but it can be read and copied:
>>> ro_sdaf = SqlDaf('people', read_only=True)
>>> ro_sdaf['p1', 'age'] = 35
Traceback (most recent call last):
daffodil.sqldaf.ReadOnlyTableError: ...
>>> ro_sdaf.copy().update_record_krow('p1', {'age': 35})
| id | name | age |
| -: | ---------: | --: |
| p1 | Ana Lopez | 35 |
| p2 | Ben Okafor | 52 |
%% sdaf rows=2; cols=3; keyfield='id'; name='daf_tmp_people_v1'
>>> people_sdaf
| id | name | age |
| -: | ---------: | --: |
| p1 | Ana Lopez | 34 |
| p2 | Ben Okafor | 52 |
%% sdaf rows=2; cols=3; keyfield='id'; name='people'
Loading a table¶
from_csv
classmethod
¶
from_csv(
path,
name="",
keyfield="",
delimiter=",",
db_path="",
dtypes=None,
strict_header=True,
)
Load one or more CSV files into a new table, without building it in memory.
Give one file, a glob pattern such as chunks/votes_*.csv, or a list of files. The
files of a pattern are loaded in sorted order, and a list in its own order. All the
rows go into one table. This is the interface of read_csv() in dask.
Each file has the column names in its first line. SQLite puts the values of a row into the columns by position, so a file whose columns differ would load into the wrong columns. By default, every file must have the names of the first file, in the same order, or ValueError names both files. That also stops a file of another kind.
With strict_header=False, a value goes into the table by the name of its column, so files
whose columns differ in order or in set load safely. The table has the columns of the
first file, then each new name in the order it is first seen. A file that lacks a column
gives Python NULL in it. A misspelled name, or a file of another kind, becomes a new column
and is not flagged.
Then the first line of every file is read before any row. A file with the table's own columns is read as it is. Only a file whose columns differ has its values placed by name. On the 20 hunks of a BIF table, 344,347 rows, one hunk in another order, the load took 5.54 s, the same as without it. Placing every file by name would cost about 13% more.
An empty file has no names and no rows, so it is skipped. The rest is read one row at a time, so no file is ever all in memory.
Without dtypes, every value is stored as the text of the file. With dtypes, the
columns are converted as the rows are loaded, as apply_dtypes() would convert them.
That saves a second pass over the table. On 200,000 rows with five int columns, the load
took 1.0 s with dtypes, against 1.4 s for a text load and then apply_dtypes().
A dtype may name a column that is not there. The dtypes are kept for the table. A dict or
list dtype keeps the text, which a Daf decodes after to_daf().
An empty cell is stored as SQL NULL, and comes back as NULL. A row shorter than the header is padded with Python NULL, and a longer one raises ValueError. As with the constructor, if any row fails, no table is made.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path | List[str | Path]
|
The CSV file, a glob pattern, or a list of CSV files. |
required |
name
|
str
|
The name of the new table. The name of the first file without its extension if empty. |
''
|
keyfield
|
str
|
The column that holds the key of each row. |
''
|
delimiter
|
str
|
The field separator. |
','
|
db_path
|
str
|
The database file. The class setting |
''
|
dtypes
|
T_dtype_dict | None
|
The type of each column, converted as the rows are loaded. Text is kept if None. |
None
|
strict_header
|
bool
|
If True, every file must have the first file's names, in order. If False, place each file's values by column name. |
True
|
Returns:
| Type | Description |
|---|---|
SqlDaf
|
A SqlDaf for the new table. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
A file is missing, or a pattern matches no file. |
ValueError
|
A table of that name exists, a column is named daf_rid, a row is longer than its header,
or the column names of a file differ from those of the first file, unless |
KeyError
|
The keyfield is not one of the columns. |
NotImplementedError
|
A dtype is not int, float, bool, str, dict or list. |
Examples:
Write two CSV files of people to a folder. One age is not known:
>>> import os, tempfile
>>> csv_dir = tempfile.mkdtemp()
>>> SqlDaf.db_path = os.path.join(csv_dir, 'job.db')
>>> for part, text in (('a', 'id,age\np1,34\np2,\n'), ('b', 'id,age\np3,27\n')):
... with open(os.path.join(csv_dir, f'people_{part}.csv'), 'w') as csv_f:
... n = csv_f.write(text)
Load one file. The table is named for the file. Every value is text, and an empty cell is NULL:
>>> SqlDaf.from_csv(os.path.join(csv_dir, 'people_a.csv')).to_lod()
[{'id': 'p1', 'age': '34'}, {'id': 'p2', 'age': ''}]
Load every file of a glob pattern, in sorted order, into one table. dtypes converts as the rows load:
>>> people_sdaf = SqlDaf.from_csv(os.path.join(csv_dir, 'people_*.csv'), name='people', keyfield='id', dtypes={'age': int})
>>> people_sdaf
| id | age |
| -: | --: |
| p1 | 34 |
| p2 | |
| p3 | 27 |
%% sdaf rows=3; cols=2; keyfield='id'; name='people'
Load a list of files, in its own order, with another delimiter:
>>> with open(os.path.join(csv_dir, 'semi.csv'), 'w') as csv_f:
... n = csv_f.write('id;age\np4;41\n')
>>> SqlDaf.from_csv([os.path.join(csv_dir, 'semi.csv')], name='semi', delimiter=';').to_lod()
[{'id': 'p4', 'age': '41'}]
Files whose columns differ raise. With strict_header=False, each value goes in by its column name:
>>> with open(os.path.join(csv_dir, 'more.csv'), 'w') as csv_f:
... n = csv_f.write('age,id,city\n45,p5,Denver\n')
>>> mixed_paths = [os.path.join(csv_dir, 'people_b.csv'), os.path.join(csv_dir, 'more.csv')]
>>> SqlDaf.from_csv(mixed_paths, name='mixed')
Traceback (most recent call last):
ValueError: ...
>>> SqlDaf.from_csv(mixed_paths, name='mixed', strict_header=False).to_lod()
[{'id': 'p3', 'age': '27', 'city': ''}, {'id': 'p5', 'age': '45', 'city': 'Denver'}]
Put the table in another file, with db_path:
>>> SqlDaf.from_csv(os.path.join(csv_dir, 'people_b.csv'), name='b_only', db_path=os.path.join(csv_dir, 'b.db')).len()
1
from_daf
classmethod
¶
from_daf(data_daf, name, keyfield='', db_path='')
Write an in-memory Daf into a new table.
Each value is stored as it is, so an int stays an int. A NULL cell is stored as SQL NULL.
The new SqlDaf keeps the Daf's dtypes, for apply_dtypes(). The keyfield is the Daf's,
unless one is given. As with the constructor, if any row fails, no table is made.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_daf
|
Daf
|
The Daf to write. It is not changed. |
required |
name
|
str
|
The name of the new table. |
required |
keyfield
|
str
|
The column that holds the key of each row. The Daf's keyfield if empty. |
''
|
db_path
|
str
|
The database file. The class setting |
''
|
Returns:
| Type | Description |
|---|---|
SqlDaf
|
A SqlDaf for the new table. |
Raises:
| Type | Description |
|---|---|
ValueError
|
A table of that name exists, or a column is named daf_rid. |
KeyError
|
The keyfield is not one of the columns. |
Examples:
Create a Daf of people in memory. One age is not known:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_daf = Daf(cols=['id', 'name', 'age'], keyfield='id', lol=[['p1', 'Ana Lopez', 34], ['p2', 'Ben Okafor', '']])
Write it into a new SqlDaf table. The keyfield comes with it:
>>> people_sdaf = SqlDaf.from_daf(people_daf, name='people')
>>> people_sdaf
| id | name | age |
| -: | ---------: | --: |
| p1 | Ana Lopez | 34 |
| p2 | Ben Okafor | |
%% sdaf rows=2; cols=3; keyfield='id'; name='people'
Write it with another keyfield, into another file:
>>> by_name_sdaf = SqlDaf.from_daf(people_daf, name='by_name', keyfield='name', db_path=tempfile.mkdtemp() + '/by_name.db')
>>> by_name_sdaf.select_record('Ben Okafor')
{'id': 'p2', 'name': 'Ben Okafor', 'age': ''}
from_db
classmethod
¶
from_db(path, name, new_name='', db_path='')
Copy a table from another database file into the working file, and open the copy.
It makes a permanent table in the working file. Use it to build a file named for the table a
stage makes, with each input copied into it. A join, concat() or keys with a table in another
file need no copy made this way: they bring the other table in themselves, as a TEMP copy.
The source file is only read, once, and never changed. It is attached read-only, so SQLite
refuses any write to it. A change made to the copy stays in the working file. To keep a result in a file of its own, write it with save(db_path=).
The rows are copied in their order, with the values as stored. The keyfield and dtypes are those recorded for the table in the source file, if any. Only this table and its own record are copied. The other tables of the source file stay there.
The source file is attached only during the copy, which is one SQL statement, so no row passes through Python. On 1,000,000 rows of 5 columns the copy took 0.62 s. Through Python it took 2.54 s. Nothing stays attached, so any number of files can be copied in.
A source in the working file itself is copied within it, so new_name must differ.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
The database file that holds the table. It is only read. |
required |
name
|
str
|
The table in that file. |
required |
new_name
|
str
|
The name of the copy in the working file. |
''
|
db_path
|
str
|
The working file. The class setting |
''
|
Returns:
| Type | Description |
|---|---|
SqlDaf
|
A SqlDaf for the copy, a permanent table in the working file. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
The source file is not there. |
KeyError
|
The source file has no table of that name. |
ValueError
|
There is no working file, the working file has a table of the new name, or a transaction is open on the working file. |
Examples:
Create a table of people in a file of its own:
>>> import os, tempfile
>>> job_dir = tempfile.mkdtemp()
>>> people_sdaf = SqlDaf('people', cols=['id', 'name', 'age'], keyfield='id', db_path=job_dir + '/people.db',
... lol=[['p1', 'Ana Lopez', 34], ['p2', 'Ben Okafor', 52]])
Copy it into the working file. The source file is only read:
>>> SqlDaf.db_path = job_dir + '/work.db'
>>> work_sdaf = SqlDaf.from_db(job_dir + '/people.db', 'people')
>>> work_sdaf.db_path == SqlDaf.db_path, work_sdaf.keyfield, len(work_sdaf)
(True, 'id', 2)
Give the copy another name, with new_name:
>>> SqlDaf.from_db(job_dir + '/people.db', 'people', new_name='people_copy').name
'people_copy'
Copy it into another working file, with db_path:
>>> SqlDaf.from_db(job_dir + '/people.db', 'people', db_path=os.path.join(job_dir, 'other_work.db')).to_lod()
[{'id': 'p1', 'name': 'Ana Lopez', 'age': 34}, {'id': 'p2', 'name': 'Ben Okafor', 'age': 52}]
table_exists
classmethod
¶
table_exists(name, db_path='')
Say whether the database file has a table of this name.
Use it to decide whether to open a table or to build it, as from its CSV files. It returns False if the database file does not exist, and does not create the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the table. |
required |
db_path
|
str
|
The database file. The class setting |
''
|
Returns:
| Type | Description |
|---|---|
bool
|
True if the table is there. |
Raises:
| Type | Description |
|---|---|
ValueError
|
There is no database path. |
Examples:
Choose a new database file. It has no tables yet:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> SqlDaf.table_exists('people')
False
Make the table, and ask again, here and in another file:
>>> people_sdaf = SqlDaf('people', cols=['id', 'age'], lol=[['p1', 34]])
>>> SqlDaf.table_exists('people'), SqlDaf.table_exists('people', db_path=tempfile.mkdtemp() + '/other.db')
(True, False)
Tables¶
name
property
¶
name
The name of the table in the database. copy(name=) and save(name) give a new one.
Examples:
Create a small SqlDaf table of people:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'age'], keyfield='id', lol=[['p1', 34], ['p2', 52]])
Read the name of its table, and of a named copy:
>>> people_sdaf.name
'people'
>>> people_sdaf.copy(name='people_copy').name
'people_copy'
is_child
property
¶
is_child
True for a child, a selection that refers to rows of its parent. False for a parent, which holds its own rows.
Examples:
Create a small SqlDaf table of people:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'age'], keyfield='id', lol=[['p1', 34], ['p2', 52]])
The table holds its own rows. A selection of it is a child, which refers to them:
>>> people_sdaf.is_child, people_sdaf.select_krows(['p2']).is_child
(False, True)
copy ¶
copy(
level=None,
name="",
deep=False,
for_sorting=False,
inplace=False,
)
Copy the rows into a TEMP table of their own, as Daf.copy() copies a Daf.
The copy is a parent, with daf_rid, the rows in order, and this SqlDaf's keyfield and
dtypes. Nothing ties it to the rows it came from: a change to one does not show in the
other. A SQL cell holds a plain value, so every level gives what deep gives in a Daf.
The level is only checked, as Daf.copy() checks it.
With inplace=True, this SqlDaf becomes the copy, and is returned. Use it on a child, to
make it a table of its own, independent of its parent. As in a Daf, a level that would
not copy the rows, such as sortable, raises ValueError then.
The copy is a TEMP table, so it is removed when the connection closes. save() keeps it in the
file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
str | T_copybits | None
|
As in |
None
|
name
|
str
|
The name of the copy. Generated if empty, as in daf_tmp_people_v4. |
''
|
deep
|
bool
|
Deprecated, as in |
False
|
for_sorting
|
bool
|
Deprecated, as in |
False
|
inplace
|
bool
|
If True, this SqlDaf becomes the copy, and is returned. |
False
|
Returns:
| Type | Description |
|---|---|
SqlDaf
|
The copy, a new SqlDaf, or this one if |
Raises:
| Type | Description |
|---|---|
ValueError
|
A table of that name exists, |
Examples:
Create a small SqlDaf table of people, and a selection of those over 30:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'age'], keyfield='id', lol=[['p1', 34], ['p2', 52], ['p3', 27]])
>>> people_sdaf
| id | age |
| -: | --: |
| p1 | 34 |
| p2 | 52 |
| p3 | 27 |
%% sdaf rows=3; cols=2; keyfield='id'; name='people'
>>> over_30_sdaf = people_sdaf.select_where_sql('age > 30')
>>> over_30_sdaf
| id | age |
| -: | --: |
| p1 | 34 |
| p2 | 52 |
%% sdaf rows=2; cols=2; keyfield='id'; name='daf_tmp_people_v1'
Give the selection rows of its own, with inplace=True. It is then no longer a child:
>>> over_30_sdaf.copy(inplace=True)
| id | age |
| -: | --: |
| p1 | 34 |
| p2 | 52 |
%% sdaf rows=2; cols=2; keyfield='id'; name='daf_tmp_people_v2'
>>> over_30_sdaf.is_child
False
A later change to the table no longer shows in it:
>>> people_sdaf.update_record_krow('p1', {'age': 35})
| id | age |
| -: | --: |
| p1 | 35 |
| p2 | 52 |
| p3 | 27 |
%% sdaf rows=3; cols=2; keyfield='id'; name='people'
>>> over_30_sdaf
| id | age |
| -: | --: |
| p1 | 34 |
| p2 | 52 |
%% sdaf rows=2; cols=2; keyfield='id'; name='daf_tmp_people_v2'
Give a copy a name:
>>> people_sdaf.copy(name='people_copy')
| id | age |
| -: | --: |
| p1 | 35 |
| p2 | 52 |
| p3 | 27 |
%% sdaf rows=3; cols=2; keyfield='id'; name='people_copy'
A level that copies the rows gives a TEMP table of its own:
>>> people_sdaf.copy(level='editable')
| id | age |
| -: | --: |
| p1 | 35 |
| p2 | 52 |
| p3 | 27 |
%% sdaf rows=3; cols=2; keyfield='id'; name='daf_tmp_people_v3'
save ¶
save(name='', db_path='')
Keep this table in the database file, as a permanent table, to be opened again later.
The name is the one this SqlDaf has, unless one is given: the name given to the
constructor, or to copy(name=). A table with only a generated name, such as
daf_tmp_people_v4, needs one. The keyfield and dtypes are recorded with it, so
SqlDaf(name) opens it as it was.
- A TEMP table, made by
copy(), a sort or a join, is moved into the file. The TEMP table is removed. - A permanent table saved under its own name is left as it is, and its keyfield and dtypes are recorded again.
- A permanent table saved under a new name is copied to it, and this SqlDaf then refers to the copy. The first table stays.
A child has no rows of its own. Make it a table first, with copy(inplace=True).
With db_path, the table is written into that file instead, which is made if it is not
there. This keeps a result in a file of its own, as for a table copied in by from_db().
A TEMP table is moved there, and a permanent table is copied, as above. This SqlDaf then
refers to the table in that file. The file is attached only during the copy, which is one
SQL statement. On 1,000,000 rows of 8 columns it took 0.64 s.
A name already in use raises ValueError. To replace a table with a sorted or changed copy,
delete the old table first, as in SqlDaf('items').delete(), then save the copy under its name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name to keep it under. This SqlDaf's name if empty. |
''
|
db_path
|
str
|
The database file to keep it in. This SqlDaf's file if empty. |
''
|
Returns:
| Type | Description |
|---|---|
SqlDaf
|
This SqlDaf, as a permanent table. |
Raises:
| Type | Description |
|---|---|
ValueError
|
This is a child, the name is a generated one, or a table of that name exists.
With |
Examples:
Create a small SqlDaf table of people:
>>> import os, tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'age'], keyfield='id', lol=[['p1', 34], ['p2', 52], ['p3', 27]])
Keep a selection in the file, as a permanent table named by its copy:
>>> over_30_sdaf = people_sdaf.select_where_sql('age > 30').copy(name='over_30').save()
>>> SqlDaf('over_30').keyfield, len(SqlDaf('over_30'))
('id', 2)
Keep a copy under a name given to save():
>>> people_sdaf.copy().save('people_kept').name
'people_kept'
Keep a copy in another database file, with db_path:
>>> other_path = os.path.join(tempfile.mkdtemp(), 'other.db')
>>> people_sdaf.copy().save('people_elsewhere', db_path=other_path).name, os.path.exists(other_path)
('people_elsewhere', True)
delete ¶
delete()
Delete this table from the database file, with its metadata.
The table is dropped. Inside a transaction() block that then raises, the drop is
undone with the rest of the block. Otherwise it is final.
A child has no table of its own to delete. Delete its parent, or let the child go.
After this, the SqlDaf, and any child of it, can no longer be read.
Raises:
| Type | Description |
|---|---|
ValueError
|
This is a child. |
Examples:
Create a small SqlDaf table of people:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'age'], keyfield='id', lol=[['p1', 34], ['p2', 52]])
A selection has no table of its own to delete:
>>> people_sdaf.select_krows(['p1']).delete()
Traceback (most recent call last):
ValueError: SqlDaf.delete: '...' is a child, with no table of its own. Delete its parent instead.
Delete the table from the file:
>>> people_sdaf.delete()
>>> SqlDaf.table_exists('people')
False
The database¶
db_path
class-attribute
instance-attribute
¶
db_path = ''
The database file every SqlDaf opens, unless its constructor names another. Set it once, at the start.
engine
class-attribute
instance-attribute
¶
engine = 'sqlite'
The database engine. Only SQLite so far.
conn
property
writable
¶
conn
The connection to the database file, which every SqlDaf on the file shares.
Every statement a SqlDaf runs reads this first. So while a read-only SqlDaf is open on the file, it sets the authorizer for the SqlDaf that runs the statement. A read-only one gets one that refuses a change to its own table. Any other gets one that allows every statement.
The authorizer is set again only when that changes, as between a reader and a writer. Setting it makes SQLite prepare its statements again under it. That matters, because SQLite checks a statement only when it prepares it, and Python's sqlite3 reuses prepared statements. A switch costs about 5 to 15 us.
close
classmethod
¶
close(db_path='')
Close a database file: the connection that every SqlDaf on it shares.
It closes a file, not one table, so call it on the class, as SqlDaf.close(). Called on
an instance, it still closes the file of db_path, or of the class setting, not the
file that instance uses.
The permanent tables in the file stay, with every committed change.
SqlDaf(name) opens them again, on a new connection.
TEMP tables, such as those made by copy() or a sort, are removed.
Every SqlDaf that was on the file can no longer be used. sqlite3 raises ProgrammingError.
A file that is not open is left as it is.
Without close(), the file stays open until the program ends.
Each statement is committed when it finishes, or at the end of a transaction() block.
So a committed change is kept either way.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db_path
|
str
|
The database file. The class setting |
''
|
Raises:
| Type | Description |
|---|---|
ValueError
|
There is no database path. |
Examples:
Create a small SqlDaf table of people, and a TEMP copy of it:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'age'], keyfield='id', lol=[['p1', 34], ['p2', 52]])
>>> people_sdaf
| id | age |
| -: | --: |
| p1 | 34 |
| p2 | 52 |
%% sdaf rows=2; cols=2; keyfield='id'; name='people'
>>> copy_sdaf = people_sdaf.copy()
Close the file:
>>> SqlDaf.close()
The permanent table opens again. The TEMP copy went with the connection:
>>> SqlDaf('people')
| id | age |
| -: | --: |
| p1 | 34 |
| p2 | 52 |
%% sdaf rows=2; cols=2; keyfield='id'; name='people'
>>> copy_sdaf.col('age')
Traceback (most recent call last):
sqlite3.ProgrammingError: Cannot operate on a closed database.
Close another file, with db_path. A file that is not open is left as it is:
>>> other_path = tempfile.mkdtemp() + '/other.db'
>>> notes_sdaf = SqlDaf('notes', cols=['id'], lol=[['n1']], db_path=other_path)
>>> SqlDaf.close(db_path=other_path)
>>> SqlDaf.close(db_path=other_path)
>>> SqlDaf('notes', db_path=other_path)
| id |
| -: |
| n1 |
%% sdaf rows=1; cols=1; keyfield=''; name='notes'
transaction ¶
transaction()
Run the statements inside the with block as one transaction, on this database file.
A transaction belongs to the file, not to this table. Every SqlDaf on the file shares one
connection, so the work of any of them inside the block is committed or undone with the
rest. Wrap the writes of a stage that must succeed or fail together in one block.
Methods that change several things run their own transaction(). Inside a block, it
becomes part of the block. Do not run BEGIN, COMMIT or ROLLBACK through sql(): they
would end a block that another SqlDaf opened.
Everything in the block is committed together when it ends, or undone together if it raises. It also makes a run of small statements faster, because the file is locked once for the block instead of once per statement. On 1,000,000 rows, a lookup by key took 12.4 us inside a transaction, against 24.1 us outside.
While the block is open, no other connection can write to the database file. So keep it to the work that needs it.
A transaction() inside another one becomes a savepoint: if the inner block raises, only
its own work is undone.
Examples:
Create a small SqlDaf table of people:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'age'], keyfield='id', lol=[['p1', 34], ['p2', 52], ['p3', 27]])
>>> people_sdaf
| id | age |
| -: | --: |
| p1 | 34 |
| p2 | 52 |
| p3 | 27 |
%% sdaf rows=3; cols=2; keyfield='id'; name='people'
Add a year to the age of several people, in one transaction. The changes are committed together at the end of the block, which is much faster than a commit for each:
>>> def add_a_year(sdaf, keys):
... with sdaf.transaction():
... for key in keys:
... sdaf.sql(f'UPDATE {sdaf.name} SET age = age + 1 WHERE id = ?', [key])
>>> add_a_year(people_sdaf, ['p1', 'p2'])
>>> people_sdaf
| id | age |
| -: | --: |
| p1 | 35 |
| p2 | 53 |
| p3 | 27 |
%% sdaf rows=3; cols=2; keyfield='id'; name='people'
sql ¶
sql(stmt, params=())
Run a SQL statement of your own, and return its result as a Daf.
This is the way to do anything that SqlDaf has no method for. The statement runs on this
SqlDaf's connection, so it can use every table in the file, and the TEMP tables of the
connection. Refer to this table by sdaf.name.
Pass values as params, with ? in the statement, instead of putting them in the text.
A SELECT gives a Daf of its rows, with its column names. SQL NULL becomes Python NULL. A
statement that returns no rows, such as UPDATE or CREATE, gives an empty Daf. Outside
transaction(), it is committed when it finishes.
The whole result is pulled into memory, so select only what you need. Do not run BEGIN,
COMMIT or ROLLBACK here. Use transaction(), which every SqlDaf on the file shares.
A change to a table's columns made here, such as ALTER TABLE, is not seen by a SqlDaf
already open on that table. Open it again by name to see the new columns. Nor does it
update the keyfield and dtypes that SqlDaf records. For column changes, prefer
insert_col(), drop_cols() and rename_cols(), which keep both up to date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stmt
|
str
|
One SQL statement. |
required |
params
|
Iterable[Any]
|
Values for the |
()
|
Returns:
| Type | Description |
|---|---|
Daf
|
A Daf of the rows the statement returns. |
Raises:
| Type | Description |
|---|---|
ReadOnlyTableError
|
The statement changes the data of a table opened with |
Examples:
Create a small SqlDaf table of people:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'city', 'age'], keyfield='id', lol=[
... ['p1', 'Denver', 34], ['p2', 'Austin', 52], ['p3', 'Denver', 27]])
>>> people_sdaf
| id | city | age |
| -: | -----: | --: |
| p1 | Denver | 34 |
| p2 | Austin | 52 |
| p3 | Denver | 27 |
%% sdaf rows=3; cols=3; keyfield='id'; name='people'
Run a SELECT of your own, which gives a Daf. Pass values as params, with ? in the statement:
>>> people_sdaf.sql(f'SELECT city, AVG(age) AS mean_age FROM {people_sdaf.name} WHERE age > ? GROUP BY city', [20])
| city | mean_age |
| -----: | -------: |
| Austin | 52.0 |
| Denver | 30.5 |
%% daf rows=2; cols=2; keyfield=''; name=''
A statement that returns no rows gives an empty Daf, and is committed:
>>> len(people_sdaf.sql(f'UPDATE {people_sdaf.name} SET age = age + 1 WHERE city = ?', ['Austin']))
0
>>> people_sdaf
| id | city | age |
| -: | -----: | --: |
| p1 | Denver | 34 |
| p2 | Austin | 53 |
| p3 | Denver | 27 |
%% sdaf rows=3; cols=3; keyfield='id'; name='people'
Keys and types¶
set_keyfield ¶
set_keyfield(keyfield='')
Set the column that holds the key of each row.
As in a Daf, nothing is built yet. The unique index on the column is made when a key is
first used, by ensure_key_index(). An empty keyfield clears it. Avoid Python NULL in the
column: a Python NULL key gives undefined results, as SqlDaf explains.
On a permanent table with a record in the metadata, the record is changed too, so the
table opens with this keyfield next time. A table made by other code has no record until
save() makes one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keyfield
|
str
|
The column. '' for none. |
''
|
Returns:
| Type | Description |
|---|---|
SqlDaf
|
This SqlDaf. |
Raises:
| Type | Description |
|---|---|
KeyError
|
The keyfield is not a column. |
Examples:
Create a small SqlDaf table of people, with no keyfield:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'name', 'age'], lol=[['p1', 'Ana Lopez', 34], ['p2', 'Ben Okafor', 52]])
>>> people_sdaf
| id | name | age |
| -: | ---------: | --: |
| p1 | Ana Lopez | 34 |
| p2 | Ben Okafor | 52 |
%% sdaf rows=2; cols=3; keyfield=''; name='people'
Make the name the keyfield, and look a row up by it:
>>> people_sdaf.set_keyfield('name')
| id | name | age |
| -: | ---------: | --: |
| p1 | Ana Lopez | 34 |
| p2 | Ben Okafor | 52 |
%% sdaf rows=2; cols=3; keyfield='name'; name='people'
>>> people_sdaf.select_record('Ben Okafor')
{'id': 'p2', 'name': 'Ben Okafor', 'age': 52}
The keyfield is recorded, so the table opens with it next time:
>>> SqlDaf('people').keyfield
'name'
Clear the keyfield:
>>> people_sdaf.set_keyfield('')
| id | name | age |
| -: | ---------: | --: |
| p1 | Ana Lopez | 34 |
| p2 | Ben Okafor | 52 |
%% sdaf rows=2; cols=3; keyfield=''; name='people'
key_index_name ¶
key_index_name()
The name of the unique index on the keyfield, as in daf_ix_people_id.
Examples:
Create a small SqlDaf table of people, keyed by id:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'age'], keyfield='id', lol=[['p1', 34]])
Give the name of the unique index on its keyfield:
>>> people_sdaf.key_index_name()
'daf_ix_people_id'
ensure_key_index ¶
ensure_key_index()
Make the unique index on the keyfield of a parent, if it is not there yet.
A Daf builds its key index the first time a key is needed. A SqlDaf does the same: the methods that use keys call this first. On 1,000,000 rows it took 0.50 s, about what a Daf takes. After that, a lookup by key uses the index instead of reading every row.
The index is unique. A Daf keeps the last row of a repeated key without a word. A SqlDaf raises instead, so a duplicate is never missed. Once the index is there, adding a row with a key that is already present raises too.
A Python NULL key, SQL NULL or the text '', raises ValueError when the index is made. SqlDaf's results with one would be undefined, and the unique index does not stop several SQL NULL keys. The check uses the new index, so it costs about 0.3 ms. A Daf accepts a Python NULL key.
Returns:
| Type | Description |
|---|---|
SqlDaf
|
This SqlDaf. |
Raises:
| Type | Description |
|---|---|
ValueError
|
There is no keyfield, this is a selection, or a key is a Python NULL. Nothing is made. |
IntegrityError
|
A key is repeated. Nothing is made. |
Examples:
Create a small SqlDaf table of people, keyed by id:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'age'], keyfield='id', lol=[['p1', 34], ['p2', 52]])
Make the unique index on the keyfield, and find it in the file:
>>> people_sdaf.ensure_key_index().sql("SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = ?", ['people']).col('name')
['daf_ix_people_id']
A repeated key raises, and no index is made:
>>> signups_sdaf = SqlDaf('signups', cols=['email', 'name'], keyfield='email', lol=[
... ['ana@example.com', 'Ana Lopez'], ['ana@example.com', 'Ana L.']])
>>> signups_sdaf.ensure_key_index()
Traceback (most recent call last):
sqlite3.IntegrityError: UNIQUE constraint failed: signups.email
apply_dtypes ¶
apply_dtypes(
*,
dtypes=None,
cols=None,
from_str=True,
silent_error=False,
)
Convert the columns to their dtypes, in place, in the database.
New dtypes given here are kept in the metadata record of the table, if it has one.
A table loaded from a CSV file holds text. Call this to turn the columns you need into
numbers. Each value is converted by the same function Daf.apply_dtypes() uses, so the
results are the same as in memory.
- '12' becomes 12, and '2.5' with dtype int becomes 2.
- A value that does not convert, such as 'abc', stays as it is.
- Python NULL stays Python NULL, except in a bool column, where it becomes 0, as in a Daf.
- A str column is not touched, unless
from_stris False.
By default the cells are taken to be text already, as from a CSV file, so a str column is
skipped. Pass from_str=False when a str column may hold numbers, as from from_daf() of a
typed Daf. Then each number becomes its text, as Daf.apply_dtypes() gives, so 3 becomes '3'
and 1.5 becomes '1.5'. The table then holds what from_csv() of the same rows holds.
Conversion does not check that every value got the requested type. A converted column
can still hold some text. silent_error does not change that. It is about a column that
has no dtype, not about a value that does not convert.
All the columns are converted in one pass over the table, in one transaction. On 1,000,000 rows, two int columns took 1.8 s.
int, float and bool are converted. str, dict and list are recorded, and nothing is converted: the
stored text is the value. A dict or list cell is the text a Daf's to_csv_file() writes. On the
SqlDaf it stays text. reduce(by='sparse_row') reads it as it goes, and after to_daf() a Daf's
apply_dtypes() decodes it.
On a selection, the rows are first copied into a TEMP table of its own, as
copy(inplace=True) does, and the copy is converted. The parent is not changed. A Daf
selection shares its rows, so there the parent's rows are converted too. Converting is
costly, so convert a selection rather than a large parent that is not needed otherwise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dtypes
|
T_dtype_dict | None
|
The types to convert to, by column. It may name columns that are not there. This SqlDaf's dtypes if None. |
None
|
cols
|
str | T_ls | None
|
Convert only these columns, or this one column. Every column if None, and each needs a dtype. |
None
|
from_str
|
bool
|
If True, the cells are text, so str columns are not converted. |
True
|
silent_error
|
bool
|
If False, a column to convert that has no dtype raises ValueError. If True, it is left as it is. |
False
|
Returns:
| Type | Description |
|---|---|
SqlDaf
|
This SqlDaf, whose table has been changed. |
Raises:
| Type | Description |
|---|---|
KeyError
|
A name in |
ValueError
|
A column to convert has no dtype, and |
NotImplementedError
|
A dtype is not int, float, bool, str, dict or list. |
Examples:
Write a CSV file of people, and load it. Every cell is text. One age is not a number:
>>> import os, tempfile
>>> csv_dir = tempfile.mkdtemp()
>>> SqlDaf.db_path = os.path.join(csv_dir, 'job.db')
>>> with open(os.path.join(csv_dir, 'people.csv'), 'w') as csv_f:
... n = csv_f.write('id,age,height_m,member\np1,34,1.68,1\np2,unknown,,0\np3,27,1.75,\n')
>>> people_sdaf = SqlDaf.from_csv(os.path.join(csv_dir, 'people.csv'), keyfield='id')
>>> people_sdaf
| id | age | height_m | member |
| -: | ------: | -------: | -----: |
| p1 | 34 | 1.68 | 1 |
| p2 | unknown | | 0 |
| p3 | 27 | 1.75 | |
%% sdaf rows=3; cols=4; keyfield='id'; name='people'
Convert only the age. A value that does not convert, such as 'unknown', stays as it is. The tables quote the text, and show the dtypes in the header, so text can be told from a number:
>>> print(people_sdaf.apply_dtypes(dtypes={'age': int}, cols='age').to_md(show=['dtypes', 'quotes']))
| id | age: int (str) | height_m | member |
| ---: | -------------: | -------: | -----: |
| 'p1' | 34 | '1.68' | '1' |
| 'p2' | 'unknown' | '' | '0' |
| 'p3' | 27 | '1.75' | '' |
Convert several columns. Python NULL in a bool column becomes 0:
>>> print(people_sdaf.apply_dtypes(dtypes={'height_m': float, 'member': bool}, cols=['height_m', 'member']).to_md(show=['dtypes', 'quotes']))
| id | age: int (str) | height_m: float | member: bool |
| ---: | -------------: | --------------: | -----------: |
| 'p1' | 34 | 1.68 | 1 |
| 'p2' | 'unknown' | '' | 0 |
| 'p3' | 27 | 1.75 | 0 |
Without cols, every column is converted, so each needs a dtype. A column without one raises, unless
silent_error=True leaves it as it is:
>>> people_sdaf.apply_dtypes(dtypes={'age': int})
Traceback (most recent call last):
ValueError: SqlDaf.apply_dtypes: no dtype for the columns ['id', 'height_m', 'member']. ...
>>> print(people_sdaf.apply_dtypes(dtypes={'age': int}, silent_error=True).to_md(show=['dtypes', 'quotes']))
| id | age: int (str) | height_m: float | member: bool |
| ---: | -------------: | --------------: | -----------: |
| 'p1' | 34 | 1.68 | 1 |
| 'p2' | 'unknown' | '' | 0 |
| 'p3' | 27 | 1.75 | 0 |
With from_str=False, a str column that holds numbers becomes text:
>>> codes_sdaf = SqlDaf('codes', cols=['id', 'zip'], lol=[['p1', 80202], ['p2', 73301]])
>>> print(codes_sdaf.apply_dtypes(dtypes={'id': str, 'zip': str}, from_str=False).to_md(show=['dtypes', 'quotes']))
| id: str | zip: str |
| ------: | -------: |
| 'p1' | '80202' |
| 'p2' | '73301' |
Add-ons¶
See the Guide page Add-ons.
register_sqldaf_namespace ¶
register_sqldaf_namespace(name)
Add a class of methods to every SqlDaf, under one name, as register_daf_namespace() does for a Daf.
A SqlDaf holds its rows in SQLite, so an add-on written for a Daf, which reads rows in memory,
does not work on it. An add-on registers a SqlDaf version here, under the same name as its Daf
version or another. Then sdaf.<name> is an object of that class for that SqlDaf, a selection
included. Without one, sdaf.<name> of a Daf add-on raises NotImplementedError.
A name already in use raises ValueError: a method or attribute of SqlDaf, or another SqlDaf add-on. The name of a Daf add-on is free here, for its SqlDaf version.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The attribute name, such as |
required |
Returns:
| Type | Description |
|---|---|
Callable[[type], type]
|
A decorator that registers the class and returns it unchanged. |
Raises:
| Type | Description |
|---|---|
ValueError
|
The name is not a public identifier, or it is already in use on SqlDaf. |
Examples:
Add a namespace of your own methods to every SqlDaf, here totals, with a method that totals a column:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> @register_sqldaf_namespace('totals')
... class SqlTotals:
... def __init__(self, sdaf):
... self._sdaf = sdaf
... def of(self, col):
... return self._sdaf.sum([col])[col]
Create a small SqlDaf table of orders:
>>> orders_sdaf = SqlDaf('orders', cols=['id', 'qty'], keyfield='id', lol=[['o1', 12], ['o2', 30]],
... dtypes={'id': str, 'qty': int})
Call the method through the namespace, on the table and on a selection of it:
>>> orders_sdaf.totals.of('qty'), orders_sdaf[0:1].totals.of('qty')
(42, 12)
Remove the namespace again:
>>> del SqlDaf.totals