You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

load.mysql.sh 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #!/bin/bash
  2. # Prompt for MySQL root password securely
  3. read -sp "Enter MySQL root password: " MYSQL_PASSWORD
  4. echo # Newline after password input
  5. DEFAULT_INSTANCENAME="cihsr"
  6. echo "Enter instance name (default: $DEFAULT_INSTANCENAME):"
  7. read instancename
  8. INSTANCENAME=${instancename:-$DEFAULT_INSTANCENAME}
  9. # Prompt for the database name with a default value
  10. read -p "Enter the database name (default: cihsr): " DB_NAME
  11. DB_NAME=${DB_NAME:-$INSTANCENAME}
  12. # Default the SQL file to 'create.mysql.db.sql' in the current directory
  13. SQL_FILE="elxr/create.mysql.db.sql"
  14. # Confirm if the SQL file exists
  15. if [[ ! -f "$SQL_FILE" ]]; then
  16. echo "SQL file '$SQL_FILE' does not exist in the current directory. Please check the file path and try again."
  17. exit 1
  18. fi
  19. # MySQL user credentials
  20. MYSQL_USER="root"
  21. # Checking if the database exists
  22. echo "Checking if the database exists..."
  23. DB_EXISTS=$(mysql -u $MYSQL_USER -p$MYSQL_PASSWORD -e "SHOW DATABASES LIKE '$DB_NAME';" -s -N)
  24. if [[ -z "$DB_EXISTS" ]]; then
  25. # Database does not exist, create it
  26. echo "Database '$DB_NAME' does not exist. Creating database..."
  27. mysql -u $MYSQL_USER -p$MYSQL_PASSWORD -e "CREATE DATABASE IF NOT EXISTS $DB_NAME;"
  28. fi
  29. # Replace the placeholder {{DB_NAME}} in the SQL file with the database name
  30. TEMP_SQL_FILE=$(mktemp)
  31. sed "s/{{DB_NAME}}/$DB_NAME/g" "$SQL_FILE" > "$TEMP_SQL_FILE"
  32. # Run the SQL script with the provided database name
  33. echo "Running the SQL script to create the schema..."
  34. mysql -u $MYSQL_USER -p$MYSQL_PASSWORD $DB_NAME < "$TEMP_SQL_FILE"
  35. # Clean up the temporary file
  36. rm "$TEMP_SQL_FILE"
  37. # Run additional SQL files if any
  38. echo "Loading data into the database..."
  39. mysql -u $MYSQL_USER -p$MYSQL_PASSWORD $DB_NAME < "$INSTANCENAME-data/$DB_NAME.sql"
  40. echo "SQL script executed successfully on database $INSTANCENAME-data/$DB_NAME"