Added support for bytes and datetime.datetime

This commit is contained in:
Simon Willison 2019-01-24 18:59:21 -08:00
commit 6ad9037c96
2 changed files with 25 additions and 8 deletions

View file

@ -1,5 +1,6 @@
import sqlite3
from collections import namedtuple
import datetime
import json
Column = namedtuple(
@ -53,16 +54,20 @@ class Database:
key=lambda p: column_order.index(p[0]) if p[0] in column_order else 999
)
extra = ""
col_type_mapping = {
float: "FLOAT",
int: "INTEGER",
bool: "INTEGER",
str: "TEXT",
bytes.__class__: "BLOB",
bytes: "BLOB",
datetime.datetime: "TEXT",
None.__class__: "TEXT",
}
columns_sql = ",\n".join(
" [{col_name}] {col_type} {primary_key} {references}".format(
col_name=col_name,
col_type={
float: "FLOAT",
int: "INTEGER",
bool: "INTEGER",
str: "TEXT",
None.__class__: "TEXT",
}[col_type],
col_type=col_type_mapping[col_type],
primary_key=" PRIMARY KEY" if (pk == col_name) else "",
references=(
" REFERENCES [{other_table}]([{other_column}])".format(
@ -252,6 +257,8 @@ class Table:
t = int
elif {int, float, bool}.issuperset(types):
t = float
elif {bytes, str}.issuperset(types):
t = bytes
else:
t = str
column_types[key] = t

View file

@ -1,5 +1,6 @@
from sqlite_utils.db import Index
import collections
import datetime
import pytest
import json
@ -8,7 +9,14 @@ def test_create_table(fresh_db):
assert [] == fresh_db.table_names
table = fresh_db.create_table(
"test_table",
{"text_col": str, "float_col": float, "int_col": int, "bool_col": bool},
{
"text_col": str,
"float_col": float,
"int_col": int,
"bool_col": bool,
"bytes_col": bytes,
"datetime_col": datetime.datetime,
},
)
assert ["test_table"] == fresh_db.table_names
assert [
@ -16,6 +24,8 @@ def test_create_table(fresh_db):
{"name": "float_col", "type": "FLOAT"},
{"name": "int_col", "type": "INTEGER"},
{"name": "bool_col", "type": "INTEGER"},
{"name": "bytes_col", "type": "BLOB"},
{"name": "datetime_col", "type": "TEXT"},
] == [{"name": col.name, "type": col.type} for col in table.columns]