Skip to content

Commit 139f9d6

Browse files
committed
fixes #10
1 parent 78deaae commit 139f9d6

File tree

7 files changed

+82
-33
lines changed

7 files changed

+82
-33
lines changed

README.md

Lines changed: 74 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ to be particularly of interest to folks using Jupyter.
1515
## Overview
1616

1717
``` python
18-
from sqlite_utils import Database
1918
from fastlite import *
2019
from fastcore.utils import *
2120
from fastcore.net import urlsave
@@ -29,7 +28,7 @@ url = 'https://github.com/lerocha/chinook-database/raw/master/ChinookDatabase/Da
2928
path = Path('chinook.sqlite')
3029
if not path.exists(): urlsave(url, path)
3130

32-
db = Database("chinook.sqlite")
31+
db = database("chinook.sqlite")
3332
```
3433

3534
Databases have a `t` property that lists all tables:
@@ -171,9 +170,11 @@ to a module, which you can then import from:
171170
create_mod(db, 'db_dc')
172171
```
173172

173+
Indexing into a table does a query on primary key:
174+
174175
``` python
175176
from db_dc import Track
176-
Track(**dt.Track.get(1))
177+
Track(**dt.Track[1])
177178
```
178179

179180
Track(TrackId=1, Name='For Those About To Rock (We Salute You)', AlbumId=1, MediaTypeId=1, GenreId=1, Composer='Angus Young, Malcolm Young, Brian Johnson', Milliseconds=343719, Bytes=11170334, UnitPrice=0.99)
@@ -190,35 +191,46 @@ album(limit=2)
190191
[Album(AlbumId=1, Title='For Those About To Rock We Salute You', ArtistId=1),
191192
Album(AlbumId=2, Title='Balls to the Wall', ArtistId=2)]
192193

193-
Pass a truthy value as the first param and you’ll get tuples of primary
194-
keys and records:
194+
Pass a truthy value as `with_pk` and you’ll get tuples of primary keys
195+
and records:
195196

196197
``` python
197-
album(1, limit=2)
198+
album(with_pk=1, limit=2)
198199
```
199200

200201
[(1,
201202
Album(AlbumId=1, Title='For Those About To Rock We Salute You', ArtistId=1)),
202203
(2, Album(AlbumId=2, Title='Balls to the Wall', ArtistId=2))]
203204

204-
`get` also uses the dataclass by default:
205+
Indexing also uses the dataclass by default:
205206

206207
``` python
207-
album.get(1)
208+
album[5]
208209
```
209210

210-
Album(AlbumId=1, Title='For Those About To Rock We Salute You', ArtistId=1)
211+
Album(AlbumId=5, Title='Big Ones', ArtistId=3)
212+
213+
If you set `xtra` fields, then indexing is also filtered by those. As a
214+
result, for instance in this case, nothing is returned since album 5 is
215+
not created by artist 1:
216+
217+
``` python
218+
album.xtra(ArtistId=1)
219+
220+
try: album[5]
221+
except NotFoundError: print("Not found")
222+
```
211223

212-
If you want the dataclass-conversion behaviour for *all* tables (and
213-
optionally views) then you can create them all at once with
214-
[`all_dcs`](https://AnswerDotAI.github.io/fastlite/core.html#all_dcs).
224+
Not found
225+
226+
The same filtering is done when using the table as a callable:
215227

216228
``` python
217-
dcs = all_dcs(db)
218-
dcs[0]
229+
album()
219230
```
220231

221-
types.Album
232+
[Album(AlbumId=1, Title='For Those About To Rock We Salute You', ArtistId=1),
233+
Album(AlbumId=4, Title='Let There Be Rock', ArtistId=1)]
222234

223235
## Insert, upsert, and update
224236

@@ -233,56 +245,90 @@ The following methods accept `**kwargs`, passing them along to the first
233245
- `upsert`
234246
- `lookup`
235247

248+
We can access a table that doesn’t actually exist yet:
249+
236250
``` python
237251
cats = dt.cats
238-
cats.create(id=int, name=str, weight=float, pk='id')
252+
cats
253+
```
254+
255+
<Table cats (does not exist yet)>
256+
257+
We can use keyword arguments to now create that table:
258+
259+
``` python
260+
cats.create(id=int, name=str, weight=float, uid=int, pk='id')
239261
hl_md(cats.schema, 'sql')
240262
```
241263

242264
``` sql
243265
CREATE TABLE [cats] (
244266
[id] INTEGER PRIMARY KEY,
245267
[name] TEXT,
246-
[weight] FLOAT
268+
[weight] FLOAT,
269+
[uid] INTEGER
247270
)
248271
```
249272

250-
…the same applies to `insert` here:
273+
It we set `xtra` then the additional fields are used for `insert`,
274+
`update`, and `delete`:
251275

252276
``` python
277+
cats.xtra(uid=2)
253278
cat = cats.insert(name='meow', weight=6)
254279
```
255280

256-
The inserted row is returned.
281+
The inserted row is returned, including the xtra ‘uid’ field.
257282

258283
``` python
259284
cat
260285
```
261286

262-
{'id': 1, 'name': 'meow', 'weight': 6.0}
287+
{'id': 1, 'name': 'meow', 'weight': 6.0, 'uid': 2}
263288

264-
Using `**` in upsert here doesn’t actually achieve anything, since we
289+
Using `**` in `update` here doesn’t actually achieve anything, since we
265290
can just pass a `dict` directly – it’s just to show that it works:
266291

267292
``` python
268293
cat['name'] = "moo"
269-
cats.upsert(**cat)
294+
cat['uid'] = 1
295+
cats.update(**cat)
270296
cats()
271297
```
272298

273-
[{'id': 1, 'name': 'moo', 'weight': 6.0}]
299+
[{'id': 1, 'name': 'moo', 'weight': 6.0, 'uid': 2}]
300+
301+
Attempts to update or insert with xtra fields are ignored.
302+
303+
An error is raised if there’s an attempt to update a record not matching
304+
`xtra` fields:
305+
306+
``` python
307+
cats.xtra(uid=1)
308+
try: cats.update(**cat)
309+
except NotFoundError: print("Not found")
310+
```
311+
312+
Not found
274313

275314
This all also works with dataclasses:
276315

277316
``` python
278-
catdc = cats.dataclass()
279-
cat = cats.get(1)
317+
cats.xtra(uid=2)
318+
cats.dataclass()
319+
cat = cats[1]
320+
cat
321+
```
322+
323+
Cats(id=1, name='moo', weight=6.0, uid=2)
324+
325+
``` python
280326
cat.name = 'foo'
281327
cats.upsert(cat)
282328
cats()
283329
```
284330

285-
[Cats(id=1, name='foo', weight=6.0)]
331+
[Cats(id=1, name='foo', weight=6.0, uid=2)]
286332

287333
``` python
288334
cats.drop()
@@ -299,7 +345,7 @@ If you have graphviz installed, you can create database diagrams:
299345
diagram(db.tables)
300346
```
301347

302-
![](index_files/figure-commonmark/cell-27-output-1.svg)
348+
![](index_files/figure-commonmark/cell-31-output-1.svg)
303349

304350
Pass a subset of tables to just diagram those. You can also adjust the
305351
size and aspect ratio.
@@ -308,4 +354,4 @@ size and aspect ratio.
308354
diagram(db.t['Artist','Album','Track','Genre','MediaType'], size=8, ratio=0.4)
309355
```
310356

311-
![](index_files/figure-commonmark/cell-28-output-1.svg)
357+
![](index_files/figure-commonmark/cell-32-output-1.svg)

fastlite/_modidx.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
'fastlite.core.View.c': ('core.html#view.c', 'fastlite/core.py'),
1818
'fastlite.core._Col': ('core.html#_col', 'fastlite/core.py'),
1919
'fastlite.core._Col.__init__': ('core.html#_col.__init__', 'fastlite/core.py'),
20+
'fastlite.core._Col.__iter__': ('core.html#_col.__iter__', 'fastlite/core.py'),
2021
'fastlite.core._Col.__repr__': ('core.html#_col.__repr__', 'fastlite/core.py'),
2122
'fastlite.core._Col.__str__': ('core.html#_col.__str__', 'fastlite/core.py'),
2223
'fastlite.core._ColsGetter': ('core.html#_colsgetter', 'fastlite/core.py'),

fastlite/core.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from fastcore.utils import *
1111
from fastcore.xml import highlight
1212
from fastcore.xtras import hl_md, dataclass_src
13-
from sqlite_utils.db import *
13+
from sqlite_minutils.db import *
1414

1515
try: from graphviz import Source
1616
except ImportError: pass
@@ -40,6 +40,7 @@ class _Col:
4040
def __init__(self, t, c): self.t,self.c = t,c
4141
def __str__(self): return f'"{self.t}"."{self.c}"'
4242
def __repr__(self): return self.c
43+
def __iter__(self): return iter(self.c)
4344

4445
class _ColsGetter:
4546
def __init__(self, tbl): self.tbl = tbl

fastlite/kw.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from dataclasses import is_dataclass, MISSING, asdict
22
from typing import Any,Union,Tuple,List,Iterable
33
from fastcore.utils import *
4-
from sqlite_utils.db import Database,Table,DEFAULT,ForeignKeysType,Default,Queryable,NotFoundError
4+
from sqlite_minutils.db import Database,Table,DEFAULT,ForeignKeysType,Default,Queryable,NotFoundError
55

66
opt_bool = Union[bool, Default, None]
77

nbs/00_core.ipynb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838
"from fastcore.utils import *\n",
3939
"from fastcore.xml import highlight\n",
4040
"from fastcore.xtras import hl_md, dataclass_src\n",
41-
"from sqlite_utils.db import *\n",
41+
"from sqlite_minutils.db import *\n",
4242
"\n",
4343
"try: from graphviz import Source\n",
4444
"except ImportError: pass"
@@ -187,6 +187,7 @@
187187
" def __init__(self, t, c): self.t,self.c = t,c\n",
188188
" def __str__(self): return f'\"{self.t}\".\"{self.c}\"'\n",
189189
" def __repr__(self): return self.c\n",
190+
" def __iter__(self): return iter(self.c)\n",
190191
"\n",
191192
"class _ColsGetter:\n",
192193
" def __init__(self, tbl): self.tbl = tbl\n",

nbs/index.ipynb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@
6969
"path = Path('chinook.sqlite')\n",
7070
"if not path.exists(): urlsave(url, path)\n",
7171
"\n",
72-
"db = Database(\"chinook.sqlite\")"
72+
"db = database(\"chinook.sqlite\")"
7373
]
7474
},
7575
{

settings.ini

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ version = 0.0.5
55
min_python = 3.10
66
license = apache2
77
black_formatting = False
8-
requirements = fastcore>=1.5.41 sqlite-utils
8+
requirements = fastcore>=1.5.41 sqlite-minutils
99
conda_user = fastai
1010
doc_path = _docs
1111
lib_path = fastlite

0 commit comments

Comments
 (0)