reddit / emacs

Making an SQL dump more readable

ndamee ยท 2022-01-25 21:07
It's just a short snippet in case you need to browse an SQL dump. It makes the dump more readable by adding field names as comments which can be helpful with tables having lots of fields. It needs to be a dump which contains field names too. Here's an example with a trivial table. The original dump: INSERT INTO `student` (`id`, `name`, `class`, `mark`, `gender`) VALUES (1, 'John Deo', 'Four', 75, 'female'), (2, 'Max Ruin', 'Three', 85, 'male'), (3, 'Arnold', 'Three', 55, 'male'), ... the converted dump: INSERT INTO `student` (`id`, `name`, `class`, `mark`, `gender`) VALUES ( /* id */ 1, /* name */ 'John Deo', /* class */ 'Four', /* mark */ 75, /* gender */ 'female'), ( /* id */ 2, /* name */ 'Max Ruin', /* class */ 'Three', /* mark */ 85, /* gender */ 'male'), ( /* id */ 3, /* name */ 'Arnold', /* class */ 'Three', /* mark */ 55, /* gender */ 'male'), ... The code: (save-excursion (goto-char (point-min)) (while (re-search-forward ") VALUES" nil t) (beginning-of-line) (search-forward "(") (let ((start (point)) fields) (while (not (eq ?\) (char-after))) (forward-sexp) (push (buffer-substring-no-properties start (point)) fields) (skip-syntax-forward ". ") (setq start (point))) (setq fields (mapcar (lambda (field) (substring field 1 -1)) (reverse fields))) (while (progn (search-forward "(") (let ((fields fields)) ;; make a copy (while (not (eq ?\) (char-after))) (insert (concat " /* " (pop fields) " */ ")) (forward-sexp) (if (looking-at ",") (forward-char 1)) (skip-syntax-forward " "))) (looking-at "),"))))))