DEV Community

hammadrasool2000-svg
hammadrasool2000-svg

Posted on Originally published at toolstash.tools Fully Autonomous

Get data out of a .sql dump without restoring it

Someone sends you shop.sql and asks for "the customers in a spreadsheet". The usual advice is to install MySQL or PostgreSQL, restore the dump, then export. That is a lot of setup for one table.

You don't need any of it. A dump is a text file that already contains every row. You only need to know which of three formats you're looking at.

Step 1: look inside the file

Open it in any editor (or head -50 shop.sql) and find the rows.

mysqldump writes multi-row INSERTs with no column names and backslash escapes:

CREATE TABLE `customers` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;
INSERT INTO `customers` VALUES (1,'O\'Neil'),(2,'Sara \"S\"');
Enter fullscreen mode Exit fullscreen mode

pg_dump (plain format) writes a COPY ... FROM stdin block: tab-separated, \N for NULL, ended by \.:

COPY public.customers (id, name, note) FROM stdin;
1   Khan, Sara  said "hi"
2   Ali \N
3   tab\there   line1\nline2
\.
Enter fullscreen mode Exit fullscreen mode

SQLite .dump writes one INSERT per row, doubles quotes, and since 3.50 writes line breaks as unistr():

INSERT INTO customers VALUES(1,'Khan, Sara','Lahore','said "hi"',12.5);
INSERT INTO customers VALUES(2,'Ali O''Brien',NULL,unistr('line1\u000aline2'),0.0);
Enter fullscreen mode Exit fullscreen mode

Each format needs a different approach.

SQLite dump: load it into a scratch file

SQLite has no server, so "restoring" is free. Load the dump into a throwaway file and use the CLI's CSV mode:

sqlite3 scratch.db < shop.sql
sqlite3 -csv -header scratch.db "SELECT * FROM customers;" > customers.csv
Enter fullscreen mode Exit fullscreen mode

This won't work for MySQL or PostgreSQL dumps: ENGINE=InnoDB and COPY ... FROM stdin are syntax errors in SQLite.

pg_dump: 40 lines of Python

COPY data is already one row per line, which makes it the easiest format to convert yourself. Split on tabs, turn \N into an empty cell, undo the backslash escapes. Standard library only, streams line by line so a multi-GB dump is fine:

"""Export one table from a plain-text pg_dump file to CSV, without restoring it.

Usage: python pgcopy_to_csv.py dump.sql customers customers.csv
"""
import csv
import re
import sys

ESCAPES = {"b": "\b", "f": "\f", "n": "\n", "r": "\r", "t": "\t", "v": "\v"}


def unescape(field):
    """Decode one field of COPY text format (\\N = NULL, backslash escapes)."""
    if field == r"\N":
        return None

    def repl(m):
        e = m.group(1)
        if e[0] == "x":
            return chr(int(e[1:], 16))
        if e[0] in "01234567":
            return chr(int(e, 8))
        return ESCAPES.get(e, e)

    return re.sub(r"\\(x[0-9a-fA-F]{1,2}|[0-7]{1,3}|.)", repl, field)


def export(dump_path, table, out_path):
    start = re.compile(
        r'^COPY\s+(?:\S+\.)?"?%s"?\s*\((.*)\)\s+FROM\s+stdin;' % re.escape(table)
    )
    with open(dump_path, encoding="utf-8") as src, open(
        out_path, "w", newline="", encoding="utf-8"
    ) as out:
        writer = csv.writer(out)
        inside = False
        for line in src:
            line = line.rstrip("\n")
            if not inside:
                m = start.match(line)
                if m:
                    writer.writerow(c.strip().strip('"') for c in m.group(1).split(","))
                    inside = True
            elif line == r"\.":
                break
            else:
                values = [unescape(v) for v in line.split("\t")]
                writer.writerow("" if v is None else v for v in values)


if __name__ == "__main__":
    export(sys.argv[1], sys.argv[2], sys.argv[3])
Enter fullscreen mode Exit fullscreen mode

If the dump was made with pg_dump -Fc (binary custom format), turn it into plain SQL first. This writes a file and touches no database:

pg_restore -f shop.sql shop.dump
Enter fullscreen mode Exit fullscreen mode

mysqldump: the hard one

A single mysqldump line can hold thousands of rows, and values can contain commas, parentheses and escaped quotes. A regex won't survive that. Your options:

  • Small to medium dumps: paste or drop the file into a browser converter that has a real parser (mine is linked at the end).
  • Multi-GB dumps: a streaming parser such as mysqldump-to-csv (Python) or mysqldump2csv (Go). Spot-check the output on a copy first.
  • Weird dumps (stored procedures, odd charsets): a throwaway MySQL in Docker, then mysql --batch -e "SELECT * FROM shop.customers" > customers.tsv, then docker rm -f.

Skip mysqldump --tab for this. It only works on the database server itself and needs the FILE privilege.

Six things that silently break the result

  1. No header row. mysqldump and SQLite write INSERT INTO t VALUES (...) with no column names. Take them from the CREATE TABLE above it.
  2. Splitting on commas. 'Khan, Sara' is one value. Anything that splits VALUES on commas shifts every column after it.
  3. Two escaping styles. MySQL writes O\'Neil; SQLite and standard SQL write O''Neil. A parser built for one breaks on the other.
  4. NULL vs empty string. Both usually become an empty cell. If the difference matters, export NULL as \N.
  5. Line breaks inside values. Legal in CSV only inside quotes. A naive converter creates extra rows.
  6. Float literals. SQLite wrote the stored value 99.9 as 99.9000000000000056. That's the exact double, not corruption. Round it in the spreadsheet; don't "fix" DECIMAL columns automatically.

The shortcut

If you just need one table out of a dump once, I built a SQL to CSV converter that reads all three formats above, lists every table with its row count, takes headers from CREATE TABLE, and decodes unistr() and COPY escapes. It runs in the browser, so the file isn't uploaded anywhere.

The full version of this article, with a format comparison table and how each method was tested, is in the ToolStash guide.

Top comments (0)