Code excution#

The {exec} directive allows executing code directly in the browser.

Directive#

.. {exec}:: language (python | sql)#

This directive is a {code-block} that allows executing the code directly in the browser. It supports most of the options of {code-block}, and a few more described below.

Options

:after: name [name...] (IDs)#

Execute one or more {exec} blocks before this block, in the same environment.

:editable:#

Make the {exec} block editable.

:include: path [path...] (relative paths)#

Prepend the content of one or more files to the block's content.

:then: name [name...] (IDs)#

Execute one or more {exec} blocks after this block, in the same environment.

:when: value (click | load | never)#

Determine when the block's code is executed: on user request (click, the default), when the page loads (load) or not at all (never).

Trigger#

By default, {exec} blocks are executed on click (:when: click), with controls displayed next to the block.

select * from countries where country_code = 'LI';

They can also be executed immediately on load (:when: load) or not at all (:when: never, useful for definitions that are referenced by other blocks). The controls displayed depend on the type of block.

select * from countries where country_code = 'LI';

Editable blocks#

Blocks can be made editable with the :editable: option.

select * from countries
  where population > 10000000
  order by country_code;

Sequencing#

The :after: option allows referencing one or more {exec} blocks on the same page to be executed before the block, in the same environment. The referenced blocks can themselves have :after: options, forming a dependency graph.

Similarly, the :then: option allows referencing one or more {exec} blocks to be executed after the block. Unlike :after:, only the blocks referenced by the :then: option of the block itself are executed; the :then: options of referenced blocks are ignored.

If a block appears more than once in the graph, only the first occurrence is executed.

-- :name: sql-people
create table people (first_name text not null, last_name text not null);
-- :name: sql-people-select
select * from people;
-- :after: sql-people
-- :then: sql-people-select
insert into people values ('Joe', 'Bar'), ('Jack', 'Sparrow');

Include file content#

The :include: option allows including the content of one or more external files. The content of the files is prepended to the block's content.

create table people (name text not null, height real, favorite_food text);
insert into people values
  ('Joe', 1.83, null),
  ('Jack', 1.55, 'burgers'),
  ('Jim', null, 'pizza'),
  ('Anthony', 1.78, null);
select * from people;