Reading¶
Size, looping, single rows and columns, and moving rows into memory.
Size¶
__len__ ¶
__len__()
Count the rows.
For a parent, this runs a COUNT. For a child, its rows are found first, and then its references are counted, which is one lookup. A row deleted from the parent is still counted, so do not delete rows from a parent that has children.
Returns:
| Type | Description |
|---|---|
int
|
The number of rows. |
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]])
Count the rows of the table, and of a selection:
>>> len(people_sdaf)
3
>>> len(people_sdaf.select_by_dict({'city': 'Denver'}))
2
len ¶
len()
Count the rows, as len(sdaf) does.
It is here so that code written for a Daf, which calls daf.len(), runs on a SqlDaf.
Returns:
| Type | Description |
|---|---|
int
|
The number of 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]])
Count the rows, as a method:
>>> people_sdaf.len()
2
__bool__ ¶
__bool__()
Say whether there is at least one row.
This stops at the first row, so it is fast on a large table. A child has its rows found
first, and then its references are checked, as len() counts them.
Returns:
| Type | Description |
|---|---|
bool
|
True if there is a row. |
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]])
Ask whether the table has a row, and whether a selection with no match does:
>>> bool(people_sdaf)
True
>>> bool(people_sdaf.select_where_sql('age > ?', [90]))
False
num_rows ¶
num_rows()
Count the rows, as len() does. It is here so that code written for a Daf runs on a SqlDaf.
Returns:
| Type | Description |
|---|---|
int
|
The number of 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]])
Count the rows:
>>> people_sdaf.num_rows()
2
num_cols ¶
num_cols()
Count the columns.
The hidden daf_rid column is not counted.
Returns:
| Type | Description |
|---|---|
int
|
The number of columns. |
Examples:
Create a small SqlDaf table of people:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'name', 'age'], keyfield='id', lol=[['p1', 'Ana Lopez', 34]])
Count the columns:
>>> people_sdaf.num_cols()
3
shape ¶
shape()
Give the number of rows and the number of columns, as Daf.shape() does.
A table with no rows gives (0, 0), as in a Daf. The rows are counted with len().
Returns:
| Type | Description |
|---|---|
Tuple[int, int]
|
A tuple of the number of rows and the number of columns. |
Examples:
Create a small SqlDaf table of people:
>>> 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', 52]])
Give the number of rows and of columns:
>>> people_sdaf.shape()
(2, 3)
A table with no rows gives (0, 0), whatever its columns:
>>> people_sdaf.select_where_sql('age > ?', [90]).shape()
(0, 0)
Looping¶
__iter__ ¶
__iter__()
Loop over the rows as dicts, as in for row in sdaf.
Rows are read in order, in batches, so a table of any size fits in memory. Each dict is a
copy: changing it does not change the table. A Daf can give KeyedList rows instead, by its
itermode. A SqlDaf always gives dicts. Use iter_klist() for KeyedList rows.
Do not change the table inside the loop. Whether the loop sees the change is not defined.
Returns:
| Type | Description |
|---|---|
Iterator[T_da]
|
The rows, as dicts. |
Examples:
Create a small SqlDaf table of people. One age is not known:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'age'], keyfield='id', lol=[['p1', 34], ['p2', ''], ['p3', 27]])
Loop over the rows, each a dict, to add up the known ages:
>>> def total_age(sdaf):
... total = 0
... for row in sdaf:
... total += row['age'] or 0
... return total
>>> total_age(people_sdaf)
61
iter_dict ¶
iter_dict()
Loop over the rows as dicts, as Daf.iter_dict() does.
Rows are read in order, in batches. SQL NULL comes back as Python NULL. Each dict is a copy, so changing it does not change the table.
Returns:
| Type | Description |
|---|---|
Iterator[T_da]
|
Each row as a dict of column name to value. |
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]])
>>> people_sdaf
| id | age |
| -: | --: |
| p1 | 34 |
| p2 | 52 |
%% sdaf rows=2; cols=2; keyfield='id'; name='people'
Read the rows as dicts:
>>> list(people_sdaf.iter_dict())
[{'id': 'p1', 'age': 34}, {'id': 'p2', 'age': 52}]
Each dict is a copy. Changing it leaves the table as it was:
>>> for row in people_sdaf.iter_dict():
... row['age'] = 0
>>> people_sdaf
| id | age |
| -: | --: |
| p1 | 34 |
| p2 | 52 |
%% sdaf rows=2; cols=2; keyfield='id'; name='people'
iter_klist ¶
iter_klist()
Loop over the rows as KeyedList objects.
A row reads by column name, as in a Daf. But each row is a copy. In a Daf, assigning to a KeyedList row changes the Daf. Here it changes only the copy.
Returns:
| Type | Description |
|---|---|
Iterator[KeyedList]
|
Each row as a KeyedList. |
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]])
>>> people_sdaf
| id | age |
| -: | --: |
| p1 | 34 |
| p2 | 52 |
%% sdaf rows=2; cols=2; keyfield='id'; name='people'
Read each row as a KeyedList, by column name:
>>> [row['age'] for row in people_sdaf.iter_klist()]
[34, 52]
Assigning to a row changes only the copy:
>>> for row in people_sdaf.iter_klist():
... row['age'] = 0
>>> people_sdaf
| id | age |
| -: | --: |
| p1 | 34 |
| p2 | 52 |
%% sdaf rows=2; cols=2; keyfield='id'; name='people'
To change values, use update_record_krow() or apply_in_place():
>>> people_sdaf.update_record_krow('p1', {'age': 35})
| id | age |
| -: | --: |
| p1 | 35 |
| p2 | 52 |
%% sdaf rows=2; cols=2; keyfield='id'; name='people'
iter_list ¶
iter_list()
Loop over the rows as lists, with the values in column order.
Each list is a copy. In a Daf, these are the Daf's own row lists, and assigning to one changes the Daf. Here it changes only the copy.
Returns:
| Type | Description |
|---|---|
Iterator[T_la]
|
Each row as a list. |
Examples:
Create a small SqlDaf table of people. One age is not known:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'age'], keyfield='id', lol=[['p1', 34], ['p2', '']])
Read the rows as lists, the values in column order:
>>> list(people_sdaf.iter_list())
[['p1', 34], ['p2', '']]
One row¶
select_record ¶
select_record(key, silent_error=True)
Read one row by its key, as a dict, as Daf.select_record() does, in one query.
The keyfield's unique index is made first if it is not there yet, so the lookup does not
read every row. It took about 18 us on 1,000,000 rows, or 9 us inside transaction().
On a selection, only the selection's rows are searched. A key that is in the parent but not in the selection is missing. The call makes no selection. On a selection whose rows are not yet found, it does not fix them: they are still found when it is first read.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Any
|
The key of the row. |
required |
silent_error
|
bool
|
If True, a missing key gives an empty dict. If False, it raises KeyError. |
True
|
Returns:
| Type | Description |
|---|---|
T_da
|
The row as a dict, or an empty dict. |
Raises:
| Type | Description |
|---|---|
KeyError
|
The key is missing, and |
ValueError
|
There is no keyfield. |
Examples:
Create a small SqlDaf table of people:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'name', 'city', 'age'], keyfield='id', lol=[
... ['p1', 'Ana Lopez', 'Denver', 34], ['p2', 'Ben Okafor', 'Austin', 52], ['p3', 'Chen Wu', 'Boston', 27]])
Read one row by its key, as a dict:
>>> people_sdaf.select_record('p3')
{'id': 'p3', 'name': 'Chen Wu', 'city': 'Boston', 'age': 27}
A key that is not there gives an empty dict, or raises with silent_error=False:
>>> people_sdaf.select_record('p9')
{}
>>> people_sdaf.select_record('p9', silent_error=False)
Traceback (most recent call last):
KeyError: 'p9'
iloc ¶
iloc(
irow: int = 0,
include_cols: T_ls | None = None,
rtype: Literal["dict"] = "dict",
) -> T_da
iloc(
irow: int = 0,
include_cols: T_ls | None = None,
*,
rtype: Literal["list"],
) -> T_la
iloc(
irow: int = 0,
include_cols: T_ls | None = None,
rtype: str = "dict",
) -> T_da | T_la
iloc(irow=0, include_cols=None, rtype='dict')
Read one row by position, as Daf.iloc() does, in one query.
On a selection, the position is within the selection's own rows, in its order.
The call makes no selection. On a selection whose rows are not yet found, it does not
fix them: they are still found when the selection is first read.
In a parent with daf_rid, or a child whose rows are found, the position is looked up directly. Otherwise SQLite
steps over the rows before it, which takes longer the further in it is. A negative
position counts from the end, which costs a len() first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
irow
|
int
|
The position of the row. Negative counts from the end. |
0
|
include_cols
|
T_ls | None
|
Only these columns, in this order. All if None. |
None
|
rtype
|
str
|
'dict' for a dict, or 'list' for a list of the values. |
'dict'
|
Returns:
| Type | Description |
|---|---|
T_da | T_la
|
The row. Python NULL for SQL NULL. |
Raises:
| Type | Description |
|---|---|
IndexError
|
There is no row at that position. |
KeyError
|
A name in |
NotImplementedError
|
|
ValueError
|
This is a parent that has had rows deleted. See SqlDaf. |
Examples:
Create a small SqlDaf table of people:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'name', 'city', 'age'], keyfield='id', lol=[
... ['p1', 'Ana Lopez', 'Denver', 34], ['p2', 'Ben Okafor', 'Austin', 52], ['p3', 'Chen Wu', 'Boston', 27]])
Read the first row, by position, as a dict:
>>> people_sdaf.iloc(0)
{'id': 'p1', 'name': 'Ana Lopez', 'city': 'Denver', 'age': 34}
Read the last row. A negative position counts from the end:
>>> people_sdaf.iloc(-1)
{'id': 'p3', 'name': 'Chen Wu', 'city': 'Boston', 'age': 27}
Read only some columns, in the order given:
>>> people_sdaf.iloc(1, include_cols=['age', 'name'])
{'age': 52, 'name': 'Ben Okafor'}
Read a row as a list of its values:
>>> people_sdaf.iloc(1, rtype='list')
['p2', 'Ben Okafor', 'Austin', 52]
On a selection, the position is within its own rows:
>>> people_sdaf.select_where_sql('age < ?', [40]).iloc(1)
{'id': 'p3', 'name': 'Chen Wu', 'city': 'Boston', 'age': 27}
iloc_exists ¶
iloc_exists(irow)
Say whether there is a row at this position, from 0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
irow
|
int
|
The position, from 0. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if a row is there. |
Raises:
| Type | Description |
|---|---|
ValueError
|
This is a parent that has had rows deleted. See SqlDaf. |
Examples:
Create a small SqlDaf table of two people:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'age'], keyfield='id', lol=[['p1', 34], ['p2', 52]])
Ask whether there is a row at position 1, and at position 2:
>>> people_sdaf.iloc_exists(1), people_sdaf.iloc_exists(2)
(True, False)
Columns¶
col ¶
col(
colname,
*,
unique=False,
omit_nulls=False,
silent_error=False,
astype=None,
indirect_col=None,
default=NULL,
)
Get one column as a list, by name, as Daf.col() does.
Only that column is read into memory, or only indirect_col for a value inside a dict
column. The options act as in a Daf. With omit_nulls, both SQL NULL and the text '' are
left out, since both read as Python NULL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colname
|
str
|
The column, or the key inside |
required |
unique
|
bool
|
If True, leave out repeated values and keep the order. |
False
|
omit_nulls
|
bool
|
If True, leave out Python NULL. |
False
|
silent_error
|
bool
|
If True, a name that is not a column gives an empty list. |
False
|
astype
|
Callable | str | type | None
|
A type or function to convert each value with. |
None
|
indirect_col
|
str | None
|
A column that holds a dict, to read |
None
|
default
|
Any
|
The value for a dict that lacks |
NULL
|
Returns:
| Type | Description |
|---|---|
T_la
|
The values of the column, in row order. |
Raises:
| Type | Description |
|---|---|
ColumnNotFoundError
|
The name is not a column, and |
Examples:
Create a small SqlDaf table of people. One age is not known, and each has a dict of contact details:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'city', 'age', 'contact'], keyfield='id', lol=[
... ['p1', 'Denver', 34, {'phone': '555-0101'}], ['p2', 'Austin', '', {}],
... ['p3', 'Denver', 27, {'phone': '555-0103'}]])
>>> people_sdaf
| id | city | age | contact |
| -: | -----: | --: | --------------------: |
| p1 | Denver | 34 | {'phone': '555-0101'} |
| p2 | Austin | | {} |
| p3 | Denver | 27 | {'phone': '555-0103'} |
%% sdaf rows=3; cols=4; keyfield='id'; name='people'
Read one column as a list:
>>> people_sdaf.col('age')
[34, '', 27]
Read each city once, in the order first seen:
>>> people_sdaf.col('city', unique=True)
['Denver', 'Austin']
Leave out the unknown age, and convert the rest to float:
>>> people_sdaf.col('age', omit_nulls=True)
[34, 27]
>>> people_sdaf.col('age', omit_nulls=True, astype=float)
[34.0, 27.0]
A name that is not a column gives an empty list with silent_error=True:
>>> people_sdaf.col('email', silent_error=True)
[]
Read a value inside the dict column, with a default for a dict that lacks it:
>>> people_sdaf.col('phone', indirect_col='contact', default='none')
['555-0101', 'none', '555-0103']
col_to_la ¶
col_to_la(
colname,
*,
unique=False,
omit_nulls=False,
silent_error=False,
astype=None,
indirect_col=None,
default=NULL,
)
Get one column as a list, by name. This does the same as col(). See that method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colname
|
str
|
The column, or the key inside |
required |
unique
|
bool
|
If True, leave out repeated values and keep the order. |
False
|
omit_nulls
|
bool
|
If True, leave out Python NULL. |
False
|
silent_error
|
bool
|
If True, a name that is not a column gives an empty list. |
False
|
astype
|
Callable | str | type | None
|
A type or function to convert each value with. |
None
|
indirect_col
|
str | None
|
A column that holds a dict, to read |
None
|
default
|
Any
|
The value for a dict that lacks |
NULL
|
Returns:
| Type | Description |
|---|---|
T_la
|
The values of the column, in row order. |
Examples:
Create a small SqlDaf table of people. 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', ''], ['p3', 'Chen Wu', 27]])
Read the known ages as a list, as col() does:
>>> people_sdaf.col_to_la('age', omit_nulls=True)
[34, 27]
icol ¶
icol(icol)
Get one column as a list, by its place among the columns, as Daf.icol() does.
The place is looked up in the column names, so it does not depend on the rows. A negative place counts from the end. A place out of range raises IndexError, unless the table has no rows, as in a Daf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
icol
|
int
|
The place of the column, from 0. |
required |
Returns:
| Type | Description |
|---|---|
T_la
|
The values of the column, in row order. |
Raises:
| Type | Description |
|---|---|
IndexError
|
The place is out of range, and the table has rows. |
Examples:
Create a small SqlDaf table of people:
>>> 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', 52], ['p3', 'Chen Wu', 27]])
Read the second column, by its place:
>>> people_sdaf.icol(1)
['Ana Lopez', 'Ben Okafor', 'Chen Wu']
Read the last column. A negative place counts from the end:
>>> people_sdaf.icol(-1)
[34, 52, 27]
icol_to_la ¶
icol_to_la(icol, unique=False, omit_nulls=False)
Get one column as a list, by its place among the columns, with options.
See icol() for the place, and col() for the options.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
icol
|
int
|
The place of the column, from 0. |
required |
unique
|
bool
|
If True, leave out repeated values and keep the order. |
False
|
omit_nulls
|
bool
|
If True, leave out Python NULL. |
False
|
Returns:
| Type | Description |
|---|---|
T_la
|
The values of the column, in row order. |
Raises:
| Type | Description |
|---|---|
IndexError
|
The place is out of range, and the table has rows. |
Examples:
Create a small SqlDaf table of people. One age is not known:
>>> 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', ''], ['p3', 'Denver', 27]])
Read each city once, by the column's place:
>>> people_sdaf.icol_to_la(1, unique=True)
['Denver', 'Austin']
Read the known ages, by the column's place:
>>> people_sdaf.icol_to_la(2, omit_nulls=True)
[34, 27]
cols_to_dol ¶
cols_to_dol(colname1, colname2)
Map each value of one column to the values seen with it in another, as Daf.cols_to_dol() does.
Only the two columns are read into memory. If a name is not a column, or there are no rows, the result is empty.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colname1
|
str
|
The column of keys. |
required |
colname2
|
str
|
The column of values. |
required |
Returns:
| Type | Description |
|---|---|
Dict[Any, T_la]
|
A dict from each value of the first column to the values of the second, in the order first seen. |
Examples:
Create a small SqlDaf table of people:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'city', 'name'], keyfield='id', lol=[
... ['p1', 'Denver', 'Ana Lopez'], ['p2', 'Austin', 'Ben Okafor'], ['p3', 'Denver', 'Chen Wu']])
List the people in each city:
>>> people_sdaf.cols_to_dol('city', 'name')
{'Denver': ['Ana Lopez', 'Chen Wu'], 'Austin': ['Ben Okafor']}
Into memory¶
to_daf ¶
to_daf(name=None)
Pull every row into an ordinary Daf in memory.
Use it once the rows you need are few enough to hold. The rows come in order. A SQL NULL comes back as Python NULL. The new Daf has this SqlDaf's keyfield and dtypes. Nothing ties it to the table afterwards: a change to one does not show in the other. A child has its rows found first.
The Daf has the table's name. A selection, or a copy or join made without a name, has a name
that SqlDaf made up, as daf_tmp_items_v1. Give name to set another.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
The name of the new Daf. If None, the table's name. |
None
|
Returns:
| Type | Description |
|---|---|
Daf
|
A Daf of every row. |
Examples:
Create a small SqlDaf table of people. 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', ''], ['p3', 'Chen Wu', 27]])
Read every row into a Daf in memory:
>>> people_daf = people_sdaf.to_daf()
>>> people_daf
| id | name | age |
| -: | ---------: | --: |
| p1 | Ana Lopez | 34 |
| p2 | Ben Okafor | |
| p3 | Chen Wu | 27 |
%% daf rows=3; cols=3; keyfield='id'; name='people'
The Daf is a copy. A change to it does not reach the table:
>>> people_daf['p1', 'age'] = 99
>>> people_sdaf.select_record('p1')
{'id': 'p1', 'name': 'Ana Lopez', 'age': 34}
Select first, so only the rows needed come into memory:
>>> people_sdaf.select_where_sql('age > ?', [30]).to_daf()
| id | name | age |
| -: | --------: | --: |
| p1 | Ana Lopez | 34 |
%% daf rows=1; cols=3; keyfield='id'; name='daf_tmp_people_v1'
Give the Daf a name of your own with name:
>>> people_sdaf.select_where_sql('age > ?', [30]).to_daf(name='over_30').name
'over_30'
to_dict ¶
to_dict()
Read a table of one row as a dict, as Daf.to_dict() does.
A child has its rows found first. For a row by key or by position, select_record() and
iloc() are cheaper: they make no selection.
Returns:
| Type | Description |
|---|---|
T_da
|
The row as a dict. An empty dict if there are no rows. |
Raises:
| Type | Description |
|---|---|
ValueError
|
There is more than one row. |
Examples:
Create a small SqlDaf table of people:
>>> 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', 52]])
Select one row with brackets, and read it as a dict:
>>> people_sdaf['p2'].to_dict()
{'id': 'p2', 'name': 'Ben Okafor', 'age': 52}
select_record() gives the same dict, with no selection made:
>>> people_sdaf.select_record('p2')
{'id': 'p2', 'name': 'Ben Okafor', 'age': 52}
to_list ¶
to_list()
Read a table of one row, or of one column, as a list, as Daf.to_list() does.
One column gives every value of the column, in order, so select first. A child has its rows found first.
Returns:
| Type | Description |
|---|---|
T_la
|
The values of the row, or of the column. |
Raises:
| Type | Description |
|---|---|
ValueError
|
There is more than one row and more than one column. |
Examples:
Create a small SqlDaf table of people:
>>> 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', 52], ['p3', 'Chen Wu', 27]])
Read one row as a list of its values:
>>> people_sdaf['p3'].to_list()
['p3', 'Chen Wu', 27]
Read one column as a list:
>>> people_sdaf[:, 'age'].to_list()
[34, 52, 27]
to_value ¶
to_value()
Read a table of one row and one column as its value, as Daf.to_value() does.
A child has its rows found first.
Returns:
| Type | Description |
|---|---|
Any
|
The value. Python NULL for SQL NULL. |
Raises:
| Type | Description |
|---|---|
ValueError
|
The table is not one row and one column. |
Examples:
Create a small SqlDaf table of people. 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', '']])
Read one cell as a value:
>>> people_sdaf['p1', 'age'].to_value()
34
The unknown age, SQL NULL in the table, comes back as Python NULL, the empty string:
>>> people_sdaf['p2', 'age'].to_value()
''
to_lod ¶
to_lod()
Make a list of dicts, one for each row, as Daf.to_lod() does.
Every row is read into memory. Use iter_dict() to go through the rows one at a time.
Returns:
| Type | Description |
|---|---|
List[T_da]
|
The rows as dicts, in order. |
Examples:
Create a small SqlDaf table of people. 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', '']])
Read the rows as a list of dicts:
>>> people_sdaf.to_lod()
[{'id': 'p1', 'name': 'Ana Lopez', 'age': 34}, {'id': 'p2', 'name': 'Ben Okafor', 'age': ''}]
to_dod ¶
to_dod(remove_keyfield=True)
Make a dict of dicts, named by the keyfield, as Daf.to_dod() does.
Every row is read into memory, through to_daf().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
remove_keyfield
|
bool
|
If True, leave the keyfield out of the inner dicts. |
True
|
Returns:
| Type | Description |
|---|---|
Dict[Any, T_da]
|
Each row as a dict, under its key. |
Raises:
| Type | Description |
|---|---|
KeysDisabledError
|
There is no keyfield, and there are rows. |
Examples:
Create a small SqlDaf table of people:
>>> 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', 52]])
Read the rows as a dict of dicts, under each key. The key is left out of each row:
>>> people_sdaf.to_dod()
{'p1': {'name': 'Ana Lopez', 'age': 34}, 'p2': {'name': 'Ben Okafor', 'age': 52}}
Keep the key in each row too:
>>> people_sdaf.to_dod(remove_keyfield=False)
{'p1': {'id': 'p1', 'name': 'Ana Lopez', 'age': 34}, 'p2': {'id': 'p2', 'name': 'Ben Okafor', 'age': 52}}
to_json ¶
to_json(concise=True)
Make JSON text that holds the whole table, as Daf.to_json() does.
Every row is read into memory, through to_daf(). The text holds the rows, the column
names, the dtypes, the keyfield and the name. Daf.from_json() reads it back as a Daf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
concise
|
bool
|
If True, leave out the parts that are empty. |
True
|
Returns:
| Type | Description |
|---|---|
str
|
The JSON text. |
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]])
Make JSON text of the whole table, leaving out the parts that are empty:
>>> people_sdaf.to_json()
'{"name": "people", "lol": [["p1", 34], ["p2", 52]], "hd": {"id": 0, "age": 1}, "keyfield": "id"}'
Make it with every part:
>>> people_sdaf.to_json(concise=False)
'{"name": "people", "lol": [["p1", 34], ["p2", 52]], "hd": {"id": 0, "age": 1}, "dtypes": {}, "keyfield": "id", "attrs": {}, "disp_cols": []}'
Display and files¶
__str__ ¶
__str__()
Show the rows as a Markdown table, as str() of a Daf shows them.
At most md_max_rows rows and md_max_cols columns, 10 by default, then the summary line.
print(), an f-string and repr() give the same, as for a Daf.
Returns:
| Type | Description |
|---|---|
str
|
The Markdown text. |
Examples:
Create a SqlDaf table of 12 people:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'age'], lol=[[f'p{i:02}', 20 + 3 * i] for i in range(12)])
Print it, with at most four rows, the first and the last:
>>> people_sdaf.md_max_rows = 4
>>> print(people_sdaf)
| id | age |
| --: | --: |
| p00 | 20 |
| p01 | 23 |
| ... | ... |
| p10 | 50 |
| p11 | 53 |
%% sdaf rows=12; cols=2; keyfield=''; name='people'
__repr__ ¶
__repr__()
Show the rows as a Markdown table, for the Python prompt, as repr() of a Daf shows them.
This is the same text as str(), with a newline in front, so the table starts at the left
margin when it is echoed. is_child and is_temp tell what kind of SqlDaf it is.
Returns:
| Type | Description |
|---|---|
str
|
The Markdown text. |
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]])
Echo it at the prompt to see it as a table:
>>> people_sdaf
| id | age |
| -: | --: |
| p1 | 34 |
| p2 | 52 |
%% sdaf rows=2; cols=2; keyfield='id'; name='people'
__format__ ¶
__format__(format_spec)
Format the rows for an f-string, as a Daf formats.
With no format spec this is str(). With one, such as .2f, there must be exactly one cell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
format_spec
|
str
|
A format spec such as |
required |
Returns:
| Type | Description |
|---|---|
str
|
The formatted text. |
Raises:
| Type | Description |
|---|---|
ValueError
|
A spec is given and there is not exactly one cell. |
Examples:
Create a small SqlDaf table of people, with heights in meters:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'height_m'], keyfield='id', lol=[['p1', 1.684], ['p2', 1.8]])
Format one cell in an f-string, with a format spec:
>>> f"height: {people_sdaf['p1', 'height_m']:.2f} m"
'height: 1.68 m'
A format spec needs exactly one cell:
>>> f"{people_sdaf[:, 'height_m']:.2f}"
Traceback (most recent call last):
ValueError: to_value() requires 1×1, got shape (2+, 1)
summary_tag
class-attribute
instance-attribute
¶
summary_tag = 'sdaf'
The word after %% in the summary line, so a printout shows it came from a SqlDaf.
md_max_rows
class-attribute
instance-attribute
¶
md_max_rows = 10
The number of rows that str() shows, half from the start and half from the end.
md_max_cols
class-attribute
instance-attribute
¶
md_max_cols = 10
The number of columns that str() shows, half from the start and half from the end.
to_md ¶
to_md(
max_rows=0,
max_cols=0,
just="",
shorten_text=True,
max_text_len=80,
smart_fmt=False,
include_summary=False,
disp_cols=None,
header=None,
col_fmt=None,
show=None,
)
Make a Markdown table, as Daf.to_md() does.
Set max_rows for a large table. Then only the first and last rows are read. Without it,
every row is read into memory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_rows
|
int
|
The most rows to show, the first and the last. 0 for all. |
0
|
max_cols
|
int
|
The most columns to show, the first and the last. 0 for all. |
0
|
just
|
str
|
The justification of each column: '<', '^' or '>'. |
''
|
shorten_text
|
bool
|
If True, shorten long text, keeping the ends. |
True
|
max_text_len
|
int
|
The length past which text is shortened. |
80
|
smart_fmt
|
bool
|
If True, limit the digits after the point in numbers. |
False
|
include_summary
|
bool
|
If True, add a line with the shape, keyfield and name. |
False
|
disp_cols
|
T_cs | None
|
Names to show in the header: a dict of column name to name shown, for some columns, or a list for every column. |
None
|
header
|
Any
|
A header to use in place of the column names. |
None
|
col_fmt
|
T_da | None
|
How to show the cells of some columns, by column name. See |
None
|
show
|
str | T_ls | None
|
What else to show: 'dtypes', 'quotes' or 'types', or a list of them. See |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The Markdown text. |
Examples:
Create a small SqlDaf table of people, with a long address and a height in meters:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'name', 'height_m', 'address'], keyfield='id', lol=[
... ['p1', 'Ana Lopez', 1.68, '12 Oak St'], ['p2', 'Ben Okafor', 1.8, ''],
... ['p3', 'Chen Wu', 1.755, '4500 Long Meadow Parkway, Apartment 12B']])
Make a Markdown table of every row and column:
>>> print(people_sdaf.to_md())
| id | name | height_m | address |
| -: | ---------: | -------: | --------------------------------------: |
| p1 | Ana Lopez | 1.68 | 12 Oak St |
| p2 | Ben Okafor | 1.8 | |
| p3 | Chen Wu | 1.755 | 4500 Long Meadow Parkway, Apartment 12B |
Show only the first and last rows and columns. Only those rows are read:
>>> print(people_sdaf.to_md(max_rows=2, max_cols=3))
| id | name | ... | address |
| --: | --------: | --: | --------------------------------------: |
| p1 | Ana Lopez | ... | 12 Oak St |
| ... | ... | ... | ... |
| p3 | Chen Wu | ... | 4500 Long Meadow Parkway, Apartment 12B |
Justify each column, shorten long text, and show numbers with fewer digits:
>>> print(people_sdaf.to_md(just='<<><', max_text_len=16, smart_fmt=True))
| id | name | height_m | address |
| :- | :--------- | -------: | :--------------- |
| p1 | Ana Lopez | 1.7 | 12 Oak St |
| p2 | Ben Okafor | 1.8 | |
| p3 | Chen Wu | 1.8 | 4500 Lo..ent 12B |
Write long text in full, rename one column in the header, and add the summary line:
>>> print(people_sdaf.to_md(shorten_text=False, disp_cols={'height_m': 'Height (m)'}, include_summary=True))
| id | name | Height (m) | address |
| -: | ---------: | ---------: | --------------------------------------: |
| p1 | Ana Lopez | 1.68 | 12 Oak St |
| p2 | Ben Okafor | 1.8 | |
| p3 | Chen Wu | 1.755 | 4500 Long Meadow Parkway, Apartment 12B |
%% sdaf rows=3; cols=4; keyfield='id'; name='people'
Show the height in centimeters, with a function, and keep the other columns as they are:
>>> print(people_sdaf.to_md(col_fmt={'height_m': lambda val: f'{val * 100:.0f} cm'}))
| id | name | height_m | address |
| -: | ---------: | -------: | --------------------------------------: |
| p1 | Ana Lopez | 168 cm | 12 Oak St |
| p2 | Ben Okafor | 180 cm | |
| p3 | Chen Wu | 176 cm | 4500 Long Meadow Parkway, Apartment 12B |
Give a header row of your own:
>>> print(people_sdaf[0:1].to_md(header=['ID', 'Name', 'Height', 'Address']))
| ID | Name | Height | Address |
| -: | --------: | -----: | --------: |
| p1 | Ana Lopez | 1.68 | 12 Oak St |
to_md_cols ¶
to_md_cols(
max_rows=0,
max_cols=0,
just="",
shorten_text=True,
max_text_len=80,
smart_fmt=False,
include_summary=False,
disp_cols=None,
)
Make a Markdown table with each row as a column, as Daf.to_md_cols() does.
Set max_rows for a large table. Then only the first and last rows are read.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_rows
|
int
|
The most rows to show, the first and the last. 0 for all. |
0
|
max_cols
|
int
|
The most columns to show, the first and the last. 0 for all. |
0
|
just
|
str
|
The justification of each column: '<', '^' or '>'. |
''
|
shorten_text
|
bool
|
If True, shorten long text, keeping the ends. |
True
|
max_text_len
|
int
|
The length past which text is shortened. |
80
|
smart_fmt
|
bool
|
If True, limit the digits after the point in numbers. |
False
|
include_summary
|
bool
|
Not used, as in a Daf. |
False
|
disp_cols
|
T_cs | None
|
Names to show in the header: a dict of column name to name shown, for some columns, or a list for every column. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The Markdown text. |
Examples:
Create a small SqlDaf table of people, with a long address:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'name', 'height_m', 'address'], keyfield='id', lol=[
... ['p1', 'Ana Lopez', 1.68, '12 Oak St'], ['p2', 'Ben Okafor', 1.8, ''],
... ['p3', 'Chen Wu', 1.755, '4500 Long Meadow Parkway, Apartment 12B']])
Make a Markdown table with each row as a column:
>>> print(people_sdaf.to_md_cols())
| id | p1 | p2 | p3 |
| name | Ana Lopez | Ben Okafor | Chen Wu |
| height_m | 1.68 | 1.8 | 1.755 |
| address | 12 Oak St | | 4500 Long Meadow Parkway, Apartment 12B |
Keep the first and last rows, justify left, shorten text, and rename the first column:
>>> print(people_sdaf.to_md_cols(max_rows=2, just='<<<', max_text_len=16, smart_fmt=True, disp_cols={'id': 'ID'}))
| ID | p1 | ... | p3 |
| name | Ana Lopez | ... | Chen Wu |
| height_m | 1.7 | ... | 1.8 |
| address | 12 Oak St | ... | 4500 Lo..ent 12B |
Keep the first and last columns of the table, with long text in full:
>>> print(people_sdaf.to_md_cols(max_cols=2, shorten_text=False))
| id | p1 | p2 | p3 |
| ... | ... | ... | ... |
| address | 12 Oak St | | 4500 Long Meadow Parkway, Apartment 12B |
daf_to_lol_summary ¶
daf_to_lol_summary(
max_rows=10, max_cols=10, disp_cols=None
)
Give the header and the rows to display, as Daf.daf_to_lol_summary() does.
With max_rows, only the first and last rows are read, around a row of '...'. Without
it, every row is read.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_rows
|
int
|
The most rows to show. 0 for all. |
10
|
max_cols
|
int
|
The most columns to show. 0 for all. |
10
|
disp_cols
|
T_cs | None
|
Names to show in the header: a dict of column name to name shown, for some columns, or a list for every column. |
None
|
Returns:
| Type | Description |
|---|---|
T_lola
|
The header, then the rows. |
Examples:
Create a SqlDaf table of six people, with three numbers each:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'age', 'visits', 'points'], lol=[
... [f'p{i}', 20 + i, 3 * i, 100 * i] for i in range(1, 7)])
Keep four rows, the first and the last, around a row of '...'. The limits default to 10, and
0 means no limit, so max_cols=0 keeps every column:
>>> people_sdaf.daf_to_lol_summary(max_rows=4, max_cols=0)
[['id', 'age', 'visits', 'points'], ['p1', 21, 3, 100], ['p2', 22, 6, 200], ['...', '...', '...', '...'], ['p5', 25, 15, 500], ['p6', 26, 18, 600]]
Keep two columns, the first and the last. max_rows=0 keeps every row:
>>> people_sdaf.daf_to_lol_summary(max_rows=0, max_cols=2)
[['id', '...', 'points'], ['p1', '...', 100], ['p2', '...', 200], ['p3', '...', 300], ['p4', '...', 400], ['p5', '...', 500], ['p6', '...', 600]]
Show another name in the header for one column, with every column kept:
>>> people_sdaf.daf_to_lol_summary(max_rows=2, max_cols=0, disp_cols={'age': 'Age'})
[['id', 'Age', 'visits', 'points'], ['p1', 21, 3, 100], ['...', '...', '...', '...'], ['p6', 26, 18, 600]]
md_daf_table_snippet ¶
md_daf_table_snippet()
Make a short Markdown table of the rows, with a summary line, as Daf.md_daf_table_snippet() does.
It is the same text as for a Daf of the same rows, byte for byte. It reads the rows from the table in SQL: a count, then the first and the last rows it shows. So a table of any size shows in the same time. On 1,603,908 rows it took 0.64 s.
Returns:
| Type | Description |
|---|---|
str
|
The Markdown text. |
Examples:
Create a SqlDaf table of 30 people, more than a snippet shows:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'age'], lol=[[f'p{i:02}', 20 + i] for i in range(30)])
Show a short Markdown table of it, the first and last rows, with a summary line:
>>> print(people_sdaf.md_daf_table_snippet())
| id | age |
| --: | --: |
| p00 | 20 |
| p01 | 21 |
| p02 | 22 |
| p03 | 23 |
| p04 | 24 |
| ... | ... |
| p25 | 45 |
| p26 | 46 |
| p27 | 47 |
| p28 | 48 |
| p29 | 49 |
%% sdaf rows=30; cols=2; keyfield=''; name='people'
to_csv_buff ¶
to_csv_buff(line_terminator=None, include_header=True)
Make CSV text from the rows, as Daf.to_csv_buff() does.
The whole text is built in memory, so use it for a selection of modest size. To write a
large table, use to_csv_file(), which writes as it reads.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
line_terminator
|
str | None
|
The line ending. If None, |
None
|
include_header
|
bool
|
If True, write the column names first. |
True
|
Returns:
| Type | Description |
|---|---|
T_buff
|
The CSV text. |
Examples:
Create a small SqlDaf table of people. 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', '']])
Make the CSV text in memory:
>>> people_sdaf.to_csv_buff()
'id,name,age\r\np1,Ana Lopez,34\r\np2,Ben Okafor,\r\n'
Make it without the header line, and with another line ending:
>>> people_sdaf.to_csv_buff(line_terminator='\n', include_header=False)
'p1,Ana Lopez,34\np2,Ben Okafor,\n'
to_csv_file ¶
to_csv_file(
file_path="", line_terminator=None, include_header=True
)
Write the rows to a CSV file, as Daf.to_csv_file() does.
A local file is written as the rows are read, 10,000 at a time, so a table larger than
memory can be written. The text is the same as a Daf of the same rows would write: each
cell with str(), Python NULL and SQL NULL as nothing, and \r\n line endings by default.
A column name stored with the __HH encoding is written decoded. So a table that another
program stored with a column __67roup is written with the header group.
A path that starts with s3 is not streamed: the text is built in memory and uploaded, as a Daf does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str | Path
|
Where to write the file. |
''
|
line_terminator
|
str | None
|
The line ending. If None, |
None
|
include_header
|
bool
|
If True, write the column names first. |
True
|
Returns:
| Type | Description |
|---|---|
str
|
The path that was written. |
Examples:
Create a small SqlDaf table of people. One age is not known:
>>> import os, 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', '']])
Write it to a CSV file, and read the file back as text. The unknown age is an empty cell.
newline='' keeps the line endings as written, \r\n by default:
>>> csv_path = people_sdaf.to_csv_file(os.path.join(tempfile.mkdtemp(), 'people.csv'))
>>> open(csv_path, newline='').read()
'id,name,age\r\np1,Ana Lopez,34\r\np2,Ben Okafor,\r\n'
Write it without the header line, and with another line ending:
>>> csv_path = people_sdaf.to_csv_file(os.path.join(tempfile.mkdtemp(), 'people.csv'), line_terminator='\n', include_header=False)
>>> open(csv_path).read()
'p1,Ana Lopez,34\np2,Ben Okafor,\n'