Skip to content

Commit c1b26ee

Browse files
committed
sqlite-utils memory handles files with same filename, closes #325
1 parent 7427a91 commit c1b26ee

File tree

3 files changed

+35
-1
lines changed

3 files changed

+35
-1
lines changed

docs/cli.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,10 @@ The in-memory tables will be named after the files without their extensions. The
281281

282282
$ sqlite-utils memory example.csv "select * from t"
283283

284+
If two files have the same name they will be assigned a numeric suffix::
285+
286+
$ sqlite-utils memory foo/data.csv bar/data.csv "select * from data_2"
287+
284288
To read from standard input, use either ``-`` or ``stdin`` as the filename - then use ``stdin`` or ``t`` or ``t1`` as the table name::
285289

286290
$ cat example.csv | sqlite-utils memory - "select * from stdin"

sqlite_utils/cli.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1275,6 +1275,7 @@ def memory(
12751275
if (dump or save or schema or analyze) and not paths:
12761276
paths = [sql]
12771277
sql = None
1278+
stem_counts = {}
12781279
for i, path in enumerate(paths):
12791280
# Path may have a :format suffix
12801281
if ":" in path and path.rsplit(":", 1)[-1].upper() in Format.__members__:
@@ -1287,7 +1288,12 @@ def memory(
12871288
csv_table = "stdin"
12881289
else:
12891290
csv_path = pathlib.Path(path)
1290-
csv_table = csv_path.stem
1291+
stem = csv_path.stem
1292+
if stem_counts.get(stem):
1293+
csv_table = "{}_{}".format(stem, stem_counts[stem])
1294+
else:
1295+
csv_table = stem
1296+
stem_counts[stem] = stem_counts.get(stem, 1) + 1
12911297
csv_fp = csv_path.open("rb")
12921298
rows, format_used = rows_from_file(csv_fp, format=format, encoding=encoding)
12931299
tracker = None

tests/test_cli_memory.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,3 +241,27 @@ def test_memory_analyze():
241241
" Blank rows: 0\n\n"
242242
" Distinct values: 2\n\n"
243243
)
244+
245+
246+
def test_memory_two_files_with_same_stem(tmpdir):
247+
(tmpdir / "one").mkdir()
248+
(tmpdir / "two").mkdir()
249+
one = tmpdir / "one" / "data.csv"
250+
two = tmpdir / "two" / "data.csv"
251+
one.write_text("id,name\n1,Cleo\n2,Bants", encoding="utf-8")
252+
two.write_text("id,name\n3,Blue\n4,Lila", encoding="utf-8")
253+
result = CliRunner().invoke(cli.cli, ["memory", str(one), str(two), "", "--schema"])
254+
assert result.exit_code == 0
255+
assert result.output == (
256+
'CREATE TABLE "data" (\n'
257+
" [id] INTEGER,\n"
258+
" [name] TEXT\n"
259+
");\n"
260+
"CREATE VIEW t1 AS select * from [data];\n"
261+
"CREATE VIEW t AS select * from [data];\n"
262+
'CREATE TABLE "data_2" (\n'
263+
" [id] INTEGER,\n"
264+
" [name] TEXT\n"
265+
");\n"
266+
"CREATE VIEW t2 AS select * from [data_2];\n"
267+
)

0 commit comments

Comments
 (0)