|
| 1 | +JSON Property |
| 2 | +============= |
| 3 | + |
| 4 | +GINO provides additional support to leverage native JSON type in the database as |
| 5 | +flexible GINO model fields. |
| 6 | + |
| 7 | +Quick Start |
| 8 | +----------- |
| 9 | + |
| 10 | +:: |
| 11 | + |
| 12 | + from gino import Gino |
| 13 | + from sqlalchemy.dialects.postgresql import JSONB |
| 14 | + |
| 15 | + db = Gino() |
| 16 | + |
| 17 | + class User(db.Model): |
| 18 | + __tablename__ = "users" |
| 19 | + |
| 20 | + id = db.Column(db.Integer, primary_key=True) |
| 21 | + name = db.Column(db.String) |
| 22 | + profile = db.Column(JSONB, nullable=False, server_default="{}") |
| 23 | + |
| 24 | + age = db.IntegerProperty() |
| 25 | + birthday = db.DateTimeProperty() |
| 26 | + |
| 27 | +The ``age`` and ``birthday`` are JSON properties stored in the ``profile`` column. You |
| 28 | +may use them the same way as a normal GINO model field:: |
| 29 | + |
| 30 | + u = await User.create(name="daisy", age=18) |
| 31 | + print(u.name, u.age) # daisy 18 |
| 32 | + |
| 33 | +.. note:: |
| 34 | + |
| 35 | + ``profile`` is the default column name for all JSON properties in a model. If you |
| 36 | + need a different column name for some JSON properties, you'll need to specify |
| 37 | + explicitly:: |
| 38 | + |
| 39 | + audit_profile = db.Column(JSON, nullable=False, server_default="{}") |
| 40 | + |
| 41 | + access_log = db.ArrayProperty(prop_name="audit_profile") |
| 42 | + abnormal_detected = db.BooleanProperty(prop_name="audit_profile") |
| 43 | + |
| 44 | +Using JSON properties in queries is supported:: |
| 45 | + |
| 46 | + await User.query.where(User.age > 16).gino.all() |
| 47 | + |
| 48 | +This is simply translated into a native JSON query like this: |
| 49 | + |
| 50 | +.. code-block:: plpgsql |
| 51 | +
|
| 52 | + SELECT users.id, users.name, users.profile |
| 53 | + FROM users |
| 54 | + WHERE CAST((users.profile ->> $1) AS INTEGER) > $2; -- ('age', 16) |
| 55 | +
|
| 56 | +Datetime type is very much the same:: |
| 57 | + |
| 58 | + from datetime import datetime |
| 59 | + |
| 60 | + await User.query.where(User.birthday > datetime(1990, 1, 1)).gino.all() |
| 61 | + |
| 62 | +And the generated SQL: |
| 63 | + |
| 64 | +.. code-block:: plpgsql |
| 65 | +
|
| 66 | + SELECT users.id, users.name, users.profile |
| 67 | + FROM users |
| 68 | + WHERE CAST((users.profile ->> $1) AS TIMESTAMP WITHOUT TIME ZONE) > $2 |
| 69 | + -- ('birthday', datetime.datetime(1990, 1, 1, 0, 0)) |
| 70 | +
|
| 71 | +Here's a list of all the supported JSON properties: |
| 72 | + |
| 73 | ++----------------------------+-----------------------------+-------------+---------------+ |
| 74 | +| JSON Property | Python type | JSON type | Database Type | |
| 75 | ++============================+=============================+=============+===============+ |
| 76 | +| :class:`.StringProperty` | :class:`str` | ``string`` | ``text`` | |
| 77 | ++----------------------------+-----------------------------+-------------+---------------+ |
| 78 | +| :class:`.IntegerProperty` | :class:`int` | ``number`` | ``int`` | |
| 79 | ++----------------------------+-----------------------------+-------------+---------------+ |
| 80 | +| :class:`.BooleanProperty` | :class:`bool` | ``boolean`` | ``boolean`` | |
| 81 | ++----------------------------+-----------------------------+-------------+---------------+ |
| 82 | +| :class:`.DateTimeProperty` | :class:`~datetime.datetime` | ``string`` | ``text`` | |
| 83 | ++----------------------------+-----------------------------+-------------+---------------+ |
| 84 | +| :class:`.ObjectProperty` | :class:`dict` | ``object`` | JSON | |
| 85 | ++----------------------------+-----------------------------+-------------+---------------+ |
| 86 | +| :class:`.ArrayProperty` | :class:`list` | ``array`` | JSON | |
| 87 | ++----------------------------+-----------------------------+-------------+---------------+ |
| 88 | + |
| 89 | + |
| 90 | +Hooks |
| 91 | +----- |
| 92 | + |
| 93 | +JSON property provides 2 instance-level hooks to customize the data:: |
| 94 | + |
| 95 | + class User(db.Model): |
| 96 | + __tablename__ = "users" |
| 97 | + |
| 98 | + id = db.Column(db.Integer, primary_key=True) |
| 99 | + profile = db.Column(JSONB, nullable=False, server_default="{}") |
| 100 | + |
| 101 | + age = db.IntegerProperty() |
| 102 | + |
| 103 | + @age.before_set |
| 104 | + def age(self, val): |
| 105 | + return val - 1 |
| 106 | + |
| 107 | + @age.after_get |
| 108 | + def age(self, val): |
| 109 | + return val + 1 |
| 110 | + |
| 111 | + u = await User.create(name="daisy", age=18) |
| 112 | + print(u.name, u.profile, u.age) # daisy {'age': 17} 18 |
| 113 | + |
| 114 | +And 1 class-level hook to customize the SQLAlchemy expression of the property:: |
| 115 | + |
| 116 | + class User(db.Model): |
| 117 | + __tablename__ = "users" |
| 118 | + |
| 119 | + id = db.Column(db.Integer, primary_key=True) |
| 120 | + profile = db.Column(JSONB, nullable=False, server_default="{}") |
| 121 | + |
| 122 | + height = db.JSONProperty() |
| 123 | + |
| 124 | + @height.expression |
| 125 | + def height(cls, exp): |
| 126 | + return exp.cast(db.Float) # CAST(profile -> 'height' AS FLOAT) |
| 127 | + |
| 128 | + |
| 129 | +Create Index on JSON Properties |
| 130 | +------------------------------- |
| 131 | + |
| 132 | +We'll need to use :meth:`~gino.declarative.declared_attr` to wait until the model class |
| 133 | +is initialized. The rest is very much the same as defining a usual index:: |
| 134 | + |
| 135 | + class User(db.Model): |
| 136 | + __tablename__ = "users" |
| 137 | + |
| 138 | + id = db.Column(db.Integer, primary_key=True) |
| 139 | + profile = db.Column(JSONB, nullable=False, server_default="{}") |
| 140 | + |
| 141 | + age = db.IntegerProperty() |
| 142 | + |
| 143 | + @db.declared_attr |
| 144 | + def age_idx(cls): |
| 145 | + return db.Index("age_idx", cls.age) |
| 146 | + |
| 147 | +This will lead to the SQL below executed if you run ``db.gino.create_all()``: |
| 148 | + |
| 149 | +.. code-block:: plpgsql |
| 150 | +
|
| 151 | + CREATE INDEX age_idx ON users (CAST(profile ->> 'age' AS INTEGER)); |
| 152 | +
|
| 153 | +.. warning:: |
| 154 | + |
| 155 | + Alembic doesn't support auto-generating revisions for functional indexes yet. You'll |
| 156 | + need to manually edit the revision. Please follow `this issue |
| 157 | + <https://github.com/sqlalchemy/alembic/issues/676>`__ for updates. |
0 commit comments