def backupConnections(): user_data_dir = mforms.App.get().get_user_data_folder() connections_path = os.path.join(user_data_dir, 'connections.xml') instances_path = os.path.join(user_data_dir, 'server_instances.xml') file_chooser = mforms.newFileChooser(mforms.Form.main_form(), mforms.SaveFile) file_chooser.set_title('Export Connections As') file_chooser.set_extensions('ZIP Files (*.zip)|*.zip', 'import') if file_chooser.run_modal() == mforms.ResultOk: backup_path = file_chooser.get_path() if isinstance(backup_path, unicode): backup_path = backup_path.encode('utf-8') try: backup_file = zipfile.ZipFile(backup_path, 'w', zipfile.ZIP_DEFLATED) except Exception: mforms.Utilities.show_error('Backup file creation error', 'Could not create the backup file. Please check path and permissions and try ' 'again.', 'OK', '', '') return 1 backup_file.write(connections_path, 'connections.xml') backup_file.write(instances_path, 'server_instances.xml') if mforms.Utilities.show_message('Connections saved', 'Your connections were successfully backed up to ' + backup_path, 'OK', '', 'Show File') == mforms.ResultOther: mforms.Utilities.reveal_file(backup_path) return 0
def _browse_files(self, option, title): form = mforms.newFileChooser(mforms.Form.main_form(), mforms.SaveFile) form.set_title(title) form.set_path(getattr(self, option + "_entry").get_string_value()) if form.run_modal(): getattr(self, option + "_entry").set_value(form.get_path()) setattr(self, option + "_check_duplicate", False)
def save_clicked(self): file_chooser = mforms.newFileChooser(self.main, mforms.OpenDirectory) if file_chooser.run_modal() == mforms.ResultOk: path = file_chooser.get_path() i = len(glob.glob(path + "/*_table.js")) unixTimestamp = time.strftime('%Y%m%d%H%M%S') for key in sorted(migrations): try: search_format = "*_{tableName}_table.js".format( tableName=migration_tables[key]) search = glob.glob(path + "/" + search_format) for file in search: with open(file, 'w+') as f: f.write(''.join(migrations[key])) if len(search) == 0: save_format = '{timestamp}_add_{tableName}_table.js'.format( timestamp=unixTimestamp, tableName=migration_tables[key]) with open(path + "/" + save_format, 'w+') as f: f.write(''.join(migrations[key])) i += 1 except IOError as e: mforms.Utilities.show_error( 'Save to File', 'Could not save to file "%s": %s' % (path, str(e)), 'OK', '', '')
def save_clicked(self): file_chooser = mforms.newFileChooser(self.main, mforms.OpenDirectory) if file_chooser.run_modal() == mforms.ResultOk: path = file_chooser.get_path() i = len(glob.glob(path + "/*_table.php")) now = datetime.datetime.now() for key in sorted(migrations): try: search_format = "*_create_{tableName}_table.php".format( tableName=migration_tables[key] ) search = glob.glob(path + "/" + search_format) for file in search: with open(file, 'w+') as f: f.write(''.join(migrations[key])) if len(search) == 0: components = migration_tables[key].split('_') save_format = 'Create{tableNameCamelCase}Table.php'.format( tableNameCamelCase=("".join(x.title() for x in components[0:])) ) with open(path + "/" + save_format, 'w+') as f: f.write(''.join(migrations[key])) i += 1 except IOError as e: mforms.Utilities.show_error( 'Save to File', 'Could not save to file "%s": %s' % (path, str(e)), 'OK', '', '' )
def backupConnections(): user_data_dir = mforms.App.get().get_user_data_folder() connections_path = os.path.join(user_data_dir, 'connections.xml') instances_path = os.path.join(user_data_dir, 'server_instances.xml') file_chooser = mforms.newFileChooser(mforms.Form.main_form(), mforms.SaveFile) file_chooser.set_title('Export Connections As') file_chooser.set_extensions('ZIP Files (*.zip)|*.zip', 'import') if file_chooser.run_modal() == mforms.ResultOk: backup_path = file_chooser.get_path() if isinstance(backup_path, unicode): backup_path = backup_path.encode('utf-8') try: backup_file = zipfile.ZipFile(backup_path, 'w', zipfile.ZIP_DEFLATED) except Exception: mforms.Utilities.show_error( 'Backup file creation error', 'Could not create the backup file. Please check path and permissions and try ' 'again.', 'OK', '', '') return 1 backup_file.write(connections_path, 'connections.xml') backup_file.write(instances_path, 'server_instances.xml') if mforms.Utilities.show_message( 'Connections saved', 'Your connections were successfully backed up to ' + backup_path, 'OK', '', 'Show File') == mforms.ResultOther: mforms.Utilities.reveal_file(backup_path) return 0
def save_clicked(self): file_chooser = mforms.newFileChooser(self.main, mforms.OpenDirectory) if file_chooser.run_modal() == mforms.ResultOk: path = file_chooser.get_path() i = len(glob.glob(path + "/*_table.php")) now = datetime.datetime.now() for key in sorted(migrations): try: search_format = "*_create_{tableName}_table.php".format( tableName=migration_tables[key]) search = glob.glob(path + "/" + search_format) for file in search: with open(file, 'w+') as f: f.write(''.join(migrations[key])) if len(search) == 0: save_format = '{year}_{month}_{day}_{number}_create_{tableName}_table.php'.format( year=now.strftime('%Y'), month=now.strftime('%m'), day=now.strftime('%d'), number=str(i).zfill(6), tableName=migration_tables[key]) with open(path + "/" + save_format, 'w+') as f: f.write(''.join(migrations[key])) i += 1 except IOError as e: mforms.Utilities.show_error( 'Save to File', 'Could not save to file "%s": %s' % (path, str(e)), 'OK', '', '')
def importRecordsetDataFromFile(resultset): file_chooser = mforms.newFileChooser(None, mforms.OpenFile) file_chooser.set_title('Import Recordset From CSV File') file_chooser.set_directory(os.path.expanduser('~')) file_chooser.set_extensions('CSV Files (*.csv)|*.csv', 'import') if file_chooser.run_modal(): with open(file_chooser.get_path(), 'rb') as import_file: ext = os.path.splitext(import_file.name)[1].lower() import_module = None if ext == '.csv': import csv as import_module elif ext == '.sql': pass # Here will go our not yet written .sql reader else: import csv as import_module if import_module: reader = import_module.reader(import_file) column_count = len(resultset.columns) type_classes = { 'string': str, 'int': int, 'real': float, 'blob': str, 'date': str, 'time': str, 'datetime': str, 'geo': str, } converters = tuple(type_classes[column.columnType] for column in resultset.columns) for row in reader: if len(row) < column_count: # Fill with default values row.extend(converter() for converter in converters[len(row):]) try: converted_values = [ converter(value) for converter, value in zip(converters, row) ] except ValueError: continue # TODO: log a warning here resultset.addNewRow() for column, value in enumerate(converted_values): if isinstance(value, str): resultset.setStringFieldValue(column, value) elif isinstance(value, int): resultset.setIntFieldValue(column, value) elif isinstance(value, float): resultset.setFloatFieldValue(column, value) else: resultset.setFieldNull(column) resultset.addNewRow( ) # needed in Windows to refresh display for last row return 0
def _browse_files(self): form = mforms.newFileChooser(mforms.Form.main_form(), mforms.SaveFile) form.set_title("Save SQL Script As") default_path = os.path.abspath(self._create_script_file.get_string_value()) # Use as starting directory the directory corresponding to the path stored in the text box if it exists # or use the home directory if it doesn't form.set_path(default_path if os.path.exists(default_path if os.path.isdir(default_path) else os.path.dirname(default_path)) else os.path.expanduser('~') ) if form.run_modal(): self._create_script_file.set_value(form.get_path()) self._check_file_duplicate = False
def save_clicked(self): file_chooser = mforms.newFileChooser(self.main, mforms.SaveFile) file_chooser.set_extensions('SQL Files (*.sql)|*.sql', 'sql') if file_chooser.run_modal() == mforms.ResultOk: path = file_chooser.get_path() text = self.sql_text.get_text(False) try: with open(path, 'w+') as f: f.write(text) except IOError as e: mforms.Utilities.show_error( 'Save to File', 'Could not save to file "%s": %s' % (path, str(e)), 'OK')
def _browse_files(self): form = mforms.newFileChooser(mforms.Form.main_form(), mforms.SaveFile) form.set_title("Save SQL Script As") default_path = os.path.abspath( self._create_script_file.get_string_value()) # Use as starting directory the directory corresponding to the path stored in the text box if it exists # or use the home directory if it doesn't form.set_path(default_path if os.path.exists( default_path if os.path.isdir(default_path) else os.path. dirname(default_path)) else os.path.expanduser('~')) if form.run_modal(): self._create_script_file.set_value(form.get_path()) self._check_file_duplicate = False
def importRecordsetDataFromFile(resultset): file_chooser = mforms.newFileChooser(None, mforms.OpenFile) file_chooser.set_title('Import Recordset From CSV File') file_chooser.set_directory(os.path.expanduser('~')) file_chooser.set_extensions('CSV Files (*.csv)|*.csv', 'import') if file_chooser.run_modal(): with open(file_chooser.get_path(), 'rb') as import_file: ext = os.path.splitext(import_file.name)[1].lower() import_module = None if ext == '.csv': import csv as import_module elif ext == '.sql': pass # Here will go our not yet written .sql reader else: import csv as import_module if import_module: reader = import_module.reader(import_file) column_count = len(resultset.columns) type_classes = { 'string':str, 'int':int, 'real':float, 'blob':str, 'date':str, 'time':str, 'datetime':str, 'geo':str, } converters = tuple(type_classes[column.columnType] for column in resultset.columns) for row in reader: if len(row) < column_count: # Fill with default values row.extend(converter() for converter in converters[len(row):]) try: converted_values = [ converter(value) for converter, value in zip(converters, row) ] except ValueError: continue # TODO: log a warning here resultset.addNewRow() for column, value in enumerate(converted_values): if isinstance(value, str): resultset.setStringFieldValue(column, value) elif isinstance(value, int): resultset.setIntFieldValue(column, value) elif isinstance(value, float): resultset.setFloatFieldValue(column, value) else: resultset.setFieldNull(column) resultset.addNewRow() # needed in Windows to refresh display for last row return 0
def browse_extra_behaviors_box(self): tBox = PropelForm.spaced_box(True) label = mforms.newLabel("extra behaviors") tBox.add(label, False, True) self.widgets['extra_behaviors_path'] = mforms.newTextEntry() self.widgets['extra_behaviors_path'].set_value(self.db.cache['extra_behaviors_path']) tBox.add(self.widgets['extra_behaviors_path'], True, True) self.widgets['extra_behaviors_file'] = mforms.newFileChooser(mforms.OpenFile) self.widgets['extra_behaviors_file'].set_extensions('Python files (*.py)|*.py','py') self.widgets['extra_behaviors_file'].set_title("extra behaviors file") browse = mforms.newButton() browse.set_text("Browse") browse.add_clicked_callback(lambda: self.browse_schema()) tBox.add(browse, False, True) label = mforms.newLabel("see http://m4z3.me/extrabehaviors for details") tBox.add(label, False, True) self.add_end(tBox, False, True)
def browse_schema_box(self): tBox = PropelForm.spaced_box(True) label = mforms.newLabel("external propel schema") tBox.add(label, False, True) self.widgets['external_schema_path'] = mforms.newTextEntry() tBox.add(self.widgets['external_schema_path'], True, True) self.widgets['external_schema_file'] = mforms.newFileChooser(mforms.OpenFile) self.widgets['external_schema_file'].set_extensions('XML files (*.xml)|*.xml','xml') self.widgets['external_schema_file'].set_title("external schema file") browse = mforms.newButton() browse.set_text("Browse") browse.add_clicked_callback(lambda: self.browse_schema()) tBox.add(browse, False, True) add = mforms.newButton() add.set_text("Add") add.add_clicked_callback(lambda: self.add_schema()) tBox.add(add, False, True) self.add(tBox, False, True)
def save_clicked(self): file_chooser = mforms.newFileChooser(self.main, mforms.OpenDirectory) if file_chooser.run_modal() == mforms.ResultOk: path = file_chooser.get_path() text = self.sql_text.get_text(False) i = 0 now = datetime.datetime.now() for mkey in sorted(migrations): try: with open(path + '/%s_%s_%s_%s_create_%s_table.php' % (now.strftime('%Y'), now.strftime('%m'), now.strftime('%d'), str(i).zfill(6), mkey), 'w+') as f: f.write(''.join(migrations[mkey])) i = i + 1 except IOError as e: mforms.Utilities.show_error( 'Save to File', 'Could not save to file "%s": %s' % (path, str(e)), 'OK')
def browse_schema_box(self): tBox = PropelForm.spaced_box(True) label = mforms.newLabel("export propel schema") tBox.add(label, False, True) self.widgets['export_schema_path'] = mforms.newTextEntry() self.widgets['export_schema_path'].set_value(self.db.cache['export_schema_path']) tBox.add(self.widgets['export_schema_path'], True, True) self.widgets['export_schema_file'] = mforms.newFileChooser(mforms.SaveFile) self.widgets['export_schema_file'].set_extensions('XML files (*.xml)|*.xml','xml') self.widgets['export_schema_file'].set_title("export schema file") browse = mforms.newButton() browse.set_text("Browse") browse.add_clicked_callback(lambda: self.browse_schema()) tBox.add(browse, False, True) save = mforms.newButton() save.set_text("Save") save.add_clicked_callback(lambda: self.save_schema()) tBox.add(save, False, True) self.add(tBox, False, True)
def save_clicked(self): file_chooser = mforms.newFileChooser(self.main, mforms.OpenFile) file_chooser.add_selector_option('name', 'label', 'options|*.*') if file_chooser.run_modal() == mforms.ResultOk: path = file_chooser.get_directory() i = len(glob.glob(path + "/*_table.php")) now = datetime.datetime.now() for key in sorted(migrations): try: search_format = "*_create_{tableName}_table.php".format( tableName=migration_tables[key]) search = glob.glob(path + "/" + search_format) for file in search: with open(file, 'w+') as f: f.write(''.join(migrations[key])) if len(search) == 0: save_format = '{year}_{month}_{day}_{number}_create_{tableName}_table.php'.format( year=now.strftime('%Y'), month=now.strftime('%m'), day=now.strftime('%d'), number=str(i).zfill(6), tableName=migration_tables[key]) with open(path + "/" + save_format, 'w+') as f: f.write(''.join(migrations[key])) i += 1 except IOError as e: mforms.Utilities.show_error( 'Save to File', 'Could not save to file "%s": %s' % (path, str(e)), 'OK', '', '') mforms.Utilities.show_message( 'Migration Files processed!', 'The process to save migrations file has ended, you can click "Finish" button', 'OK', '', '')
def save_clicked(self): file_chooser = mforms.newFileChooser(self.main, mforms.OpenDirectory) if file_chooser.run_modal() == mforms.ResultOk: path = file_chooser.get_path() text = self.sql_text.get_text(False) i = 0 now = datetime.datetime.now() for mkey in sorted(migrations): try: with open( path + '/%s_%s_%s_%s_create_%s_table.php' % (now.strftime('%Y'), now.strftime('%m'), now.strftime('%d'), str(i).zfill(6), mkey), 'w+') as f: f.write(''.join(migrations[mkey])) i = i + 1 except IOError as e: mforms.Utilities.show_error( 'Save to File', 'Could not save to file "%s": %s' % (path, str(e)), 'OK')
self.split_groups(node.get_string(1)))) import pprint f = open(self.output_path, "w+") f.write("variable_groups = ") pp = pprint.PrettyPrinter(indent=2, stream=f) pp.pprint(l) f.close() script_dir = os.getcwd() form = mforms.Form(None, 0) form.set_size(800, 600) file_chooser = mforms.newFileChooser(form, mforms.OpenDirectory) file_chooser.set_title('Choose the base directory') file_chooser.set_path(script_dir) file_chooser_result = file_chooser.run_modal() print "File chooser result: %s" % file_chooser_result if not file_chooser_result: sys.exit() temp_path = file_chooser.get_path() sys.path.append(temp_path) import variable_groups import status_groups import raw_opts import raw_vars
l.append((node.get_string(0).encode("utf-8"), self.split_groups(node.get_string(1)))) import pprint f = open(self.output_path, "w+") f.write("variable_groups = ") pp = pprint.PrettyPrinter(indent=2, stream=f) pp.pprint(l) f.close() script_dir = os.getcwd() form = mforms.Form(None, 0) form.set_size(800,600) file_chooser = mforms.newFileChooser(form, mforms.OpenDirectory) file_chooser.set_title('Choose the base directory') file_chooser.set_path(script_dir) file_chooser_result = file_chooser.run_modal() print "File chooser result: %s" % file_chooser_result if not file_chooser_result: sys.exit() temp_path = file_chooser.get_path() sys.path.append(temp_path) import variable_groups import status_groups import raw_opts import raw_vars
def choose_directory(self): file_chooser = mforms.newFileChooser(self, 3, 1) file_chooser.set_title("Choose a directory!") file_chooser.run_modal() self.pattern.set_value(file_chooser.get_path())
def restoreConnections(): def generate_unique_name(name, name_set): new_name = name idx = 1 while True: if not new_name in name_set: return new_name new_name = name + ' (%d)' % idx idx += 1 file_chooser = mforms.newFileChooser(mforms.Form.main_form(), mforms.OpenFile) file_chooser.set_title('Select a Connections Backup File') file_chooser.set_extensions('ZIP Files (*.zip)|*.zip', 'import') if file_chooser.run_modal(): backup_path = file_chooser.get_path() try: backup_file = zipfile.ZipFile(backup_path, 'r') try: instances_file = tempfile.NamedTemporaryFile(delete=False) instances_file.write(backup_file.read('server_instances.xml')) instances_file.close() connections_file = tempfile.NamedTemporaryFile(delete=False) connections_file.write(backup_file.read('connections.xml')) connections_file.close() except KeyError, error: mforms.Utilities.show_error( 'Restore Connections Error', 'The selected file is not a valid backup file ' 'or the file is corrupted: %s.' % error.message, 'OK', '', '') grt.log_error( 'restoreConnections', 'The selected file is not a valid backup file ' 'or the file is corrupted: %s.' % error.message) return instances = grt.unserialize(instances_file.name) connections = grt.unserialize(connections_file.name) if not isinstance(instances, grt.List) or not isinstance( connections, grt.List): mforms.Utilities.show_error( 'Restore Connections Error', 'The selected file is not a valid backup file ' 'or the file is corrupted.', 'OK', '', '') grt.log_error( 'restoreConnections', 'The selected file is not a valid backup file or the file is corrupted.' ) return inserted_connections = {} existent_connection_names = set( conn.name for conn in grt.root.wb.rdbmsMgmt.storedConns) for candidate_connection in connections: new_name = generate_unique_name(candidate_connection.name, existent_connection_names) if new_name != candidate_connection.name: candidate_connection.name = new_name existent_connection_names.add(candidate_connection.name) old_id = candidate_connection.__id__ candidate_connection = candidate_connection.shallow_copy() inserted_connections[old_id] = candidate_connection grt.root.wb.rdbmsMgmt.storedConns.append(candidate_connection) existent_instance_names = set( instance.name for instance in grt.root.wb.rdbmsMgmt.storedInstances) previous_instances_conns = set() for candidate_instance in instances: if candidate_instance.connection.__id__ in previous_instances_conns: continue # Skip instances whose connections are associated to previously processed instances previous_instances_conns.add( candidate_instance.connection.__id__) new_name = generate_unique_name(candidate_instance.name, existent_instance_names) if new_name != candidate_instance.name: candidate_instance.name = new_name existent_instance_names.add(candidate_instance.name) new_conn = inserted_connections.get( candidate_instance.connection.__id__, None) candidate_instance = candidate_instance.shallow_copy() candidate_instance.connection = new_conn grt.root.wb.rdbmsMgmt.storedInstances.append( candidate_instance) grt.modules.Workbench.refreshHomeConnections() grt.modules.Workbench.saveConnections() grt.modules.Workbench.saveInstances() except zipfile.BadZipfile, error: mforms.Utilities.show_error( 'Restore Connections Error', 'The selected file is not a valid backup file ' 'or the file is corrupted.', 'OK', '', '') grt.log_error( 'restoreConnections', 'The selected file is not a valid backup file or the file is corrupted: %s' % error)
def restoreConnections(): def generate_unique_name(name, name_set): new_name = name idx = 1 while True: if not new_name in name_set: return new_name new_name = name + ' (%d)' % idx idx += 1 file_chooser = mforms.newFileChooser(mforms.Form.main_form(), mforms.OpenFile) file_chooser.set_title('Select a Connections Backup File') file_chooser.set_extensions('ZIP Files (*.zip)|*.zip', 'import') if file_chooser.run_modal(): backup_path = file_chooser.get_path() try: backup_file = zipfile.ZipFile(backup_path, 'r') try: instances_file = tempfile.NamedTemporaryFile(delete=False) instances_file.write(backup_file.read('server_instances.xml')) instances_file.close() connections_file = tempfile.NamedTemporaryFile(delete=False) connections_file.write(backup_file.read('connections.xml')) connections_file.close() except KeyError, error: mforms.Utilities.show_error('Restore Connections Error', 'The selected file is not a valid backup file ' 'or the file is corrupted: %s.' % error.message, 'OK', '', '') grt.log_error('restoreConnections', 'The selected file is not a valid backup file ' 'or the file is corrupted: %s.' % error.message) return instances = grt.unserialize(instances_file.name) connections = grt.unserialize(connections_file.name) if not isinstance(instances, grt.List) or not isinstance(connections, grt.List): mforms.Utilities.show_error('Restore Connections Error', 'The selected file is not a valid backup file ' 'or the file is corrupted.', 'OK', '', '') grt.log_error('restoreConnections', 'The selected file is not a valid backup file or the file is corrupted.') return inserted_connections = {} existent_connection_names = set(conn.name for conn in grt.root.wb.rdbmsMgmt.storedConns) for candidate_connection in connections: new_name = generate_unique_name(candidate_connection.name, existent_connection_names) if new_name != candidate_connection.name: candidate_connection.name = new_name existent_connection_names.add(candidate_connection.name) old_id = candidate_connection.__id__ candidate_connection = candidate_connection.shallow_copy() inserted_connections[old_id] = candidate_connection grt.root.wb.rdbmsMgmt.storedConns.append(candidate_connection) existent_instance_names = set(instance.name for instance in grt.root.wb.rdbmsMgmt.storedInstances) previous_instances_conns = set() for candidate_instance in instances: if candidate_instance.connection.__id__ in previous_instances_conns: continue # Skip instances whose connections are associated to previously processed instances previous_instances_conns.add(candidate_instance.connection.__id__) new_name = generate_unique_name(candidate_instance.name, existent_instance_names) if new_name != candidate_instance.name: candidate_instance.name = new_name existent_instance_names.add(candidate_instance.name) new_conn = inserted_connections.get(candidate_instance.connection.__id__, None) candidate_instance = candidate_instance.shallow_copy() candidate_instance.connection = new_conn grt.root.wb.rdbmsMgmt.storedInstances.append(candidate_instance) grt.modules.Workbench.refreshHomeConnections() grt.modules.Workbench.saveConnections() grt.modules.Workbench.saveInstances() except zipfile.BadZipfile, error: mforms.Utilities.show_error('Restore Connections Error', 'The selected file is not a valid backup file ' 'or the file is corrupted.', 'OK', '', '') grt.log_error('restoreConnections', 'The selected file is not a valid backup file or the file is corrupted: %s' % error)
def restoreConnections(): def generate_unique_name(name, name_set): new_name = name idx = 1 while True: if not new_name in name_set: return new_name new_name = name + ' (%d)' % idx idx += 1 file_chooser = mforms.newFileChooser(mforms.Form.main_form(), mforms.OpenFile) file_chooser.set_title('Select a Connections Backup File') file_chooser.set_extensions('ZIP Files (*.zip)|*.zip', 'import') if file_chooser.run_modal(): backup_path = file_chooser.get_path() try: backup_file = zipfile.ZipFile(backup_path, 'r') try: instances_file = tempfile.NamedTemporaryFile(delete=False) instances_file.write(backup_file.read('server_instances.xml')) instances_file.close() connections_file = tempfile.NamedTemporaryFile(delete=False) connections_file.write(backup_file.read('connections.xml')) connections_file.close() except KeyError, error: mforms.Utilities.show_error('Restore Connections Error', 'The selected file is not a valid backup file ' 'or the file is corrupted: %s.' % error.message, 'OK', '', '') grt.log_error('restoreConnections', 'The selected file is not a valid backup file ' 'or the file is corrupted: %s.' % error.message) return connections = grt.unserialize(connections_file.name) if not isinstance(connections, grt.List): mforms.Utilities.show_error('Restore Connections Error', 'The selected file is not a valid backup file ' 'or the file is corrupted.', 'OK', '', '') grt.log_error('restoreConnections', 'The selected archive does not have a valid connection backup file.\n') return inserted_connections = {} existent_connection_names = set(conn.name for conn in grt.root.wb.rdbmsMgmt.storedConns) existent_connection_ids = set(conn.__id__ for conn in grt.root.wb.rdbmsMgmt.storedConns) duplicate_connection_count = 0 for candidate_connection in connections: if candidate_connection.__id__ in existent_connection_ids: duplicate_connection_count = duplicate_connection_count + 1 continue candidate_connection.name = generate_unique_name(candidate_connection.name, existent_connection_names) existent_connection_names.add(candidate_connection.name) candidate_connection.owner = grt.root.wb.rdbmsMgmt inserted_connections[candidate_connection.__id__] = candidate_connection grt.root.wb.rdbmsMgmt.storedConns.append(candidate_connection) instances = grt.unserialize(instances_file.name) if not isinstance(instances, grt.List): mforms.Utilities.show_error('Restore Connections Error', 'The selected file is not a valid backup file ' 'or the file is corrupted.', 'OK', '', '') grt.log_error('restoreConnections', 'Workbench restored %i valid connections but server configuration data could not be found or is not valid.\n' % len(connections)) return existent_instance_names = set(instance.name for instance in grt.root.wb.rdbmsMgmt.storedInstances) previous_instances_conns = set() duplicated_instance_count = 0 for candidate_instance in instances: if candidate_instance.connection.__id__ in previous_instances_conns: duplicated_instance_count = duplicated_instance_count + 1 continue # Skip instances whose connections are associated to previously processed instances previous_instances_conns.add(candidate_instance.connection.__id__) candidate_instance.name = generate_unique_name(candidate_instance.name, existent_instance_names) existent_instance_names.add(candidate_instance.name) new_conn = inserted_connections.get(candidate_instance.connection.__id__, None) candidate_instance = candidate_instance.shallow_copy() candidate_instance.connection = new_conn grt.root.wb.rdbmsMgmt.storedInstances.append(candidate_instance) grt.modules.Workbench.refreshHomeConnections() grt.modules.Workbench.saveConnections() grt.modules.Workbench.saveInstances() if duplicate_connection_count > 0 or duplicated_instance_count > 0: message = [] message.append('Workbench detected ') if duplicate_connection_count > 0: message.append('%i duplicated connections' % duplicate_connection_count) if duplicated_instance_count > 0: if duplicate_connection_count > 0: message.append(' and ') message.append('%i duplicated instances' % duplicated_instance_count) message.append(', which were not restored.') mforms.Utilities.show_warning('Restore Connections', ''.join(message), 'OK', '', '') except zipfile.BadZipfile, error: mforms.Utilities.show_error('Restore Connections Error', 'The selected file is not a valid backup file ' 'or the file is corrupted.', 'OK', '', '') grt.log_error('restoreConnections', 'The selected file is not a valid backup file or the file is corrupted: %s\n' % error)