Datasets:

Modalities:
Text
Formats:
json
Languages:
English
ArXiv:
License:
File size: 11,740 Bytes
1c77159
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
"""Prepare the Spider databases used by the bundled REUSE-QA SQL questions.

Adapted from the RECAP project's sql_api_bench_dataset.py. This keeps its Spider
Google Drive download and database-discovery workflow, but reads REUSE-QA's
existing JSONL records instead of downloading or regenerating question data.

Use an existing Spider distribution without downloading anything:
    python scripts/prepare_sql_api_bench.py --spider-dir /path/to/spider

Or download and extract Spider into a separate working directory:
    python scripts/prepare_sql_api_bench.py --work-dir ./sql_api_bench_data

Only the download path needs the optional gdown package. No package is installed
automatically. The complete archive, including upstream notices, is retained.
This script prepares databases, not the scalar tools or an agent environment.
"""

import argparse
from contextlib import closing
import json
import os
from pathlib import Path, PurePosixPath, PureWindowsPath
import re
import shutil
import sqlite3
import stat
import sys
import zipfile


SPIDER_DRIVE_ID = "1403EGqzIDoHMdQF4c9Bkyl7dZLZ5Wt6J"
QUESTION_FILE = Path(__file__).resolve().parents[1] / "data" / "sql_api_bench.jsonl"


def load_required_databases(question_file=QUESTION_FILE):
    """Read database names from the bundled questions without changing them."""
    required = set()
    question_count = 0
    with question_file.open(encoding="utf-8-sig") as handle:
        for line_number, line in enumerate(handle, 1):
            if not line.strip():
                raise ValueError(f"Blank JSONL line {line_number} in {question_file}")
            try:
                row = json.loads(line)
            except json.JSONDecodeError as exc:
                raise ValueError(
                    f"Invalid JSONL line {line_number} in {question_file}: {exc}"
                ) from exc
            if not isinstance(row, dict) or row.get("dataset") != "sql_api_bench":
                raise ValueError(f"Unexpected source on JSONL line {line_number}")
            context = row.get("context")
            db_name = context.get("db_name") if isinstance(context, dict) else None
            if not isinstance(db_name, str) or not re.fullmatch(r"[A-Za-z0-9_]+", db_name):
                raise ValueError(f"Invalid context.db_name on JSONL line {line_number}")
            required.add(db_name)
            question_count += 1
    if not required:
        raise ValueError(f"No SQL questions found in {question_file}")
    return question_count, required


def database_path(database_dir, db_name):
    """Support Spider's name/name.sqlite layout and flat database directories."""
    for path in (
        database_dir / db_name / f"{db_name}.sqlite",
        database_dir / f"{db_name}.sqlite",
    ):
        if path.is_file():
            return path
    return None


def find_database_dir(spider_dir, required):
    """Find the directory containing the requested Spider databases."""
    candidates = [
        spider_dir,
        spider_dir / "spider_data" / "database",
        spider_dir / "database",
        spider_dir / "spider" / "database",
    ]
    if spider_dir.is_dir():
        for root, dirs, _ in os.walk(spider_dir, followlinks=False):
            dirs[:] = sorted(d for d in dirs if d != "__MACOSX")
            if Path(root).name == "database":
                candidates.append(Path(root))

    best = None
    best_count = 0
    seen = set()
    for candidate in candidates:
        key = candidate.resolve()
        if key in seen or not candidate.is_dir():
            continue
        seen.add(key)
        count = sum(database_path(candidate, name) is not None for name in required)
        if count == len(required):
            return candidate
        if count > best_count:
            best, best_count = candidate, count
    return best


def safe_extract(archive, destination):
    """Extract every archive member after rejecting unsafe paths and links."""
    destination = destination.resolve()
    if destination.exists() and (
        not destination.is_dir() or any(destination.iterdir())
    ):
        raise ValueError(
            f"Extraction directory is not empty: {destination}. "
            "Choose a fresh --work-dir or use --spider-dir for an existing copy."
        )

    with zipfile.ZipFile(archive) as zf:
        members = []
        targets = {}
        for info in zf.infolist():
            name = info.filename.replace("\\", "/")
            relative = PurePosixPath(name)
            windows_path = PureWindowsPath(name)
            if (
                not name
                or relative.is_absolute()
                or windows_path.drive
                or ".." in relative.parts
                or any(
                    part.endswith((" ", "."))
                    or any(ch in '<>:"|?*' or ord(ch) < 32 for ch in part)
                    for part in relative.parts
                )
            ):
                raise ValueError(f"Unsafe archive member path: {info.filename!r}")
            mode = info.external_attr >> 16
            file_type = stat.S_IFMT(mode)
            if stat.S_ISLNK(mode) or file_type not in (0, stat.S_IFREG, stat.S_IFDIR):
                raise ValueError(f"Unsupported archive link or special file: {info.filename!r}")
            target = destination.joinpath(*relative.parts).resolve()
            if not target.is_relative_to(destination) or target == destination:
                raise ValueError(f"Unsafe archive member path: {info.filename!r}")
            key = target.as_posix().casefold()
            is_dir = info.is_dir() or file_type == stat.S_IFDIR
            if key in targets:
                if is_dir and targets[key]:
                    continue
                raise ValueError(f"Conflicting archive member path: {info.filename!r}")
            targets[key] = is_dir
            members.append((info, target, is_dir))

        # A regular file cannot also be a parent directory of another member.
        for _, target, _ in members:
            for parent in target.parents:
                if parent == destination:
                    break
                if targets.get(parent.as_posix().casefold()) is False:
                    raise ValueError(f"Archive file/directory conflict: {target}")

        destination.mkdir(parents=True, exist_ok=True)
        for info, target, is_dir in members:
            if is_dir:
                target.mkdir(parents=True, exist_ok=True)
            else:
                target.parent.mkdir(parents=True, exist_ok=True)
                with zf.open(info) as source, target.open("xb") as output:
                    shutil.copyfileobj(source, output)


def download_spider(work_dir, required):
    """Download the original Spider archive and keep its complete contents."""
    work_dir = work_dir.resolve()
    spider_dir = work_dir / "spider"
    if spider_dir.exists():
        database_dir = find_database_dir(spider_dir, required)
        if database_dir and all(database_path(database_dir, n) for n in required):
            print(f"Using existing extracted Spider copy: {spider_dir}")
            return database_dir
        raise ValueError(
            f"Existing extraction is incomplete: {spider_dir}. "
            "Choose a fresh --work-dir or provide a complete --spider-dir."
        )

    archive = work_dir / "spider_data.zip"
    if not archive.is_file():
        try:
            import gdown
        except ImportError as exc:
            raise RuntimeError(
                "Downloading Spider requires gdown. Install it explicitly with:\n"
                f'  "{sys.executable}" -m pip install gdown\n'
                "Then rerun, or provide --spider-dir for an existing distribution."
            ) from exc
        work_dir.mkdir(parents=True, exist_ok=True)
        partial = work_dir / "spider_data.zip.part"
        print("Downloading the Spider archive from Google Drive...")
        try:
            result = gdown.download(
                f"https://drive.google.com/uc?id={SPIDER_DRIVE_ID}",
                str(partial),
                quiet=False,
            )
        except Exception as exc:
            raise RuntimeError(f"Spider download failed: {exc}") from exc
        if not result or not partial.is_file() or not zipfile.is_zipfile(partial):
            raise RuntimeError(
                "Spider download did not produce a ZIP archive. "
                "Check the download source or use --spider-dir."
            )
        partial.replace(archive)

    print(f"Extracting the full Spider archive to: {spider_dir}")
    safe_extract(archive, spider_dir)
    print(f"Archive retained, including upstream notices: {archive}")
    database_dir = find_database_dir(spider_dir, required)
    if database_dir is None:
        raise FileNotFoundError(f"No requested Spider databases found in {spider_dir}")
    return database_dir


def verify_databases(database_dir, required):
    """Check required files and their SQLite integrity without writing to them."""
    missing = [name for name in sorted(required) if database_path(database_dir, name) is None]
    if missing:
        raise FileNotFoundError(
            f"Missing {len(missing)} required databases in {database_dir}: "
            + ", ".join(missing)
        )
    details = []
    for name in sorted(required):
        path = database_path(database_dir, name).resolve()
        uri = path.as_uri() + "?mode=ro&immutable=1"
        with closing(sqlite3.connect(uri, uri=True)) as connection:
            connection.execute("PRAGMA query_only=ON")
            check = [row[0] for row in connection.execute("PRAGMA integrity_check")]
            if check != ["ok"]:
                raise ValueError(f"SQLite integrity check failed for {path}: {check}")
            table_count = connection.execute(
                "SELECT COUNT(*) FROM sqlite_master "
                "WHERE type='table' AND name NOT LIKE 'sqlite_%'"
            ).fetchone()[0]
        details.append((name, path, table_count))
    return details


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--spider-dir", type=Path,
        help="Existing Spider root or database directory; read in place without downloading.",
    )
    parser.add_argument(
        "--work-dir", type=Path, default=Path("sql_api_bench_data"),
        help="Download/extraction directory when --spider-dir is omitted (default: %(default)s).",
    )
    args = parser.parse_args(argv)
    try:
        question_count, required = load_required_databases()
        print(f"Bundled questions: {question_count}; required databases: {len(required)}")
        if args.spider_dir is not None:
            spider_dir = args.spider_dir.resolve()
            if not spider_dir.is_dir():
                raise FileNotFoundError(f"Existing Spider directory not found: {spider_dir}")
            database_dir = find_database_dir(spider_dir, required)
            if database_dir is None:
                raise FileNotFoundError(f"No requested Spider databases found in {spider_dir}")
        else:
            database_dir = download_spider(args.work_dir, required)
        details = verify_databases(database_dir, required)
        print(f"Ready: {len(details)} databases for {question_count} bundled questions.")
        print(f"Database directory: {database_dir.resolve()}")
        for name, path, tables in details:
            print(f"  {name}: {path} ({tables} tables)")
        return 0
    except (OSError, ValueError, RuntimeError, sqlite3.Error, zipfile.BadZipFile) as exc:
        print(f"Preparation failed: {exc}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main())