"""Named table parts for projects: read, stack, join and reference lookup. The source shape is retained in the project plan. Columns are read from that shape, not from the first file mentioned. The writer embeds runtime_source() so a generated project remains a standalone standard-library program. The outside judge has its own evaluator in judge/project_sources_judge.py. """ import re from pathlib import Path # This is also the source embedded in generated projects. Keep all its names # separate from the older generated table/probe helpers. _RUNTIME = r''' import csv as _source_csv import json as _source_json import math as _source_math from pathlib import Path as _SourcePath class ProjectSourceError(ValueError): pass def _source_path(root, name): base = _SourcePath(root).resolve() # C15b: the name must stay inside the project folder as written ("../x.csv" is refused); a link the project keeps in # its own folder (an adopted capability reading Oracle7's live records) is one of its sources import os as _source_os named = _SourcePath(_source_os.path.normpath(str(base / name))) if named != base and base not in named.parents: raise ProjectSourceError("source %s is outside the project folder" % name) path = named if not path.is_file(): raise ProjectSourceError("source %s is not in the project yet; add it and continue" % name) return path def _source_table(root, name): path = _source_path(root, name) try: if str(name).lower().endswith('.jsonl'): rows = [_source_json.loads(line) for line in path.read_text(encoding='utf-8-sig').splitlines() if line.strip()] cols = list(rows[0]) if rows and isinstance(rows[0], dict) else [] elif str(name).lower().endswith('.json'): rows = _source_json.loads(path.read_text(encoding='utf-8-sig')) if isinstance(rows, dict): rows = next((v for v in rows.values() if isinstance(v, list)), [rows]) if not isinstance(rows, list): raise ProjectSourceError("%s must contain a table of records" % name) cols = list(rows[0]) if rows and isinstance(rows[0], dict) else [] elif str(name).lower().endswith('.csv'): with path.open(encoding='utf-8-sig', newline='') as handle: reader = _source_csv.DictReader(handle) cols = list(reader.fieldnames or []) rows = list(reader) if len(set(cols)) != len(cols) or any(not c for c in cols): raise ProjectSourceError("%s has missing or duplicate column names" % name) else: raise ProjectSourceError("%s is not a CSV, JSON or JSONL table" % name) except (OSError, ValueError, TypeError) as exc: if isinstance(exc, ProjectSourceError): raise raise ProjectSourceError("%s could not be read as a table: %s" % (name, exc)) from exc if any(not isinstance(row, dict) or set(row) != set(cols) for row in rows): raise ProjectSourceError("%s has records with different columns or non-record rows" % name) if any(not isinstance(c, str) for c in cols): raise ProjectSourceError("%s has non-text column names" % name) return cols, [dict(row) for row in rows] def _source_key(row, columns): key = [] for column in columns: value = row.get(column) if value is None or str(value).strip() == '': return None if isinstance(value, (list, dict)) or isinstance(value, float) and not _source_math.isfinite(value): raise ProjectSourceError("join column %s must contain finite scalar keys" % column) key.append(str(value).strip()) return tuple(key) def source_snapshot(source, root='.'): """Return (ordered columns, rows), retaining empty CSV schemas.""" if not isinstance(source, dict): raise ProjectSourceError("the source shape must name its part") op = source.get('op') if op == 'read': return _source_table(root, source['file']) if op == 'union': inputs = source.get('inputs') or [] if not inputs: raise ProjectSourceError("stacking needs at least one source") cols, rows = None, [] for child in inputs: child_cols, child_rows = source_snapshot(child, root) if not child_cols and not child_rows: continue if cols is None: cols = child_cols if set(child_cols) != set(cols): raise ProjectSourceError("stacked sources have different columns: %s versus %s" % (cols, child_cols)) rows.extend({c: row[c] for c in cols} for row in child_rows) return cols or [], rows if op not in ('join', 'lookup'): raise ProjectSourceError("unknown source part %r" % op) left_cols, left_rows = source_snapshot(source['left'], root) right_cols, right_rows = source_snapshot(source['right'], root) keys = source.get('keys') or [] if not keys or any(not isinstance(pair, (list, tuple)) or len(pair) != 2 for pair in keys): raise ProjectSourceError("a join needs named left and right key columns") left_keys, right_keys = [p[0] for p in keys], [p[1] for p in keys] if len(set(left_keys)) != len(left_keys) or len(set(right_keys)) != len(right_keys): raise ProjectSourceError("a join key column was bound more than once") if any(c not in left_cols for c in left_keys) or any(c not in right_cols for c in right_keys): raise ProjectSourceError("join key columns are missing: %s; left %s; right %s" % (keys, left_cols, right_cols)) right_out = [c for c in right_cols if c not in right_keys] collisions = sorted(set(left_cols) & set(right_out)) if collisions: raise ProjectSourceError("both sources supply %s; rename the non-key columns explicitly before joining" % ', '.join(collisions)) how = source.get('how', 'inner') if how not in ('inner', 'left'): raise ProjectSourceError("join kind %r is not represented; name inner or left" % how) index = {} for row in right_rows: key = _source_key(row, right_keys) if key is not None: if op == 'lookup' and key in index: raise ProjectSourceError("lookup has more than one reference row for key %s" % (key,)) index.setdefault(key, []).append(row) rows = [] for row in left_rows: key = _source_key(row, left_keys) matches = index.get(key, []) if key is not None else [] if not matches and op == 'lookup': raise ProjectSourceError("lookup has no reference row for key %s; supply a matching reference" % (key,)) for match in matches: rows.append(dict(row, **{c: match[c] for c in right_out})) if not matches and how == 'left': rows.append(dict(row, **{c: None for c in right_out})) return left_cols + right_out, rows SOURCE_ROOT = '.' # where this program's sources are read: its folder when run there; an adopted capability's own folder def read_source(source, root=None): return source_snapshot(source, SOURCE_ROOT if root is None else root)[1] ''' exec(_RUNTIME) SourceError = ProjectSourceError DATA = re.compile(r"(?= 2) try: if not names: source = fallback elif len(names) == 1: source = _read(names[0]) if is_lookup and fallback and names[0] not in files(fallback): left, right = fallback, source keys, span = _keys(text, source_snapshot(left, root)[0], source_snapshot(right, root)[0], files(left), files(right), key_override) source = {'op': 'lookup', 'left': left, 'right': right, 'keys': keys, 'how': 'left'} if span: result['ops_text'] = text[:span[0]] + ' ' + text[span[1]:] if key_override is not None: result['retired_key_bindings'] = [text[span[0]:span[1]]] elif is_lookup or is_join: if len(names) != 2: raise SourceError('join or lookup names more than two sources; supply the next pair and its matching columns explicitly') left, right = _read(names[0]), _read(names[1]) # "lookup rates.csv for prices.csv" names the reference first. if re.search(r'\b(?:lookup|look up)\s+`?' + re.escape(names[0]) + r'\b', text, re.I): left, right = right, left keys, span = _keys(text, source_snapshot(left, root)[0], source_snapshot(right, root)[0], files(left), files(right), key_override) left_position = text.lower().find(files(left)[0].lower()) before_left = text[:left_position] if left_position >= 0 else '' keeps_left = re.search(r'\bleft\s+(?:outer\s+)?join\b', low) or re.search(r'\b(?:each|every|all)\b', before_left, re.I) how = 'left' if is_lookup or keeps_left else 'inner' if re.search(r'\binner\s+join\b', low): how = 'inner' source = {'op': 'lookup' if is_lookup else 'join', 'left': left, 'right': right, 'keys': keys, 'how': how} if span: result['ops_text'] = text[:span[0]] + ' ' + text[span[1]:] if key_override is not None: result['retired_key_bindings'] = [text[span[0]:span[1]]] elif is_stack or re.search(r'\bFILE\s*(?:,|and)', low): source = {'op': 'union', 'inputs': [_read(name) for name in names]} else: raise SourceError('several input tables are named; say whether to stack them or join them on named columns') if source is None: return result world = describe(root, source) result.update(source=source, world=world, files=files(source)) if source.get('op') != 'read': result['owned'] = _RELATION_WORDS.split() except (SourceError, KeyError, TypeError, OSError) as exc: result['holes'].append({'kind': 'source', 'files': names, 'text': str(exc)}) result['source'] = locals().get('source') return result