docker-volume-backup/database_entry_seeder.py

45 lines
1.7 KiB
Python
Raw Normal View History

2023-12-25 23:20:30 +01:00
import pandas as pd
import argparse
2023-12-25 23:36:21 +01:00
import os
2023-12-25 23:20:30 +01:00
def check_and_add_entry(file_path, instance, database, username, password):
2023-12-25 23:36:21 +01:00
# Check if the file exists and is not empty
if os.path.exists(file_path) and os.path.getsize(file_path) > 0:
# Read the existing CSV file with header
df = pd.read_csv(file_path, sep=';')
else:
# Create a new DataFrame with columns if file does not exist
df = pd.DataFrame(columns=['instance', 'database', 'username', 'password'])
2023-12-25 23:20:30 +01:00
2023-12-25 23:29:54 +01:00
# Check if the entry exists and remove it
mask = (df['instance'] == instance) & (df['database'] == database) & (df['username'] == username)
2023-12-25 23:20:30 +01:00
if not df[mask].empty:
2023-12-25 23:29:54 +01:00
print("Replacing existing entry.")
df = df[~mask]
2023-12-25 23:20:30 +01:00
else:
2023-12-25 23:29:54 +01:00
print("Adding new entry.")
2023-12-25 23:39:28 +01:00
# Create a new DataFrame for the new entry
new_entry = pd.DataFrame([{'instance': instance, 'database': database, 'username': username, 'password': password}])
2023-12-25 23:39:28 +01:00
# Add (or replace) the entry using concat
df = pd.concat([df, new_entry], ignore_index=True)
2023-12-25 23:29:54 +01:00
# Save the updated CSV file
df.to_csv(file_path, sep=';', index=False)
2023-12-25 23:20:30 +01:00
def main():
2023-12-25 23:29:54 +01:00
parser = argparse.ArgumentParser(description="Check and replace (or add) a database entry in a CSV file.")
2023-12-25 23:20:30 +01:00
parser.add_argument("file_path", help="Path to the CSV file")
2023-12-26 00:27:27 +01:00
parser.add_argument("instance", help="Database instance")
2023-12-25 23:20:30 +01:00
parser.add_argument("database", help="Database name")
parser.add_argument("username", help="Username")
2023-12-26 04:01:29 +01:00
parser.add_argument("password", nargs='?', default="", help="Password (optional)")
2023-12-25 23:20:30 +01:00
args = parser.parse_args()
check_and_add_entry(args.file_path, args.instance, args.database, args.username, args.password)
2023-12-25 23:20:30 +01:00
if __name__ == "__main__":
main()