Skip to main content

ToolingClient

Struct ToolingClient 

Source
pub struct ToolingClient { /* private fields */ }
Expand description

Salesforce Tooling API client.

Provides typed methods for Tooling API operations:

  • Execute anonymous Apex
  • Query Apex classes, triggers, and logs
  • Manage debug logs and trace flags
  • Code coverage information

§Example

use sf_tooling::ToolingClient;

let client = ToolingClient::new(
    "https://myorg.my.salesforce.com",
    "access_token_here",
)?;

// Execute anonymous Apex
let result = client.execute_anonymous("System.debug('Hello');").await?;

// Query Apex classes
let classes: Vec<ApexClass> = client
    .query_all("SELECT Id, Name FROM ApexClass")
    .await?;

Implementations§

Source§

impl ToolingClient

Source

pub async fn get_apex_classes(&self) -> Result<Vec<ApexClass>, Error>

Get all Apex classes in the org.

Source

pub async fn get_apex_class_by_name( &self, name: &str, ) -> Result<Option<ApexClass>, Error>

Get an Apex class by name.

Source

pub async fn get_apex_class(&self, id: &str) -> Result<ApexClass, Error>

Get an Apex class by ID.

Source

pub async fn get_apex_triggers(&self) -> Result<Vec<ApexTrigger>, Error>

Get all Apex triggers in the org.

Source

pub async fn get_apex_trigger_by_name( &self, name: &str, ) -> Result<Option<ApexTrigger>, Error>

Get an Apex trigger by name.

Source§

impl ToolingClient

Source

pub async fn completions_apex(&self) -> Result<Value, Error>

Get code completions for Apex system symbols.

Returns the raw JSON response because the Salesforce completions response format varies between Apex and Visualforce types and across API versions.

Available since API v28.0.

Source

pub async fn completions_visualforce(&self) -> Result<Value, Error>

Get code completions for Visualforce components.

Returns the raw JSON response because the Salesforce completions response format varies between Apex and Visualforce types and across API versions.

Available since API v38.0.

Source§

impl ToolingClient

Source

pub async fn get_multiple<T>( &self, sobject: &str, ids: &[&str], fields: &[&str], ) -> Result<Vec<T>, Error>

Get multiple Tooling API records by ID in a single request.

Uses a Tooling API SOQL query (WHERE Id IN (...)) internally. The Tooling API’s SObject Collections GET endpoint is documented but does not work reliably for most objects, so we use SOQL instead.

§Arguments
  • sobject - The SObject type (e.g., “ApexClass”, “CustomField”)
  • ids - Array of record IDs to retrieve
  • fields - Array of field names to return
§Example
let classes: Vec<serde_json::Value> = client
    .get_multiple("ApexClass", &["01p...", "01p..."], &["Id", "Name", "Body"])
    .await?;
Source

pub async fn create_multiple<T>( &self, sobject: &str, records: &[T], all_or_none: bool, ) -> Result<Vec<CollectionResult>, Error>
where T: Serialize,

Create multiple Tooling API records in a single request (up to 200).

Available since API v45.0.

§Arguments
  • sobject - The SObject type (e.g., “ApexClass”, “CustomField”)
  • records - Array of records to create
  • all_or_none - If true, all records must succeed or all fail
§Example
use serde_json::json;

let records = vec![
    json!({"Name": "TestClass1", "Body": "public class TestClass1 {}"}),
    json!({"Name": "TestClass2", "Body": "public class TestClass2 {}"}),
];

let results = client.create_multiple("ApexClass", &records, false).await?;
Source

pub async fn update_multiple<T>( &self, sobject: &str, records: &[(String, T)], all_or_none: bool, ) -> Result<Vec<CollectionResult>, Error>
where T: Serialize,

Update multiple Tooling API records in a single request (up to 200).

Available since API v45.0.

§Arguments
  • sobject - The SObject type (e.g., “ApexClass”, “CustomField”)
  • records - Array of (id, record) tuples to update
  • all_or_none - If true, all records must succeed or all fail
Source

pub async fn delete_multiple( &self, ids: &[&str], all_or_none: bool, ) -> Result<Vec<CollectionResult>, Error>

Delete multiple Tooling API records in a single request (up to 200).

Available since API v45.0.

§Arguments
  • ids - Array of record IDs to delete
  • all_or_none - If true, all records must succeed or all fail
Source§

impl ToolingClient

Source

pub async fn composite( &self, request: &CompositeRequest, ) -> Result<CompositeResponse, Error>

Execute a Tooling API composite request with multiple subrequests.

The Tooling API composite endpoint allows up to 25 subrequests in a single API call. Subrequests can reference results from earlier subrequests using @{referenceId}.

Available since API v40.0.

§Example
use busbar_sf_tooling::{CompositeRequest, CompositeSubrequest};

let request = CompositeRequest {
    all_or_none: false,
    collate_subrequests: false,
    subrequests: vec![
        CompositeSubrequest {
            method: "GET".to_string(),
            url: "/services/data/v62.0/tooling/sobjects/ApexClass/01p...".to_string(),
            reference_id: "refApexClass".to_string(),
            body: None,
        },
    ],
};

let response = client.composite(&request).await?;
Source

pub async fn composite_batch( &self, request: &CompositeBatchRequest, ) -> Result<CompositeBatchResponse, Error>

Execute a Tooling API composite batch request with multiple independent subrequests.

The composite batch API executes up to 25 subrequests independently. Unlike the standard composite API, subrequests cannot reference each other’s results.

Available since API v40.0.

Source

pub async fn composite_tree( &self, sobject: &str, request: &CompositeTreeRequest, ) -> Result<CompositeTreeResponse, Error>

Execute a Tooling API composite tree request to create record hierarchies.

Creates parent records with nested child records in a single request. Supports up to 200 records total across all levels of the hierarchy.

Available since API v42.0.

§Arguments
  • sobject - The parent SObject type (e.g., “ApexClass”, “CustomField”)
  • request - The tree request containing parent records and nested children
Source§

impl ToolingClient

Source

pub async fn get_code_coverage( &self, ) -> Result<Vec<ApexCodeCoverageAggregate>, Error>

Get code coverage for all Apex classes and triggers.

Source

pub async fn get_org_wide_coverage(&self) -> Result<f64, Error>

Get overall org-wide code coverage percentage.

Source§

impl ToolingClient

Source

pub async fn get_metadata_component_dependencies( &self, where_clause: Option<&str>, ) -> Result<Vec<MetadataComponentDependency>, Error>

Get metadata component dependencies.

Returns dependency relationships between metadata components in your org. Note: Limited to 2000 records per query in Tooling API.

Available since API v43.0 for Tooling API.

§Security

IMPORTANT: If you are including user-provided values in the WHERE clause, you MUST escape them to prevent SOQL injection attacks:

use busbar_sf_client::security::soql;

// CORRECT - properly escaped:
let safe_type = soql::escape_string(user_input);
let filter = format!("MetadataComponentType = '{}'", safe_type);
let deps = client.get_metadata_component_dependencies(Some(&filter)).await?;
§Example
// Get all dependencies (limited to 2000)
let deps = client.get_metadata_component_dependencies(None).await?;

// Filter by component type (hardcoded - safe)
let apex_deps = client.get_metadata_component_dependencies(
    Some("MetadataComponentType = 'ApexClass'")
).await?;
Source§

impl ToolingClient

Source

pub async fn describe_global(&self) -> Result<DescribeGlobalResult, Error>

Get a list of all Tooling API SObjects available in the org.

Source

pub async fn describe_sobject( &self, sobject: &str, ) -> Result<DescribeSObjectResult, Error>

Get detailed metadata for a specific Tooling API SObject.

Source

pub async fn basic_info(&self, sobject: &str) -> Result<Value, Error>

Get basic information about a Tooling API SObject.

Source

pub async fn resources(&self) -> Result<Value, Error>

Get a list of all available Tooling API resources.

Source§

impl ToolingClient

Source

pub async fn execute_anonymous( &self, apex_code: &str, ) -> Result<ExecuteAnonymousResult, Error>

Execute anonymous Apex code.

§Example
let result = client.execute_anonymous("System.debug('Hello World');").await?;
if result.success {
    println!("Execution successful");
} else if let Some(err) = result.compile_problem {
    println!("Compilation error: {}", err);
}
Source§

impl ToolingClient

Source

pub async fn get_apex_logs( &self, limit: Option<u32>, ) -> Result<Vec<ApexLog>, Error>

Get recent Apex logs.

§Arguments
  • limit - Maximum number of logs to return (defaults to 20)
Source

pub async fn get_apex_log_body(&self, log_id: &str) -> Result<String, Error>

Get the body of a specific Apex log.

Source

pub async fn delete_apex_log(&self, log_id: &str) -> Result<(), Error>

Delete an Apex log.

Source

pub async fn delete_all_apex_logs(&self) -> Result<u32, Error>

Delete all Apex logs for the current user.

Source§

impl ToolingClient

Source

pub async fn query<T>(&self, soql: &str) -> Result<QueryResult<T>, Error>

Execute a SOQL query against the Tooling API.

Returns the first page of results. Use query_all for automatic pagination.

§Security

IMPORTANT: If you are including user-provided values in the WHERE clause, you MUST escape them to prevent SOQL injection attacks:

use busbar_sf_client::security::soql;

// CORRECT - properly escaped:
let safe_name = soql::escape_string(user_input);
let query = format!("SELECT Id FROM ApexClass WHERE Name = '{}'", safe_name);
Source

pub async fn query_all<T>(&self, soql: &str) -> Result<Vec<T>, Error>

Execute a SOQL query and return all results (automatic pagination).

§Security

IMPORTANT: Escape user-provided values with busbar_sf_client::security::soql::escape_string() to prevent SOQL injection attacks. See query() for examples.

Source

pub async fn query_all_records<T>( &self, soql: &str, ) -> Result<QueryResult<T>, Error>

Execute a SOQL query including deleted and archived records.

Note: The Tooling API does not expose a /queryAll endpoint. This method uses the standard REST API /queryAll resource, which also works for Tooling API objects (ApexClass, ApexTrigger, etc.).

Source

pub async fn search<T>(&self, sosl: &str) -> Result<SearchResult<T>, Error>

Execute a SOSL search against Tooling API objects.

Source§

impl ToolingClient

Source

pub async fn get<T>(&self, sobject: &str, id: &str) -> Result<T, Error>

Get a Tooling API SObject by ID.

Source

pub async fn create<T>( &self, sobject: &str, record: &T, ) -> Result<String, Error>
where T: Serialize,

Create a Tooling API SObject.

Source

pub async fn update<T>( &self, sobject: &str, id: &str, record: &T, ) -> Result<(), Error>
where T: Serialize,

Update a Tooling API SObject (partial update).

Source

pub async fn delete(&self, sobject: &str, id: &str) -> Result<(), Error>

Delete a Tooling API SObject.

Source§

impl ToolingClient

Source

pub async fn run_tests_async( &self, request: &RunTestsAsyncRequest, ) -> Result<String, Error>

Run tests asynchronously.

Returns the AsyncApexJob ID as a plain string.

Source

pub async fn run_tests_sync( &self, request: &RunTestsSyncRequest, ) -> Result<RunTestsSyncResult, Error>

Run tests synchronously.

Blocks until completion. Returns full results including successes and failures.

Source

pub async fn discover_tests( &self, category: Option<&str>, ) -> Result<TestDiscoveryResult, Error>

Discover available tests (Apex and Flow tests).

Requires API v65.0 or later.

Source

pub async fn run_tests( &self, request: &RunTestsRequest, ) -> Result<String, Error>

Run tests using the unified Test Runner API (v65.0+).

Source§

impl ToolingClient

Source

pub async fn get_trace_flags(&self) -> Result<Vec<TraceFlag>, Error>

Get all active trace flags.

Source

pub async fn get_debug_levels(&self) -> Result<Vec<DebugLevel>, Error>

Get all debug levels.

Source§

impl ToolingClient

Source

pub fn new( instance_url: impl Into<String>, access_token: impl Into<String>, ) -> Result<ToolingClient, Error>

Create a new Tooling API client with the given instance URL and access token.

Source

pub fn with_config( instance_url: impl Into<String>, access_token: impl Into<String>, config: ClientConfig, ) -> Result<ToolingClient, Error>

Create a new Tooling API client with custom HTTP configuration.

Source

pub fn from_client(client: SalesforceClient) -> ToolingClient

Create a Tooling client from an existing SalesforceClient.

Source

pub fn inner(&self) -> &SalesforceClient

Get the underlying SalesforceClient.

Source

pub fn instance_url(&self) -> &str

Get the instance URL.

Source

pub fn api_version(&self) -> &str

Get the API version.

Source

pub fn with_api_version(self, version: impl Into<String>) -> ToolingClient

Set the API version.

Trait Implementations§

Source§

impl Clone for ToolingClient

Source§

fn clone(&self) -> ToolingClient

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ToolingClient

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more