conn_str = _db_str(":memory:"); conn_str'sqlite:///:memory:'
Database and DBTable
Initialize self. See help(type(self)) for accurate signature.
Database and DBTableWe create a Database class and a DBTable class (which is returned by Database.create), using sqlalchemy v2. These classes will allow us to directly work with dataclasses such as these:
A connection to a SQLAlchemy database
FacadeDict({'test': Table('test', MetaData(), Column('id', INTEGER(), table=<test>, primary_key=True), Column('name', TEXT(), table=<test>), Column('age', INTEGER(), table=<test>), schema=None)})
Query database with raw SQL and optional parameters. Returns list of dicts.
[]
[{'id': 1, 'name': 'Alice', 'age': 30}, {'id': 2, 'name': 'Bob', 'age': 25}]
[]
[{'id': 1, 'name': 'Alice', 'age': 32}, {'id': 2, 'name': 'Bob', 'age': 25}]
A connection to a SQLAlchemy table, created if needed
<Table test (id, name, age)>
(Table('test', MetaData(), Column('id', INTEGER(), table=<test>, primary_key=True), Column('name', TEXT(), table=<test>), Column('age', INTEGER(), table=<test>), schema=None),
<sqlalchemy.sql.base.ReadOnlyColumnCollection>)
Create a Database from a path or connection string
Create module for dataclasses for db
dataclasses for all objects in db
Add objects for all table objects to namespace glb
Add set all table dataclasses using types in namespace glb
Set the internal dataclass type links for tables using mod (created via create_mod)
def upsert(
record:Any=None, pk:Default=<__main__.Default object at 0x7fe1bb4866f0>,
foreign_keys:Default=<__main__.Default object at 0x7fe1bb4866f0>,
column_order:Union=<__main__.Default object at 0x7fe1bb4866f0>,
not_null:Union=<__main__.Default object at 0x7fe1bb4866f0>,
defaults:Union=<__main__.Default object at 0x7fe1bb4866f0>,
hash_id:Union=<__main__.Default object at 0x7fe1bb4866f0>,
hash_id_columns:Union=<__main__.Default object at 0x7fe1bb4866f0>,
alter:Union=<__main__.Default object at 0x7fe1bb4866f0>,
extracts:Union=<__main__.Default object at 0x7fe1bb4866f0>,
conversions:Union=<__main__.Default object at 0x7fe1bb4866f0>,
columns:Union=<__main__.Default object at 0x7fe1bb4866f0>,
strict:Union=<__main__.Default object at 0x7fe1bb4866f0>, kwargs:VAR_KEYWORD
)->Any:
Get the underlying type.
def create(
cls:type, pk:str='id', name:str | None=None, foreign_keys:NoneType=None, defaults:NoneType=None,
column_order:NoneType=None, not_null:NoneType=None, hash_id:NoneType=None, hash_id_columns:NoneType=None,
extracts:NoneType=None, if_not_exists:bool=False, replace:bool=False, ignore:bool=True, transform:bool=False,
strict:bool=False, constraints:NoneType=None
):
Get a table object, creating in DB if needed
Show all tables and columns
Table: student
* id: INTEGER
* grad_year: INTEGER
- name: VARCHAR
Table: todo
- title: VARCHAR
- name: VARCHAR
* id: INTEGER
- done: BOOLEAN
- details: VARCHAR
Table: user
* name: VARCHAR
- pwd: VARCHAR
By returning a _TablesGetter we get a repr and auto-complete that shows all tables in the DB.
Similarly, we return _ColsGetter for a table’s columns
def create(
columns:Dict=None, pk:Any=None, foreign_keys:NoneType=None, column_order:Optional=None, not_null:Optional=None,
defaults:Optional=None, hash_id:str | None=None, hash_id_columns:Optional=None, extracts:Union=None,
if_not_exists:bool=False, replace:bool=False, ignore:bool=False, transform:bool=False, strict:bool=False,
kwargs:VAR_KEYWORD
):
Create table from column definitions passed as kwargs or columns dict
Check if this table exists in the DB
def insert(
record:Dict=None, pk:Default=<__main__.Default object at 0x7fe1bb4866f0>,
foreign_keys:Default=<__main__.Default object at 0x7fe1bb4866f0>,
column_order:Union=<__main__.Default object at 0x7fe1bb4866f0>,
not_null:Union=<__main__.Default object at 0x7fe1bb4866f0>,
defaults:Union=<__main__.Default object at 0x7fe1bb4866f0>,
hash_id:Union=<__main__.Default object at 0x7fe1bb4866f0>,
hash_id_columns:Union=<__main__.Default object at 0x7fe1bb4866f0>,
alter:Union=<__main__.Default object at 0x7fe1bb4866f0>,
ignore:Union=<__main__.Default object at 0x7fe1bb4866f0>,
replace:Union=<__main__.Default object at 0x7fe1bb4866f0>,
extracts:Union=<__main__.Default object at 0x7fe1bb4866f0>,
conversions:Union=<__main__.Default object at 0x7fe1bb4866f0>,
columns:Union=<__main__.Default object at 0x7fe1bb4866f0>,
strict:Union=<__main__.Default object at 0x7fe1bb4866f0>, kwargs:VAR_KEYWORD
)->Any:
Insert an object into this table, and return it
def insert_all(
records:Optional=None, pk:Default=<__main__.Default object at 0x7fe1bb4866f0>,
foreign_keys:Default=<__main__.Default object at 0x7fe1bb4866f0>,
column_order:Union=<__main__.Default object at 0x7fe1bb4866f0>,
not_null:Union=<__main__.Default object at 0x7fe1bb4866f0>,
defaults:Union=<__main__.Default object at 0x7fe1bb4866f0>,
batch_size:Default=<__main__.Default object at 0x7fe1bb4866f0>,
hash_id:Union=<__main__.Default object at 0x7fe1bb4866f0>,
hash_id_columns:Union=<__main__.Default object at 0x7fe1bb4866f0>,
alter:Union=<__main__.Default object at 0x7fe1bb4866f0>,
ignore:Union=<__main__.Default object at 0x7fe1bb4866f0>,
replace:Union=<__main__.Default object at 0x7fe1bb4866f0>, truncate:bool=False,
extracts:Union=<__main__.Default object at 0x7fe1bb4866f0>,
conversions:Union=<__main__.Default object at 0x7fe1bb4866f0>,
columns:Union=<__main__.Default object at 0x7fe1bb4866f0>,
strict:Union=<__main__.Default object at 0x7fe1bb4866f0>, upsert:bool=False, analyze:bool=False,
xtra:dict | None=None, kwargs:VAR_KEYWORD
)->DBTable:
def __call__(
where:str | None=None, # SQL where fragment to use, for example `id > ?`
where_args:Union=None, # Parameters to use with `where`; iterable for `id>?`, or dict for `id>:id`
order_by:str | None=None, # Column or fragment of SQL to order by
limit:int | None=None, # Number of rows to limit to
offset:int | None=None, # SQL offset
select:str='*', # Comma-separated list of columns to select
with_pk:bool=False, # Return tuple of (pk,row)?
as_cls:bool=True, # Convert returned dict to stored dataclass?
xtra:dict | None=None, # Extra constraints
kw:VAR_KEYWORD
):
Result of select query on the table. Returns list of returned objects.
[Todo(title='do it', name='jph', id=1, done=False, details=''),
Todo(title='get it done', name='rlt', id=2, done=False, details=''),
Todo(title='do it', name='jph', id=3, done=False, details=''),
Todo(title='get it done', name='rlt', id=4, done=False, details='')]
Create a view with the given name and SQL query
[{'title': 'do it', 'name': 'jph', 'id': 1, 'done': False, 'details': ''},
{'title': 'get it done',
'name': 'rlt',
'id': 2,
'done': False,
'details': ''},
{'title': 'do it', 'name': 'jph', 'id': 3, 'done': False, 'details': ''},
{'title': 'get it done',
'name': 'rlt',
'id': 4,
'done': False,
'details': ''}]
Common base class for all non-exit exceptions.
Common base class for all non-exit exceptions.
Get item with PK key
[User(name='jph', pwd='new'), User(name='rlt', pwd='bar')]
Update rows matching where with updates. Returns updated rows.
Update rows matching where with updates. Returns updated rows.
[Todo(title='do it', name='jph', id=1, done=True, details=''),
Todo(title='do it', name='jph', id=3, done=True, details='')]
Delete item with PK key and return the deleted object
[Todo(title='do it', name='jph', id=1, done=True, details=''),
Todo(title='do it', name='jph', id=3, done=True, details='')]
Is the item with the specified primary key value in this table?
Demonstration with single field primary key:
For compound primary keys, lets whether a student is in the students table or not.
Drop this table from the database
Initialize self. See help(type(self)) for accurate signature.
CREATE TABLE _meta (
id INTEGER,
version INTEGER,
PRIMARY KEY (id),
CHECK (id = 1)
)
[(1, Path('migrations/1-add_priority_and_due_date_to_todo.sql'))]
Applied migration 1: 1-add_priority_and_due_date_to_todo.sql
Default dir() implementation.
Default dir() implementation.
[Column('title', VARCHAR(), table=<todo>),
Column('name', VARCHAR(), table=<todo>),
Column('id', INTEGER(), table=<todo>, primary_key=True),
Column('done', BOOLEAN(), table=<todo>),
Column('details', VARCHAR(), table=<todo>),
Column('priority', INTEGER(), table=<todo>, server_default=DefaultClause(<sqlalchemy.sql.elements.TextClause object>, for_update=False)),
Column('due_date', TEXT(), table=<todo>)]
Execute statement string and return DataFrame of results (if any)
Execute statement string and return results (if any)
Get all results as named tuples
Select from table, optionally limited by where and limit clauses
This is the query that will run behind the scenes:
SELECT todo.title, todo.name, todo.id, todo.done, todo.details, todo.priority, todo.due_date
FROM todo
WHERE (todo.title LIKE :title_1 || '%')
LIMIT :param_1
Close the connection