Skip to content

Instantly share code, notes, and snippets.

@NickGreen
Last active October 9, 2020 22:14
Show Gist options
  • Save NickGreen/1cde4d925e1a6590fa9766ec7dfff7f5 to your computer and use it in GitHub Desktop.
Save NickGreen/1cde4d925e1a6590fa9766ec7dfff7f5 to your computer and use it in GitHub Desktop.
Create primary keys if they are missing
#!/bin/bash
# Export a database backup beforehand
wp-cli db export --path=/htdocs/__wp__
# Get a list of tables missing primary kkeys
TABLES=$(wp-cli --path=/htdocs/__wp__ db query 'SELECT TABLES.TABLE_NAME FROM INFORMATION_SCHEMA.TABLES LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS c ON ( TABLES.TABLE_NAME = c.TABLE_NAME AND c.CONSTRAINT_SCHEMA = TABLES.TABLE_SCHEMA AND c.constraint_name = "PRIMARY" ) WHERE c.constraint_name IS NULL AND TABLE_TYPE = "BASE TABLE"')
# loop through each table and check if certain columns exist. id, object_id, product_id, slider_id, fb_post_id
# if one of those columns exists, set it as the primary key
# if none exist, create a new column called pressable_primary_key and set it as primary
for TABLE in ${TABLES:10}
do
if
wp-cli --path=/htdocs/__wp__ db query "ALTER TABLE $TABLE ADD PRIMARY KEY (id);" >/dev/null 2>&1
then
echo $TABLE
echo "id updated"
echo ""
elif
wp-cli --path=/htdocs/__wp__ db query "ALTER TABLE $TABLE ADD PRIMARY KEY (object_id);" >/dev/null 2>&1
then
echo $TABLE
echo "object_id updated"
echo ""
elif
wp-cli --path=/htdocs/__wp__ db query "ALTER TABLE $TABLE ADD PRIMARY KEY (product_id);" >/dev/null 2>&1
then
echo $TABLE
echo "product_id updated"
echo ""
elif
wp-cli --path=/htdocs/__wp__ db query "ALTER TABLE $TABLE ADD PRIMARY KEY (slider_id);" >/dev/null 2>&1
then
echo $TABLE
echo "slider_id updated"
echo ""
elif
wp-cli --path=/htdocs/__wp__ db query "ALTER TABLE $TABLE ADD PRIMARY KEY (fb_post_id);" >/dev/null 2>&1
then
echo $TABLE
echo "fb_post_id updated"
echo ""
elif
wp-cli --path=/htdocs/__wp__ db query "ALTER TABLE $TABLE ADD PRIMARY KEY (claim_id);" >/dev/null 2>&1
then
echo $TABLE
echo "claim_id updated"
echo ""
elif
wp-cli --path=/htdocs/__wp__ db query "ALTER TABLE $TABLE ADD PRIMARY KEY (action_id);" >/dev/null 2>&1
then
echo $TABLE
echo "action_id updated"
echo ""
elif
wp-cli --path=/htdocs/__wp__ db query "ALTER TABLE $TABLE ADD PRIMARY KEY (log_id);" >/dev/null 2>&1
then
echo $TABLE
echo "log_id updated"
echo ""
elif
wp-cli --path=/htdocs/__wp__ db query "ALTER TABLE $TABLE ADD PRIMARY KEY (group_id);" >/dev/null 2>&1
then
echo $TABLE
echo "group_id updated"
echo ""
else
wp-cli --path=/htdocs/__wp__ db query "ALTER TABLE $TABLE ADD COLUMN pressable_primary_key INT NOT NULL PRIMARY KEY;" >/dev/null 2>&1
echo $TABLE
echo "created pressable_primary_key"
echo ""
fi
done
wp-cli cache flush --path=/htdocs/__wp__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment