{
  "manifest_version": 1,
  "community_extension": {
    "extension": {
      "name": "duckhts",
      "description": "DuckDB extension for reading HTS file formats via htslib",
      "language": "C",
      "build": "cmake",
      "license": "MIT",
      "requires_toolchains": "python3",
      "excluded_platforms": "windows_amd64;windows_arm64",
      "maintainers": [
        "sounkou-bioinfo"
      ]
    },
    "repo": {
      "github": "RGenomicsETL/duckhts",
      "ref_source": "git_head"
    },
    "docs": {
      "hello_world_lines": [
        "-- Load the extension",
        "LOAD duckhts;",
        "",
        "-- Read a VCF/BCF file (tidy FORMAT columns)",
        "SELECT CHROM, POS, REF, ALT, SAMPLE_ID",
        "FROM read_bcf('test/data/formatcols.vcf.gz', tidy_format := true)",
        "LIMIT 5;",
        "",
        "-- Read a BAM/SAM file",
        "SELECT QNAME, RNAME, POS, READ_GROUP_ID, SAMPLE_ID",
        "FROM read_bam('test/data/rg.sam.gz')",
        "LIMIT 5;"
      ],
      "extended_intro": [
        "DuckHTS provides DuckDB table functions for common high-throughput sequencing (HTS) formats using htslib. Query VCF, BCF, BAM, CRAM, FASTA, FASTQ, GTF, GFF, and tabix-indexed files directly in SQL.",
        "The extension also includes sequence utility UDFs, SAM flag predicate helpers, and HTS metadata helpers."
      ],
      "feature_notes": [
        "Reader table functions accept scan_mode := 'sequential' to force full-file streaming/counting instead of index-backed count/parallel paths where applicable; region queries remain index-backed and are incompatible with sequential mode.",
        "Paired FASTQ is supported via `mate_path` or `interleaved := true`.",
        "CRAM reads are supported with an explicit reference file.",
        "GTF/GFF attributes can be returned as a parsed `MAP` with `attributes_map := true` via `read_gff` or `read_gtf`.",
        "Optional SAM tag columns and an auxiliary tag map are available through `standard_tags` and `auxiliary_tags`.",
        "Tabix readers support `header`, `header_names`, type inference with `auto_detect`, and explicit `column_types`.",
        "MSVC builds (`windows_amd64`/`windows_arm64`) are not supported; use MinGW/RTools on Windows."
      ]
    }
  },
  "functions": [
    {
      "name": "duckhts_simd_backend",
      "kind": "scalar",
      "category": "Diagnostics",
      "signature": "duckhts_simd_backend()",
      "returns": "VARCHAR",
      "r_wrapper": "rduckhts_simd_backend",
      "description": "Return the current DuckHTS SIMD dispatch label. For explicit scalar or concrete backend requests this is the requested policy; for auto it is the single selected backend when all logical kernels resolve to the same backend, or mixed when per-kernel auto-dispatch resolves to multiple backends. Use duckhts_simd_kernel_info() for per-kernel details.",
      "examples": [
        "SELECT duckhts_simd_backend();"
      ]
    },
    {
      "name": "duckhts_simd_requested_backend",
      "kind": "scalar",
      "category": "Diagnostics",
      "signature": "duckhts_simd_requested_backend()",
      "returns": "VARCHAR",
      "r_wrapper": "rduckhts_simd_requested_backend",
      "description": "Return the current explicit SIMD backend request, usually auto unless `SELECT backend FROM duckhts_simd_set_backend('auto'|'scalar'|backend)` was called. The selected per-kernel backend may differ under auto-dispatch across x86, ARM, wasm, and scalar-only builds.",
      "examples": [
        "SELECT duckhts_simd_requested_backend();"
      ]
    },
    {
      "name": "duckhts_simd_backend_compiled",
      "kind": "scalar",
      "category": "Diagnostics",
      "signature": "duckhts_simd_backend_compiled(backend)",
      "returns": "BOOLEAN",
      "r_wrapper": "rduckhts_simd_backend_compiled",
      "description": "Return whether a concrete DuckHTS SIMD backend was compiled into this build. This is independent of whether the current CPU/runtime supports executing that backend; for example avx512 can be compiled but not CPU-supported on the running host.",
      "examples": [
        "SELECT duckhts_simd_backend_compiled('scalar');",
        "SELECT duckhts_simd_backend_compiled('avx512');"
      ]
    },
    {
      "name": "duckhts_simd_backend_cpu_supported",
      "kind": "scalar",
      "category": "Diagnostics",
      "signature": "duckhts_simd_backend_cpu_supported(backend)",
      "returns": "BOOLEAN",
      "r_wrapper": "rduckhts_simd_backend_cpu_supported",
      "description": "Return whether the current CPU/runtime supports a concrete DuckHTS SIMD backend, independent of whether DuckHTS compiled an implementation for it. Availability is the intersection of compiled and CPU-supported.",
      "examples": [
        "SELECT duckhts_simd_backend_cpu_supported('avx2');",
        "SELECT duckhts_simd_backend_cpu_supported('avx512');"
      ]
    },
    {
      "name": "duckhts_simd_backend_available",
      "kind": "scalar",
      "category": "Diagnostics",
      "signature": "duckhts_simd_backend_available(backend)",
      "returns": "BOOLEAN",
      "r_wrapper": "rduckhts_simd_backend_available",
      "description": "Return whether a concrete SIMD backend is usable in the current process. Availability means the backend is compiled into DuckHTS and supported by the current CPU/runtime. auto is a selection request rather than a concrete backend and is not reported as available here.",
      "examples": [
        "SELECT duckhts_simd_backend_available('scalar');",
        "SELECT duckhts_simd_backend_available('avx2');",
        "SELECT duckhts_simd_backend_available('avx512');"
      ]
    },
    {
      "name": "duckhts_simd_info",
      "kind": "table",
      "category": "Diagnostics",
      "signature": "duckhts_simd_info()",
      "returns": "table",
      "r_wrapper": "rduckhts_simd_info",
      "description": "Return one row per known concrete DuckHTS SIMD backend with extension-owned selectable, compiled, CPU-supported, available, selected, requested, and dispatch-mode diagnostics. Availability is the intersection of compiled and CPU/runtime-supported. selectable reports whether the backend has a selectable implementation path; explicit selection still requires available = TRUE. selected is TRUE when the current dispatch table uses that backend for at least one logical kernel. auto is a selection request and is not a concrete backend row.",
      "examples": [
        "SELECT * FROM duckhts_simd_info();",
        "SELECT backend FROM duckhts_simd_info() WHERE available;"
      ]
    },
    {
      "name": "duckhts_simd_kernel_info",
      "kind": "table",
      "category": "Diagnostics",
      "signature": "duckhts_simd_kernel_info()",
      "returns": "table",
      "r_wrapper": "rduckhts_simd_kernel_info",
      "description": "Return one row per logical DuckHTS SIMD kernel showing the concrete backend selected by the current immutable dispatch table, the selected capability, the requested backend policy, whether scalar was used as a per-kernel fallback, and the dispatch mode. This is the authoritative diagnostic for mixed auto-dispatch when different kernels resolve to different backends.",
      "examples": [
        "SELECT * FROM duckhts_simd_kernel_info();",
        "SELECT kernel, selected_backend FROM duckhts_simd_kernel_info();"
      ]
    },
    {
      "name": "duckhts_simd_set_backend",
      "kind": "table",
      "category": "Diagnostics",
      "signature": "duckhts_simd_set_backend(backend)",
      "returns": "table(backend VARCHAR)",
      "r_wrapper": "rduckhts_simd_set_backend",
      "description": "Explicitly select the DuckHTS SIMD dispatch policy for this process using a one-row table-function call and return the current dispatch label in a backend column. Use auto for per-kernel runtime dispatch or scalar for a portable baseline; unavailable platform-specific requests such as avx512 on non-AVX-512 CPUs raise an error instead of silently falling back.",
      "examples": [
        "SELECT backend FROM duckhts_simd_set_backend('scalar');",
        "SELECT backend FROM duckhts_simd_set_backend('auto');"
      ]
    },
    {
      "name": "duckhts_duckdb_type_supported",
      "kind": "scalar_macro",
      "category": "Diagnostics",
      "signature": "duckhts_duckdb_type_supported(type_name)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Return whether the currently open DuckDB runtime advertises a logical type with the given name through duckdb_types(). This is a catalog-level runtime probe for feature gating SQL/macros across DuckDB versions.",
      "examples": [
        "SELECT duckhts_duckdb_type_supported('VARIANT');",
        "SELECT duckhts_duckdb_type_supported('GEOMETRY');"
      ]
    },
    {
      "name": "duckhts_duckdb_supports_variant",
      "kind": "scalar_macro",
      "category": "Diagnostics",
      "signature": "duckhts_duckdb_supports_variant()",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Return whether the currently open DuckDB runtime advertises the VARIANT logical type. Use this to gate optional SQL that depends on DuckDB VARIANT support.",
      "examples": [
        "SELECT duckhts_duckdb_supports_variant();"
      ]
    },
    {
      "name": "duckhts_duckdb_supports_geometry",
      "kind": "scalar_macro",
      "category": "Diagnostics",
      "signature": "duckhts_duckdb_supports_geometry()",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Return whether the currently open DuckDB runtime advertises the GEOMETRY logical type. Use this to gate optional SQL that depends on DuckDB GEOMETRY support.",
      "examples": [
        "SELECT duckhts_duckdb_supports_geometry();"
      ]
    },
    {
      "name": "read_bcf",
      "kind": "table",
      "category": "Readers",
      "signature": "read_bcf(path, region := NULL, index_path := NULL, tidy_format := FALSE, additional_csq_column_types := NULL, scan_mode := 'auto', decompression_threads := 0, decode_error_policy := 'null')",
      "returns": "table",
      "r_wrapper": "rduckhts_bcf",
      "description": "Read VCF and BCF variant data with typed INFO, FORMAT, typed CSQ/ANN/BCSQ subfields, optional tidy sample output, optional bcftools-style CSQ type overrides, explicit scan_mode control ('auto' or full-file 'sequential'), optional htslib decompression worker threads via decompression_threads (default 0 for single-threaded reads), and decode_error_policy ('null', 'warn', or 'error') for corrupt BCF header-vs-payload decode mismatches.",
      "examples": [
        "SELECT CHROM, POS, REF, ALT FROM read_bcf('vcf_file.bcf') LIMIT 5;"
      ]
    },
    {
      "name": "read_bcf_v2",
      "kind": "table",
      "category": "Readers",
      "signature": "read_bcf_v2(path, region := NULL, index_path := NULL, tidy_format := FALSE, additional_csq_column_types := NULL, scan_mode := 'auto', decompression_threads := 0, decode_error_policy := 'null', samples := NULL, samples_file := NULL, exclude_samples := NULL, exclude_samples_file := NULL, force_samples := FALSE, include_info := TRUE, include_format := TRUE, include_vep := TRUE, info_fields := NULL, format_fields := NULL, vep_fields := NULL)",
      "returns": "table",
      "r_wrapper": "",
      "description": "Experimental clone of read_bcf(...) for non-destructive benchmarking of current-schema scan optimizations. It preserves the read_bcf wide/tidy output schema by default, streams full-file scans by default instead of auto-iterating indexed contigs, accepts the same scan_mode and decode_error_policy ('null', 'warn', or 'error') contract as read_bcf, sets htslib VCF text max_unpack from DuckDB projection pushdown so unprojected INFO/FORMAT text can be skipped earlier, keeps INFO/FORMAT/GT decode buffers and parsed VEP/CSQ records in local scan state across output chunks, repeats VEP-derived values correctly across tidy sample rows, supports v2-only htslib sample pushdown via comma-separated samples/exclude_samples strings or samples_file/exclude_samples_file lists, can bind only requested INFO/FORMAT/VEP fields through include_info/include_format/include_vep and comma-separated info_fields/format_fields/vep_fields controls, rejects format_fields when no samples are selected, treats tidy_format := true with include_format := false as one row per variant because no SAMPLE_ID/FORMAT columns are bound, and counts VCF text rows without parsing when no columns are projected.",
      "examples": [
        "SELECT CHROM, POS, REF, ALT FROM read_bcf_v2('vcf_file.bcf') LIMIT 5;"
      ]
    },
    {
      "name": "read_bcf_appender",
      "kind": "table",
      "category": "Readers",
      "signature": "read_bcf_appender(path, target_table, region := NULL, tidy_format := TRUE, overwrite := TRUE, include_file_offset := FALSE, region_threads := 1, decompression_threads := 0, decode_error_policy := 'null')",
      "returns": "table",
      "r_wrapper": "",
      "description": "Experimental side-effecting benchmark helper that reads BCF/VCF with htslib and appends a narrow scalar tidy table through DuckDB's chunk appender API. The target table is created in the default schema with columns CHROM, POS, REF, ALT, SAMPLE_ID, and FORMAT_GT; set include_file_offset := TRUE to also add FILE_OFFSET. For comma-separated region queries, region_threads > 1 claims regions in parallel and adds duckhts_region_idx so callers can restore requested-region order with ORDER BY duckhts_region_idx, POS. The single-stream (region_threads = 1) path runs inside an internal transaction and surfaces malformed-record errors as DuckDB errors; decode_error_policy controls corrupt BCF FORMAT/GT header-vs-payload mismatches with 'null', 'warn', or 'error'. The parallel path shares one DuckDB connection across worker appenders and is best-effort benchmarking only, with no transactional rollback. target_table must be an unqualified SQL identifier. This is intended to compare appender-based materialization against read_bcf(...) query pipelines, not as a full replacement for the typed read_bcf surface.",
      "examples": [
        "SELECT * FROM read_bcf_appender('vcf_file.bcf', 'bcf_app', region := '1:1-1000000');",
        "SELECT count(*) FROM bcf_app;"
      ]
    },
    {
      "name": "read_bam",
      "kind": "table",
      "category": "Readers",
      "signature": "read_bam(path, standard_tags := FALSE, auxiliary_tags := FALSE, region := NULL, index_path := NULL, reference := NULL, sequence_encoding := 'string', quality_representation := 'string', cigar_representation := 'string', scan_mode := 'auto', decompression_threads := 2)",
      "returns": "table",
      "r_wrapper": "rduckhts_bam",
      "description": "Read SAM, BAM, and CRAM alignments with optional typed SAMtags and auxiliary tag maps. Use sequence_encoding := 'nt16' to return SEQ as UTINYINT[], quality_representation := 'phred' to return QUAL as UTINYINT[], and cigar_representation := 'binary' to return packed BAM CIGAR operations as UINTEGER[] instead of SAM text. scan_mode := 'sequential' forces a full-file streaming scan instead of index-backed count/parallel paths and is incompatible with region. decompression_threads controls per-file htslib worker threads and defaults to 2; use 0 to disable worker threads.",
      "examples": [
        "SELECT QNAME, FLAG, RNAME, POS FROM read_bam('range.bam') LIMIT 5;"
      ]
    },
    {
      "name": "duckhts_bcf_convert_parquet_sql",
      "kind": "scalar_macro",
      "category": "Converters",
      "signature": "duckhts_bcf_convert_parquet_sql(path, output, columns := []::VARCHAR[], region := NULL, index_path := NULL, tidy_format := FALSE, additional_csq_column_types := NULL, decompression_threads := 0, where_sql := NULL, compression := 'zstd', row_group_size := 100000, partition_by := []::VARCHAR[], include_metadata := TRUE, header_text := NULL, metadata := map([]::VARCHAR[], []::VARCHAR[]), metadata_json_file := NULL, overwrite := FALSE, write_format_version := '1')",
      "returns": "VARCHAR",
      "r_wrapper": "rduckhts_bcf_convert_parquet",
      "description": "Build a DuckDB COPY statement that converts read_bcf(...) output to Parquet with DuckHTS key-value metadata, preserved or corrected VCF header text, user metadata from metadata := map(...), selected columns, filters, and partition columns. Optional metadata_json_file is caller-managed and requires DuckDB's json extension to be available when the builder is called; use metadata maps for CRAN/offline-safe workflows. Clients execute the returned SQL string; the R wrapper is a thin DBI helper that does this execution.",
      "examples": [
        "SELECT duckhts_bcf_convert_parquet_sql('cohort.vcf.gz', 'cohort.parquet', columns := ['CHROM','POS','REF','ALT'], metadata := map(['project'], ['cohort-a']));"
      ]
    },
    {
      "name": "duckhts_bam_convert_parquet_sql",
      "kind": "scalar_macro",
      "category": "Converters",
      "signature": "duckhts_bam_convert_parquet_sql(path, output, columns := []::VARCHAR[], region := NULL, index_path := NULL, reference := NULL, standard_tags := FALSE, auxiliary_tags := FALSE, sequence_encoding := NULL, quality_representation := NULL, cigar_representation := NULL, decompression_threads := 2, where_sql := NULL, compression := 'zstd', row_group_size := 100000, partition_by := []::VARCHAR[], include_metadata := TRUE, header_text := NULL, metadata := map([]::VARCHAR[], []::VARCHAR[]), metadata_json_file := NULL, overwrite := FALSE, write_format_version := '1')",
      "returns": "VARCHAR",
      "r_wrapper": "rduckhts_bam_convert_parquet",
      "description": "Build a DuckDB COPY statement that converts read_bam(...) output to Parquet with DuckHTS key-value metadata, preserved or corrected SAM header text, user metadata from metadata := map(...), selected columns, filters, and partition columns. Optional metadata_json_file is caller-managed and requires DuckDB's json extension to be available when the builder is called; use metadata maps for CRAN/offline-safe workflows. Clients execute the returned SQL string; the R wrapper is a thin DBI helper that does this execution.",
      "examples": [
        "SELECT duckhts_bam_convert_parquet_sql('sample.bam', 'sample.parquet', columns := ['QNAME','FLAG','RNAME','POS']);"
      ]
    },
    {
      "name": "duckhts_gff_convert_parquet_sql",
      "kind": "scalar_macro",
      "category": "Converters",
      "signature": "duckhts_gff_convert_parquet_sql(path, output, columns := []::VARCHAR[], region := NULL, index_path := NULL, header := NULL, header_names := []::VARCHAR[], auto_detect := NULL, column_types := []::VARCHAR[], attributes_map := FALSE, attributes_list := FALSE, attributes_pairs := FALSE, strict := FALSE, where_sql := NULL, compression := 'zstd', row_group_size := 100000, partition_by := []::VARCHAR[], include_metadata := TRUE, header_text := NULL, metadata := map([]::VARCHAR[], []::VARCHAR[]), metadata_json_file := NULL, overwrite := FALSE, write_format_version := '1')",
      "returns": "VARCHAR",
      "r_wrapper": "rduckhts_gff_convert_parquet",
      "description": "Build a DuckDB COPY statement that converts read_gff(...) output to Parquet with DuckHTS key-value metadata, preserved or corrected GFF/tabix header text, user metadata from metadata := map(...), selected columns, filters, and partition columns. Optional metadata_json_file is caller-managed and requires DuckDB's json extension to be available when the builder is called; use metadata maps for CRAN/offline-safe workflows. Clients execute the returned SQL string; the R wrapper is a thin DBI helper that does this execution.",
      "examples": [
        "SELECT duckhts_gff_convert_parquet_sql('annotations.gff3.gz', 'annotations/', columns := ['seqname','feature','start','end'], partition_by := ['feature']);"
      ]
    },
    {
      "name": "duckhts_tabix_convert_parquet_sql",
      "kind": "scalar_macro",
      "category": "Converters",
      "signature": "duckhts_tabix_convert_parquet_sql(path, output, columns := []::VARCHAR[], region := NULL, index_path := NULL, header := NULL, header_names := []::VARCHAR[], auto_detect := NULL, column_types := []::VARCHAR[], where_sql := NULL, compression := 'zstd', row_group_size := 100000, partition_by := []::VARCHAR[], include_metadata := TRUE, header_text := NULL, metadata := map([]::VARCHAR[], []::VARCHAR[]), metadata_json_file := NULL, overwrite := FALSE, write_format_version := '1')",
      "returns": "VARCHAR",
      "r_wrapper": "rduckhts_tabix_convert_parquet",
      "description": "Build a DuckDB COPY statement that converts read_tabix(...) output to Parquet with DuckHTS key-value metadata, preserved or corrected tabix header text, user metadata from metadata := map(...), selected columns, filters, and partition columns. Optional metadata_json_file is caller-managed and requires DuckDB's json extension to be available when the builder is called; use metadata maps for CRAN/offline-safe workflows. Clients execute the returned SQL string; the R wrapper is a thin DBI helper that does this execution.",
      "examples": [
        "SELECT duckhts_tabix_convert_parquet_sql('regions.tsv.gz', 'regions.parquet', header_names := ['chrom','pos','value'], auto_detect := TRUE);"
      ]
    },
    {
      "name": "read_pileup",
      "kind": "table",
      "category": "Coverage",
      "signature": "read_pileup(path, region := NULL, index_path := NULL, min_mapq := 0, flag_mask := 1796)",
      "returns": "table",
      "r_wrapper": "rduckhts_pileup",
      "description": "Construct a region-scoped BAM pileup with one row per covered position, emitting chrom, 1-based position, depth, observed bases, and Phred+33 qualities after SAM flag and MAPQ filtering. This is a compact htslib pileup view, not samtools mpileup text parity.",
      "examples": [
        "SELECT chrom, pos, depth FROM read_pileup('range.bam', region := 'CHROMOSOME_I:1-200') LIMIT 5;"
      ]
    },
    {
      "name": "read_fasta",
      "kind": "table",
      "category": "Readers",
      "signature": "read_fasta(path, region := NULL, index_path := NULL, gzi_path := NULL, sequence_encoding := 'string', scan_mode := 'auto')",
      "returns": "table",
      "r_wrapper": "rduckhts_fasta",
      "description": "Read FASTA records or indexed FASTA regions as sequence rows. Use sequence_encoding := 'nt16' to return SEQUENCE as UTINYINT[] (htslib nt16 4-bit codes) instead of VARCHAR. For bgzipped FASTA, gzi_path may point to an explicit .gzi sidecar when it is not colocated with the FASTA. scan_mode := 'sequential' forces full-file streaming/counting instead of index-backed count paths and is incompatible with region.",
      "examples": [
        "SELECT NAME, length(SEQUENCE) FROM read_fasta('ce.fa');"
      ]
    },
    {
      "name": "read_bed",
      "kind": "table",
      "category": "Readers",
      "signature": "read_bed(path, region := NULL, index_path := NULL, scan_mode := 'auto')",
      "returns": "table",
      "r_wrapper": "rduckhts_bed",
      "description": "Read BED3-BED12 interval files with canonical typed columns and optional tabix-backed region filtering. scan_mode := 'sequential' forces full-file streaming/counting instead of index-backed count paths and is incompatible with region.",
      "examples": [
        "SELECT chrom, start, \"end\", name FROM read_bed('targets.bed') LIMIT 5;"
      ]
    },
    {
      "name": "fasta_nuc",
      "kind": "table",
      "category": "Readers",
      "signature": "fasta_nuc(path, bed_path := NULL, bin_width := NULL, region := NULL, index_path := NULL, gzi_path := NULL, bed_index_path := NULL, include_seq := FALSE)",
      "returns": "table",
      "r_wrapper": "rduckhts_fasta_nuc",
      "description": "Compute bedtools nuc-style nucleotide composition for supplied BED intervals or generated fixed-width bins over a FASTA reference. For bgzipped FASTA, gzi_path may point to an explicit .gzi sidecar when it is not colocated with the FASTA.",
      "examples": [
        "SELECT chrom, start, \"end\", pct_gc FROM fasta_nuc('ce.fa', bin_width := 1000) LIMIT 5;"
      ]
    },
    {
      "name": "duckhts_cgranges_create",
      "kind": "scalar",
      "category": "Intervals",
      "signature": "duckhts_cgranges_create(name)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Create an empty session-scoped cgranges registry entry that can be populated with intervals and finalized for overlap queries.",
      "examples": [
        "SELECT duckhts_cgranges_create('targets_idx');"
      ]
    },
    {
      "name": "duckhts_cgranges_add",
      "kind": "scalar",
      "category": "Intervals",
      "signature": "duckhts_cgranges_add(name, chrom, start, end[, label])",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Append an interval to a session-scoped cgranges registry entry before finalization. Labels may be BIGINT-like, DOUBLE, VARCHAR, or BOOLEAN.",
      "examples": [
        "SELECT duckhts_cgranges_add('targets_idx', 'chr1', 10, 20, 'exon1');"
      ]
    },
    {
      "name": "duckhts_cgranges_index",
      "kind": "scalar",
      "category": "Intervals",
      "signature": "duckhts_cgranges_index(name)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Finalize a populated cgranges registry entry and build its immutable overlap index for subsequent queries.",
      "examples": [
        "SELECT duckhts_cgranges_index('targets_idx');"
      ]
    },
    {
      "name": "duckhts_cgranges_destroy",
      "kind": "scalar",
      "category": "Intervals",
      "signature": "duckhts_cgranges_destroy(name)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Destroy a session-scoped cgranges registry entry and release its indexed interval storage when it is not in active use.",
      "examples": [
        "SELECT duckhts_cgranges_destroy('targets_idx');"
      ]
    },
    {
      "name": "duckhts_cgranges_from_query",
      "kind": "scalar",
      "category": "Intervals",
      "signature": "duckhts_cgranges_from_query(name, query, chrom_col, start_col, end_col[, label_col])",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Execute a SQL query on an extension-owned DuckDB connection, append its interval rows into a session-scoped cgranges registry entry, and leave the populated index ready for explicit finalization with duckhts_cgranges_index(...).",
      "examples": [
        "SELECT duckhts_cgranges_from_query('targets_idx', 'SELECT chrom, start, \"end\", name FROM targets', 'chrom', 'start', 'end', 'name');"
      ]
    },
    {
      "name": "duckhts_cgranges_from_table",
      "kind": "scalar",
      "category": "Intervals",
      "signature": "duckhts_cgranges_from_table(name, table_name, chrom_col, start_col, end_col[, label_col])",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Reserved convenience constructor for bulk cgranges population from a table name. The current implementation is intentionally deferred and directs callers to duckhts_cgranges_from_query(...).",
      "examples": [
        "SELECT duckhts_cgranges_from_table('targets_idx', 'targets', 'chrom', 'start', 'end', 'name');"
      ]
    },
    {
      "name": "duckhts_cgranges_has_overlap",
      "kind": "scalar",
      "category": "Intervals",
      "signature": "duckhts_cgranges_has_overlap(name, chrom, start, end[, mode])",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Vectorized scalar predicate for streaming provider rows through a finalized session-scoped cgranges index. Returns TRUE when the query interval overlaps at least one indexed interval, or when mode = 'contain' and it fully contains at least one indexed interval; NULL inputs return NULL.",
      "examples": [
        "SELECT * FROM read_bed('queries.bed') WHERE duckhts_cgranges_has_overlap('targets_idx', chrom, start, \"end\");"
      ]
    },
    {
      "name": "duckhts_cgranges_count_overlaps",
      "kind": "scalar",
      "category": "Intervals",
      "signature": "duckhts_cgranges_count_overlaps(name, chrom, start, end[, mode])",
      "returns": "BIGINT",
      "r_wrapper": "",
      "description": "Vectorized scalar overlap counter for streaming provider rows through a finalized session-scoped cgranges index. Returns the number of indexed intervals that overlap the query interval, or with mode = 'contain' the number fully contained by it; NULL inputs return NULL.",
      "examples": [
        "SELECT chrom, start, \"end\", duckhts_cgranges_count_overlaps('targets_idx', chrom, start, \"end\") AS n_targets FROM read_bed('queries.bed');"
      ]
    },
    {
      "name": "duckhts_cgranges_overlaps_list",
      "kind": "scalar",
      "category": "Intervals",
      "signature": "duckhts_cgranges_overlaps_list(name, chrom, start, end[, mode])",
      "returns": "STRUCT(interval_ordinal BIGINT, label VARCHAR, label_type VARCHAR, interval_chrom VARCHAR, interval_start INTEGER, interval_end INTEGER)[]",
      "r_wrapper": "",
      "description": "Vectorized scalar overlap expander for streaming provider rows through a finalized session-scoped cgranges index. Returns a LIST of hit STRUCTs that can be expanded with UNNEST, preserving provider columns while emitting one row per matching indexed interval. Because scalar return types are fixed, labels are returned as text with label_type describing the original cgranges label kind; NULL inputs return NULL.",
      "examples": [
        "SELECT q.*, hit.interval_chrom, hit.interval_start, hit.interval_end, hit.label FROM read_bed('queries.bed') AS q CROSS JOIN UNNEST(duckhts_cgranges_overlaps_list('targets_idx', q.chrom, q.start, q.\"end\")) AS u(hit);"
      ]
    },
    {
      "name": "duckhts_cgranges_overlaps",
      "kind": "table",
      "category": "Intervals",
      "signature": "duckhts_cgranges_overlaps(name, chrom, start, end, mode := 'overlap', query_row_id := NULL)",
      "returns": "table",
      "r_wrapper": "",
      "description": "Query a finalized session-scoped cgranges registry entry and return one row per overlapping or containing indexed interval, preserving the original label type and interval coordinates.",
      "examples": [
        "SELECT * FROM duckhts_cgranges_overlaps('targets_idx', 'chr1', 100, 150);"
      ]
    },
    {
      "name": "duckhts_cgranges_overlaps_bulk",
      "kind": "table",
      "category": "Intervals",
      "signature": "duckhts_cgranges_overlaps_bulk(name, query, chrom_col, start_col, end_col, mode := 'overlap', query_row_id_col := NULL)",
      "returns": "table",
      "r_wrapper": "",
      "description": "Run a SQL query that yields overlap probes, stream those rows through a finalized session-scoped cgranges registry entry, and return one row per matching indexed interval. The probe query runs on the extension-owned helper connection, so it must reference regular tables/views rather than connection-local temp tables. When query_row_id_col is omitted, query_row_id defaults to the 1-based probe row ordinal.",
      "examples": [
        "SELECT * FROM duckhts_cgranges_overlaps_bulk('targets_idx', 'SELECT probe_id, chrom, start, \"end\" FROM probes', 'chrom', 'start', 'end', query_row_id_col := 'probe_id');"
      ]
    },
    {
      "name": "read_fastq",
      "kind": "table",
      "category": "Readers",
      "signature": "read_fastq(path, interleaved := FALSE, mate_path := NULL, sequence_encoding := 'string', quality_representation := 'string', input_quality_encoding := 'phred33', scan_mode := 'auto')",
      "returns": "table",
      "r_wrapper": "rduckhts_fastq",
      "description": "Read single-end, paired-end, or interleaved FASTQ files with optional legacy quality decoding. By default, FASTQ qualities are interpreted as modern Phred+33 input. Use sequence_encoding := 'nt16' to return SEQUENCE as UTINYINT[] and quality_representation := 'phred' to return QUALITY as UTINYINT[] instead of VARCHAR. input_quality_encoding accepts 'phred33', 'auto', 'phred64', or 'solexa64'. scan_mode := 'sequential' forces raw streaming/counting instead of index-backed count paths.",
      "examples": [
        "SELECT NAME, MATE FROM read_fastq('r1.fq', mate_path := 'r2.fq') LIMIT 5;"
      ]
    },
    {
      "name": "detect_quality_encoding",
      "kind": "table",
      "category": "Metadata",
      "signature": "detect_quality_encoding(path, max_records := 10000)",
      "returns": "table",
      "r_wrapper": "rduckhts_detect_quality_encoding",
      "description": "Inspect a FASTQ file's observed quality ASCII range and report compatible legacy encodings with a heuristic guessed encoding.",
      "examples": [
        "SELECT * FROM detect_quality_encoding('reads.fq.gz');"
      ]
    },
    {
      "name": "read_gff",
      "kind": "table",
      "category": "Readers",
      "signature": "read_gff(path, header_names := NULL, header := FALSE, column_types := NULL, auto_detect := FALSE, attributes_map := FALSE, attributes_list := FALSE, attributes_pairs := FALSE, strict := FALSE, region := NULL, index_path := NULL, scan_mode := 'auto')",
      "returns": "table",
      "r_wrapper": "rduckhts_gff",
      "description": "Read GFF annotations with optional raw scalar and richer list/pair parsed attribute columns, strict GFF3 structural validation, and indexed region filtering. scan_mode := 'sequential' forces full-file streaming/counting instead of index-backed count paths and is incompatible with region.",
      "examples": [
        "SELECT seqname, feature, start, \"end\" FROM read_gff('gff_file.gff.gz') LIMIT 5;"
      ]
    },
    {
      "name": "read_gtf",
      "kind": "table",
      "category": "Readers",
      "signature": "read_gtf(path, header_names := NULL, header := FALSE, column_types := NULL, auto_detect := FALSE, attributes_map := FALSE, attributes_list := FALSE, attributes_pairs := FALSE, region := NULL, index_path := NULL, scan_mode := 'auto')",
      "returns": "table",
      "r_wrapper": "rduckhts_gtf",
      "description": "Read GTF annotations with optional raw scalar and richer list/pair parsed attribute columns and indexed region filtering. scan_mode := 'sequential' forces full-file streaming/counting instead of index-backed count paths and is incompatible with region.",
      "examples": [
        "SELECT seqname, feature, start, \"end\" FROM read_gtf('annotations.gtf.gz') LIMIT 5;"
      ]
    },
    {
      "name": "read_tabix",
      "kind": "table",
      "category": "Readers",
      "signature": "read_tabix(path, header_names := NULL, header := FALSE, column_types := NULL, auto_detect := FALSE, region := NULL, index_path := NULL, scan_mode := 'auto')",
      "returns": "table",
      "r_wrapper": "rduckhts_tabix",
      "description": "Read generic tabix-indexed text data with optional header handling and type inference. scan_mode := 'sequential' forces full-file streaming/counting instead of index-backed count paths and is incompatible with region.",
      "examples": [
        "SELECT * FROM read_tabix('meta_tabix.tsv.gz') LIMIT 5;"
      ]
    },
    {
      "name": "fasta_index",
      "kind": "table",
      "category": "Readers",
      "signature": "fasta_index(path, index_path := NULL)",
      "returns": "table",
      "r_wrapper": "rduckhts_fasta_index",
      "description": "Build a FASTA index (.fai) and return a single row with columns success (BOOLEAN) and index_path (VARCHAR).",
      "examples": [
        "SELECT * FROM fasta_index('ce.fa');"
      ]
    },
    {
      "name": "bgzip",
      "kind": "table",
      "category": "Compression",
      "signature": "bgzip(path, output_path := NULL, threads := 4, level := -1, keep := TRUE, overwrite := FALSE)",
      "returns": "table",
      "r_wrapper": "rduckhts_bgzip",
      "description": "Compress a plain file to BGZF and return the created output path and byte counts.",
      "examples": [
        "SELECT * FROM bgzip('regions.bed');"
      ]
    },
    {
      "name": "bgunzip",
      "kind": "table",
      "category": "Compression",
      "signature": "bgunzip(path, output_path := NULL, threads := 4, keep := TRUE, overwrite := FALSE)",
      "returns": "table",
      "r_wrapper": "rduckhts_bgunzip",
      "description": "Decompress a BGZF-compressed file and return the created output path and byte counts.",
      "examples": [
        "SELECT * FROM bgunzip('regions.bed.gz');"
      ]
    },
    {
      "name": "bam_index",
      "kind": "table",
      "category": "Indexing",
      "signature": "bam_index(path, index_path := NULL, min_shift := 0, threads := 4)",
      "returns": "table",
      "r_wrapper": "rduckhts_bam_index",
      "description": "Build a BAM or CRAM index and report the written index path and format.",
      "examples": [
        "SELECT * FROM bam_index('range.bam');"
      ]
    },
    {
      "name": "bcf_index",
      "kind": "table",
      "category": "Indexing",
      "signature": "bcf_index(path, index_path := NULL, min_shift := NULL, threads := 4)",
      "returns": "table",
      "r_wrapper": "rduckhts_bcf_index",
      "description": "Build a TBI or CSI index for a VCF or BCF file and report the written index path and format.",
      "examples": [
        "SELECT * FROM bcf_index('formatcols.vcf.gz');"
      ]
    },
    {
      "name": "tabix_index",
      "kind": "table",
      "category": "Indexing",
      "signature": "tabix_index(path, preset := 'vcf', index_path := NULL, min_shift := 0, threads := 4, seq_col := NULL, start_col := NULL, end_col := NULL, comment_char := NULL, skip_lines := NULL)",
      "returns": "table",
      "r_wrapper": "rduckhts_tabix_index",
      "description": "Build a tabix index for a BGZF-compressed text file using a preset or explicit coordinate columns.",
      "examples": [
        "SELECT * FROM tabix_index('gff_file.gff.gz', preset := 'gff');"
      ]
    },
    {
      "name": "bam_bin_counts",
      "kind": "table",
      "category": "Coverage",
      "signature": "bam_bin_counts(path, bin_width, chrom := NULL, reference := NULL, index_path := NULL, mapq := 0, require_flags := 0, exclude_flags := 0, rmdup := 'none', stats := NULL)",
      "returns": "table",
      "r_wrapper": "rduckhts_bam_bin_counts",
      "description": "Count BAM or CRAM read starts into fixed-width bins. Returns one row per bin across the selected contig span, including zero-count bins, with total, forward, and reverse counts; `rmdup := 'streaming'` applies the WisecondorX-style larp/larp2 consecutive-position deduplication, `rmdup := 'flag'` drops SAM duplicate-flagged reads, and `stats := 'gc'`, `'mq'`, or `'gc,mq'` adds per-bin pre/post-filter GC and MAPQ sufficient statistics, including reference GC when `reference` is provided.",
      "examples": [
        "SELECT * FROM bam_bin_counts('fixture_mixed.cram', 5000, reference := 'fixture_ref.fa', rmdup := 'streaming', stats := 'gc,mq');"
      ]
    },
    {
      "name": "duckhts_bam_bed_coverage",
      "kind": "table",
      "category": "Coverage",
      "signature": "duckhts_bam_bed_coverage(path, bed_path, reference := NULL, index_path := NULL, bed_index_path := NULL, mapq := 0, min_baseq := 0, min_read_len := 0, require_flags := 0, exclude_flags := 1796, min_depth := 1, max_depth := 1000000, decompression_threads := 0, fragment_mode := FALSE, strand_outputs := TRUE, processing_threads := 0)",
      "returns": "table",
      "r_wrapper": "rduckhts_bam_bed_coverage",
      "description": "Compute samtools coverage-like regional summaries for BAM or CRAM input over a BED target set, returning one row per BED interval with DuckHTS-specific pre/post-filter read counts, covered bases, percentage covered, mean depth, mean baseQ, mean mapQ, and strand-specific post-filter summaries in read mode. Indexed BAM/CRAM input is required in the current implementation. decompression_threads controls htslib worker threads for BAM/CRAM decoding; use 0 to disable them.",
      "examples": [
        "SELECT chrom, start, \"end\", numreads_post, covbases_post, coverage_post FROM duckhts_bam_bed_coverage('fixture_mixed.bam', 'fixture_mixed_regions.bed');"
      ]
    },
    {
      "name": "duckhts_mosdepth",
      "kind": "table",
      "category": "Coverage",
      "signature": "duckhts_mosdepth(prefix, path, chrom := NULL, by := NULL, fasta := NULL, read_groups := NULL, no_per_base := FALSE, threads := 2, processing_threads := 2, flag := 1796, include_flag := 0, fast_mode := FALSE, fragment_mode := FALSE, use_median := FALSE, mapq := 0, min_frag_len := -1, max_frag_len := -1, precision_digits := 2, quantize := NULL, thresholds := NULL, index_path := NULL, overwrite := FALSE)",
      "returns": "table",
      "r_wrapper": "rduckhts_mosdepth",
      "description": "Write native mosdepth-compatible coverage outputs for indexed BAM or CRAM input. Produces mosdepth-style summary, global distribution, per-base BED.gz + CSI, optional window/BED region outputs, optional quantized BED.gz + CSI, and optional threshold counts for `by`; `fast_mode` defaults to FALSE to match upstream mosdepth, default mode performs CIGAR-aware coverage with mate-overlap correction, `fragment_mode` switches coverage to full-fragment insert spans for proper pairs, `use_median` switches `by` outputs from mean to median, `read_groups` filters by comma-separated RG IDs, `min_frag_len` and `max_frag_len` filter on absolute template length, `fasta` is required for CRAM when htslib needs a reference, `precision_digits` controls decimal places in the text outputs, and `processing_threads` enables parallel contig processing (0 = sequential, >0 = number of worker threads).",
      "examples": [
        "SELECT * FROM duckhts_mosdepth('sample', 'range.cram', fasta := 'ce.fa', by := '1000', fragment_mode := TRUE, read_groups := '1', use_median := TRUE, min_frag_len := 50, max_frag_len := 500, quantize := ':1:4:', thresholds := '1,10,20', precision_digits := 4, overwrite := TRUE);"
      ]
    },
    {
      "name": "duckhts_samtools_idxstats",
      "kind": "table",
      "category": "Metadata",
      "signature": "duckhts_samtools_idxstats(path, output := NULL, index_path := NULL, threads := 0, overwrite := FALSE)",
      "returns": "table",
      "r_wrapper": "rduckhts_samtools_idxstats",
      "description": "Write samtools idxstats-compatible TAB-delimited output for BAM, CRAM, or SAM input. Indexed BAM uses `hts_idx_get_stat(...)` for the fast path; CRAM, SAM, and unindexed BAM fall back to a full scan while preserving samtools-style contig rows plus the final `*` row.",
      "examples": [
        "SELECT * FROM duckhts_samtools_idxstats('range.bam', output := 'range.idxstats.txt', overwrite := TRUE);"
      ]
    },
    {
      "name": "read_hts_header",
      "kind": "table",
      "category": "Metadata",
      "signature": "read_hts_header(path, format := NULL, mode := NULL)",
      "returns": "table",
      "r_wrapper": "rduckhts_hts_header",
      "description": "Inspect HTS headers in parsed, raw, or combined form across supported formats. Raw VCF/BCF mode includes the final `#CHROM` sample header line so the returned text is suitable for Parquet metadata and future VCF/BCF regeneration.",
      "examples": [
        "SELECT record_type, id FROM read_hts_header('formatcols.vcf.gz') LIMIT 10;"
      ]
    },
    {
      "name": "read_hts_index",
      "kind": "table",
      "category": "Metadata",
      "signature": "read_hts_index(path, format := NULL, index_path := NULL)",
      "returns": "table",
      "r_wrapper": "rduckhts_hts_index",
      "description": "Inspect high-level HTS index metadata such as sequence names and mapped counts.",
      "examples": [
        "SELECT seqname, index_type FROM read_hts_index('vcf_file.bcf');"
      ]
    },
    {
      "name": "read_hts_index_spans",
      "kind": "table",
      "category": "Metadata",
      "signature": "read_hts_index_spans(path, format := NULL, index_path := NULL)",
      "returns": "table",
      "r_wrapper": "rduckhts_hts_index_spans",
      "description": "Expand index metadata into span and chunk rows suitable for low-level index inspection.",
      "examples": [
        "SELECT seqname, chunk_beg_vo, chunk_end_vo FROM read_hts_index_spans('vcf_file.bcf') LIMIT 5;"
      ]
    },
    {
      "name": "read_hts_index_raw",
      "kind": "table_macro",
      "category": "Metadata",
      "signature": "read_hts_index_raw(path, format := NULL, index_path := NULL)",
      "returns": "table",
      "r_wrapper": "rduckhts_hts_index_raw",
      "description": "Return the raw on-disk HTS index blob together with basic identifying metadata.",
      "examples": [
        "SELECT length(raw) FROM read_hts_index_raw('formatcols.vcf.gz');"
      ]
    },
    {
      "name": "variantkey",
      "kind": "scalar",
      "category": "Variants",
      "signature": "variantkey(chrom, pos, ref, alt)",
      "returns": "UBIGINT",
      "r_wrapper": "",
      "description": "Encode a normalized biallelic variant as an official VariantKey-compatible 64-bit unsigned integer. This DuckHTS wrapper accepts 1-based VCF/DuckHTS POS to match bcftools `%VKX` / `+add-variantkey`, internally converts to the upstream 0-based field, and preserves the official hashed nonreversible mode for large, ambiguous, and symbolic REF/ALT strings. Only CHROM, POS, REF, and ALT are encoded; END, SVLEN, mate breakend coordinates, and other SV metadata are not.",
      "examples": [
        "SELECT variantkey_hex(variantkey('1', 324684, 'C', 'G'));"
      ]
    },
    {
      "name": "variantkey_hex",
      "kind": "scalar",
      "category": "Variants",
      "signature": "variantkey_hex(vk)",
      "returns": "VARCHAR",
      "r_wrapper": "",
      "description": "Render a VariantKey as its lowercase 16-character hexadecimal string representation.",
      "examples": [
        "SELECT variantkey_hex(variantkey('1', 324684, 'C', 'G'));"
      ]
    },
    {
      "name": "parse_variantkey_hex",
      "kind": "scalar",
      "category": "Variants",
      "signature": "parse_variantkey_hex(hex)",
      "returns": "UBIGINT",
      "r_wrapper": "",
      "description": "Parse a 16-character hexadecimal VariantKey string back into its UBIGINT code. Invalid or non-hex strings return NULL.",
      "examples": [
        "SELECT parse_variantkey_hex('08027a2588b00000');"
      ]
    },
    {
      "name": "encode_variantkey",
      "kind": "scalar",
      "category": "Variants",
      "signature": "encode_variantkey(chrom_code, pos0, refalt_code)",
      "returns": "UBIGINT",
      "r_wrapper": "",
      "description": "Encode the raw upstream VariantKey fields directly: chromosome code, 0-based position, and 31-bit REF+ALT code.",
      "examples": [
        "SELECT variantkey_hex(encode_variantkey(1, 324683, 145752064));"
      ]
    },
    {
      "name": "extract_variantkey_chrom",
      "kind": "scalar",
      "category": "Variants",
      "signature": "extract_variantkey_chrom(vk)",
      "returns": "UTINYINT",
      "r_wrapper": "",
      "description": "Extract the raw upstream VariantKey chromosome code.",
      "examples": [
        "SELECT extract_variantkey_chrom(parse_variantkey_hex('08027a2588b00000'));"
      ]
    },
    {
      "name": "extract_variantkey_pos",
      "kind": "scalar",
      "category": "Variants",
      "signature": "extract_variantkey_pos(vk)",
      "returns": "UINTEGER",
      "r_wrapper": "",
      "description": "Extract the raw upstream VariantKey 0-based position field.",
      "examples": [
        "SELECT extract_variantkey_pos(parse_variantkey_hex('08027a2588b00000'));"
      ]
    },
    {
      "name": "extract_variantkey_refalt",
      "kind": "scalar",
      "category": "Variants",
      "signature": "extract_variantkey_refalt(vk)",
      "returns": "UINTEGER",
      "r_wrapper": "",
      "description": "Extract the raw upstream 31-bit VariantKey REF+ALT code.",
      "examples": [
        "SELECT extract_variantkey_refalt(parse_variantkey_hex('08027a2588b00000'));"
      ]
    },
    {
      "name": "decode_variantkey",
      "kind": "scalar",
      "category": "Variants",
      "signature": "decode_variantkey(vk)",
      "returns": "STRUCT",
      "r_wrapper": "",
      "description": "Decode a VariantKey into its raw upstream numeric fields: chrom_code, pos0, and refalt_code.",
      "examples": [
        "SELECT (decode_variantkey(parse_variantkey_hex('08027a2588b00000'))).pos0;"
      ]
    },
    {
      "name": "reverse_variantkey",
      "kind": "scalar",
      "category": "Variants",
      "signature": "reverse_variantkey(vk)",
      "returns": "STRUCT",
      "r_wrapper": "",
      "description": "Decode a VariantKey into a STRUCT with chrom, chrom_code, 1-based pos, upstream 0-based pos0, ref, alt, refalt_code, and reversible. For hashed nonreversible keys, reversible is FALSE and ref/alt are returned as NULL because DuckHTS v1 does not ship the optional NRVK lookup sidecar.",
      "examples": [
        "SELECT (reverse_variantkey(parse_variantkey_hex('08027a2588b00000'))).ref;"
      ]
    },
    {
      "name": "variantkey_range",
      "kind": "scalar",
      "category": "Variants",
      "signature": "variantkey_range(chrom, pos_min, pos_max)",
      "returns": "STRUCT",
      "r_wrapper": "",
      "description": "Return the inclusive minimum and maximum VariantKey bounds for a chromosome plus 1-based VCF position range, suitable for numeric range filtering on precomputed VariantKeys.",
      "examples": [
        "SELECT variantkey_hex((variantkey_range('1', 100, 100)).min), variantkey_hex((variantkey_range('1', 100, 100)).max);"
      ]
    },
    {
      "name": "regionkey",
      "kind": "scalar",
      "category": "Intervals",
      "signature": "regionkey(chrom, start, end, strand := 0)",
      "returns": "UBIGINT",
      "r_wrapper": "",
      "description": "Encode a genomic interval as an official RegionKey-compatible 64-bit unsigned integer. Start and end use 0-based half-open interval semantics, matching BED-style coordinates; strand accepts -1, 0, or 1.",
      "examples": [
        "SELECT regionkey_hex(regionkey('X', 1007, 1807, 1));"
      ]
    },
    {
      "name": "regionkey_hex",
      "kind": "scalar",
      "category": "Intervals",
      "signature": "regionkey_hex(rk)",
      "returns": "VARCHAR",
      "r_wrapper": "",
      "description": "Render a RegionKey as its lowercase 16-character hexadecimal string representation.",
      "examples": [
        "SELECT regionkey_hex(regionkey('X', 1007, 1807, 1));"
      ]
    },
    {
      "name": "parse_regionkey_hex",
      "kind": "scalar",
      "category": "Intervals",
      "signature": "parse_regionkey_hex(hex)",
      "returns": "UBIGINT",
      "r_wrapper": "",
      "description": "Parse a 16-character hexadecimal RegionKey string back into its UBIGINT code. Invalid or non-hex strings return NULL.",
      "examples": [
        "SELECT parse_regionkey_hex('b80001f78000387a');"
      ]
    },
    {
      "name": "encode_regionkey",
      "kind": "scalar",
      "category": "Intervals",
      "signature": "encode_regionkey(chrom_code, start, end, strand_code)",
      "returns": "UBIGINT",
      "r_wrapper": "",
      "description": "Encode the raw upstream RegionKey fields directly: chromosome code, 0-based start, 0-based end, and strand code (0 = unknown, 1 = +, 2 = -).",
      "examples": [
        "SELECT regionkey_hex(encode_regionkey(23, 1007, 1807, 1));"
      ]
    },
    {
      "name": "extract_regionkey_chrom",
      "kind": "scalar",
      "category": "Intervals",
      "signature": "extract_regionkey_chrom(rk)",
      "returns": "UTINYINT",
      "r_wrapper": "",
      "description": "Extract the raw upstream RegionKey chromosome code.",
      "examples": [
        "SELECT extract_regionkey_chrom(parse_regionkey_hex('b80001f78000387a'));"
      ]
    },
    {
      "name": "extract_regionkey_startpos",
      "kind": "scalar",
      "category": "Intervals",
      "signature": "extract_regionkey_startpos(rk)",
      "returns": "UINTEGER",
      "r_wrapper": "",
      "description": "Extract the raw upstream RegionKey 0-based start position.",
      "examples": [
        "SELECT extract_regionkey_startpos(parse_regionkey_hex('b80001f78000387a'));"
      ]
    },
    {
      "name": "extract_regionkey_endpos",
      "kind": "scalar",
      "category": "Intervals",
      "signature": "extract_regionkey_endpos(rk)",
      "returns": "UINTEGER",
      "r_wrapper": "",
      "description": "Extract the raw upstream RegionKey 0-based end position.",
      "examples": [
        "SELECT extract_regionkey_endpos(parse_regionkey_hex('b80001f78000387a'));"
      ]
    },
    {
      "name": "extract_regionkey_strand",
      "kind": "scalar",
      "category": "Intervals",
      "signature": "extract_regionkey_strand(rk)",
      "returns": "UTINYINT",
      "r_wrapper": "",
      "description": "Extract the raw upstream RegionKey strand code (0 = unknown, 1 = +, 2 = -).",
      "examples": [
        "SELECT extract_regionkey_strand(parse_regionkey_hex('b80001f78000387a'));"
      ]
    },
    {
      "name": "decode_regionkey",
      "kind": "scalar",
      "category": "Intervals",
      "signature": "decode_regionkey(rk)",
      "returns": "STRUCT",
      "r_wrapper": "",
      "description": "Decode a RegionKey into its raw upstream numeric fields: chrom_code, start, end, and strand_code.",
      "examples": [
        "SELECT (decode_regionkey(parse_regionkey_hex('b80001f78000387a'))).strand_code;"
      ]
    },
    {
      "name": "reverse_regionkey",
      "kind": "scalar",
      "category": "Intervals",
      "signature": "reverse_regionkey(rk)",
      "returns": "STRUCT",
      "r_wrapper": "",
      "description": "Decode a RegionKey into a STRUCT with chrom, chrom_code, start, end, strand, and strand_code.",
      "examples": [
        "SELECT (reverse_regionkey(parse_regionkey_hex('b80001f78000387a'))).strand;"
      ]
    },
    {
      "name": "extend_regionkey",
      "kind": "scalar",
      "category": "Intervals",
      "signature": "extend_regionkey(rk, size)",
      "returns": "UBIGINT",
      "r_wrapper": "",
      "description": "Extend a RegionKey interval by a fixed number of bases on both sides, clamping to the official 28-bit RegionKey position range.",
      "examples": [
        "SELECT reverse_regionkey(extend_regionkey(regionkey('X', 10000, 20000, -1), 1000));"
      ]
    },
    {
      "name": "are_overlapping_regions",
      "kind": "scalar",
      "category": "Intervals",
      "signature": "are_overlapping_regions(chrom_a, start_a, end_a, chrom_b, start_b, end_b)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Return TRUE when two explicit 0-based half-open intervals overlap on the same canonical chromosome.",
      "examples": [
        "SELECT are_overlapping_regions('1', 2, 4, '1', 3, 7);"
      ]
    },
    {
      "name": "are_overlapping_region_regionkey",
      "kind": "scalar",
      "category": "Intervals",
      "signature": "are_overlapping_region_regionkey(chrom, start, end, rk)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Return TRUE when a 0-based half-open interval overlaps the supplied RegionKey interval.",
      "examples": [
        "SELECT are_overlapping_region_regionkey('X', 1008, 1800, parse_regionkey_hex('b80001f78000387a'));"
      ]
    },
    {
      "name": "are_overlapping_regionkeys",
      "kind": "scalar",
      "category": "Intervals",
      "signature": "are_overlapping_regionkeys(rka, rkb)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Return TRUE when two RegionKeys overlap.",
      "examples": [
        "SELECT are_overlapping_regionkeys(regionkey('X', 1007, 1807, 1), parse_regionkey_hex('b80001f78000387a'));"
      ]
    },
    {
      "name": "bcftools_liftover",
      "kind": "scalar",
      "category": "Variants",
      "signature": "bcftools_liftover(chrom, pos, ref, alt, chain_path, dst_fasta_ref, src_fasta_ref, max_snp_gap, max_indel_inc, lift_mt, end_pos, no_left_align)",
      "returns": "STRUCT",
      "r_wrapper": "rduckhts_liftover",
      "description": "Row-oriented liftover kernel intended to mirror bcftools +liftover semantics as closely as possible while returning one STRUCT per input row with fields: src_chrom, src_pos, src_ref, src_alt, dest_chrom, dest_pos, dest_end, dest_ref, dest_alt, mapped, reverse_complemented, swap, reject_reason, and note. Set no_left_align := true to skip post-liftover left-alignment of lifted indels (mirrors --no-left-align in bcftools +liftover).",
      "examples": [
        "SELECT (bcftools_liftover(chrom, pos, ref, alt, 'hg19ToHg38.over.chain.gz', 'hg38.fa', 'hg19.fa', 1, 250, false, NULL::BIGINT, false)).dest_pos FROM variants;"
      ]
    },
    {
      "name": "duckdb_liftover",
      "kind": "table_macro",
      "category": "Variants",
      "signature": "duckdb_liftover(table_name, chrom_col, pos_col, ref_col := NULL, alt_col := NULL, chain_path := NULL, dst_fasta_ref := NULL, src_fasta_ref := NULL, max_snp_gap := 1, max_indel_inc := 250, lift_mt := false, end_pos_col := NULL, no_left_align := false)",
      "returns": "table",
      "r_wrapper": "rduckhts_liftover",
      "description": "DuckDB-specific wrapper over bcftools_liftover that takes either a table name or a derived-table expression plus column-name strings for chrom/pos/ref/alt and returns the lifted table. The no_left_align parameter mirrors --no-left-align in bcftools +liftover.",
      "examples": [
        "SELECT * FROM duckdb_liftover('variants', 'chrom', 'pos', ref_col := 'ref', alt_col := 'alt', chain_path := 'hg19ToHg38.over.chain.gz', dst_fasta_ref := 'hg38.fa');",
        "SELECT * FROM duckdb_liftover('(SELECT chrom, pos, ref, alt FROM variants) AS v', 'chrom', 'pos', ref_col := 'ref', alt_col := 'alt', chain_path := 'hg19ToHg38.over.chain.gz', dst_fasta_ref := 'hg38.fa');"
      ]
    },
    {
      "name": "bcftools_norm_row",
      "kind": "scalar",
      "category": "Variants",
      "signature": "bcftools_norm_row(chrom, pos, ref, alt, fasta_ref, end_pos := NULL, svlen := NULL, fasta_index_path := NULL, gzi_path := NULL)",
      "returns": "STRUCT",
      "r_wrapper": "",
      "description": "Normalize one variant row with bcftools/vt-style left-alignment semantics against a FASTA reference. The alt argument may be either a comma-delimited VARCHAR or a VARCHAR[] list. The returned STRUCT contains pos_normed, end_pos_normed, ref_normed, alt_normed (always VARCHAR[]), normed (TRUE/FALSE/NULL), and norm_status. Symbolic <DEL> rows can use end_pos, and symbolic <DUP> rows can use svlen. gVCF <NON_REF>/<*> reference-block alleles pass through with GVCFReferenceBlock, and mixed real-plus-gVCF-symbolic alleles normalize the real alleles while preserving symbolic alleles and caller-supplied reference-block END in site-preserving output.",
      "examples": [
        "SELECT nr.pos_normed, nr.ref_normed, nr.alt_normed FROM (SELECT bcftools_norm_row('chr1', 100, 'AC', 'A', 'ref.fa', NULL::BIGINT, NULL::BIGINT, NULL, NULL) AS nr);"
      ]
    },
    {
      "name": "duckhts_bcftools_norm",
      "kind": "table_macro",
      "category": "Variants",
      "signature": "duckhts_bcftools_norm(table_name, fasta_ref, chrom_col := 'chrom', pos_col := 'pos', ref_col := 'ref', alt_col := 'alt', split_multiallelic := FALSE, end_pos_col := NULL, svlen_col := NULL, fasta_index_path := NULL, gzi_path := NULL)",
      "returns": "table",
      "r_wrapper": "rduckhts_bcftools_norm",
      "description": "DuckDB table macro wrapper over bcftools_norm_row that normalizes variants from a table or derived-table expression while preserving the original columns. The input ALT column may be either VARCHAR or VARCHAR[]. The result appends pos_normed, end_pos_normed, ref_normed, alt_normed, normed, and norm_status; with split_multiallelic := TRUE, multiallelic sites are split before normalization and alt_normed becomes VARCHAR plus alt_index. This is a vt/vcfnorm-style row/table transform, not a full-record VCF/BCF rewrite: genotype, PL/GP/DS, and PS fields are preserved as caller columns unless a separate full-record writer/remapper layer is used.",
      "examples": [
        "SELECT * FROM duckhts_bcftools_norm('variants', 'ref.fa');",
        "SELECT * FROM duckhts_bcftools_norm('(SELECT CHROM AS chrom, POS AS pos, REF AS ref, ALT AS alt FROM read_bcf(''cohort.vcf.gz'')) AS v', 'ref.fa', split_multiallelic := TRUE);"
      ]
    },
    {
      "name": "bcftools_score",
      "kind": "table",
      "category": "Variants",
      "signature": "bcftools_score(bcf_path, summary_path_or_list, use := NULL, columns := 'PLINK', columns_file := NULL, q_score_thr := NULL, summaries_list_file := NULL, log_path := NULL, use_variant_id := FALSE, counts := FALSE, samples := NULL, force_samples := FALSE, regions := NULL, regions_file := NULL, regions_overlap := 1, targets := NULL, targets_file := NULL, targets_overlap := 0, apply_filters := NULL, include := NULL, exclude := NULL)",
      "returns": "table",
      "r_wrapper": "rduckhts_score",
      "description": "Compute polygenic scores from one genotype BCF/VCF and one or more summary-statistics files with bcftools +score-compatible GT/DS/HDS/AP/GP/AS dosage semantics, sample subsetting, and region/target/FILTER-string controls. The second argument accepts a scalar path or a DuckDB LIST/array of paths; TSV/SSF summaries produce one PRS column per file in a single genotype scan, while GWAS-VCF summaries still produce one PRS column per FORMAT sample. Use summaries_list_file with a NULL second argument to read paths from a file or directory; list-file entries are interpreted as written, matching upstream `bcftools +score --summaries` behavior, while directory inputs scan supported regular summary files in lexicographic order and ignore index sidecars. Use log_path to write per-PRS loaded/matched/allele-mismatch/duplicate-marker audit counts.",
      "examples": [
        "SELECT * FROM bcftools_score('cohort.bcf', 'gwas.tsv.gz', columns := 'PLINK') LIMIT 5;",
        "SELECT * FROM bcftools_score('cohort.bcf', ['score1.tsv.gz', 'score2.tsv.gz'], columns := 'GWAS-SSF') LIMIT 5;",
        "SELECT * FROM bcftools_score('cohort.bcf', NULL, columns := 'GWAS-SSF', summaries_list_file := 'scores.list', log_path := 'score.log') LIMIT 5;"
      ]
    },
    {
      "name": "bcftools_munge_row",
      "kind": "scalar",
      "category": "Variants",
      "signature": "bcftools_munge_row(chrom, pos, a1, a2, id, p, z, or, beta, n, n_cas, n_con, info, frq, se, lp, ac, neff, neffdiv2, het_i2, het_p, het_lp, dire, fasta_ref, iffy_tag := 'IFFY', mismatch_tag := 'REF_MISMATCH', ns := NULL, nc := NULL, ne := NULL)",
      "returns": "STRUCT",
      "r_wrapper": "",
      "description": "Normalize one summary-statistics row into GWAS-VCF-style fields (chrom/pos/ref/alt/effect metrics), resolving REF/ALT orientation against a FASTA reference and applying swap-aware sign/frequency/count transforms. The output flag `alleles_swapped` means REF/ALT orientation was swapped to match the FASTA reference.",
      "examples": [
        "SELECT (bcftools_munge_row('chr1', 12345, 'A', 'G', 'rs1', 0.01, NULL, NULL, 0.12, 1000, NULL, NULL, NULL, 0.3, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'ref.fa')).ref;"
      ]
    },
    {
      "name": "duckdb_munge",
      "kind": "table_macro",
      "category": "Variants",
      "signature": "duckdb_munge(table_name, preset := '', column_map := map([''], ['']), column_map_file := '', fasta_ref := NULL, iffy_tag := 'IFFY', mismatch_tag := 'REF_MISMATCH', ns := NULL, nc := NULL, ne := NULL)",
      "returns": "table",
      "r_wrapper": "rduckhts_munge",
      "description": "DuckDB macro wrapper over bcftools_munge_row that maps source columns (via preset or explicit map) and returns normalized GWAS-VCF-style rows with lean outputs and explicit `alleles_swapped` semantics. Output columns: chrom, pos, id, ref, alt, alleles_swapped, filter, ns, ez, nc, es, se, lp, af, ac, ne (16 columns). For METAL meta-analysis output with SI/I2/CQ/ED columns, use duckdb_munge_metal.",
      "examples": [
        "SELECT * FROM duckdb_munge('gwas_table', preset := 'PLINK', fasta_ref := 'ref.fa');",
        "SELECT * FROM duckdb_munge('(SELECT * FROM gwas_table) AS s', column_map := map(['CHR','BP','A1','A2','SNP'], ['chrom','pos','ea','nea','id']), fasta_ref := 'ref.fa');"
      ]
    },
    {
      "name": "duckdb_munge_metal",
      "kind": "table_macro",
      "category": "Variants",
      "signature": "duckdb_munge_metal(table_name, preset := '', column_map := map([''], ['']), column_map_file := '', fasta_ref := NULL, iffy_tag := 'IFFY', mismatch_tag := 'REF_MISMATCH', ns := NULL, nc := NULL, ne := NULL)",
      "returns": "table",
      "r_wrapper": "rduckhts_munge",
      "description": "Extended munge macro with METAL meta-analysis output columns. Same as duckdb_munge but additionally emits: si (imputation info, from INFO input), i2 (Cochran's I² heterogeneity, from HET_I2), cq (Cochran's Q -log10 p, from HET_LP or -log10(HET_P)), and ed (effect direction string, from DIRE; +/- flipped on allele swap). The R wrapper rduckhts_munge() auto-dispatches to this macro when metal keys (INFO, HET_I2, HET_P, HET_LP, DIRE) are present in the resolved column map.",
      "examples": [
        "SELECT * FROM duckdb_munge_metal('metal_results', preset := 'METAL', fasta_ref := 'ref.fa');",
        "SELECT * FROM duckdb_munge_metal('meta', column_map := map(['CHR','BP','A1','A2','SNP','HET_I2','DIRE'], ['chr','pos','ea','nea','snp','HetISq','Direction']), fasta_ref := 'ref.fa');"
      ]
    },
    {
      "name": "hts_union_query",
      "kind": "scalar_macro",
      "category": "Readers",
      "signature": "hts_union_query(reader, pattern, params := '')",
      "returns": "VARCHAR",
      "r_wrapper": "rduckhts_bam_multi, rduckhts_bcf_multi, rduckhts_fastq_multi, rduckhts_fasta_multi, rduckhts_bed_multi, rduckhts_tabix_multi, rduckhts_gff_multi, rduckhts_gtf_multi",
      "description": "Generate a UNION ALL BY NAME query string that reads every file matching a glob pattern through the named reader function. The result includes a 'filename' column identifying the source file for each row. Assign to a variable with SET VARIABLE and execute via query(getvariable(...)). Optional params string is appended to each reader call. In R, use the typed rduckhts_*_multi() helpers instead, which accept file vectors with optional per-file parameters and create DuckDB tables directly.",
      "examples": [
        "SET VARIABLE q = hts_union_query('read_bam', 'samples/*.bam'); SELECT * FROM query(getvariable('q'));",
        "SET VARIABLE q = hts_union_query('read_bcf', 'cohort/*.vcf.gz', 'tidy_format := true'); SELECT * FROM query(getvariable('q'));"
      ]
    },
    {
      "name": "hts_region_union_query",
      "kind": "scalar_macro",
      "category": "Readers",
      "signature": "hts_region_union_query(reader, path, regions, params := '')",
      "returns": "VARCHAR",
      "r_wrapper": "",
      "description": "Generate a UNION ALL BY NAME query string that reads one HTS file through separate per-region table-function scans. The result adds filename, duckhts_region_shard_id, and duckhts_region_shard columns so benchmark queries can compare region-sharded execution and explicit ordered writes. Pass regions as a DuckDB list of region strings; params is appended to each reader call and should not include region. The generated UNION ALL does not deduplicate records; adjacent or overlapping shards can duplicate BAM alignments or BCF/VCF records that span shard boundaries, so add explicit shard-local filters or downstream deduplication when exact once-only semantics are required.",
      "examples": [
        "SET VARIABLE q = hts_region_union_query('read_bam', 'sample.bam', ['chr1:1-1000000','chr1:1000001-2000000']); SELECT * FROM query(getvariable('q'));",
        "SET VARIABLE q = hts_region_union_query('read_bcf', 'cohort.vcf.gz', string_split('22:16000000-16999999,22:17000000-17999999', ','), 'tidy_format := true'); SELECT * FROM query(getvariable('q'));"
      ]
    },
    {
      "name": "seq_revcomp",
      "kind": "scalar",
      "category": "Sequence UDFs",
      "signature": "seq_revcomp(sequence)",
      "returns": "VARCHAR",
      "r_wrapper": "",
      "description": "Compute the reverse complement of a DNA sequence using A, C, G, T, and N bases. Overloaded: accepts either a VARCHAR text sequence (returns VARCHAR) or a UTINYINT[] of htslib nt16 codes as produced by read_bam(sequence_encoding := 'nt16') (returns UTINYINT[]); the nt16 overload is bit-identical to the text path after decoding, so BAM pipelines can reverse-complement without leaving the nt16 encoding.",
      "examples": [
        "SELECT seq_revcomp('ACGTN');",
        "SELECT seq_revcomp(SEQ) FROM read_bam('reads.bam', sequence_encoding := 'nt16');"
      ]
    },
    {
      "name": "seq_canonical",
      "kind": "scalar",
      "category": "Sequence UDFs",
      "signature": "seq_canonical(sequence)",
      "returns": "VARCHAR",
      "r_wrapper": "",
      "description": "Return the lexicographically smaller of a sequence and its reverse complement. Overloaded: accepts either a VARCHAR text sequence (returns VARCHAR) or a UTINYINT[] of htslib nt16 codes as produced by read_bam(sequence_encoding := 'nt16') (returns UTINYINT[]); the nt16 overload compares by decoded base order and is bit-identical to the text path after decoding.",
      "examples": [
        "SELECT seq_canonical('ACGTN');",
        "SELECT seq_canonical(SEQ) FROM read_bam('reads.bam', sequence_encoding := 'nt16');"
      ]
    },
    {
      "name": "seq_hash_2bit",
      "kind": "scalar",
      "category": "Sequence UDFs",
      "signature": "seq_hash_2bit(sequence)",
      "returns": "UBIGINT",
      "r_wrapper": "",
      "description": "Encode a short DNA sequence as a 2-bit unsigned integer hash. Overloaded to also accept a UTINYINT[] of htslib nt16 codes (from read_bam(sequence_encoding := 'nt16')); non-ACGT codes yield NULL, bit-identical to the text path.",
      "examples": [
        "SELECT seq_hash_2bit('ACGT');"
      ]
    },
    {
      "name": "seq_encode_4bit",
      "kind": "scalar",
      "category": "Sequence UDFs",
      "signature": "seq_encode_4bit(sequence)",
      "returns": "UTINYINT[]",
      "r_wrapper": "",
      "description": "Encode an IUPAC DNA sequence as a list of 4-bit base codes, preserving ambiguity symbols including N.",
      "examples": [
        "SELECT seq_encode_4bit('ACGTRYSWKMBDHVN');"
      ]
    },
    {
      "name": "seq_decode_4bit",
      "kind": "scalar",
      "category": "Sequence UDFs",
      "signature": "seq_decode_4bit(codes)",
      "returns": "VARCHAR",
      "r_wrapper": "",
      "description": "Decode a list of 4-bit IUPAC DNA base codes back into a sequence string.",
      "examples": [
        "SELECT seq_decode_4bit(seq_encode_4bit('ACGTRYSWKMBDHVN'));"
      ]
    },
    {
      "name": "seq_gc_content",
      "kind": "scalar",
      "category": "Sequence UDFs",
      "signature": "seq_gc_content(sequence)",
      "returns": "DOUBLE",
      "r_wrapper": "",
      "description": "Compute GC fraction for a DNA sequence as a value between 0 and 1. Overloaded: accepts either a VARCHAR text sequence or a UTINYINT[] of htslib nt16 codes as produced by read_bam(sequence_encoding := 'nt16'); the nt16 overload classifies codes directly and is bit-identical to the text path, so BAM pipelines can compute GC without decoding sequences back to text.",
      "examples": [
        "SELECT seq_gc_content('ACGT');",
        "SELECT seq_gc_content(SEQ) FROM read_bam('reads.bam', sequence_encoding := 'nt16');"
      ]
    },
    {
      "name": "seq_kmers",
      "kind": "table",
      "category": "Sequence UDFs",
      "signature": "seq_kmers(sequence, k, canonical := FALSE)",
      "returns": "table",
      "r_wrapper": "",
      "description": "Expand a sequence into positional k-mers with optional canonicalization.",
      "examples": [
        "SELECT * FROM seq_kmers('ACGT', 2);"
      ]
    },
    {
      "name": "sam_flag_bits",
      "kind": "scalar",
      "category": "SAM Flag UDFs",
      "signature": "sam_flag_bits(flag)",
      "returns": "STRUCT",
      "r_wrapper": "",
      "description": "Decode a SAM flag into a struct of boolean bit fields using explicit SAM-oriented names such as `is_paired`, `is_proper_pair`, `is_next_segment_unmapped`, and `is_supplementary`.",
      "examples": [
        "SELECT (sam_flag_bits(99)).is_proper_pair;"
      ]
    },
    {
      "name": "sam_flag_has",
      "kind": "scalar",
      "category": "SAM Flag UDFs",
      "signature": "sam_flag_has(flag, mask)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Test whether any bits from the provided SAM flag mask are set in a flag value.",
      "examples": [
        "SELECT sam_flag_has(99, 2);"
      ]
    },
    {
      "name": "is_forward_aligned",
      "kind": "scalar",
      "category": "SAM Flag UDFs",
      "signature": "is_forward_aligned(flag)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Test whether a mapped segment is aligned to the forward strand. Returns `NULL` for unmapped segments because SAM flag `0x10` does not define genomic strand when `0x4` is set.",
      "examples": [
        "SELECT is_forward_aligned(0);"
      ]
    },
    {
      "name": "cigar_has_soft_clip",
      "kind": "scalar",
      "category": "CIGAR Utils",
      "signature": "cigar_has_soft_clip(cigar)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Test whether a CIGAR string contains any soft-clipped segment (`S`). Overloaded to also accept a UINTEGER[] binary CIGAR (as produced by read_bam(cigar_representation := 'binary')); the binary overload is bit-identical to the text path.",
      "examples": [
        "SELECT cigar_has_soft_clip('5S90M5S');"
      ]
    },
    {
      "name": "cigar_has_hard_clip",
      "kind": "scalar",
      "category": "CIGAR Utils",
      "signature": "cigar_has_hard_clip(cigar)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Test whether a CIGAR string contains any hard-clipped segment (`H`). Overloaded to also accept a UINTEGER[] binary CIGAR (as produced by read_bam(cigar_representation := 'binary')); the binary overload is bit-identical to the text path.",
      "examples": [
        "SELECT cigar_has_hard_clip('5H95M');"
      ]
    },
    {
      "name": "cigar_left_soft_clip",
      "kind": "scalar",
      "category": "CIGAR Utils",
      "signature": "cigar_left_soft_clip(cigar)",
      "returns": "BIGINT",
      "r_wrapper": "",
      "description": "Return the left-end soft-clipped length from a CIGAR string, or zero if the alignment does not start with `S`. Overloaded to also accept a UINTEGER[] binary CIGAR (as produced by read_bam(cigar_representation := 'binary')); the binary overload is bit-identical to the text path.",
      "examples": [
        "SELECT cigar_left_soft_clip('5S90M5S');"
      ]
    },
    {
      "name": "cigar_right_soft_clip",
      "kind": "scalar",
      "category": "CIGAR Utils",
      "signature": "cigar_right_soft_clip(cigar)",
      "returns": "BIGINT",
      "r_wrapper": "",
      "description": "Return the right-end soft-clipped length from a CIGAR string, or zero if the alignment does not end with `S`. Overloaded to also accept a UINTEGER[] binary CIGAR (as produced by read_bam(cigar_representation := 'binary')); the binary overload is bit-identical to the text path.",
      "examples": [
        "SELECT cigar_right_soft_clip('5S90M5S');"
      ]
    },
    {
      "name": "cigar_query_length",
      "kind": "scalar",
      "category": "CIGAR Utils",
      "signature": "cigar_query_length(cigar)",
      "returns": "BIGINT",
      "r_wrapper": "",
      "description": "Return the query-consuming length from a CIGAR string, counting `M`, `I`, `S`, `=`, and `X`. Overloaded to also accept a UINTEGER[] binary CIGAR (as produced by read_bam(cigar_representation := 'binary')); the binary overload is bit-identical to the text path.",
      "examples": [
        "SELECT cigar_query_length('5S90M5I');"
      ]
    },
    {
      "name": "cigar_aligned_query_length",
      "kind": "scalar",
      "category": "CIGAR Utils",
      "signature": "cigar_aligned_query_length(cigar)",
      "returns": "BIGINT",
      "r_wrapper": "",
      "description": "Return the aligned query length from a CIGAR string, counting `M`, `=`, and `X` but excluding clips and insertions. Overloaded to also accept a UINTEGER[] binary CIGAR (as produced by read_bam(cigar_representation := 'binary')); the binary overload is bit-identical to the text path.",
      "examples": [
        "SELECT cigar_aligned_query_length('5S90M5I');"
      ]
    },
    {
      "name": "cigar_reference_length",
      "kind": "scalar",
      "category": "CIGAR Utils",
      "signature": "cigar_reference_length(cigar)",
      "returns": "BIGINT",
      "r_wrapper": "",
      "description": "Return the reference-consuming length from a CIGAR string, counting `M`, `D`, `N`, `=`, and `X`. Overloaded to also accept a UINTEGER[] binary CIGAR (as produced by read_bam(cigar_representation := 'binary')); the binary overload is bit-identical to the text path.",
      "examples": [
        "SELECT cigar_reference_length('90M5D');"
      ]
    },
    {
      "name": "cigar_has_op",
      "kind": "scalar",
      "category": "CIGAR Utils",
      "signature": "cigar_has_op(cigar, op)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Test whether a CIGAR string contains at least one instance of the requested operator. Overloaded to also accept a UINTEGER[] binary CIGAR (as produced by read_bam(cigar_representation := 'binary')); the binary overload is bit-identical to the text path.",
      "examples": [
        "SELECT cigar_has_op('5S90M5S', 'S');"
      ]
    },
    {
      "name": "is_paired",
      "kind": "scalar",
      "category": "SAM Flag UDFs",
      "signature": "is_paired(flag)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Test whether the SAM flag indicates that the template has multiple segments in sequencing (`0x1`).",
      "examples": [
        "SELECT is_paired(99);"
      ]
    },
    {
      "name": "is_proper_pair",
      "kind": "scalar",
      "category": "SAM Flag UDFs",
      "signature": "is_proper_pair(flag)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Test whether the SAM flag indicates that each segment is properly aligned according to the aligner (`0x2`).",
      "examples": [
        "SELECT is_proper_pair(99);"
      ]
    },
    {
      "name": "is_unmapped",
      "kind": "scalar",
      "category": "SAM Flag UDFs",
      "signature": "is_unmapped(flag)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Test whether the read itself is unmapped according to the SAM flag.",
      "examples": [
        "SELECT is_unmapped(4);"
      ]
    },
    {
      "name": "is_next_segment_unmapped",
      "kind": "scalar",
      "category": "SAM Flag UDFs",
      "signature": "is_next_segment_unmapped(flag)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Test whether the next segment in the template is flagged as unmapped (`0x8`).",
      "examples": [
        "SELECT is_next_segment_unmapped(9);"
      ]
    },
    {
      "name": "is_reverse_complemented",
      "kind": "scalar",
      "category": "SAM Flag UDFs",
      "signature": "is_reverse_complemented(flag)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Test whether `SEQ` is stored reverse complemented (`0x10`); for mapped reads this corresponds to reverse-strand alignment.",
      "examples": [
        "SELECT is_reverse_complemented(16);"
      ]
    },
    {
      "name": "is_next_segment_reverse_complemented",
      "kind": "scalar",
      "category": "SAM Flag UDFs",
      "signature": "is_next_segment_reverse_complemented(flag)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Test whether `SEQ` of the next segment in the template is stored reverse complemented (`0x20`).",
      "examples": [
        "SELECT is_next_segment_reverse_complemented(32);"
      ]
    },
    {
      "name": "is_first_segment",
      "kind": "scalar",
      "category": "SAM Flag UDFs",
      "signature": "is_first_segment(flag)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Test whether the read is marked as the first segment in the template.",
      "examples": [
        "SELECT is_first_segment(64);"
      ]
    },
    {
      "name": "is_last_segment",
      "kind": "scalar",
      "category": "SAM Flag UDFs",
      "signature": "is_last_segment(flag)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Test whether the read is marked as the last segment in the template.",
      "examples": [
        "SELECT is_last_segment(128);"
      ]
    },
    {
      "name": "is_secondary",
      "kind": "scalar",
      "category": "SAM Flag UDFs",
      "signature": "is_secondary(flag)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Test whether the alignment is marked as secondary.",
      "examples": [
        "SELECT is_secondary(256);"
      ]
    },
    {
      "name": "is_qc_fail",
      "kind": "scalar",
      "category": "SAM Flag UDFs",
      "signature": "is_qc_fail(flag)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Test whether the read failed vendor or pipeline quality checks.",
      "examples": [
        "SELECT is_qc_fail(512);"
      ]
    },
    {
      "name": "is_duplicate",
      "kind": "scalar",
      "category": "SAM Flag UDFs",
      "signature": "is_duplicate(flag)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Test whether the alignment is flagged as a duplicate.",
      "examples": [
        "SELECT is_duplicate(1024);"
      ]
    },
    {
      "name": "is_supplementary",
      "kind": "scalar",
      "category": "SAM Flag UDFs",
      "signature": "is_supplementary(flag)",
      "returns": "BOOLEAN",
      "r_wrapper": "",
      "description": "Test whether the alignment is marked as supplementary.",
      "examples": [
        "SELECT is_supplementary(2048);"
      ]
    }
  ]
}
