Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.8 kB
1
Indexable
Never
import datetime  # Make sure to import the datetime module

# ... (previous code)

# Inside your main function, update the code where you construct insert_columns and insert_values
for column_name, source_val in source_row.items():
    if source_val is not None:
        if isinstance(source_val, str) and source_val.startswith('TO_DATE'):
            # If it already starts with TO_DATE, don't add TO_DATE again
            insert_values.append(source_val)
        elif is_datetime(source_val):
            # Format datetime values using the appropriate function for the database type
            if db_type_ext == 'ORACLE':
                insert_values.append(f"TO_DATE('{source_val}', 'YYYY-MM-DD HH24:MI:SS')")
            elif db_type_ext == 'MARIA':
                # For MariaDB, use STR_TO_DATE
                insert_values.append(f"STR_TO_DATE('{source_val}', '%Y-%m-%d %H:%i:%s')")
            else:
                insert_values.append(f"'{source_val}'")
            insert_columns.append(column_name)  # Add the column name
        else:
            insert_values.append(f"'{source_val}'")
            insert_columns.append(column_name)  # Add the column name
    else:
        insert_values.append('NULL')
        insert_columns.append(column_name)  # Add the column name

# Construct the INSERT query with column names
insert_query = f"INSERT INTO {schema_ext}.{table_name} ({', '.join(insert_columns)}) VALUES ({', '.join(insert_values)})"

# ... (the rest of your code remains the same)

# Add a function to check if a value is a datetime
def is_datetime(value):
    try:
        # Attempt to parse the value as a string and then as a datetime
        datetime.datetime.strptime(str(value), '%Y-%m-%d %H:%M:%S')
        return True
    except ValueError:
        return False