Projet

Général

Profil

0001-management-add-command-to-ensure-all-JSONField-field.patch

Voir les différences:

Subject: [PATCH] management: add command to ensure all JSONField fields have
 correct db type (#43501)

 .../base/management/commands/ensure_jsonb.py  | 46 +++++++++++++++++++
 1 file changed, 46 insertions(+)
 create mode 100644 passerelle/base/management/commands/ensure_jsonb.py
passerelle/base/management/commands/ensure_jsonb.py
1
# passerelle - uniform access to multiple data sources and services
2
# Copyright (C) 2017  Entr'ouvert
3
#
4
# This program is free software: you can redistribute it and/or modify it
5
# under the terms of the GNU Affero General Public License as published
6
# by the Free Software Foundation, either version 3 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU Affero General Public License for more details.
13
#
14
# You should have received a copy of the GNU Affero General Public License
15
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
16

  
17
from django.db import connection
18
from django.apps import apps
19

  
20
from django.core.management.base import BaseCommand, CommandError
21
from django.contrib.postgres.fields import JSONField
22

  
23

  
24

  
25

  
26
class Command(BaseCommand):
27
    help = 'Ensure all JSON fields are of type jsonb'
28

  
29
    def handle(self, **options):
30
        for app in apps.get_models():
31
            for field in app._meta.get_fields():
32
                if isinstance(field, JSONField):
33
                    db_type = field.db_type(connection)
34
                    if db_type == 'jsonb':
35
                        continue
36
                    with connection.cursor() as cursor:
37
                        query = 'ALTER TABLE "%(schema_name)s"."%(table_name)s" ALTER COLUMN "%(column_name)s" TYPE jsonb USING "%(column_name)s"::jsonb'
38
                        params = {
39
                            'schema_name': connection.get_tenant().schema_name,
40
                            'table_name': app._meta.db_table,
41
                            'column_name': app._meta.get_field(field.name).column
42
                        }
43
                        try:
44
                            cursor.execute(query % params)
45
                        except Exception as e:
46
                            raise CommandError(e)
0
-