This function used to create database and returns the database id
(server, db_name, encoding=None)
| 158 | |
| 159 | |
| 160 | def create_database(server, db_name, encoding=None): |
| 161 | """This function used to create database and returns the database id""" |
| 162 | db_id = '' |
| 163 | connection = get_db_connection( |
| 164 | server['db'], |
| 165 | server['username'], |
| 166 | server['db_password'], |
| 167 | server['host'], |
| 168 | server['port'], |
| 169 | server['sslmode'] |
| 170 | ) |
| 171 | old_isolation_level = connection.isolation_level |
| 172 | set_isolation_level(connection, 0) |
| 173 | connection.autocommit = True |
| 174 | pg_cursor = connection.cursor() |
| 175 | if encoding is None: |
| 176 | pg_cursor.execute( |
| 177 | '''CREATE DATABASE "%s" TEMPLATE template0''' % db_name) |
| 178 | else: |
| 179 | pg_cursor.execute( |
| 180 | '''CREATE DATABASE "%s" TEMPLATE template0 |
| 181 | ENCODING='%s' LC_COLLATE='%s' LC_CTYPE='%s' ''' % |
| 182 | (db_name, encoding[0], encoding[1], encoding[1])) |
| 183 | connection.autocommit = False |
| 184 | set_isolation_level(connection, old_isolation_level) |
| 185 | connection.commit() |
| 186 | |
| 187 | # Get 'oid' from newly created database |
| 188 | pg_cursor.execute("SELECT db.oid from pg_catalog.pg_database db WHERE" |
| 189 | " db.datname='%s'" % db_name) |
| 190 | oid = pg_cursor.fetchone() |
| 191 | if oid: |
| 192 | db_id = oid[0] |
| 193 | connection.close() |
| 194 | |
| 195 | # In PostgreSQL 15 the default public schema that every database has |
| 196 | # will have a different set of permissions. In fact, before PostgreSQL |
| 197 | # 15, every user could manipulate the public schema of a database he is |
| 198 | # not owner. Since the upcoming new version, only the database owner |
| 199 | # will be granted full access to the public schema, while other users |
| 200 | # will need to get an explicit GRANT |
| 201 | connection = get_db_connection( |
| 202 | db_name, |
| 203 | server['username'], |
| 204 | server['db_password'], |
| 205 | server['host'], |
| 206 | server['port'], |
| 207 | server['sslmode'] |
| 208 | ) |
| 209 | pg_cursor = connection.cursor() |
| 210 | pg_cursor.execute('''GRANT ALL ON SCHEMA public TO PUBLIC''') |
| 211 | connection.commit() |
| 212 | connection.close() |
| 213 | |
| 214 | return db_id |
| 215 | |
| 216 | |
| 217 | def create_table(server, db_name, table_name, extra_columns=[]): |
no test coverage detected