This function is used to restore the schema. :param server: :param db_name: :param schema_name: :param sql_path: :return:
(server, db_name, schema_name, sql_path)
| 16 | |
| 17 | |
| 18 | def restore_schema(server, db_name, schema_name, sql_path): |
| 19 | """ |
| 20 | This function is used to restore the schema. |
| 21 | :param server: |
| 22 | :param db_name: |
| 23 | :param schema_name: |
| 24 | :param sql_path: |
| 25 | :return: |
| 26 | """ |
| 27 | schema_id = None |
| 28 | try: |
| 29 | connection = utils.get_db_connection(db_name, |
| 30 | server['username'], |
| 31 | server['db_password'], |
| 32 | server['host'], |
| 33 | server['port'], |
| 34 | server['sslmode'] |
| 35 | ) |
| 36 | |
| 37 | old_isolation_level = connection.isolation_level |
| 38 | utils.set_isolation_level(connection, 0) |
| 39 | pg_cursor = connection.cursor() |
| 40 | |
| 41 | with open(sql_path, 'r') as content_file: |
| 42 | sql = content_file.read() |
| 43 | # Replace hardcoded 'postgres' role with the actual test user |
| 44 | # so the restore works on systems without a 'postgres' role. |
| 45 | # Use qtIdent to properly quote usernames with special chars. |
| 46 | import re |
| 47 | from pgadmin.utils.driver.psycopg3 import Driver |
| 48 | username = Driver.qtIdent(None, server['username']) |
| 49 | sql = re.sub(r'\bOWNER [Tt][Oo] postgres\b', |
| 50 | 'OWNER TO ' + username, sql) |
| 51 | sql = re.sub(r'\bTO postgres\b', 'TO ' + username, sql) |
| 52 | sql = re.sub(r'\bFROM postgres\b', 'FROM ' + username, sql) |
| 53 | sql = re.sub(r'\bFOR postgres\b', 'FOR ' + username, sql) |
| 54 | sql = sql.replace('Owner: postgres', |
| 55 | 'Owner: ' + server['username']) |
| 56 | pg_cursor.execute(sql) |
| 57 | utils.set_isolation_level(connection, old_isolation_level) |
| 58 | connection.commit() |
| 59 | |
| 60 | SQL = """SELECT |
| 61 | nsp.oid |
| 62 | FROM |
| 63 | pg_catalog.pg_namespace nsp |
| 64 | WHERE nsp.nspname = '{0}'""".format(schema_name) |
| 65 | |
| 66 | pg_cursor.execute(SQL) |
| 67 | schema = pg_cursor.fetchone() |
| 68 | if schema: |
| 69 | schema_id = schema[0] |
| 70 | connection.close() |
| 71 | except Exception as e: |
| 72 | print(str(e)) |
| 73 | return False, schema_id |
| 74 | |
| 75 | return True, schema_id |