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  | 48 +++++++++++++++++
 tests/test_ensure_jsonbfields.py              | 52 +++++++++++++++++++
 2 files changed, 100 insertions(+)
 create mode 100644 passerelle/base/management/commands/ensure_jsonb.py
 create mode 100644 tests/test_ensure_jsonbfields.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.apps import apps
18
from django.db import connection
19

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

  
23

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

  
27
    def handle(self, **options):
28
        for app in apps.get_models():
29
            for field in app._meta.get_fields():
30
                if isinstance(field, JSONField):
31
                    table_name = app._meta.db_table
32
                    column_name = app._meta.get_field(field.name).column
33
                    with connection.cursor() as cursor:
34
                        query = 'SELECT table_schema, data_type FROM information_schema.columns WHERE table_name=%s AND column_name=%s'
35
                        cursor.execute(query, [table_name, column_name])
36
                        for schema_name, db_type in cursor.fetchall():
37
                            if db_type == 'jsonb':
38
                                continue
39
                            alter = 'ALTER TABLE "%(schema_name)s"."%(table_name)s" ALTER COLUMN "%(column_name)s" TYPE jsonb USING "%(column_name)s"::jsonb'
40
                            params = {
41
                                "schema_name": schema_name,
42
                                'table_name': table_name,
43
                                'column_name': column_name
44
                            }
45
                            try:
46
                                cursor.execute(alter % params)
47
                            except Exception as e:
48
                                raise CommandError(e)
tests/test_ensure_jsonbfields.py
1
# -*- coding: utf-8 -*-
2

  
3
import pytest
4

  
5
from django.db import connection
6
from django.core.files import File
7
from django.utils.six import BytesIO
8

  
9
from django.core.management import call_command
10

  
11
from passerelle.apps.csvdatasource.models import CsvDataSource
12
from passerelle.contrib.teamnet_axel.models import TeamnetAxel
13

  
14
pytestmark = pytest.mark.django_db
15

  
16
@pytest.fixture
17
def setup():
18

  
19
    def maker(columns_keynames='fam,id,lname,fname,sex', filename='data.csv', sheet_name='Feuille2',
20
              data=b''):
21
        csv = CsvDataSource.objects.create(csv_file=File(BytesIO(data), filename),
22
                                           sheet_name=sheet_name, columns_keynames=columns_keynames,
23
                                           slug='test', title='a title',
24
                                           description='a description')
25
        teamnet = TeamnetAxel.objects.create(slug='test', billing_regies={},
26
                                             wsdl_url='http://example.net/AXEL_WS/AxelWS.php?wsdl')
27
        return csv, teamnet
28
    return maker
29

  
30

  
31
def test_create_reference_column(setup):
32
    with connection.cursor() as cursor:
33
        query = "SELECT table_name, column_name, data_type FROM information_schema.columns WHERE column_name IN ('_dialect_options', 'billing_regies')"
34
        cursor.execute(query)
35

  
36
        # make sure the data_type is correct
37
        for line in cursor.fetchall():
38
            assert line[2] == 'jsonb'
39

  
40
        # alter columns
41
        cursor.execute('ALTER TABLE csvdatasource_csvdatasource ALTER COLUMN _dialect_options TYPE text USING _dialect_options::text')
42
        cursor.execute('ALTER TABLE teamnet_axel_teamnetaxel ALTER COLUMN billing_regies TYPE text USING billing_regies::text')
43

  
44
    call_command('ensure_jsonb')
45

  
46
    with connection.cursor() as cursor:
47
        query = "SELECT table_name, column_name, data_type FROM information_schema.columns WHERE column_name IN ('_dialect_options', 'billing_regies')"
48
        cursor.execute(query)
49

  
50
        # check the data_type is correct
51
        for line in cursor.fetchall():
52
            assert line[2] == 'jsonb'
0
-