FeatureDB¶
The query database. All methods below are rendered from the live docstrings.
Close it, or use with
DuckDB takes an exclusive lock on the database file for the life of a
writable handle. Use a with block, or call close():
with FeatureDB("gencode.duckdb") as db:
...
db = FeatureDB("gencode.duckdb", read_only=True) # shareable by N processes
read_only=True is what lets several worker processes read one annotation
database at once. See
Connections & concurrency.
Use the _batched methods for bulk work
children(), parents() and region() return Feature objects one at a
time — right for exploring, wrong for feeding a model. children_batched(),
parents_batched() and region_batched() answer the same question for
thousands of anchors in a single query, returning Arrow / pandas / polars
without constructing any Feature objects.
gffbase.interface.FeatureDB ¶
FeatureDB(dbfn, default_encoding: str = 'utf-8', keep_order: bool = False, pragmas: dict | None = None, sort_attribute_values: bool = False, text_factory=str, upgrade: str = 'auto', read_only: bool = False, _own_conn: bool | None = None)
Drop-in successor to gffutils.FeatureDB.
Source code in python/gffbase/interface.py
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 | |
derived_source
property
¶
source for features this database derives rather than reads.
gffutils_derived under compat so ported scripts that filter on it
keep working; gffbase_derived under strict, which reports honest
provenance.
schema ¶
The database schema as SQL text.
A METHOD, not a property: gffutils documents db.schema() and callers
write it that way. Exposing it as a property meant the documented call
raised TypeError: 'str' object is not callable.
Source code in python/gffbase/interface.py
close ¶
Release the DuckDB connection. Idempotent.
The lazily-created segment cursor is closed whether or not the
connection is owned -- gffbase created it via conn.cursor(), so
gffbase closes it. The connection itself is closed only when this
handle opened it: a caller who passed their own connection in still
holds it afterwards.
Source code in python/gffbase/interface.py
validate ¶
Check this database's structural invariants.
See :func:gffbase.validate.validate_db. Run automatically at the end
of a strict-mode ingest; worth running by hand after update(),
delete() or coalesce_multipart(), which are the operations that can
leave the two halves of a discontinuous feature disagreeing.
Source code in python/gffbase/interface.py
count_features_of_type ¶
Count features, optionally of one type.
Parameters:
-
featuretype(str | None, default:None) –Restrict the count to this GFF column-3 value (
"gene","exon", …).Nonecounts every feature.
Returns:
-
int–The number of matching features. A discontinuous feature counts
-
int–once, however many input lines it was built from.
Source code in python/gffbase/interface.py
featuretypes ¶
Yield every distinct featuretype in the database, alphabetically.
Yields:
-
str–Each distinct GFF column-3 value, once.
Source code in python/gffbase/interface.py
seqids ¶
Yield every distinct sequence id in the database, alphabetically.
Useful for checking naming convention before a region() query --
chr1, 1 and NC_000001.11 are three different sequences as far as
the database is concerned, and GENCODE, Ensembl and RefSeq each pick a
different one.
Yields:
-
str–Each distinct GFF column-1 value, once.
Source code in python/gffbase/interface.py
all_features ¶
all_features(limit: RegionLike | None = None, strand: str | None = None, featuretype: str | list[str] | None = None, order_by: str | None = None, reverse: bool = False, completely_within: bool = False) -> Iterator[Feature]
Iterate over every feature in the database.
Parameters:
-
limit(RegionLike | None, default:None) –Restrict to a genomic region, as
"seqid:start-end"or a(seqid, start, end)tuple.Nonescans everything. -
strand(str | None, default:None) –Restrict to
"+","-"or".". -
featuretype(str | list[str] | None, default:None) –One featuretype, or a list of them.
-
order_by(str | None, default:None) –Column to sort by. One of
id,seqid,source,featuretype,start,end,score,strand,frame,attributes,extra,file_order,length. Anything else raisesValueError-- this is a whitelist, not a SQL fragment. -
reverse(bool, default:False) –Sort descending.
-
completely_within(bool, default:False) –With
limit, return only features contained entirely inside the region rather than merely overlapping it.
Yields:
-
Feature–Featureobjects infile_orderunlessorder_bysays otherwise.
Raises:
-
ValueError–order_bynames something outside the whitelist.
Example
Source code in python/gffbase/interface.py
method ¶
features_of_type ¶
features_of_type(featuretype: str | list[str], limit: RegionLike | None = None, strand: str | None = None, order_by: str | None = None, reverse: bool = False, completely_within: bool = False) -> Iterator[Feature]
Iterate over every feature of one type (or several).
Equivalent to all_features(featuretype=...); both exist because
gffutils has both.
Parameters:
-
featuretype(str | list[str]) –One featuretype (
"exon"), or a list of them. -
limit(RegionLike | None, default:None) –Restrict to a genomic region -- see
all_features. -
strand(str | None, default:None) –Restrict to
"+","-"or".". -
order_by(str | None, default:None) –Column to sort by -- see
all_featuresfor the permitted names. -
reverse(bool, default:False) –Sort descending.
-
completely_within(bool, default:False) –With
limit, require full containment.
Yields:
-
Feature–Matching
Featureobjects.
Source code in python/gffbase/interface.py
region ¶
region(region=None, seqid: str | None = None, start: int | None = None, end: int | None = None, strand: str | None = None, featuretype: str | list[str] | None = None, completely_within: bool = False) -> Iterator[Feature]
Features overlapping a genomic interval.
The interval can be given as a string, a tuple, or the three keyword arguments::
db.region("chr1:1000-2000")
db.region(("chr1", 1000, 2000))
db.region(seqid="chr1", start=1000, end=2000)
Parameters¶
region : str or tuple
"chrom:start-stop", or (chrom, start, stop).
seqid, start, end : optional
The same interval, spelled out. Mutually exclusive with region.
strand : {"+", "-", "."}, optional
Restrict to one orientation.
featuretype : str or list of str, optional
Restrict to one or several types.
completely_within : bool
False (default) returns anything that OVERLAPS the interval; True
returns only features contained entirely within it.
Which index answers the query is chosen here, not by the caller: an
R-tree when one was built and the interval is fully specified, the
multi-column B-tree otherwise. The two are semantically identical --
tests/test_spatial_parity.py asserts they return the same features --
so this is a planner decision, not a behavioural one.
A feature with no coordinates (a GFF row carrying . in columns 4 and
5) is not in coordinate space and is never returned.
Source code in python/gffbase/interface.py
to_table ¶
to_table(featuretype: str | list[str] | None = None, *, format: str = 'arrow', limit: RegionLike | None = None, strand: str | None = None, order_by: str | None = None, reverse: bool = False, completely_within: bool = False) -> Any
Return the whole database (or a slice of it) as one table.
The columnar counterpart to all_features(): same filters, but the
result is a pyarrow.Table / pandas.DataFrame / polars.DataFrame
instead of a stream of Feature objects, and no Feature is
constructed at any layer.
For "give me every exon as a dataframe", the row-by-row API pays a Python object per row -- millions of them on a whole-genome corpus -- and that allocation dominates everything else. This is one query and one hand-off.
Parameters:
-
featuretype(str | list[str] | None, default:None) –One featuretype, or a list of them.
Noneis everything. -
format(str, default:'arrow') –"arrow"(default, zero-copy),"df"for pandas, or"polars". -
limit(RegionLike | None, default:None) –Restrict to a genomic region, as
"seqid:start-end"or a(seqid, start, end)tuple. -
strand(str | None, default:None) –Restrict to
"+","-"or".". -
order_by(str | None, default:None) –Column to sort by -- the same whitelist
all_featuresaccepts. -
reverse(bool, default:False) –Sort descending.
-
completely_within(bool, default:False) –With
limit, require full containment.
Returns:
-
Any–A table in the shape named by
format, with one row per feature and the columns of thefeaturestable (id, seqid, source, featuretype, start, end, score, strand, frame, file_order).
Raises:
-
ValueError–order_bynames something outside the whitelist, orformatis not one of the three. -
ImportError–format="df"/"polars"without that package.
Example
Note
Attributes are not included: they are a long-form table, so
flattening them would either invent a column per key or collapse
multi-valued keys. Query the attributes table with execute()
when you need them.
Source code in python/gffbase/interface.py
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 | |
region_batched ¶
region_batched(regions, featuretype: str | list[str] | None = None, completely_within: bool = False, format: str = 'arrow', explode_segments: bool = False, on_invalid: str = 'raise')
Bulk overlap query. Performs a SINGLE spatial JOIN between every
input region and the features table, returning a column-oriented
result that maps each query (query_idx) back to its overlapping
features.
query_idx indexes regions as you passed it. That is the whole
contract of the column -- it is how a caller reassembles per-query
groups without re-issuing N queries.
Parameters¶
regions : iterable of (seqid, start, end) | str | Feature
Each item is normalized through _normalize_region_args; the
same four input shapes accepted by region() are accepted here.
featuretype : str | list[str] | None
Optional features.featuretype filter applied to all regions.
completely_within : bool
If True, only features fully contained in the region are returned
(default False — overlap is sufficient).
format : "arrow" | "df" | "polars"
Return shape (default "arrow").
on_invalid : {"raise", "skip"}
What to do with an item that does not normalize to a region.
"raise" (default) raises ValueError naming the offending
position and value. "skip" drops it while leaving every other
item's query_idx at its position in regions, so the gap is
visible rather than silently closed up.
bool
Emit one row per physical INPUT LINE rather than one per logical
feature, adding a seg_idx column. A discontinuous feature then
contributes a row per segment, each with its own coordinates,
score and phase -- which is what a caller writing a coverage track
or exporting to a line-oriented format actually needs.
Offered on the tabular APIs only, never on region() /
children() / all_features(): those must keep yielding
Feature objects, and letting FeatureSegment rows leak into
them would corrupt legacy consumers.
Result columns are query_idx, query_seqid, query_start,
query_end, id, seqid, source, featuretype, start, end, score,
strand, frame, file_order -- plus seg_idx when explode_segments.
Source code in python/gffbase/interface.py
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 | |
children ¶
children(id, level: int | None = None, featuretype: str | list[str] | None = None, order_by=None, reverse: bool = False, limit=None, completely_within: bool = False) -> Iterator[Feature]
Descendants of a feature, in hierarchy order.
Parameters¶
id : str or Feature
The anchor. A Feature built by hand has id is None and is
rejected rather than silently matching nothing.
level : int, optional
Only descendants exactly this many steps down -- 1 is direct
children. None (default) walks the whole subtree.
featuretype : str or list of str, optional
order_by : str or sequence of str, optional
A whitelisted sort key; anything else raises ValueError naming
the accepted set. See docs/security/2026-sql-injection.md for
why this is not a free-text field.
reverse : bool
Applies to every key, not just the last.
limit : str or tuple, optional
Restrict to a genomic interval, as region() accepts it.
completely_within : bool
With limit, require containment rather than overlap.
Reads from the materialized closure table when level is within the
database's recorded depth, and falls back to a recursive CTE when a
deeper walk is asked for. Both are cycle-safe: a Parent graph
containing a loop is traversed once, not until the depth budget runs
out.
Source code in python/gffbase/interface.py
parents ¶
parents(id, level: int | None = None, featuretype: str | list[str] | None = None, order_by=None, reverse: bool = False, completely_within: bool = False, limit=None) -> Iterator[Feature]
Ancestors of a feature, in hierarchy order.
The mirror of :meth:children, taking the same arguments and making
the same routing decision. level=1 is direct parents.
GFF3 permits a feature to name several Parents, so the hierarchy is
a DAG rather than a tree and one ancestor can be reachable by more
than one path. Each is returned once.
Source code in python/gffbase/interface.py
children_batched ¶
children_batched(feature_ids, level: int | None = None, featuretype: str | list[str] | None = None, format: str = 'arrow', explode_segments: bool = False)
Bulk children lookup. Returns the descendants of ALL feature_ids
in a single vectorized DuckDB query.
Parameters¶
feature_ids : iterable of str | Feature
Anchors. May contain Feature objects or raw ID strings.
level : int | None
None → all descendants (closure cache when materialized,
otherwise dynamic CTE). Integer → exact-depth point lookup.
featuretype : str | list[str] | None
Optional filter on features.featuretype.
format : "arrow" | "df" | "polars"
Return shape (default "arrow" — pyarrow.Table).
bool
Emit one row per physical INPUT LINE rather than one per logical
feature, adding a seg_idx column. Tabular APIs only -- see
region_batched.
Result columns are anchor (the parent ID supplied),
descendant_id, seqid, source, featuretype, start, end, score,
strand, frame, file_order, depth -- plus seg_idx when
explode_segments.
Source code in python/gffbase/interface.py
parents_batched ¶
parents_batched(feature_ids, level: int | None = None, featuretype: str | list[str] | None = None, format: str = 'arrow', explode_segments: bool = False)
Bulk parents lookup. Mirrors children_batched but walks the
closure / edges in the reverse direction.
Source code in python/gffbase/interface.py
delete ¶
delete(features: FeatureLike | Iterable[FeatureLike], make_backup: bool = True, **kwargs) -> FeatureDB
Delete features, and everything that referenced them.
Removes the rows from features, attributes, segments and edges,
then rebuilds the transitive closure so no path through a deleted node
survives -- deleting a transcript really does remove its exons from its
gene's descendants.
Parameters:
-
features(FeatureLike | Iterable[FeatureLike]) –A feature id, a
Feature, or an iterable of either. -
make_backup(bool, default:True) –Accepted for gffutils compatibility and currently ignored; no
.bakis written.
Returns:
-
FeatureDB–self, so calls can be chained.
Raises:
-
ReadOnlyError–The database was opened with
read_only=True.
Source code in python/gffbase/interface.py
update ¶
Add features to an existing database.
Appends to features, attributes and edges, then rebuilds the
transitive closure and re-reads the corpus statistics the relational
dispatcher routes on.
Parameters:
-
data(Iterable) –An iterable of
FeatureorParsedFeatureobjects, or anotherFeatureDBwhose features are copied in. -
make_backup(bool, default:True) –Accepted for gffutils compatibility and currently ignored; no
.bakis written.
Returns:
-
FeatureDB–self, so calls can be chained.
Raises:
-
ReadOnlyError–The database was opened with
read_only=True. -
TypeError–An item is neither a
Featurenor aParsedFeature.
Source code in python/gffbase/interface.py
2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 | |
add_relation ¶
Link one parent to one child.
parent_func / child_func receive (parent, child), and whatever
they RETURN is written back to the database. That is upstream's
contract and the reason assign_child returns the child: the callback
exists to edit an attribute (Parent=) that then has to be persisted.
Previously the return value was discarded and nothing was written, so
child_func=assign_child set an attribute on a throwaway object.
A string id is resolved to a Feature first, so callbacks fire whether
the caller passed objects or ids -- they used to be skipped silently
for ids.
Source code in python/gffbase/interface.py
add_relations ¶
add_relation for many pairs, with ONE closure rebuild.
Deriving the closure costs a recursive CTE over every edge, so doing it
per pair makes a bulk operation quadratic. merge_all links every
component of every merged feature and is the caller that made this
necessary.
Source code in python/gffbase/interface.py
interfeatures ¶
interfeatures(features, new_featuretype=None, merge_attributes: bool = True, numeric_sort: bool = False, dialect=None, attribute_func=None, update_attributes=None)
The gaps between consecutive features.
attribute_func takes ONE argument -- an attribute mapping -- and
returns one, matching the oracle. It is applied to each neighbour's
attributes before they are merged, not to the merged result. The
previous three-argument (prev, cur, attrs) form meant any gffutils
caller passing a callback got a TypeError.
Source code in python/gffbase/interface.py
2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 | |
merge ¶
Collapse runs of features that satisfy every criterion.
Consumes features in the order given. That is the oracle's
contract and it matters: merge_all supplies a specific
merge_order, and re-sorting here (which this used to do) silently
discarded it.
A feature that merged with nothing is yielded unchanged with
children set to no_children, so a caller can tell a real merge from
a pass-through by truthiness. merge_all depends on exactly that.
Source code in python/gffbase/interface.py
2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 | |
merge_all ¶
merge_all(merge_order=('seqid', 'featuretype', 'strand', 'start'), merge_criteria=None, featuretypes_groups=(None,), exclude_components: bool = False) -> list[Feature]
Merge everything in the database and write the results back.
Three things were wrong here and all three were silent. The method
returned every input feature including ones that merged with nothing,
so a caller could not tell what had actually been merged; it persisted
nothing, despite documenting that "the resulting records are added to
the database"; and it accepted exclude_components and ignored it, so
asking for the components to be removed did nothing at all.
Source code in python/gffbase/interface.py
create_introns ¶
create_introns(exon_featuretype: str = 'exon', grandparent_featuretype: str | None = 'gene', parent_featuretype: str | None = None, new_featuretype: str = 'intron', merge_attributes: bool = True, numeric_sort: bool = False) -> Iterator[Feature]
Introns, computed per transcript.
grandparent_featuretype="gene" descends one level first and computes
the gaps within each transcript separately. Treating the gene as the
direct anchor -- which this used to do -- pools the exons of every
isoform into one sorted list, so the "introns" of a multi-isoform gene
were computed across transcript boundaries and were not introns of
anything.
Source code in python/gffbase/interface.py
create_splice_sites ¶
create_splice_sites(exon_featuretype: str = 'exon', grandparent_featuretype: str | None = 'gene', parent_featuretype: str | None = None, merge_attributes: bool = True, numeric_sort: bool = False) -> Iterator[Feature]
The two-base splice sites flanking each intron.
A splice site is a dinucleotide -- GT at the donor, AG at the acceptor -- so these are 2 bp features, not the 1 bp ones this used to emit. They are typed by their position in the transcript rather than in the genome, so the left site of a minus-strand transcript is its 3' site.
Emission order is every left site, then every right site, matching the oracle; the intron's merged attributes are carried through with the ID prefixed by the featuretype so the two sites of one intron differ.
Source code in python/gffbase/interface.py
children_bp ¶
children_bp(feature: FeatureLike, child_featuretype: str = 'exon', merge: bool = False, merge_criteria: Sequence | None = None, **kwargs) -> int
Total base pairs covered by a feature's children.
Parameters:
-
feature(FeatureLike) –The parent, as an id or a
Feature. -
child_featuretype(str, default:'exon') –Which children to measure.
-
merge(bool, default:False) –Merge overlapping children first, so shared bases are counted once. Without it, overlapping children double-count.
-
merge_criteria(Sequence | None, default:None) –Predicates controlling what may merge; see
gffbase.merge_criteria. Defaults to same seqid, strand and featuretype with inclusive overlap.
Returns:
-
int–The summed length in base pairs.
Raises:
-
ValueError–The removed
ignore_strandargument was passed. -
TypeError–Any other unexpected keyword argument.
Source code in python/gffbase/interface.py
bed12 ¶
bed12(feature: FeatureLike, block_featuretype: Sequence[str] = ('exon',), thick_featuretype: Sequence[str] = ('CDS',), thin_featuretype: Sequence[str] | None = None, name_field: str = 'ID', color: str | None = None) -> str
Render a feature and its children as one BED12 line.
Parameters:
-
feature(FeatureLike) –The parent, as an id or a
Feature. -
block_featuretype(Sequence[str], default:('exon',)) –Child types that become BED blocks (exons).
-
thick_featuretype(Sequence[str], default:('CDS',)) –Child types that define the thick region (coding sequence).
-
thin_featuretype(Sequence[str] | None, default:None) –Child types that define the thin region. When given, it is honoured rather than inferred.
-
name_field(str, default:'ID') –Attribute used for BED column 4. Falls back to the feature id when absent.
-
color(str | None, default:None) –RGB string for column 9, e.g.
"255,0,0".
Returns:
-
str–A tab-separated BED12 line, without a trailing newline.
Note
A feature with no thick children is emitted as entirely thick.
blockSizes and blockStarts carry no trailing comma.
Source code in python/gffbase/interface.py
2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 | |
iter_by_parent_childs ¶
iter_by_parent_childs(featuretype: str = 'gene', level: int | None = None, order_by: str | None = None, reverse: bool = False, completely_within: bool = False) -> Iterator[list[Feature]]
Group the database by parent, yielding one list per parent.
Parameters:
-
featuretype(str, default:'gene') –The parent featuretype to group by.
-
level(int | None, default:None) –How deep to collect children.
Nonetakes the whole subtree;1takes direct children only. -
order_by(str | None, default:None) –Column to sort parents by -- see
all_features. -
reverse(bool, default:False) –Sort parents descending.
-
completely_within(bool, default:False) –Passed through to the child query.
Yields:
-
list[Feature]–A list per parent, the parent first followed by its children.
Source code in python/gffbase/interface.py
attribute_search ¶
Features with an attribute VALUE matching text, case-insensitively.
text is SQL LIKE syntax, so % and _ are wildcards; a bare
string matches as a substring, which is what a caller searching for an
accession expects.
gffutils' CLI calls db.attribute_search(...), but no such method
exists anywhere in gffutils -- only in that call site and in an
obsolete test file -- so gffutils-cli search raises AttributeError
on every invocation. This is a working implementation rather than a
port of one.
The search is over the long-form attributes table, not over the raw
column-9 blob, so it matches DECODED values: searching for a;b finds
a feature whose source said a%3Bb.
Source code in python/gffbase/interface.py
execute ¶
Execute arbitrary SQL. Returns DuckDB's relation cursor.
SQLite-style queries against features_compat and relations_compat
views are supported; see compat_views.sql.
Deliberately NOT guarded against read_only: this is the escape
hatch, the SQL is the caller's, and DuckDB's own refusal names the
statement it rejected, which is more use here than a generic message
from us.
Source code in python/gffbase/interface.py
analyze ¶
Refresh DuckDB's planner statistics for this database.
Worth running once after a large update(); the planner otherwise
keeps costing queries against the shape the database had at ingest.
Raises:
-
ReadOnlyError–The database was opened with
read_only=True.
Source code in python/gffbase/interface.py
set_pragmas ¶
Apply DuckDB settings, ignoring pragmas that only SQLite has.
Legacy callers pass constants.default_pragmas -- synchronous,
journal_mode, main.page_size, main.cache_size -- none of which
DuckDB has. Those are skipped, which is what makes a gffutils script
run here unchanged.
Both the name and the value used to be interpolated straight into the
statement, and the whole loop body sat inside except duckdb.Error:
continue. DuckDB executes trailing statements, so
db.set_pragmas({"threads": "1; DROP TABLE attributes"})
dropped the table -- and because the exception was swallowed, a payload that failed was silent too. Names are now matched against DuckDB's own settings catalog and values rendered as SQL literals, so nothing a caller supplies reaches the parser as syntax.
Matching the live catalog rather than a hardcoded list means the check tracks whatever DuckDB build is installed, instead of going stale and rejecting settings a newer version added.