-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysql_convert_table_collation
executable file
·163 lines (131 loc) · 4.69 KB
/
mysql_convert_table_collation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
#!/usr/bin/env python3
from configparser import ConfigParser
from optparse import OptionParser
import getpass
import sys
import os
try:
import MySQLdb
from MySQLdb.cursors import DictCursor
from MySQLdb._exceptions import OperationalError
except ModuleNotFoundError:
print("Module mysqlclient is missing, try installing python3-mysqldb package")
sys.exit()
#endtry
# ------------------------------------------------------------------------------
parser = OptionParser("Usage: %prog [OPTIONS] <database> <from_collation> <to_collation>")
def print_help(option, opt, value, parser):
parser.print_help()
sys.exit(0)
#enddef
parser.remove_option("-h")
parser.add_option("-?", "--help", action="callback", callback=print_help)
parser.add_option("-h", "--host",
dest="host", default="localhost", help="Connect to host.")
parser.add_option("-u", "--user", dest="user",
help="User for login if not current user.")
parser.add_option("-p", "--password", dest="ask_pass", action="store_true", default=False,
help="Ask for password to use when connecting to server.")
(options, args) = parser.parse_args()
if len(args) < 3:
parser.print_help()
sys.exit(1)
#endif
database = args[0]
from_collation = args[1]
to_collation = args[2]
# ------------------------------------------------------------------------------
connection_options = {
'db' : args[0],
'host' : options.host,
'user' : options.user or getpass.getuser(),
'cursorclass' : DictCursor
}
if options.ask_pass:
connection_options['passwd'] = getpass.getpass()
#endif
try:
db = MySQLdb.connect(**connection_options)
cursor = db.cursor()
except OperationalError as e:
if os.path.exists(os.path.expanduser("~/.my.cnf")):
config = ConfigParser()
config.read(os.path.expanduser("~/.my.cnf"))
if config.has_option('client', 'host'):
connection_options['host'] = config.get('client', 'host')
#endif
if config.has_option('client', 'user'):
connection_options['user'] = config.get('client', 'user')
#endif
if config.has_option('client', 'password'):
connection_options['passwd'] = config.get('client', 'password')
#endif
#endif
try:
db = MySQLdb.connect(**connection_options)
cursor = db.cursor()
except OperationalError as e:
print("%s: %s" % (e.args[0], e.args[1]))
sys.exit(1)
#endtry
#endtry
# ------------------------------------------------------------------------------
cursor.execute("""
SELECT CHARACTER_SET_NAME FROM information_schema.COLLATIONS WHERE COLLATION_NAME = %s
""", (from_collation,))
collation_info = cursor.fetchone()
if not collation_info:
print("Database doesn't support %s collation" % from_collation)
sys.exit(1)
#endif
from_charset = collation_info['CHARACTER_SET_NAME']
cursor.execute("""
SELECT CHARACTER_SET_NAME FROM information_schema.COLLATIONS WHERE COLLATION_NAME = %s
""", (to_collation,))
collation_info = cursor.fetchone()
if not collation_info:
print("Database doesn't support %s collation" % to_collation)
sys.exit(1)
#endif
to_charset = collation_info['CHARACTER_SET_NAME']
# ------------------------------------------------------------------------------
cursor.execute("""
SELECT DEFAULT_COLLATION_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = %s
""", (database,))
database_collation = cursor.fetchone()['DEFAULT_COLLATION_NAME']
if database_collation == from_collation:
sql = "ALTER DATABASE `%s` CHARACTER SET = %s COLLATE = %s;" % (
database, to_charset, to_collation
)
print(sql)
cursor.execute(sql)
#endif
# ------------------------------------------------------------------------------
cursor.execute("""
SELECT TABLE_NAME FROM information_schema.TABLES
WHERE TABLE_SCHEMA = %s AND TABLE_COLLATION = %s
""", (database, from_collation))
tables = cursor.fetchall()
for t in tables:
sql = ["CONVERT TO CHARACTER SET %s COLLATE %s" % (to_charset, to_collation)]
cursor.execute("SHOW FULL COLUMNS FROM `%s`" % t['TABLE_NAME'])
columns = cursor.fetchall()
for c in columns:
if c['Collation'] == from_collation:
sql.append("CHANGE `%s` `%s` %s CHARACTER SET %s COLLATE %s %s %s" % (
c['Field'], c['Field'], c['Type'], to_charset, to_collation,
"NULL" if c['Null'] == "YES" else "NOT NULL",
"DEFAULT '%s'" % c['Default'] if c['Default'] else ("DEFAULT NULL" if c['Null'] == "YES" else "")
))
elif c['Collation'] == "%s_bin" % from_charset:
sql.append("CHANGE `%s` `%s` %s CHARACTER SET %s COLLATE %s_bin %s %s" % (
c['Field'], c['Field'], c['Type'], to_charset, to_charset,
"NULL" if c['Null'] == "YES" else "NOT NULL",
"DEFAULT '%s'" % c['Default'] if c['Default'] else ("DEFAULT NULL" if c['Null'] == "YES" else "")
))
#endif
#endfor
sql = "ALTER TABLE `%s`\n\t%s;" % (t['TABLE_NAME'], ",\n\t".join(sql))
print(sql)
cursor.execute(sql)
#endfor