lese
lese

Reputation: 549

Python functions - pass a full if condition as a parameter

Is it possible in Python to pass as a parameter a certain condition into a function, only when it is necessary? Eg.: a full if condition:​​

  # /!\ checking if customer_name is NULL (NOT NULL field in destination database)
  if row['customer_name'] == NULL:
    row['customer_name'] = row['contact_name']

I'm working on a script that will automate data migration from mysql to postgresql. Some tables have the same structure in both databases (source and destination), others are structurally different while others have just a datatype difference.

I'm trying to understand if it is possible to "inject" a condition inside a function, in order to use the same piece of code for all the 3 cases mentioned in above paragraph The condition will be different everytime.

The following is an example (the piece of code i'm investigating the possibility of injecting is in yellow -> pass it as a parameter):

def migrate_table(select_query, insert_query, tmp_args):
  # Cursors initialization
  cur_psql = cnx_psql.cursor()

  cur_msql.execute(select_query)

  args = []
  for row in cur_msql:

    # /!\ checking if customer_name is NULL (NOT NULL field in destination database)
    if row['customer_name'] == NULL:
      row['customer_name'] = row['contact_name']
      args.append(cur_psql.mogrify(tmp_args, row))
    args_str = ','.join(args)

  if len(args_str) > 0:
    try:
      cur_psql.execute(insert_query + args_str)
    except psycopg2.Error as e:
      print "Cannot execute that query", e.pgerror
      sys.exit("Leaving early this lucky script")

  ## Closing cursors
  cur_psql.close()

Actually I call my function in this way:

migrate_compatable(
"SELECT customer_id, customer_name, contact_name, address, city, postal_code, country FROM mysqlcustomers",
"INSERT INTO psqlcustomers (customer_id, customer_name, contact_name, address, city, postal_code, country"
"(%(customer_id)s, %(customer_name)s, %(contact_name)s, %(address)s, %(city)s, %(postal_code)s, %(country)s)"
)

I would like to know If is something possible to add a parameter that take in input a full condition

Upvotes: 4

Views: 13261

Answers (1)

mguijarr
mguijarr

Reputation: 7900

As suggested by @jonrsharpe you can modify your migrate_table function to pass a checking function you would invoke with the row:

def check_customer_name(row):
    if row['customer_name'] == NULL:
        row['customer_name'] = row['contact_name']
    return row

And then in migrate_table:

def migrate_table(..., check_function = None):
    ...
    if callable(check_function):
        row = check_function(row)
    ...

Your call would become:

migrate_table("...long sql query...", "...", check_customer_name)

You can create as many check functions as you want to test your conditions.

Upvotes: 7

Related Questions