Added .schema property, improved docs, release 0.3

This commit is contained in:
Simon Willison 2018-07-31 08:33:52 -07:00
commit e888bb122d
3 changed files with 93 additions and 6 deletions

View file

@ -6,14 +6,56 @@ Tables are accessed using the indexing operator, like so:
.. code-block:: python .. code-block:: python
from sqlite_utils.db import Database from sqlite_utils import Database
import sqlite3 import sqlite3
database = Database(sqlite3.connect("my_database.db")) db = Database(sqlite3.connect("my_database.db"))
table = database["my_table"] table = db["my_table"]
If the table does not yet exist, it will be created the first time you attempt to insert or upsert data into it. If the table does not yet exist, it will be created the first time you attempt to insert or upsert data into it.
Creating tables
===============
The easiest way to create a new table is to insert a record into it:
.. code-block:: python
from sqlite_utils import Database
import sqlite3
db = Database(sqlite3.connect("/tmp/dogs.db"))
dogs = db["dogs"]
dogs.insert({
"name": "Cleo",
"twitter": "cleopaws",
"age": 3,
"is_good_dog": True,
})
This will automatically create a new table called "dogs" with the following schema::
CREATE TABLE dogs (
name TEXT,
twitter TEXT,
age INTEGER,
is_good_dog INTEGER
)
The column types are automatically derived from the types of the incoming data.
You can also specify a primary key by passing the ``pk=`` parameter to the ``.insert()`` call. This will only be obeyed if the record being inserted causes the table to be created:
.. code-block:: python
dogs.insert({
"id": 1,
"name": "Cleo",
"twitter": "cleopaws",
"age": 3,
"is_good_dog": True,
}, pk="id")
Introspection Introspection
============= =============
@ -21,13 +63,22 @@ If you have loaded an existing table, you can use introspection to find out more
>>> db["PlantType"] >>> db["PlantType"]
<sqlite_utils.db.Table at 0x10f5960b8> <sqlite_utils.db.Table at 0x10f5960b8>
The ``.count`` property shows the current number of rows (``select count(*) from table``)::
>>> db["PlantType"].count >>> db["PlantType"].count
3 3
>>> db["Street_Tree_List"].count
189144
The ``.columns`` property shows the columns in the table::
>>> db["PlantType"].columns >>> db["PlantType"].columns
[Column(cid=0, name='id', type='INTEGER', notnull=0, default_value=None, is_pk=1), [Column(cid=0, name='id', type='INTEGER', notnull=0, default_value=None, is_pk=1),
Column(cid=1, name='value', type='TEXT', notnull=0, default_value=None, is_pk=0)] Column(cid=1, name='value', type='TEXT', notnull=0, default_value=None, is_pk=0)]
>>> db["Street_Tree_List"].count
189144 The ``.foreign_keys`` property shows if the table has any foreign key relationships::
>>> db["Street_Tree_List"].foreign_keys >>> db["Street_Tree_List"].foreign_keys
[ForeignKey(table='Street_Tree_List', column='qLegalStatus', other_table='qLegalStatus', other_column='id'), [ForeignKey(table='Street_Tree_List', column='qLegalStatus', other_table='qLegalStatus', other_column='id'),
ForeignKey(table='Street_Tree_List', column='qCareAssistant', other_table='qCareAssistant', other_column='id'), ForeignKey(table='Street_Tree_List', column='qCareAssistant', other_table='qCareAssistant', other_column='id'),
@ -35,3 +86,33 @@ If you have loaded an existing table, you can use introspection to find out more
ForeignKey(table='Street_Tree_List', column='qSpecies', other_table='qSpecies', other_column='id'), ForeignKey(table='Street_Tree_List', column='qSpecies', other_table='qSpecies', other_column='id'),
ForeignKey(table='Street_Tree_List', column='qCaretaker', other_table='qCaretaker', other_column='id'), ForeignKey(table='Street_Tree_List', column='qCaretaker', other_table='qCaretaker', other_column='id'),
ForeignKey(table='Street_Tree_List', column='PlantType', other_table='PlantType', other_column='id')] ForeignKey(table='Street_Tree_List', column='PlantType', other_table='PlantType', other_column='id')]
The ``.schema`` property outputs the table's schema as a SQL string::
>>> print(db["Street_Tree_List"].schema)
CREATE TABLE "Street_Tree_List" (
"TreeID" INTEGER,
"qLegalStatus" INTEGER,
"qSpecies" INTEGER,
"qAddress" TEXT,
"SiteOrder" INTEGER,
"qSiteInfo" INTEGER,
"PlantType" INTEGER,
"qCaretaker" INTEGER,
"qCareAssistant" INTEGER,
"PlantDate" TEXT,
"DBH" INTEGER,
"PlotSize" TEXT,
"PermitNotes" TEXT,
"XCoord" REAL,
"YCoord" REAL,
"Latitude" REAL,
"Longitude" REAL,
"Location" TEXT
,
FOREIGN KEY ("PlantType") REFERENCES [PlantType](id),
FOREIGN KEY ("qCaretaker") REFERENCES [qCaretaker](id),
FOREIGN KEY ("qSpecies") REFERENCES [qSpecies](id),
FOREIGN KEY ("qSiteInfo") REFERENCES [qSiteInfo](id),
FOREIGN KEY ("qCareAssistant") REFERENCES [qCareAssistant](id),
FOREIGN KEY ("qLegalStatus") REFERENCES [qLegalStatus](id))

View file

@ -2,7 +2,7 @@ from setuptools import setup, find_packages
import io import io
import os import os
VERSION = "0.2" VERSION = "0.3"
def get_long_description(): def get_long_description():

View file

@ -104,6 +104,12 @@ class Table:
) )
return fks return fks
@property
def schema(self):
return self.db.conn.execute(
"select sql from sqlite_master where name = ?", (self.name,)
).fetchone()[0]
def create(self, columns, pk=None, foreign_keys=None): def create(self, columns, pk=None, foreign_keys=None):
columns = {name: value for (name, value) in columns.items()} columns = {name: value for (name, value) in columns.items()}
self.db.create_table(self.name, columns, pk=pk, foreign_keys=foreign_keys) self.db.create_table(self.name, columns, pk=pk, foreign_keys=foreign_keys)