mysqldump-php icon indicating copy to clipboard operation
mysqldump-php copied to clipboard

implement --tab option

Open swaibar opened this issue 3 years ago • 0 comments

An item I use often is CSV files (or more accurately tabbed separated values) . This is often complicated even if you have root on the machine as the system only wished to output this to a secure location, based on secure_file_priv. A little odd as I can dump it to SQL, but not to a faster CSV format... anyway... as a work around taking a SQL dump file I can recreate the sql and csv data by parsing a full sql dump file... I'm just not sure the best way to include this if at all?

The best solution would be to update the code to only write out what is required. but this is a very simple stand alone option that could be run after the current code to convert instead... less efficient but simple...

function convert_sql_dump_to_tsv($sql_file, $folder) {
	if ($handle = fopen($sql_file, "r")) {
		$line = fgets($handle);
		while ($line !== false) {
			$line = trim($line);
			$drop = starts_with($line, 'DROP TABLE IF EXISTS');
			$create = starts_with($line, "CREATE TABLE `");
			if ($drop || $create) {
				$table = get_between($line, $drop ? 'IF EXISTS `' : 'CREATE TABLE `', '`');
				while ($line !== false && !empty(trim($line))) {
					file_put_contents("{$folder}/{$table}.sql", trim($line) . PHP_EOL, FILE_APPEND);
					$line = fgets($handle);
				}
				file_put_contents("{$folder}/{$table}.txt", '');
			}
			if (starts_with(($line, 'INSERT INTO')) {
				$table = get_between($line, 'INSERT INTO `', '`');
				$values = get_after_first($line, ' VALUES (');
				foreach (explode('),(', $values) as $values_quoted_csv) {
					$values_quoted_csv = ends_with($values_quoted_csv, ');')
						? substr($values_quoted_csv, 0, -2)
						: $values_quoted_csv;
					$latest_row = [];
					foreach (str_getcsv($values_quoted_csv, ',', "'", "\\") as $value) {
						$latest_row[] = $value == 'NULL' ? '\N' : str_replace("\t", "\\\t", stripslashes($value));
					}
					file_put_contents("{$folder}/{$table}.txt", implode("\t", $latest_row) . PHP_EOL, FILE_APPEND);
				}
			}
			$line = fgets($handle);
		}
		fclose($handle);
	}
}
function get_between($string, $start, $end) {
	$string = ' ' . $string;
	$ini = strpos($string, $start);
	if ($ini != 0) {
		$ini += strlen($start);
		return substr($string, $ini, strpos($string, $end, $ini) - $ini);
	}
}
function get_after_first($string, $findme) {
	return substr($string, strpos($string, $findme) + strlen($findme), strlen($string) - 1);
}
function starts_with($haystack, $needle) {
	return substr($haystack, 0, strlen($needle)) === $needle;
}
function ends_with($haystack, $needle) {
	return strlen($needle) ? substr($haystack, -strlen($needle)) === $needle : true;
}

swaibar avatar Jun 14 '21 09:06 swaibar