Skip to content

Commit 634c057

Browse files
authoredSep 4, 2021
Create tables in the specified schema to avoid moving the tables afterwards (#21)
Fixes #18. * Execute "moveTableToSchema" if table was succesfully created * Function for getting the connection parameters added * Function buildConnectionString deleted This is because the parameters are now obtained through the function getConnectionParameters * dbConnectionParam and moveTableToSchema replaced by single function dbConnectionParam has been deleted because now all parameters are obtained by a single function which is called in the function handleTable. moveTableToSchema has been deleted because tables are now created in the specified schema. Therefore, there is no need to move the table after their creation. Co-authored-by: rdrg109 <>
1 parent 49d8358 commit 634c057

File tree

1 file changed

+25
-48
lines changed

1 file changed

+25
-48
lines changed
 

‎load_into_pg.py

+25-48
Original file line numberDiff line numberDiff line change
@@ -46,24 +46,30 @@ def show_progress(block_num, block_size, total_size):
4646
file_part = None
4747
six.print_("")
4848

49+
def getConnectionParameters():
50+
"""Get the parameters for the connection to the database."""
4951

50-
def buildConnectionString(dbname, mbHost, mbPort, mbUsername, mbPassword):
51-
dbConnectionParam = "dbname={}".format(dbname)
52+
parameters = {}
5253

53-
if mbPort is not None:
54-
dbConnectionParam += " port={}".format(mbPort)
54+
if args.dbname:
55+
parameters['dbname'] = args.dbname
5556

56-
if mbHost is not None:
57-
dbConnectionParam += " host={}".format(mbHost)
57+
if args.host:
58+
parameters['host'] = args.host
5859

59-
# TODO Is the escaping done here correct?
60-
if mbUsername is not None:
61-
dbConnectionParam += " user={}".format(mbUsername)
60+
if args.port:
61+
parameters['port'] = args.port
6262

63-
# TODO Is the escaping done here correct?
64-
if mbPassword is not None:
65-
dbConnectionParam += " password={}".format(mbPassword)
66-
return dbConnectionParam
63+
if args.username:
64+
parameters['user'] = args.username
65+
66+
if args.password:
67+
parameters['password'] = args.password
68+
69+
if args.schema_name:
70+
parameters['options'] = "-c search_path=" + args.schema_name
71+
72+
return parameters
6773

6874

6975
def _makeDefValues(keys):
@@ -174,7 +180,7 @@ def _getTableKeys(table):
174180
return keys
175181

176182

177-
def handleTable(table, insertJson, createFk, mbDbFile, dbConnectionParam):
183+
def handleTable(table, insertJson, createFk, mbDbFile):
178184
"""Handle the table including the post/pre processing."""
179185
keys = _getTableKeys(table)
180186
dbFile = mbDbFile if mbDbFile is not None else table + ".xml"
@@ -193,7 +199,7 @@ def handleTable(table, insertJson, createFk, mbDbFile, dbConnectionParam):
193199
sys.exit(-1)
194200

195201
try:
196-
with pg.connect(dbConnectionParam) as conn:
202+
with pg.connect(**getConnectionParameters()) as conn:
197203
with conn.cursor() as cur:
198204
try:
199205
with open(dbFile, "rb") as xml:
@@ -273,29 +279,8 @@ def handleTable(table, insertJson, createFk, mbDbFile, dbConnectionParam):
273279
six.print_("Warning from the database.", file=sys.stderr)
274280
six.print_("pg.Warning: {0}".format(str(w)), file=sys.stderr)
275281

276-
277-
def moveTableToSchema(table, schemaName, dbConnectionParam):
278-
try:
279-
with pg.connect(dbConnectionParam) as conn:
280-
with conn.cursor() as cur:
281-
# create the schema
282-
cur.execute("CREATE SCHEMA IF NOT EXISTS " + schemaName + ";")
283-
conn.commit()
284-
# move the table to the right schema
285-
cur.execute("ALTER TABLE " + table + " SET SCHEMA " + schemaName + ";")
286-
conn.commit()
287-
except pg.Error as e:
288-
six.print_("Error in dealing with the database.", file=sys.stderr)
289-
six.print_("pg.Error ({0}): {1}".format(e.pgcode, e.pgerror), file=sys.stderr)
290-
six.print_(str(e), file=sys.stderr)
291-
except pg.Warning as w:
292-
six.print_("Warning from the database.", file=sys.stderr)
293-
six.print_("pg.Warning: {0}".format(str(w)), file=sys.stderr)
294-
295-
296282
#############################################################
297283

298-
299284
parser = argparse.ArgumentParser()
300285
parser.add_argument(
301286
"-t",
@@ -384,10 +369,6 @@ def moveTableToSchema(table, schemaName, dbConnectionParam):
384369
except NameError:
385370
pass
386371

387-
dbConnectionParam = buildConnectionString(
388-
args.dbname, args.host, args.port, args.username, args.password
389-
)
390-
391372
# load given file in table
392373
if args.file and args.table:
393374
table = args.table
@@ -398,14 +379,13 @@ def moveTableToSchema(table, schemaName, dbConnectionParam):
398379
specialRules[("Posts", "Body")] = "NULL"
399380

400381
choice = input("This will drop the {} table. Are you sure [y/n]?".format(table))
382+
401383
if len(choice) > 0 and choice[0].lower() == "y":
402384
handleTable(
403-
table, args.insert_json, args.foreign_keys, args.file, dbConnectionParam
404-
)
385+
table, args.insert_json, args.foreign_keys, args.file)
405386
else:
406387
six.print_("Cancelled.")
407-
if args.schema_name != "public":
408-
moveTableToSchema(table, args.schema_name, dbConnectionParam)
388+
409389
exit(0)
410390

411391
# load a project
@@ -453,7 +433,7 @@ def moveTableToSchema(table, schemaName, dbConnectionParam):
453433

454434
for table in tables:
455435
six.print_("Load {0}.xml file".format(table))
456-
handleTable(table, args.insert_json, args.foreign_keys, None, dbConnectionParam)
436+
handleTable(table, args.insert_json, args.foreign_keys, None)
457437
# remove file
458438
os.remove(table + ".xml")
459439

@@ -465,9 +445,6 @@ def moveTableToSchema(table, schemaName, dbConnectionParam):
465445
else:
466446
six.print_("Archive '{0}' deleted".format(filepath))
467447

468-
if args.schema_name != "public":
469-
for table in tables:
470-
moveTableToSchema(table, args.schema_name, dbConnectionParam)
471448
exit(0)
472449

473450
else:

0 commit comments

Comments
 (0)
Please sign in to comment.