Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL INTO OUTFILE override existing file?

I've written a big sql script that creates a CSV file. I want to call a cronjob every night to create a fresh CSV file and have it available on the website.

Say for example I'm store my file in '/home/sites/example.com/www/files/backup.csv'

and my SQL is

SELECT * INTO OUTFILE '/home/sites/example.com/www/files/backup.csv'
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\n'
  FROM ( ....

MySQL gives me an error when the file already exists

File '/home/sites/example.com/www/files/backup.csv' already exists

Is there a way to make MySQL overwrite the file?

I could have PHP detect if the file exists and delete it before creating it again but it would be more succinct if I can do it directly in MySQL.

like image 318
Derek Organ Avatar asked Jun 06 '09 21:06

Derek Organ


3 Answers

No, there's no way to overwrite it. From the docs:

file_name cannot be an existing file, which among other things prevents files such as /etc/passwd and database tables from being destroyed.

It might be a better idea to use a different filename each night, as having multiple backups means you can recover from problems that have existed for more than a day. You could then maintain a symlink that always points at the latest complete csv.

like image 179
brian-brazil Avatar answered Sep 19 '22 02:09

brian-brazil


Why not rm -f /home/sites/example.com/www/files/backup.csv in the script ran by cron?

You can run this from inside mysql. Just escape to the shell with \! For example:

Mysql> \! rm -f /home/sites/example.com/www/files/backup.csv

like image 9
Flavius Stef Avatar answered Sep 19 '22 02:09

Flavius Stef


For a job like this I would place it into a bash file, delete the file

#!/bin/bash
rm /path/to/backup.csv
./backup_sql_query.sh  <<-- This contains the script to backup to CSV.

The better option is to actually add a timestamp though. Disk space isn't expensive in this day and age.

like image 3
user118659 Avatar answered Sep 22 '22 02:09

user118659