Passed
Push — master ( a4c24d...9369e9 )
by Konrad
02:32
created

prepare_target_database_dump()   A

Complexity

Conditions 1

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 12
rs 10
c 0
b 0
f 0
cc 1
nop 0
1
#!/usr/bin/env python3
2
# -*- coding: future_fstrings -*-
3
4
"""
5
Process script
6
"""
7
import semantic_version
8
9
from db_sync_tool.utility import parser, mode, system, helper, output
10
from db_sync_tool.database import utility as database_utility
11
12
13
def create_origin_database_dump():
14
    """
15
    Creating the origin database dump file
16
    :return:
17
    """
18
    if not mode.is_import():
19
        parser.get_database_configuration(mode.Client.ORIGIN)
20
        database_utility.generate_database_dump_filename()
21
        helper.check_and_create_dump_dir(mode.Client.ORIGIN,
22
                                         helper.get_dump_dir(mode.Client.ORIGIN))
23
24
        _dump_file_path = helper.get_dump_dir(
25
            mode.Client.ORIGIN) + database_utility.database_dump_file_name
26
27
        _database_version = database_utility.get_database_version(mode.Client.ORIGIN)
28
        output.message(
29
            output.Subject.ORIGIN,
30
            f'Creating database dump {output.CliFormat.BLACK}{_dump_file_path}{output.CliFormat.ENDC}',
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (103/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
31
            True
32
        )
33
34
        _mysqldump_options = '--no-tablespaces '
35
        # Remove --no-tablespaces option for mysql < 5.6
36
        # @ToDo: Better option handling
37
        if not _database_version is None:
38
            if _database_version[0] == database_utility.DatabaseSystem.MYSQL and \
39
                    semantic_version.Version(_database_version[1]) < semantic_version.Version('5.6.0'):
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (103/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
40
                _mysqldump_options = ''
41
42
        # Run mysql dump command, e.g.
43
        # mysqldump --no-tablespaces -u'db' -p'db' -h'db1' -P'3306' 'db'  > /tmp/_db_08-10-2021_07-00.sql
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (105/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
44
        mode.run_command(
45
            helper.get_command(mode.Client.ORIGIN, 'mysqldump') + ' ' + _mysqldump_options +
46
            database_utility.generate_mysql_credentials(mode.Client.ORIGIN) + ' \'' +
47
            system.config[mode.Client.ORIGIN]['db']['name'] + '\' ' +
48
            database_utility.generate_ignore_database_tables() +
49
            database_utility.get_database_tables() +
50
            ' > ' + _dump_file_path,
51
            mode.Client.ORIGIN,
52
            skip_dry_run=True
53
        )
54
55
        database_utility.check_database_dump(mode.Client.ORIGIN, _dump_file_path)
56
        database_utility.count_tables(mode.Client.ORIGIN, _dump_file_path)
57
        prepare_origin_database_dump()
58
59
60
def import_database_dump():
61
    """
62
    Importing the selected database dump file
63
    :return:
64
    """
65
    if not system.config['is_same_client'] and not mode.is_import():
66
        prepare_target_database_dump()
67
68
    if system.config['clear_database']:
69
        output.message(
70
            output.Subject.TARGET,
71
            'Clearing database before import',
72
            True
73
        )
74
        clear_database(mode.Client.TARGET)
75
76
    database_utility.truncate_tables()
77
78
    if not system.config['keep_dump'] and not mode.is_dump():
79
80
        database_utility.get_database_version(mode.Client.TARGET)
81
82
        output.message(
83
            output.Subject.TARGET,
84
            'Importing database dump',
85
            True
86
        )
87
88
        if not mode.is_import():
89
            _dump_path = helper.get_dump_dir(
90
                mode.Client.TARGET) + database_utility.database_dump_file_name
91
        else:
92
            _dump_path = system.config['import']
93
94
        if not system.config['yes']:
95
            _host_name = helper.get_ssh_host_name(mode.Client.TARGET, True) if mode.is_remote(
96
                mode.Client.TARGET) else 'local'
97
98
            helper.confirm(
99
                output.message(
100
                    output.Subject.TARGET,
101
                    f'Are you sure, you want to import the dump file into {_host_name} database?',
102
                    False
103
                ),
104
                True
105
            )
106
107
        database_utility.check_database_dump(mode.Client.TARGET, _dump_path)
108
109
        import_database_dump_file(mode.Client.TARGET, _dump_path)
110
111
    if 'after_dump' in system.config['target']:
112
        _after_dump = system.config['target']['after_dump']
113
        output.message(
114
            output.Subject.TARGET,
115
            f'Importing after_dump file {output.CliFormat.BLACK}{_after_dump}{output.CliFormat.ENDC}',
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (102/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
116
            True
117
        )
118
        import_database_dump_file(mode.Client.TARGET, _after_dump)
119
120
    if 'post_sql' in system.config['target']:
121
        output.message(
122
            output.Subject.TARGET,
123
            f'Running addition post sql commands',
0 ignored issues
show
introduced by
Using an f-string that does not have any interpolated variables
Loading history...
124
            True
125
        )
126
        for _sql_command in system.config['target']['post_sql']:
127
            database_utility.run_database_command(mode.Client.TARGET, _sql_command, True)
128
129
130
def import_database_dump_file(client, filepath):
131
    """
132
    Import a database dump file
133
    :param client: String
134
    :param filepath: String
135
    :return:
136
    """
137
    if helper.check_file_exists(client, filepath):
138
        mode.run_command(
139
            helper.get_command(client, 'mysql') + ' ' +
140
            database_utility.generate_mysql_credentials(client) + ' \'' +
141
            system.config[client]['db']['name'] + '\' < ' + filepath,
142
            client,
143
            skip_dry_run=True
144
        )
145
146
147
def prepare_origin_database_dump():
148
    """
149
    Preparing the origin database dump file by compressing them as .tar.gz
150
    :return:
151
    """
152
    output.message(
153
        output.Subject.ORIGIN,
154
        'Compressing database dump',
155
        True
156
    )
157
    mode.run_command(
158
        helper.get_command(mode.Client.ORIGIN, 'tar') + ' cfvz ' + helper.get_dump_dir(
159
            mode.Client.ORIGIN) + database_utility.database_dump_file_name + '.tar.gz -C ' +
160
        helper.get_dump_dir(mode.Client.ORIGIN) + ' ' +
161
        database_utility.database_dump_file_name + ' > /dev/null',
162
        mode.Client.ORIGIN,
163
        skip_dry_run=True
164
    )
165
166
167
def prepare_target_database_dump():
168
    """
169
    Preparing the target database dump by the unpacked .tar.gz file
170
    :return:
171
    """
172
    output.message(output.Subject.TARGET, 'Extracting database dump', True)
173
    mode.run_command(
174
        helper.get_command('target', 'tar') + ' xzf ' + helper.get_dump_dir(mode.Client.TARGET) +
175
        database_utility.database_dump_file_name + '.tar.gz -C ' +
176
        helper.get_dump_dir(mode.Client.TARGET) + ' > /dev/null',
177
        mode.Client.TARGET,
178
        skip_dry_run=True
179
    )
180
181
182
def clear_database(client):
183
    """
0 ignored issues
show
Bug introduced by
A suspicious escape sequence \` was found. Did you maybe forget to add an r prefix?

Escape sequences in Python are generally interpreted according to rules similar to standard C. Only if strings are prefixed with r or R are they interpreted as regular expressions.

The escape sequence that was used indicates that you might have intended to write a regular expression.

Learn more about the available escape sequences. in the Python documentation.

Loading history...
184
    Clearing the database by dropping all tables
185
    https://www.techawaken.com/drop-tables-mysql-database/
186
187
    { mysql -hHOSTNAME -uUSERNAME -pPASSWORD -Nse 'show tables' DB_NAME; } |
188
    ( while read table; do if [ -z ${i+x} ]; then echo 'SET FOREIGN_KEY_CHECKS = 0;'; fi; i=1;
189
    echo "drop table \`$table\`;"; done;
190
    echo 'SET FOREIGN_KEY_CHECKS = 1;' ) |
191
    awk '{print}' ORS=' ' | mysql -hHOSTNAME -uUSERNAME -pPASSWORD DB_NAME;
192
193
    :param client: String
194
    :return:
195
    """
196
    mode.run_command(
197
        '{ ' + helper.get_command(client, 'mysql') + ' ' +
198
        database_utility.generate_mysql_credentials(client) +
199
        ' -Nse \'show tables\' \'' +
200
        system.config[client]['db']['name'] + '\'; }' +
201
        ' | ( while read table; do if [ -z ${i+x} ]; then echo \'SET FOREIGN_KEY_CHECKS = 0;\'; fi; i=1; ' +
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (108/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
202
        'echo "drop table \\`$table\\`;"; done; echo \'SET FOREIGN_KEY_CHECKS = 1;\' ) | awk \'{print}\' ORS=' ' | ' +
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (118/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
203
        helper.get_command(client, 'mysql') + ' ' +
204
        database_utility.generate_mysql_credentials(client) + ' ' +
205
        system.config[client]['db']['name'],
206
        client,
207
        skip_dry_run=True
208
    )
209