From f804690274ce1bd93cc9e173a9d3b393312666cb Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Wed, 29 Jul 2020 18:10:25 -0700 Subject: [PATCH] Support inserting UUID and memoryview, closes #128 --- sqlite_utils/db.py | 5 +++++ tests/test_create.py | 23 +++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/sqlite_utils/db.py b/sqlite_utils/db.py index d6b9ecf..ee26433 100644 --- a/sqlite_utils/db.py +++ b/sqlite_utils/db.py @@ -7,6 +7,7 @@ import itertools import json import os import pathlib +import uuid SQLITE_MAX_VARS = 999 @@ -40,11 +41,13 @@ COLUMN_TYPE_MAPPING = { str: "TEXT", bytes.__class__: "BLOB", bytes: "BLOB", + memoryview: "BLOB", datetime.datetime: "TEXT", datetime.date: "TEXT", datetime.time: "TEXT", decimal.Decimal: "FLOAT", None.__class__: "TEXT", + uuid.UUID: "TEXT", # SQLite explicit types "TEXT": "TEXT", "INTEGER": "INTEGER", @@ -1336,6 +1339,8 @@ def jsonify_if_needed(value): return json.dumps(value, default=repr) elif isinstance(value, (datetime.time, datetime.date, datetime.datetime)): return value.isoformat() + elif isinstance(value, uuid.UUID): + return str(value) else: return value diff --git a/tests/test_create.py b/tests/test_create.py index 22e4b7b..a84eb8d 100644 --- a/tests/test_create.py +++ b/tests/test_create.py @@ -13,6 +13,7 @@ import decimal import json import pathlib import pytest +import uuid from .utils import collapse_whitespace @@ -134,6 +135,11 @@ def test_create_table_with_not_null(fresh_db): ), ({"day": datetime.time(11, 0)}, [{"name": "day", "type": "TEXT"}]), ({"decimal": decimal.Decimal("1.2")}, [{"name": "decimal", "type": "FLOAT"}]), + ( + {"memoryview": memoryview(b"hello")}, + [{"name": "memoryview", "type": "BLOB"}], + ), + ({"uuid": uuid.uuid4()}, [{"name": "uuid", "type": "TEXT"}]), ), ) def test_create_table_from_example(fresh_db, example, expected_columns): @@ -674,6 +680,23 @@ def test_insert_dictionaries_and_lists_as_json(fresh_db, data_structure): assert data_structure == json.loads(row[1]) +def test_insert_uuid(fresh_db): + uuid4 = uuid.uuid4() + fresh_db["test"].insert({"uuid": uuid4}) + row = list(fresh_db["test"].rows)[0] + assert {"uuid"} == row.keys() + assert isinstance(row["uuid"], str) + assert row["uuid"] == str(uuid4) + + +def test_insert_memoryview(fresh_db): + fresh_db["test"].insert({"data": memoryview(b"hello")}) + row = list(fresh_db["test"].rows)[0] + assert {"data"} == row.keys() + assert isinstance(row["data"], bytes) + assert row["data"] == b"hello" + + def test_insert_thousands_using_generator(fresh_db): fresh_db["test"].insert_all( {"i": i, "word": "word_{}".format(i)} for i in range(10000)