|
1 |
# fargo - document box
|
|
2 |
# Copyright (C) 2016-2022 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.db.migrations.operations.base import Operation
|
|
19 |
|
|
20 |
|
|
21 |
class EnsureJsonbType(Operation):
|
|
22 |
|
|
23 |
reversible = True
|
|
24 |
|
|
25 |
def __init__(self, model_name, field_name):
|
|
26 |
self.model_name = model_name
|
|
27 |
self.field_name = field_name
|
|
28 |
|
|
29 |
def state_forwards(self, app_label, state):
|
|
30 |
pass
|
|
31 |
|
|
32 |
def database_forwards(self, app_label, schema_editor, from_state, to_state):
|
|
33 |
if connection.vendor == 'postgresql':
|
|
34 |
model = from_state.apps.get_model(app_label, self.model_name)
|
|
35 |
table_name = model._meta.db_table
|
|
36 |
field = model._meta.get_field(self.field_name)
|
|
37 |
_, column_name = field.get_attname_column()
|
|
38 |
with schema_editor.connection.cursor() as cursor:
|
|
39 |
cursor.execute(
|
|
40 |
'ALTER TABLE {table} ALTER COLUMN {col} TYPE jsonb USING {col}::jsonb;'.format(
|
|
41 |
table=table_name, col=column_name
|
|
42 |
)
|
|
43 |
)
|
|
44 |
|
|
45 |
def database_backwards(self, app_label, schema_editor, from_state, to_state):
|
|
46 |
pass
|
|
47 |
|
|
48 |
def describe(self):
|
|
49 |
return "Migrate to postgres jsonb type"
|