We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Add new method to return the columns for PostgreSQL datasources :electric_plug: :1234: 
When MindsDB creates a new PostgreSQL datasource we get information for columns by fetching all datasources. The problem here is that if datasource is big it takes a lot of time. We need a new get_columns method to return the columns name per datasource. The PR should include this method inside the PostgreSQL class .

## Steps :male_detective: :female_detective: 

- Implement in https://github.com/mindsdb/mindsdb/blob/staging/mindsdb/integrations/postgres/postgres.py#L37
- Push to staging branch

## Additional rewards :1st_place_medal: 

Each code PR brings  :three:  point for entry into the draw for a :computer:  Deep Learning Laptop powered by the NVIDIA RTX 3080 Max-Q GPU or other swag :shirt: :bear: .  For more info check out https://mindsdb.com/hacktoberfest/
 



--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `mindsdb/integrations/postgres/postgres.py`
Content:
```
1 from contextlib import closing
2 import pg8000
3 
4 from lightwood.api import dtype
5 from mindsdb.integrations.base import Integration
6 from mindsdb.utilities.log import log
7 
8 
9 class PostgreSQLConnectionChecker:
10     def __init__(self, **kwargs):
11         self.host = kwargs.get('host')
12         self.port = kwargs.get('port')
13         self.user = kwargs.get('user')
14         self.password = kwargs.get('password')
15         self.database = kwargs.get('database', 'postgres')
16 
17     def _get_connection(self):
18         return pg8000.connect(
19             database=self.database,
20             user=self.user,
21             password=self.password,
22             host=self.host,
23             port=self.port
24         )
25 
26     def check_connection(self):
27         try:
28             con = self._get_connection()
29             with closing(con) as con:
30                 con.run('select 1;')
31             connected = True
32         except Exception:
33             connected = False
34         return connected
35 
36 
37 class PostgreSQL(Integration, PostgreSQLConnectionChecker):
38     def __init__(self, config, name, db_info):
39         super().__init__(config, name)
40         self.user = db_info.get('user')
41         self.password = db_info.get('password')
42         self.host = db_info.get('host')
43         self.port = db_info.get('port')
44         self.database = db_info.get('database', 'postgres')
45 
46     def _to_postgres_table(self, dtype_dict, predicted_cols, columns):
47         subtype_map = {
48             dtype.integer: ' int8',
49             dtype.float: 'float8',
50             dtype.binary: 'bool',
51             dtype.date: 'date',
52             dtype.datetime: 'timestamp',
53             dtype.binary: 'text',
54             dtype.categorical: 'text',
55             dtype.tags: 'text',
56             dtype.image: 'text',
57             dtype.video: 'text',
58             dtype.audio: 'text',
59             dtype.short_text: 'text',
60             dtype.rich_text: 'text',
61             dtype.array: 'text'
62         }
63 
64         column_declaration = []
65         for name in columns:
66             try:
67                 col_subtype = dtype_dict[name]
68                 new_type = subtype_map[col_subtype]
69                 column_declaration.append(f' "{name}" {new_type} ')
70                 if name in predicted_cols:
71                     column_declaration.append(f' "{name}_original" {new_type} ')
72             except Exception as e:
73                 log.error(f'Error: can not determine postgres data type for column {name}: {e}')
74 
75         return column_declaration
76 
77     def _escape_table_name(self, name):
78         return '"' + name.replace('"', '""') + '"'
79 
80     def _query(self, query):
81         con = self._get_connection()
82         with closing(con) as con:
83 
84             cur = con.cursor()
85             res = True
86             cur.execute(query)
87 
88             try:
89                 rows = cur.fetchall()
90                 keys = [k[0] if isinstance(k[0], str) else k[0].decode('ascii') for k in cur.description]
91                 res = [dict(zip(keys, row)) for row in rows]
92             except Exception:
93                 pass
94 
95             con.commit()
96 
97         return res
98 
99     def setup(self):
100         user = f"{self.config['api']['mysql']['user']}_{self.name}"
101         password = self.config['api']['mysql']['password']
102         host = self.config['api']['mysql']['host']
103         port = self.config['api']['mysql']['port']
104 
105         try:
106             self._query('''
107                 DO $$
108                 begin
109                     if not exists (SELECT 1 FROM pg_extension where extname = 'mysql_fdw') then
110                         CREATE EXTENSION mysql_fdw;
111                     end if;
112                 END
113                 $$;
114             ''')
115         except Exception:
116             print('Error: cant find or activate mysql_fdw extension for PostgreSQL.')
117 
118         self._query(f'DROP SCHEMA IF EXISTS {self.mindsdb_database} CASCADE')
119 
120         self._query(f"DROP USER MAPPING IF EXISTS FOR {self.user} SERVER server_{self.mindsdb_database}")
121 
122         self._query(f'DROP SERVER IF EXISTS server_{self.mindsdb_database} CASCADE')
123 
124         self._query(f'''
125             CREATE SERVER server_{self.mindsdb_database}
126                 FOREIGN DATA WRAPPER mysql_fdw
127                 OPTIONS (host '{host}', port '{port}');
128         ''')
129 
130         self._query(f'''
131            CREATE USER MAPPING FOR {self.user}
132                 SERVER server_{self.mindsdb_database}
133                 OPTIONS (username '{user}', password '{password}');
134         ''')
135 
136         self._query(f'CREATE SCHEMA {self.mindsdb_database}')
137 
138         q = f"""
139             CREATE FOREIGN TABLE IF NOT EXISTS {self.mindsdb_database}.predictors (
140                 name text,
141                 status text,
142                 accuracy text,
143                 predict text,
144                 select_data_query text,
145                 external_datasource text,
146                 training_options text
147             )
148             SERVER server_{self.mindsdb_database}
149             OPTIONS (dbname 'mindsdb', table_name 'predictors');
150         """
151         self._query(q)
152 
153         q = f"""
154             CREATE FOREIGN TABLE IF NOT EXISTS {self.mindsdb_database}.commands (
155                 command text
156             ) SERVER server_{self.mindsdb_database}
157             OPTIONS (dbname 'mindsdb', table_name 'commands');
158         """
159         self._query(q)
160 
161     def register_predictors(self, model_data_arr):
162         for model_meta in model_data_arr:
163             name = model_meta['name']
164             predict = model_meta['predict']
165             if not isinstance(predict, list):
166                 predict = [predict]
167             columns_sql = ','.join(self._to_postgres_table(
168                 model_meta['dtype_dict'],
169                 predict,
170                 list(model_meta['dtype_dict'].keys())
171             ))
172             columns_sql += ',"select_data_query" text'
173             columns_sql += ',"external_datasource" text'
174             for col in predict:
175                 columns_sql += f',"{col}_confidence" float8'
176                 if model_meta['dtype_dict'][col] in (dtype.integer, dtype.float):
177                     columns_sql += f',"{col}_min" float8'
178                     columns_sql += f',"{col}_max" float8'
179                 columns_sql += f',"{col}_explain" text'
180 
181             self.unregister_predictor(name)
182             q = f"""
183                 CREATE FOREIGN TABLE {self.mindsdb_database}.{self._escape_table_name(name)} (
184                     {columns_sql}
185                 ) SERVER server_{self.mindsdb_database}
186                 OPTIONS (dbname 'mindsdb', table_name '{name}');
187             """
188             self._query(q)
189 
190     def unregister_predictor(self, name):
191         q = f"""
192             DROP FOREIGN TABLE IF EXISTS {self.mindsdb_database}.{self._escape_table_name(name)};
193         """
194         self._query(q)
195 
196     def get_row_count(self, query):
197         q = f""" 
198             SELECT COUNT(*) as count
199             FROM ({query}) as query;"""
200         result = self._query(q)
201         return result[0]['count']
202     
203     def get_tables_list(self):
204         q = f""" SELECT table_schema, table_name
205                       FROM information_schema.tables
206                       WHERE table_schema != 'pg_catalog'
207                       AND table_schema != 'information_schema'
208                       ORDER BY table_schema, table_name"""
209         tables_list = self._query(q)
210         tables= [f"{table['table_schema']}.{table['table_name']}" for table in tables_list]
211         return tables
212 
213     def get_columns(self):
214         q = f"""SELECT column_name, table_name
215 		FROM information_schema.columns
216 		WHERE table_schema NOT IN ('information_schema', 'pg_catalog')
217 		ORDER BY column_name, table_name;"""
218         columns_list = self._query(q)
219         columns = [f"{columns[0]}.{columns[1]}" for columns in columns_list]
220         return columns
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/mindsdb/integrations/postgres/postgres.py b/mindsdb/integrations/postgres/postgres.py
--- a/mindsdb/integrations/postgres/postgres.py
+++ b/mindsdb/integrations/postgres/postgres.py
@@ -210,11 +210,11 @@
         tables= [f"{table['table_schema']}.{table['table_name']}" for table in tables_list]
         return tables
 
-    def get_columns(self):
-        q = f"""SELECT column_name, table_name
-		FROM information_schema.columns
-		WHERE table_schema NOT IN ('information_schema', 'pg_catalog')
-		ORDER BY column_name, table_name;"""
-        columns_list = self._query(q)
-        columns = [f"{columns[0]}.{columns[1]}" for columns in columns_list]
-        return columns
\ No newline at end of file
+    def get_columns(self,query):
+        q = f"""SELECT * from ({query}) LIMIT 1;"""
+        query_response = self._query(q)
+        if len(query_response) > 0:
+            columns = list(query_response[0].keys())
+            return columns
+        else:
+            return []
\ No newline at end of file

{"golden_diff": "diff --git a/mindsdb/integrations/postgres/postgres.py b/mindsdb/integrations/postgres/postgres.py\n--- a/mindsdb/integrations/postgres/postgres.py\n+++ b/mindsdb/integrations/postgres/postgres.py\n@@ -210,11 +210,11 @@\n         tables= [f\"{table['table_schema']}.{table['table_name']}\" for table in tables_list]\n         return tables\n \n-    def get_columns(self):\n-        q = f\"\"\"SELECT column_name, table_name\n-\t\tFROM information_schema.columns\n-\t\tWHERE table_schema NOT IN ('information_schema', 'pg_catalog')\n-\t\tORDER BY column_name, table_name;\"\"\"\n-        columns_list = self._query(q)\n-        columns = [f\"{columns[0]}.{columns[1]}\" for columns in columns_list]\n-        return columns\n\\ No newline at end of file\n+    def get_columns(self,query):\n+        q = f\"\"\"SELECT * from ({query}) LIMIT 1;\"\"\"\n+        query_response = self._query(q)\n+        if len(query_response) > 0:\n+            columns = list(query_response[0].keys())\n+            return columns\n+        else:\n+            return []\n\\ No newline at end of file\n", "issue": "Add new method to return the columns for PostgreSQL datasources :electric_plug: :1234: \nWhen MindsDB creates a new PostgreSQL datasource we get information for columns by fetching all datasources. The problem here is that if datasource is big it takes a lot of time. We need a new get_columns method to return the columns name per datasource. The PR should include this method inside the PostgreSQL class .\r\n\r\n## Steps :male_detective: :female_detective: \r\n\r\n- Implement in https://github.com/mindsdb/mindsdb/blob/staging/mindsdb/integrations/postgres/postgres.py#L37\r\n- Push to staging branch\r\n\r\n## Additional rewards :1st_place_medal: \r\n\r\nEach code PR brings  :three:  point for entry into the draw for a :computer:  Deep Learning Laptop powered by the NVIDIA RTX 3080 Max-Q GPU or other swag :shirt: :bear: .  For more info check out https://mindsdb.com/hacktoberfest/\r\n \r\n\r\n\n", "before_files": [{"content": "from contextlib import closing\nimport pg8000\n\nfrom lightwood.api import dtype\nfrom mindsdb.integrations.base import Integration\nfrom mindsdb.utilities.log import log\n\n\nclass PostgreSQLConnectionChecker:\n    def __init__(self, **kwargs):\n        self.host = kwargs.get('host')\n        self.port = kwargs.get('port')\n        self.user = kwargs.get('user')\n        self.password = kwargs.get('password')\n        self.database = kwargs.get('database', 'postgres')\n\n    def _get_connection(self):\n        return pg8000.connect(\n            database=self.database,\n            user=self.user,\n            password=self.password,\n            host=self.host,\n            port=self.port\n        )\n\n    def check_connection(self):\n        try:\n            con = self._get_connection()\n            with closing(con) as con:\n                con.run('select 1;')\n            connected = True\n        except Exception:\n            connected = False\n        return connected\n\n\nclass PostgreSQL(Integration, PostgreSQLConnectionChecker):\n    def __init__(self, config, name, db_info):\n        super().__init__(config, name)\n        self.user = db_info.get('user')\n        self.password = db_info.get('password')\n        self.host = db_info.get('host')\n        self.port = db_info.get('port')\n        self.database = db_info.get('database', 'postgres')\n\n    def _to_postgres_table(self, dtype_dict, predicted_cols, columns):\n        subtype_map = {\n            dtype.integer: ' int8',\n            dtype.float: 'float8',\n            dtype.binary: 'bool',\n            dtype.date: 'date',\n            dtype.datetime: 'timestamp',\n            dtype.binary: 'text',\n            dtype.categorical: 'text',\n            dtype.tags: 'text',\n            dtype.image: 'text',\n            dtype.video: 'text',\n            dtype.audio: 'text',\n            dtype.short_text: 'text',\n            dtype.rich_text: 'text',\n            dtype.array: 'text'\n        }\n\n        column_declaration = []\n        for name in columns:\n            try:\n                col_subtype = dtype_dict[name]\n                new_type = subtype_map[col_subtype]\n                column_declaration.append(f' \"{name}\" {new_type} ')\n                if name in predicted_cols:\n                    column_declaration.append(f' \"{name}_original\" {new_type} ')\n            except Exception as e:\n                log.error(f'Error: can not determine postgres data type for column {name}: {e}')\n\n        return column_declaration\n\n    def _escape_table_name(self, name):\n        return '\"' + name.replace('\"', '\"\"') + '\"'\n\n    def _query(self, query):\n        con = self._get_connection()\n        with closing(con) as con:\n\n            cur = con.cursor()\n            res = True\n            cur.execute(query)\n\n            try:\n                rows = cur.fetchall()\n                keys = [k[0] if isinstance(k[0], str) else k[0].decode('ascii') for k in cur.description]\n                res = [dict(zip(keys, row)) for row in rows]\n            except Exception:\n                pass\n\n            con.commit()\n\n        return res\n\n    def setup(self):\n        user = f\"{self.config['api']['mysql']['user']}_{self.name}\"\n        password = self.config['api']['mysql']['password']\n        host = self.config['api']['mysql']['host']\n        port = self.config['api']['mysql']['port']\n\n        try:\n            self._query('''\n                DO $$\n                begin\n                    if not exists (SELECT 1 FROM pg_extension where extname = 'mysql_fdw') then\n                        CREATE EXTENSION mysql_fdw;\n                    end if;\n                END\n                $$;\n            ''')\n        except Exception:\n            print('Error: cant find or activate mysql_fdw extension for PostgreSQL.')\n\n        self._query(f'DROP SCHEMA IF EXISTS {self.mindsdb_database} CASCADE')\n\n        self._query(f\"DROP USER MAPPING IF EXISTS FOR {self.user} SERVER server_{self.mindsdb_database}\")\n\n        self._query(f'DROP SERVER IF EXISTS server_{self.mindsdb_database} CASCADE')\n\n        self._query(f'''\n            CREATE SERVER server_{self.mindsdb_database}\n                FOREIGN DATA WRAPPER mysql_fdw\n                OPTIONS (host '{host}', port '{port}');\n        ''')\n\n        self._query(f'''\n           CREATE USER MAPPING FOR {self.user}\n                SERVER server_{self.mindsdb_database}\n                OPTIONS (username '{user}', password '{password}');\n        ''')\n\n        self._query(f'CREATE SCHEMA {self.mindsdb_database}')\n\n        q = f\"\"\"\n            CREATE FOREIGN TABLE IF NOT EXISTS {self.mindsdb_database}.predictors (\n                name text,\n                status text,\n                accuracy text,\n                predict text,\n                select_data_query text,\n                external_datasource text,\n                training_options text\n            )\n            SERVER server_{self.mindsdb_database}\n            OPTIONS (dbname 'mindsdb', table_name 'predictors');\n        \"\"\"\n        self._query(q)\n\n        q = f\"\"\"\n            CREATE FOREIGN TABLE IF NOT EXISTS {self.mindsdb_database}.commands (\n                command text\n            ) SERVER server_{self.mindsdb_database}\n            OPTIONS (dbname 'mindsdb', table_name 'commands');\n        \"\"\"\n        self._query(q)\n\n    def register_predictors(self, model_data_arr):\n        for model_meta in model_data_arr:\n            name = model_meta['name']\n            predict = model_meta['predict']\n            if not isinstance(predict, list):\n                predict = [predict]\n            columns_sql = ','.join(self._to_postgres_table(\n                model_meta['dtype_dict'],\n                predict,\n                list(model_meta['dtype_dict'].keys())\n            ))\n            columns_sql += ',\"select_data_query\" text'\n            columns_sql += ',\"external_datasource\" text'\n            for col in predict:\n                columns_sql += f',\"{col}_confidence\" float8'\n                if model_meta['dtype_dict'][col] in (dtype.integer, dtype.float):\n                    columns_sql += f',\"{col}_min\" float8'\n                    columns_sql += f',\"{col}_max\" float8'\n                columns_sql += f',\"{col}_explain\" text'\n\n            self.unregister_predictor(name)\n            q = f\"\"\"\n                CREATE FOREIGN TABLE {self.mindsdb_database}.{self._escape_table_name(name)} (\n                    {columns_sql}\n                ) SERVER server_{self.mindsdb_database}\n                OPTIONS (dbname 'mindsdb', table_name '{name}');\n            \"\"\"\n            self._query(q)\n\n    def unregister_predictor(self, name):\n        q = f\"\"\"\n            DROP FOREIGN TABLE IF EXISTS {self.mindsdb_database}.{self._escape_table_name(name)};\n        \"\"\"\n        self._query(q)\n\n    def get_row_count(self, query):\n        q = f\"\"\" \n            SELECT COUNT(*) as count\n            FROM ({query}) as query;\"\"\"\n        result = self._query(q)\n        return result[0]['count']\n    \n    def get_tables_list(self):\n        q = f\"\"\" SELECT table_schema, table_name\n                      FROM information_schema.tables\n                      WHERE table_schema != 'pg_catalog'\n                      AND table_schema != 'information_schema'\n                      ORDER BY table_schema, table_name\"\"\"\n        tables_list = self._query(q)\n        tables= [f\"{table['table_schema']}.{table['table_name']}\" for table in tables_list]\n        return tables\n\n    def get_columns(self):\n        q = f\"\"\"SELECT column_name, table_name\n\t\tFROM information_schema.columns\n\t\tWHERE table_schema NOT IN ('information_schema', 'pg_catalog')\n\t\tORDER BY column_name, table_name;\"\"\"\n        columns_list = self._query(q)\n        columns = [f\"{columns[0]}.{columns[1]}\" for columns in columns_list]\n        return columns", "path": "mindsdb/integrations/postgres/postgres.py"}], "after_files": [{"content": "from contextlib import closing\nimport pg8000\n\nfrom lightwood.api import dtype\nfrom mindsdb.integrations.base import Integration\nfrom mindsdb.utilities.log import log\n\n\nclass PostgreSQLConnectionChecker:\n    def __init__(self, **kwargs):\n        self.host = kwargs.get('host')\n        self.port = kwargs.get('port')\n        self.user = kwargs.get('user')\n        self.password = kwargs.get('password')\n        self.database = kwargs.get('database', 'postgres')\n\n    def _get_connection(self):\n        return pg8000.connect(\n            database=self.database,\n            user=self.user,\n            password=self.password,\n            host=self.host,\n            port=self.port\n        )\n\n    def check_connection(self):\n        try:\n            con = self._get_connection()\n            with closing(con) as con:\n                con.run('select 1;')\n            connected = True\n        except Exception:\n            connected = False\n        return connected\n\n\nclass PostgreSQL(Integration, PostgreSQLConnectionChecker):\n    def __init__(self, config, name, db_info):\n        super().__init__(config, name)\n        self.user = db_info.get('user')\n        self.password = db_info.get('password')\n        self.host = db_info.get('host')\n        self.port = db_info.get('port')\n        self.database = db_info.get('database', 'postgres')\n\n    def _to_postgres_table(self, dtype_dict, predicted_cols, columns):\n        subtype_map = {\n            dtype.integer: ' int8',\n            dtype.float: 'float8',\n            dtype.binary: 'bool',\n            dtype.date: 'date',\n            dtype.datetime: 'timestamp',\n            dtype.binary: 'text',\n            dtype.categorical: 'text',\n            dtype.tags: 'text',\n            dtype.image: 'text',\n            dtype.video: 'text',\n            dtype.audio: 'text',\n            dtype.short_text: 'text',\n            dtype.rich_text: 'text',\n            dtype.array: 'text'\n        }\n\n        column_declaration = []\n        for name in columns:\n            try:\n                col_subtype = dtype_dict[name]\n                new_type = subtype_map[col_subtype]\n                column_declaration.append(f' \"{name}\" {new_type} ')\n                if name in predicted_cols:\n                    column_declaration.append(f' \"{name}_original\" {new_type} ')\n            except Exception as e:\n                log.error(f'Error: can not determine postgres data type for column {name}: {e}')\n\n        return column_declaration\n\n    def _escape_table_name(self, name):\n        return '\"' + name.replace('\"', '\"\"') + '\"'\n\n    def _query(self, query):\n        con = self._get_connection()\n        with closing(con) as con:\n\n            cur = con.cursor()\n            res = True\n            cur.execute(query)\n\n            try:\n                rows = cur.fetchall()\n                keys = [k[0] if isinstance(k[0], str) else k[0].decode('ascii') for k in cur.description]\n                res = [dict(zip(keys, row)) for row in rows]\n            except Exception:\n                pass\n\n            con.commit()\n\n        return res\n\n    def setup(self):\n        user = f\"{self.config['api']['mysql']['user']}_{self.name}\"\n        password = self.config['api']['mysql']['password']\n        host = self.config['api']['mysql']['host']\n        port = self.config['api']['mysql']['port']\n\n        try:\n            self._query('''\n                DO $$\n                begin\n                    if not exists (SELECT 1 FROM pg_extension where extname = 'mysql_fdw') then\n                        CREATE EXTENSION mysql_fdw;\n                    end if;\n                END\n                $$;\n            ''')\n        except Exception:\n            print('Error: cant find or activate mysql_fdw extension for PostgreSQL.')\n\n        self._query(f'DROP SCHEMA IF EXISTS {self.mindsdb_database} CASCADE')\n\n        self._query(f\"DROP USER MAPPING IF EXISTS FOR {self.user} SERVER server_{self.mindsdb_database}\")\n\n        self._query(f'DROP SERVER IF EXISTS server_{self.mindsdb_database} CASCADE')\n\n        self._query(f'''\n            CREATE SERVER server_{self.mindsdb_database}\n                FOREIGN DATA WRAPPER mysql_fdw\n                OPTIONS (host '{host}', port '{port}');\n        ''')\n\n        self._query(f'''\n           CREATE USER MAPPING FOR {self.user}\n                SERVER server_{self.mindsdb_database}\n                OPTIONS (username '{user}', password '{password}');\n        ''')\n\n        self._query(f'CREATE SCHEMA {self.mindsdb_database}')\n\n        q = f\"\"\"\n            CREATE FOREIGN TABLE IF NOT EXISTS {self.mindsdb_database}.predictors (\n                name text,\n                status text,\n                accuracy text,\n                predict text,\n                select_data_query text,\n                external_datasource text,\n                training_options text\n            )\n            SERVER server_{self.mindsdb_database}\n            OPTIONS (dbname 'mindsdb', table_name 'predictors');\n        \"\"\"\n        self._query(q)\n\n        q = f\"\"\"\n            CREATE FOREIGN TABLE IF NOT EXISTS {self.mindsdb_database}.commands (\n                command text\n            ) SERVER server_{self.mindsdb_database}\n            OPTIONS (dbname 'mindsdb', table_name 'commands');\n        \"\"\"\n        self._query(q)\n\n    def register_predictors(self, model_data_arr):\n        for model_meta in model_data_arr:\n            name = model_meta['name']\n            predict = model_meta['predict']\n            if not isinstance(predict, list):\n                predict = [predict]\n            columns_sql = ','.join(self._to_postgres_table(\n                model_meta['dtype_dict'],\n                predict,\n                list(model_meta['dtype_dict'].keys())\n            ))\n            columns_sql += ',\"select_data_query\" text'\n            columns_sql += ',\"external_datasource\" text'\n            for col in predict:\n                columns_sql += f',\"{col}_confidence\" float8'\n                if model_meta['dtype_dict'][col] in (dtype.integer, dtype.float):\n                    columns_sql += f',\"{col}_min\" float8'\n                    columns_sql += f',\"{col}_max\" float8'\n                columns_sql += f',\"{col}_explain\" text'\n\n            self.unregister_predictor(name)\n            q = f\"\"\"\n                CREATE FOREIGN TABLE {self.mindsdb_database}.{self._escape_table_name(name)} (\n                    {columns_sql}\n                ) SERVER server_{self.mindsdb_database}\n                OPTIONS (dbname 'mindsdb', table_name '{name}');\n            \"\"\"\n            self._query(q)\n\n    def unregister_predictor(self, name):\n        q = f\"\"\"\n            DROP FOREIGN TABLE IF EXISTS {self.mindsdb_database}.{self._escape_table_name(name)};\n        \"\"\"\n        self._query(q)\n\n    def get_row_count(self, query):\n        q = f\"\"\" \n            SELECT COUNT(*) as count\n            FROM ({query}) as query;\"\"\"\n        result = self._query(q)\n        return result[0]['count']\n    \n    def get_tables_list(self):\n        q = f\"\"\" SELECT table_schema, table_name\n                      FROM information_schema.tables\n                      WHERE table_schema != 'pg_catalog'\n                      AND table_schema != 'information_schema'\n                      ORDER BY table_schema, table_name\"\"\"\n        tables_list = self._query(q)\n        tables= [f\"{table['table_schema']}.{table['table_name']}\" for table in tables_list]\n        return tables\n\n    def get_columns(self,query):\n        q = f\"\"\"SELECT * from ({query}) LIMIT 1;\"\"\"\n        query_response = self._query(q)\n        if len(query_response) > 0:\n            columns = list(query_response[0].keys())\n            return columns\n        else:\n            return []", "path": "mindsdb/integrations/postgres/postgres.py"}]}