-
Notifications
You must be signed in to change notification settings - Fork 1
/
neo_my2pg_0.8beta.py
315 lines (256 loc) · 9.55 KB
/
neo_my2pg_0.8beta.py
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
#*************************************************************************/
#* MYSQL TO POSTGRESQL - MIGRATION SCRIPT */
#* ============================================ */
#* */
#* Copyright (c) 2006-2014 */
#* by Federico Campoli ([email protected]) */
#* */
#* This program is free software. You can redistribute it and/or modify */
#* it under the terms of the GNU General Public License as published by */
#* the Free Software Foundation; either version 2 of the License. */
#*************************************************************************/
# VERSION 0.8.2Beta
# copy structure and data from mysql to postgresql. works with phpbb
# script dependencies
# MySQLdb - http://sourceforge.net/projects/mysql-python
# Psycopg2
#import objects string and library for mysql and postgresql
import string
import MySQLdb
import psycopg2
import os
import re
import time
#connection opening to mysql and postgresql
#you need to change the next two lines for your connections
mysql_conn = MySQLdb.connect(db='MYSQLDB', host='MYSQLHOST', user='MYSQLUSR', passwd='MYSQLPASS')
pgsql_conn = psycopg2.connect("dbname=PGDATABASE user=PGUSER host=PGHOST password=PGPASS port=PGPORT")
# FUNCTION LIBRARY
def generate_data_type(v_field_type,v_lenght):
"generate the correct postgres ddl entry for datatype"
#field int8
if v_field_type=="mediumint" or v_field_type=="bigint":
v_field_pg_type="int8"
return v_field_pg_type
#field int4
if v_field_type=="tinyint" or v_field_type=="int" or v_field_type=="smallint":
v_field_pg_type="int4"
return v_field_pg_type
#field date
if v_field_type=="datetime":
v_field_pg_type="date"
return v_field_pg_type
#field text
if v_field_type=="enum" or v_field_type=="tinytext" or v_field_type=="longtext" or v_field_type=="mediumtext":
v_field_pg_type="text"
return v_field_pg_type
#field blob
if v_field_type=="longblob" or v_field_type=="mediumblob" or v_field_type=="blob" or v_field_type=="tinyblob":
v_field_pg_type="bytea"
return v_field_pg_type
#field float8
if v_field_type=="double":
v_field_pg_type="float8"
return v_field_pg_type
#field float4
if v_field_type=="float":
v_field_pg_type="float4"
return v_field_pg_type
return v_field_type+ " " + v_lenght
def escape_char(sql_string):
"escape ' character for sql string"
if sql_string!=None:
new_sql_string=string.replace(sql_string,"\\","")
new_sql_string=string.replace(new_sql_string,"'","''")
else:
new_sql_string=sql_string
return new_sql_string
def make_bytea(binary_string):
"generate a binary string escaped for bytea use"
if binary_string!=None:
binary_string=psycopg2.Binary(binary_string)
binary_string=str(binary_string)
else:
binary_string=''
return binary_string
#datadictionary for mysql to postgresql translation
dic_datatype={'mediumint':'int8','tinyint':'int2','smallint':'int2','int':'int8','varchar':'varchar','bigint':'int8','text':'text','char':'char','datetime':'date','date':'date','longtext':'text','tinytext':'text','tinyblob':'bytea','mediumblob':'bytea','longblob':'bytea','blob':'bytea'}
dic_datavalue={'None':'Null','CURRENT_TIMESTAMP':'CURRENT_TIMESTAMP'}
dic_null={'YES':'NULL','':'NOT NULL'}
#variable multi read.
i_multi_read=10000
#MIGRATION OF TABLE STRUCTURE
#cursor to mysql
c_mys = mysql_conn.cursor()
#cursor to postgresql
c_pgs = pgsql_conn.cursor()
#MYSQL SHOW DATA DICTIONARY
c_mys.execute('show tables;')
str_l_tab=c_mys.fetchall()
#DROP AND GENERATE TABLES ON THE POSTGRESQL TARGET DATABASE
for table_name in str_l_tab:
c_mys.execute('describe '+table_name[0]+';')
str_d_tab=c_mys.fetchall()
#drop table
try:
v_drop_table_pg='DROP TABLE '+table_name[0]+' ;'
c_pgs.execute(v_drop_table_pg)
c_pgs.execute('commit;')
except:
print "Error: PG > Drop Table "+table_name[0]+" is not possible"
c_pgs.execute('commit;')
print "Notice: PG > Create Table: "+table_name[0]
v_ddl_pg='CREATE TABLE '+table_name[0]+' '
v_ddl_pg+='('
#generate DDL for table definition
for field in str_d_tab:
t_field_type = string.split(field[1])
#extract data type and attrib for current field
t_field_len_type = string.split(t_field_type[0],'(')
str_field_type = t_field_len_type[0]
try:
str_field_attr = t_field_type [1]
except:
str_field_attr=""
#extract lenght of current field
try:
str_field_lengt="("+str(string.split(t_field_len_type [1],')')[0])+")"
except:
str_field_lengt=""
v_ddl_pg+=str(field[0])+" "+generate_data_type(str(str_field_type),str(str_field_lengt))+", "
v_ddl_pg=v_ddl_pg[0:(len(v_ddl_pg)-2)]
v_ddl_pg+=');\n\r'
#create table
try:
c_pgs.execute(v_ddl_pg)
c_pgs.execute('commit;')
except:
print v_ddl_pg
#COPY DATA BETWEEN MYSQL AND POSTGRESQL DATABASES
for table_name in str_l_tab:
print "Notice: PG > importing data into table: " + table_name[0]
#extract how many records there are in the table
c_mys.execute('select count(*) as num_record from '+table_name[0]+';')
#calculate how many iteration needs for data transfer
lng_num_record=c_mys.fetchone()
i_num_read=lng_num_record[0]/i_multi_read
rng_num_read=range(i_num_read+1)
v_dml_pg=""
#copy data between tables
for rng_item in rng_num_read:
c_mys.execute('describe '+table_name[0]+';')
str_field_tab=c_mys.fetchall()
str_sql='select * from '+table_name[0]+' limit '+str(rng_item*i_multi_read)+', '+str(i_multi_read)+' ;'
c_mys.execute(str_sql)
v_dml_pg_def=""
v_dml_pg=""
try:
str_d_tab=c_mys.fetchall()
v_dml_pg='INSERT INTO '+table_name[0]+' VALUES '
for record in str_d_tab:
v_dml_pg=v_dml_pg+' ('
v_position=0
for value in record:
t_field_type=str_field_tab[v_position][1]
t_field_len_type = string.split(t_field_type,'(')
t_data_type=dic_datatype[t_field_len_type[0]]
try:
v_field_value = dic_datavalue[str(value)]
except:
if t_data_type=='bytea':
v_field_value = ""+make_bytea(str(value))+""
else:
v_field_value = "'"+escape_char(str(value))+"'"
v_dml_pg+=""+v_field_value +","
v_position=+1
v_dml_pg=v_dml_pg[0:(len(v_dml_pg)-1)]
v_dml_pg+="),"
v_dml_pg=v_dml_pg[:-1]
v_dml_pg+=";"
except:
print "Error: PG > Copy data for table "+table_name[0]+" is not possible"
try:
c_pgs.execute(v_dml_pg)
c_pgs.execute('commit;')
except:
print str_sql
print v_dml_pg
print "ERROR: PG > Error in insert into "+table_name[0]+" "
print str(time.ctime())+" - "+str(min(lng_num_record[0],(rng_item+1)*i_multi_read))+" records imported"
#CREATE SEQUENCES CONSTRAINTS AND INDEX
for table_name in str_l_tab:
print " Alter Table: " + table_name[0]
v_table_name=table_name[0]
#determine the table structure
c_mys.execute('describe '+table_name[0]+';')
str_desc_tab=c_mys.fetchall()
v_ddl_pri=""
for item in str_desc_tab:
#create sequence for auto_increment data type
if item[5]=='auto_increment':
try:
c_pgs.execute('DROP SEQUENCE '+table_name[0]+'_id_seq CASCADE;')
c_pgs.execute('commit;')
except:
print 'Error: PG > The sequence '+table_name[0]+' is not present'
try:
c_pgs.execute("CREATE SEQUENCE "+table_name[0]+"_id_seq INCREMENT 1 MINVALUE 1 MAXVALUE 9223372036854775807 START 1 CACHE 1;")
c_pgs.execute('commit;')
except:
print "Error: PG > Unable to create the sequence "+table_name[0]+"_id_seq"
v_alter_table="ALTER TABLE "+table_name[0]+" ALTER COLUMN "+item[0]+" SET DEFAULT nextval('"+table_name[0]+"_id_seq'::regclass);"
c_pgs.execute("select max("+item[0]+") from "+table_name[0])
v_max_seq=c_pgs.fetchone()
#reset sequence current value to max of auto_increment value
if str(v_max_seq[0])!='None':
print table_name[0]
v_max_seq=v_max_seq[0]+1
c_pgs.execute("ALTER SEQUENCE "+table_name[0]+"_id_seq RESTART WITH "+str(v_max_seq)+";")
c_pgs.execute('commit;')
c_pgs.execute(v_alter_table)
c_pgs.execute('commit;')
else:
try:
v_def_value = dic_datavalue[str(item[4])]
except:
v_def_value = str(item[4])
#alter column. set default value
if v_def_value!="":
try:
v_def_value=int(v_def_value)
except:
v_def_value="'"+str(v_def_value)+"'"
if v_def_value !="":
try:
v_alter_table="ALTER TABLE "+table_name[0]+" ALTER COLUMN "+item[0]+" SET DEFAULT "+ str(v_def_value)
#print v_alter_table
c_pgs.execute(v_alter_table)
c_pgs.execute('commit;')
except:
print "Error: PG > Unable to set default value"
print v_alter_table
#alter table. create primary keys and index on column
if item[3]=='PRI':
if v_ddl_pri=="":
v_ddl_pri=item[0]
else:
v_ddl_pri+=","+item[0]
elif item[3]=='MUL':
v_ddl_const="CREATE INDEX "+v_table_name+"_"+item[0]+"_IDX ON "+v_table_name+" USING btree ("+item[0]+");"
try:
c_pgs.execute(v_ddl_const)
c_pgs.execute('commit;')
except:
print "Error: PG > Unable to set primary key or index on "+v_table_name
print v_ddl_const
if v_ddl_pri!="":
v_ddl_const="ALTER TABLE "+v_table_name+" ADD CONSTRAINT "+v_table_name+"_pkey PRIMARY KEY ("+v_ddl_pri+");"
try:
c_pgs.execute(v_ddl_const)
c_pgs.execute('commit;')
except:
print "Error: PG > Unable to set primary key or index on "+v_table_name
print v_ddl_const
#closing connections
c_pgs.close()
c_mys.close()