Created
December 19, 2019 17:14
-
-
Save gormih/a24db8b4d0900dadb6d25c9c8607aea9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.core.management.base import BaseCommand, CommandError | |
from django.db import connection, connections | |
from django.db.utils import OperationalError | |
| |
| |
class Command(BaseCommand): | |
| |
def add_arguments(self, parser): | |
parser.add_argument('target_base', nargs='+', type=str) | |
| |
def handle(self, *args, **options): | |
excluded_tables = ['auth_group', | |
'auth_group_permissions', | |
'auth_permission', | |
'auth_user_groups', | |
'auth_user_user_permissions', | |
'django_admin_log', | |
'django_content_type'] | |
if not 'target_base' in options.keys(): | |
target_base = 'pg_will_be' | |
else: | |
target_base = options['target_base'][0] | |
print('Moving current base to database with alias: %s' % target_base) | |
source_db_cursor = connection.cursor() | |
target_db_cursor = connections[target_base].cursor() | |
tables = connection.introspection.table_names() | |
print('\n'.join(tables)) | |
for table in tables: | |
if table not in excluded_tables: | |
| |
source_db_cursor.execute('SELECT * FROM %s' % table) | |
headers = ','.join([d[0] for d in source_db_cursor.description]) | |
print('Colums in table %s : %s' % (table, headers)) | |
data = source_db_cursor.fetchall() | |
for d in data: | |
dd = '' | |
for val in d: | |
# Тут мы пытаемся перечислить все значения, в годном для SQL команды | |
# формате. Числа и bool должны быть без кавычек. str и всякие там unicode - в них же. | |
# А еще бывают "null", вместо них просто сразу запятая. | |
if type(val) not in (int, bool) and len(str(val)) > 0: | |
dd += '"%s"' % val | |
else: | |
dd += str(val) | |
dd += ',' | |
dd = dd[:-1] # Удаляем запятую, join() не удался :) | |
print('data: %s' % dd) | |
sql = 'INSERT INTO %s(%s) VALUES (%s)' % (table, headers, dd) | |
print(sql) | |
target_db_cursor.execute(sql) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment