Create a production and import media

A production is the durable container for everything PostProject knows about a project’s media. An integration typically creates one production file, opens a transaction, imports media, and commits. Nothing staged in the transaction is visible to readers before the commit, and an uncommitted transaction discards its work.

The example below:

  1. creates a production file with an optional display name;

  2. begins a transaction;

  3. attaches an optional revision context, which records which tool made the change and why, so the revision feed can attribute it;

  4. imports one original media file, which creates a logical asset with one single-file representation and returns the new asset ID;

  5. commits the transaction; and

  6. lists the asset’s representations.

static pp_error_code_t create_production(const char *path, const char *media,
                                         pp_production_t **out_production,
                                         pp_asset_id_t *out_asset_id,
                                         pp_representation_id_t *out_original_id,
                                         pp_error_t **error) {
  pp_production_t *production = NULL;
  pp_transaction_t *transaction = NULL;
  pp_representation_set_t *representations = NULL;

  pp_error_code_t status =
      pp_production_create(path, "Documentary", &production, error);
  if (status == PP_OK) {
    status = pp_production_begin_edit(production, NULL,
        &(pp_edit_context_t){"com.example.editor", "0.4.0", NULL,
        "Import camera original"}, &transaction, error);
  }
  if (status == PP_OK) {
    status = pp_transaction_import_file(transaction, media, "Camera A", out_asset_id, out_original_id, error);
  }
  if (status == PP_OK) {
    pp_commit_receipt_t commit_receipt;
    status = pp_transaction_commit(transaction, &commit_receipt, error);
  }
  if (status == PP_OK) {
    status = pp_production_representations(production, *out_asset_id,
                                           &representations, error);
  }
  if (status == PP_OK) {
    printf("representations: %llu\n",
           (unsigned long long)pp_representation_set_count(representations));
    *out_production = production;
    production = NULL;
  }

  pp_representation_set_release(representations);
  pp_transaction_release(transaction);
  pp_production_release(production);
  return status;
}
std::pair<postproject::Production, postproject::ImportedMedia>
create_production(const std::string &path, const std::string &media) {
  auto production = postproject::Production::create(path, "Documentary").value();

  auto transaction = production.edit({postproject::OriginIdentity{"com.example.editor", "0.4.0", std::nullopt},
       "Import camera original"}).value();

  const auto imported = transaction.importMedia(media, "Camera A").value();
  transaction.commit().value();

  std::cout << "representations: "
            << production.representations(imported.asset_id).value().size() << '\n';
  return {std::move(production), imported};
}
def create_production(path: Path, media: Path) -> tuple[Production, ImportedMedia]:
    production = Production.create(path, "Documentary")
    with production.edit(
        origin=OriginIdentity("com.example.editor", "0.4.0"),
        message="Import camera original",
    ) as transaction:
        imported = transaction.import_media(media, display_name="Camera A")
        transaction.commit()

    print(f"representations: {len(production.representations[imported.asset_id])}")
    return production, imported
fn create_production(
    path: &Path,
    media: &Path,
) -> Result<(SqliteProduction, AssetId, RepresentationId)> {
    let mut production = SqliteProduction::create(path, Some("Documentary".to_owned()))?;

    let import = prepare_original_media(media, Some("Camera A".to_owned()), None)?;
    let asset_id = import.asset().id();
    {
        let mut transaction = production.begin_transaction()?;
        transaction.set_revision_context(RevisionContext::new(
            Some(OriginIdentity::new(
                "com.example.editor",
                Some("0.4.0".to_owned()),
                None,
            )?),
            Some("Import camera original".to_owned()),
        )?)?;
        transaction.import_original(&import)?;
        transaction.commit()?;
    }

    let representations = production.representations(asset_id)?;
    println!("representations: {}", representations.len());
    Ok((production, asset_id, import.representation().id()))
}
postproject init production.pproj --name "Documentary"
postproject --json media add production.pproj rushes/A001.mov \
  --name "Camera A" > imported.json
ASSET_ID=$(jq -r .asset_id imported.json)
ORIGINAL_ID=$(jq -r .representation_id imported.json)
postproject media show production.pproj "$ASSET_ID"

Choose the language with the tabs or with the Code selector in the sidebar; the choice applies to every example on the site and is remembered in this browser.

Identity text

At an interchange boundary, parse saved UUID text into its semantic identity. Parsing establishes syntax and kind; an operation still checks existence and production membership. IDs support standard equality and containers. Python hints retain ordinary UUID runtime values:

static pp_error_code_t asset_identity(const char *saved_id, pp_error_t **error) {
  pp_asset_id_t asset;
  pp_object_ref_t target = {0};
  pp_asset_id_t projected;
  char *canonical = NULL;
  pp_error_code_t status = pp_asset_id_parse(saved_id, &asset, error);
  if (status == PP_OK) {
    status = pp_object_ref_from_asset(asset, &target, error);
  }
  if (status == PP_OK) {
    status = pp_object_ref_get_asset(&target, &projected, error);
  }
  if (status == PP_OK &&
      (memcmp(projected.bytes, asset.bytes, 16) || target.kind != PP_OBJECT_ASSET || memcmp(target.id.bytes, asset.bytes, 16))) {
    status = PP_ERROR_INTERNAL;
  }
  if (status == PP_OK) {
    status = pp_asset_id_format(asset, &canonical, error);
  }
  if (status == PP_OK) {
    printf("asset identity: %s\n", canonical);
  }
  pp_string_release(canonical);
  return status;
}
void asset_identity(std::string_view saved_id) {
  const auto asset = postproject::AssetId::fromString(saved_id).value();
  const auto target = postproject::ObjectRef::asset(asset);
  require(target.assetId().value() == asset &&
              target.kind() == postproject::ObjectKind::asset &&
              target.asUuid().bytes() == asset.bytes(), "typed asset target");
  require(std::get_if<postproject::AssetId>(&target.value()) != nullptr,
          "reference retains the semantic identity alternative");
  require(postproject::ObjectRef::fromUuid(postproject::ObjectKind::asset,
                                          asset.asUuid()).value() == target,
          "checked explicit interchange");
  require(!postproject::ObjectRef::fromUuid(
              static_cast<postproject::ObjectKind>(99), asset.asUuid()),
          "unknown reference kind rejected");
  const std::set<postproject::AssetId> ordered{asset, asset};
  const std::unordered_set<postproject::AssetId> hashed{asset, asset};
  require(ordered.size() == 1 && hashed.size() == 1, "identity value semantics");
  require(postproject::AssetId(asset.bytes()) == asset &&
              postproject::AssetId(asset.asUuid()) == asset,
          "explicit interchange preserves bytes");
  std::cout << "asset identity: " << asset.toString().value() << '\n';
}
def asset_identity(saved_id: str) -> None:
    asset = parse_id(saved_id, AssetId)
    assert isinstance(asset, UUID)
    assert AssetId(asset) is asset
    assert len({asset, asset}) == 1
    print("asset identity:", asset)
fn asset_identity(saved_id: &str) -> Result<()> {
    let asset: AssetId = saved_id.parse()?;
    let ordered = std::collections::BTreeSet::from([asset, asset]);
    let hashed = std::collections::HashSet::from([asset, asset]);
    assert_eq!(ordered.len(), 1);
    assert_eq!(hashed.len(), 1);
    println!("asset identity: {asset}");
    Ok(())
}

Pass ordinary UUID text to the command’s entity parameter; the operation checks existence and scope.

Native asset operations carry the semantic type through inputs and results. C++ dynamic references retain a private variant of typed IDs. Inspect its const value() with std::get_if, or use a kind-specific projection. UUID conversion is explicit interchange; entity existence and production scope remain checks performed by the operation.

Reopen a production

A production file outlives the process that created it. Reopening applies any pending schema migration first, then returns the same production identity. The example reopens the file, checks that a stored asset still exists, lists every asset, and reads the newest revision, which is where a revision feed consumer starts:

static pp_error_code_t open_production(const char *path,
                                       const pp_asset_id_t *asset_id,
                                       pp_production_t **out_production,
                                       pp_error_t **error) {
  pp_production_t *production = NULL;
  pp_asset_set_t *assets = NULL;
  pp_revision_set_t *latest = NULL;
  pp_production_id_t production_id;
  pp_production_id_t parsed_id = {0};
  char *identity_text = NULL;
  uint8_t exists = 0;

  pp_error_code_t status = pp_production_open(path, &production, error);
  if (status == PP_OK) {
    /* Typed parsing and formatting preserve ordinary UUID text. */
    status = pp_production_id_parse("00000000-0000-0000-0000-000000000001",
                                    &parsed_id, error);
  }
  if (status == PP_OK) {
    status = pp_production_id_format(parsed_id, &identity_text, error);
  }
  if (status == PP_OK &&
      strcmp(identity_text, "00000000-0000-0000-0000-000000000001") != 0) {
    status = PP_ERROR_INTERNAL;
  }
  if (status == PP_OK) {
    /* The production ID is stable for the lifetime of the file. */
    status = pp_production_id(production, &production_id, error);
  }
  if (status == PP_OK) {
    status = pp_production_asset_exists(production, *asset_id, &exists, error);
  }
  if (status == PP_OK) {
    printf("asset recorded: %s\n", exists != 0 ? "yes" : "no");
    /* Whole-set enumeration; use pp_production_assets_page() when large. */
    status = pp_production_assets(production, &assets, error);
  }
  for (uint64_t i = 0; status == PP_OK && i < pp_asset_set_count(assets); ++i) {
    pp_asset_id_t id;
    int64_t created_at = 0;
    const char *name = NULL;
    const char *import_source = NULL;
    status = pp_asset_set_get(assets, i, &id, &created_at, &name,
                              &import_source, error);
    if (status == PP_OK) {
      printf("asset: %s (from %s)\n", name != NULL ? name : "-",
             import_source != NULL ? import_source : "-");
    }
  }
  if (status == PP_OK) {
    status = pp_production_latest_revision(production, &latest, error);
  }
  if (status == PP_OK && pp_revision_set_count(latest) == 1) {
    pp_revision_id_t revision_id;
    pp_transaction_id_t transaction_id;
    uint64_t sequence = 0;
    int64_t committed_at = 0;
    const char *origin_name, *origin_version, *origin_uri, *message;
    status = pp_revision_set_get(latest, 0, &revision_id, &sequence,
                                 &transaction_id, &committed_at, &origin_name,
                                 &origin_version, &origin_uri, &message, error);
    if (status == PP_OK) {
      printf("latest revision %llu: %s\n", (unsigned long long)sequence,
             message != NULL ? message : "-");
    }
  }
  if (status == PP_OK) {
    *out_production = production;
    production = NULL;
  }

  pp_revision_set_release(latest);
  pp_string_release(identity_text);
  pp_asset_set_release(assets);
  pp_production_release(production);
  return status;
}
postproject::Production open_production(const std::string &path,
                                        const postproject::AssetId &asset_id) {
  auto production = postproject::Production::open(path).value();
  const auto identity = postproject::ProductionId::fromString(
      "00000000-0000-0000-0000-000000000001").value();
  require(identity.toString().value() == "00000000-0000-0000-0000-000000000001",
          "typed production identity round trip");
  require(identity.asUuid().bytes() == identity.bytes(), "explicit UUID bytes");
  const auto target = postproject::ObjectRef::production(identity);
  require(target.productionId().value() == identity, "typed production target");
  std::cout << "production " << production.id().value().toString().value() << '\n';

  if (production.containsAsset(asset_id).value()) {
    std::cout << "asset " << asset_id.toString().value() << " is present\n";
  }
  // assets() reads the whole set; use the paged overload for large productions.
  for (const auto &asset : production.assets().value()) {
    std::cout << "asset: " << asset.display_name.value_or("(unnamed)") << '\n';
  }

  if (const auto latest = production.latestRevision().value()) {
    std::cout << "latest revision: " << latest->sequence << '\n';
  }
  return production;
}
def open_production(
    path: Path, asset_id: AssetId
) -> tuple[ProductionId, list[Asset], Revision | None]:
    production = Production.open(path)
    try:
        production_id = production.id
        print(f"production: {production_id}")
        if production.asset_exists(asset_id):
            print(f"asset {asset_id} exists")

        with production.read_session() as view:
            assets = list(view.assets())
        for asset in assets:
            print(f"asset {asset.id}: {asset.display_name or '-'}")

        latest = production.latest_revision  # None for an empty production
        if latest is not None:
            print(f"latest revision {latest.sequence}: {latest.message or '-'}")
        return production_id, assets, latest
    finally:
        production.close()
fn open_production(path: &Path, asset_id: AssetId) -> Result<SqliteProduction> {
    let production = SqliteProduction::open(path)?;
    println!("production: {}", production.production().id());

    // `assets` enumerates the whole set; use `assets_page` for large productions.
    let assets = production.assets()?;
    let exists = assets.iter().any(|asset| asset.id() == asset_id);
    println!("asset {asset_id} exists: {exists}");
    for asset in &assets {
        println!("asset {}: {:?}", asset.id(), asset.display_name());
    }

    if let Some(revision) = production.latest_revision()? {
        println!(
            "latest revision {}: {:?}",
            revision.sequence(),
            revision.message()
        );
    }
    Ok(production)
}
# Each command opens the production file, reads it, and closes it again.
postproject --json media list lifecycle.pproj > assets.json
jq -r '.[] | "\(.id) \(.representation_count) representation(s)"' assets.json
if jq -e --arg id "$ASSET_ID" 'any(.[]; .id == $id)' assets.json >/dev/null; then
  echo "asset $ASSET_ID exists"
fi
postproject --json revisions latest lifecycle.pproj | jq '{id, sequence, message}'

Whole-set asset listing suits small productions and tests. Hosts that may open large productions page through assets instead; see bounded queries.

Commit and roll back explicitly

A transaction groups one semantic change. Everything staged in it becomes durable together on commit, as one revision, or not at all. Rolling back — or releasing an open transaction — discards the staged work and creates no revision. Only one transaction may be open per production at a time.

static pp_error_code_t commit_then_roll_back(pp_production_t *production,
                                             pp_error_t **error) {
  pp_transaction_t *transaction = NULL;
  pp_media_root_id_t root_id;

  /* Commit: every staged change becomes one durable revision. */
  pp_error_code_t status =
      pp_production_begin_edit(production, NULL,
          &(pp_edit_context_t){"com.example.editor", "0.4.0", NULL,
                              "Add archive root"}, &transaction, error);
  if (status == PP_OK) {
    status = pp_transaction_add_media_root(
        transaction, "archive", "Archive volume", 10, &root_id, error);
  }
  if (status == PP_OK) {
    pp_commit_receipt_t commit_receipt;
    status = pp_transaction_commit(transaction, &commit_receipt, error);
  }
  pp_transaction_release(transaction);
  transaction = NULL;

  /* Roll back: staged changes are discarded and no revision is written. */
  if (status == PP_OK) {
    status = pp_production_begin_edit(production, NULL, NULL, &transaction, error);
  }
  if (status == PP_OK) {
    status = pp_transaction_add_media_root(transaction, "scratch",
                                           "Scratch disk", 20, &root_id, error);
  }
  if (status == PP_OK) {
    status = pp_transaction_rollback(transaction, error);
  }

  pp_transaction_release(transaction);
  return status;
}
void commit_then_roll_back(postproject::Production &production) {
  auto transaction = production.edit({postproject::OriginIdentity{"com.example.editor", "0.4.0", std::nullopt},
       "Add the rushes root"}).value();

  transaction.addMediaRoot("rushes", "Camera originals").value();
  transaction.commit().value(); // one durable revision

  auto abandoned = production.edit().value();
  abandoned.addMediaRoot("renders", "Discarded root").value();
  // Rolling back discards every staged change; no revision is written.
  abandoned.rollback().value();
}
def tag_then_discard(production: Production, asset_id: AssetId) -> None:
    transaction = production.edit(
        origin=OriginIdentity("com.example.editor", "0.4.0"),
        message="Tag camera serial",
    )
    try:
        transaction.add_external_identifier(
            AssetRef(asset_id),
            ExternalIdentifier("com.example.camera.serial", "A-0007"),
        )
        transaction.commit()
    finally:
        transaction.close()  # releases the handle; harmless after commit

    before = production.latest_revision
    transaction = production.edit()
    try:
        transaction.add_external_identifier(
            AssetRef(asset_id), ExternalIdentifier("com.example.tape", "T-0012")
        )
        transaction.rollback()
    finally:
        # Closing a transaction that was neither committed nor rolled back
        # rolls it back as well.
        transaction.close()

    # A rollback creates no revision and leaves no staged change behind.
    assert production.latest_revision == before
    assert len(production.external_identifiers[AssetRef(asset_id)]) == 1
fn commit_then_roll_back(production: &mut SqliteProduction, asset_id: AssetId) -> Result<()> {
    let status = MetadataProperty::new(
        VocabularyId::new("https://example.com/ns/editorial/1")?,
        PropertyId::new("status")?,
    );
    let target = ObjectRef::Asset(asset_id);

    let mut transaction = production.begin_transaction()?;
    transaction.set_revision_context(RevisionContext::new(
        Some(OriginIdentity::new("com.example.editor", None, None)?),
        Some("Mark as selected".to_owned()),
    )?)?;
    transaction.add_metadata_value(target, &status, &MetadataValue::string("selected")?)?;
    transaction.commit()?;
    drop(transaction);
    let committed = production.latest_revision()?.map(|revision| revision.id());

    // Rolling back discards every staged change: no revision is recorded.
    let mut transaction = production.begin_transaction()?;
    transaction.add_metadata_value(target, &status, &MetadataValue::string("rejected")?)?;
    transaction.rollback()?;
    assert_eq!(transaction.state(), TransactionState::RolledBack);
    drop(transaction);

    assert_eq!(
        production.latest_revision()?.map(|revision| revision.id()),
        committed
    );
    assert_eq!(
        production.metadata_values(target, &status)?,
        [MetadataValue::string("selected")?]
    );
    Ok(())
}

Every CLI command runs as exactly one transaction: it commits when the command succeeds and leaves the production unchanged when it fails. There is no multi-command transaction.

Set the revision context before commit. It records the integrating tool and a short message on the resulting revision; it does not authenticate anyone.

Handle errors

Every surface reports the same stable error categories — invalid argument, not found, already exists, I/O, storage, migration, conflict, ambiguous resolution, fingerprint, unsupported, cancelled, and internal — in its own idiom. Branch on the category, never on message text, which is diagnostic and may change:

static int report_missing_production(const char *path) {
  pp_production_t *production = NULL;
  pp_error_t *error = NULL;

  const pp_error_code_t status = pp_production_open(path, &production, &error);
  /* The status and pp_error_code() agree; the message is for people. */
  const int not_found = status == PP_ERROR_NOT_FOUND && error != NULL &&
                        pp_error_code(error) == PP_ERROR_NOT_FOUND;
  if (error != NULL) {
    printf("open failed (%u): %s\n", pp_error_code(error),
           pp_error_message(error));
  }

  pp_error_release(error);
  pp_production_release(production);
  return not_found;
}
std::optional<postproject::ErrorCode>
try_open(const std::string &missing_path) {
  // Every fallible operation returns a Result instead of throwing, so this
  // works in code built with -fno-exceptions.
  const auto production = postproject::Production::open(missing_path);
  if (production.has_value()) {
    return std::nullopt;
  }
  // code() is stable to branch on; message() is a diagnostic for people.
  const postproject::Error &error = production.error();
  if (error.code() == postproject::ErrorCode::not_found) {
    std::cerr << "no production at " << missing_path << ": "
              << error.message() << '\n';
  }
  // With exceptions enabled, value() on a failed Result throws
  // postproject::Exception instead; without them it aborts.
  return error.code();
}

// POSTPROJECT_TRY_ASSIGN returns a failure to the caller and otherwise
// declares the value; POSTPROJECT_TRY does the same for Result<void>. The
// enclosing function must return a Result.
postproject::Result<std::size_t> count_assets(const std::string &path) {
  POSTPROJECT_TRY_ASSIGN(const auto production,
                         postproject::Production::open(path));
  // transform() maps a value and passes an error through unchanged.
  return production.assets().transform(
      [](const auto &assets) { return assets.size(); });
}
def open_missing(path: Path) -> NotFoundError | None:
    try:
        Production.open(path)
    except NotFoundError as error:
        # Every PostProjectError carries the stable C ABI code and a message.
        print(f"not found (code {error.code}): {error}")
        return error
    return None
fn open_missing(path: &Path) -> Result<()> {
    match SqliteProduction::open(path) {
        Ok(_) => println!("opened {}", path.display()),
        Err(error) if error.kind() == ErrorKind::NotFound => {
            println!("not found: {}", error.message());
        }
        Err(error) => return Err(error),
    }
    Ok(())
}
# Failures exit with a non-zero status and describe the error on stderr.
if ! postproject media list missing.pproj 2> error.txt; then
  echo "open failed: $(cat error.txt)"
fi

When a staging call fails inside a transaction, roll the transaction back unless the integration deliberately continues with the rest of the change. conflict also reports lifecycle misuse, such as a second open transaction or a call on a closed transaction. A transaction with a base revision may instead carry structured semantic conflict detail.

Handles, errors, and lifetimes

The language surfaces differ only in how they express ownership and failure:

  • The C ABI returns a status code from every fallible function and reports details through an optional error handle. Every handle returned to the caller, including result sets and error handles, must be released with its documented release function. Strings returned by a result-set accessor borrow the result set.

  • The C++17 wrapper owns handles with RAII types, copies results into values, and returns postproject::Result<T>. POSTPROJECT_TRY and POSTPROJECT_TRY_ASSIGN pass a failure on to the caller in one line, and value() throws postproject::Exception when exceptions are enabled.

  • The Python binding raises typed exceptions. A transaction used as a context manager requires explicit commit() and rolls back uncommitted work on exit.

  • Rust storage returns postproject_core::Result. The media adapter prepares an import from the filesystem before the transaction stages it.

  • The CLI commits each command as one transaction. Pass --json for structured output that scripts can parse.

Every example on this site comes from a program that CI compiles and runs against an installed package, so the listings stay in step with the public interfaces. See the C quickstart, C++ quickstart, and Python quickstart for building and running a consumer, and install a release for the packages.