source: rattail/rattail/db/types.py @ 95d55f4

Last change on this file since 95d55f4 was 95d55f4, checked in by Lance Edgar <ledgar@…>, 11 months ago

Add simple JSONTextDict data type for SQLAlchemy columns

for basic JSON awareness/conversion

  • Property mode set to 100644
File size: 2.0 KB
Line 
1# -*- coding: utf-8; -*-
2################################################################################
3#
4#  Rattail -- Retail Software Framework
5#  Copyright © 2010-2019 Lance Edgar
6#
7#  This file is part of Rattail.
8#
9#  Rattail is free software: you can redistribute it and/or modify it under the
10#  terms of the GNU General Public License as published by the Free Software
11#  Foundation, either version 3 of the License, or (at your option) any later
12#  version.
13#
14#  Rattail is distributed in the hope that it will be useful, but WITHOUT ANY
15#  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16#  FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
17#  details.
18#
19#  You should have received a copy of the GNU General Public License along with
20#  Rattail.  If not, see <http://www.gnu.org/licenses/>.
21#
22################################################################################
23"""
24Data Types
25"""
26
27from __future__ import unicode_literals, absolute_import
28
29import json
30
31from sqlalchemy import types
32
33from rattail.gpc import GPC
34
35
36class GPCType(types.TypeDecorator):
37    """
38    SQLAlchemy type engine for GPC data.
39    """
40
41    impl = types.BigInteger
42
43    def process_bind_param(self, value, dialect):
44        if value is None:
45            return None
46        return int(value)
47
48    def process_result_value(self, value, dialect):
49        if value is None:
50            return None
51        return GPC(value)
52
53
54class JSONTextDict(types.TypeDecorator):
55    """
56    SQLAlchemy type engine for JSON data.  Interprets "raw" text as JSON when
57    reading from DB, and writes JSON text back to DB.
58
59    Note that the Python value for a field with this type will appear as a dict.
60    """
61    impl = types.Text
62
63    def process_bind_param(self, value, dialect):
64        if value is not None:
65            value = json.dumps(value)
66        return value
67
68    def process_result_value(self, value, dialect):
69        if value is not None:
70            value = json.loads(value)
71        return value
Note: See TracBrowser for help on using the repository browser.