### Install Go Salesforce Library Source: https://context7.com/k-capehart/go-salesforce/llms.txt Use 'go get' to install the latest version of the go-salesforce library. ```bash go get github.com/k-capehart/go-salesforce/v3 ``` -------------------------------- ### Install Development Tools Source: https://github.com/k-capehart/go-salesforce/blob/main/CONTRIBUTING.md Run this command to install necessary tools for development, such as linters and formatters. ```bash make install-tools ``` -------------------------------- ### Get Instance URL from Salesforce Client Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Retrieves the current session's instance URL as a string. ```go url := sf.GetInstanceUrl() ``` -------------------------------- ### Run Linting Checks Source: https://github.com/k-capehart/go-salesforce/blob/main/CONTRIBUTING.md Perform static analysis on the code to catch potential errors and style issues. Ensure golangci-lint is installed. ```bash make lint ``` -------------------------------- ### Get Access Token from Salesforce Client Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Retrieves the current session's access token as a string. ```go token := sf.GetAccessToken() ``` -------------------------------- ### Account Struct with Salesforce Tag Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Example of a Go struct tagged for Salesforce API field mapping. The `salesforce` tag allows decoding API field names like 'ExternalId__c' into struct fields. ```go type Account struct { ExternalID string `salesforce:"ExternalId__c"` Name string } ``` -------------------------------- ### Initialize Salesforce Client with Client Credentials Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Use this for the Client Credentials Flow. Ensure DOMAIN, CONSUMER_KEY, and CONSUMER_SECRET are defined. ```go sf, err := salesforce.Init(salesforce.Creds{ Domain: DOMAIN, // ex: https://myslug.my.salesforce.com ConsumerKey: CONSUMER_KEY, ConsumerSecret: CONSUMER_SECRET, }) ``` -------------------------------- ### Get Authentication Flow Type Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Retrieves the authentication flow type used for the current session. ```go authType := sf.GetAuthFlow() ``` -------------------------------- ### Initialize Salesforce Client with Username-Password Flow Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Use this for the Username-Password Flow. Ensure all required credentials and keys are defined. ```go sf, err := salesforce.Init(salesforce.Creds{ Domain: DOMAIN, Username: USERNAME, Password: PASSWORD, SecurityToken: SECURITY_TOKEN, ConsumerKey: CONSUMER_KEY, ConsumerSecret: CONSUMER_SECRET, }) ``` -------------------------------- ### Initialize Salesforce Client with Access Token Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Use this when you have an existing access token from a custom OAuth flow. Ensure DOMAIN and ACCESS_TOKEN are defined. ```go sf, err := salesforce.Init(salesforce.Creds{ Domain: DOMAIN, AccessToken: ACCESS_TOKEN, }) ``` -------------------------------- ### Init Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Initializes a new Salesforce instance with provided credentials and optional configurations. Supports various OAuth flows including Client Credentials, Username-Password, JWT Bearer, and Access Token authentication. ```APIDOC ## Init ### Description Returns a new Salesforce instance given a user's credentials. - `creds`: a struct containing the necessary credentials to authenticate into a Salesforce org - `options`: optional configuration - see [Configuration](#configuration) - If an operation fails with the Error Code `INVALID_SESSION_ID`, go-salesforce will attempt to refresh the session by resubmitting the same credentials used during initialization - Configuration values are set to the defaults if not specified ### Method `func Init(creds Creds, options ...Option) *Salesforce` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go sf, err := salesforce.Init(salesforce.Creds{ Domain: DOMAIN, // ex: https://myslug.my.salesforce.com ConsumerKey: CONSUMER_KEY, ConsumerSecret: CONSUMER_SECRET, }) ``` ### Response #### Success Response (200) - `*Salesforce`: A pointer to the initialized Salesforce client instance. - `error`: An error if initialization fails. #### Response Example None explicitly provided, but implies a successful client object or an error. ``` -------------------------------- ### Get Bulk Job Results Source: https://context7.com/k-capehart/go-salesforce/llms.txt `GetJobResults` retrieves the final state and per-record outcome (successful and failed records) of a completed bulk ingest job. ```APIDOC ## GetJobResults ### Description Retrieves the final state and per-record outcome (successful and failed records) of a completed bulk ingest job. ### Method Signature `sf.GetJobResults(jobId string) (*BulkJobResult, error)` ### Parameters - `jobId` (string): The ID of the bulk job to retrieve results for. ### Response - `*BulkJobResult`: An object containing the job's state, number of successful and failed records, and lists of successful and failed records. - `Id` (string): The job ID. - `State` (string): The final state of the job (e.g., "JobComplete"). - `NumberRecordsFailed` (int): The number of records that failed during the job. - `SuccessfulRecords` ([]map[string]interface{}): A list of successfully processed records. - `FailedRecords` ([]map[string]interface{}): A list of records that failed processing, including error details. - `error`: An error if the operation fails. ### Request Example ```go type Contact struct{ LastName string } jobIds, err := sf.InsertBulk("Contact", []Contact{{LastName: "Grimm"}}, 1000, true) if err != nil { log.Fatal(err) } for _, id := range jobIds { results, err := sf.GetJobResults(id) if err != nil { log.Fatal(err) } fmt.Printf("Job %s: state=%s failed=%d\n", results.Id, results.State, results.NumberRecordsFailed) for _, rec := range results.SuccessfulRecords { fmt.Println(" Success:", rec["Id"]) } for _, rec := range results.FailedRecords { fmt.Println(" Failed:", rec["sf__Error"]) } } ``` ### Output Example ``` Job 7503t000002ABCAAM: state=JobComplete failed=0 Success: 0033t000003xXYZAAM ``` ``` -------------------------------- ### Run Unit Tests Source: https://github.com/k-capehart/go-salesforce/blob/main/CONTRIBUTING.md Execute all unit tests for the project using this command. ```bash make test ``` -------------------------------- ### Get Bulk Job Results Source: https://context7.com/k-capehart/go-salesforce/llms.txt Retrieves the final state and per-record outcomes of a completed bulk ingest job. Handles successful and failed records. ```go type Contact struct{ LastName string } jobIds, err := sf.InsertBulk("Contact", []Contact{{LastName: "Grimm"}}, 1000, true) if err != nil { log.Fatal(err) } for _, id := range jobIds { results, err := sf.GetJobResults(id) if err != nil { log.Fatal(err) } fmt.Printf("Job %s: state=%s failed=%d\n", results.Id, results.State, results.NumberRecordsFailed) for _, rec := range results.SuccessfulRecords { fmt.Println(" Success:", rec["Id"]) } for _, rec := range results.FailedRecords { fmt.Println(" Failed:", rec["sf__Error"]) } } // Output: // Job 7503t000002ABCAAM: state=JobComplete failed=0 // Success: 0033t000003xXYZAAM ``` -------------------------------- ### Initialize Salesforce Client with Custom Round Tripper Source: https://github.com/k-capehart/go-salesforce/blob/main/HTTP_CLIENT_CONFIG.md Use this to provide a custom http.RoundTripper for fine-grained HTTP control, such as setting up proxies or TLS configurations. Ensure all necessary credentials and options are provided. ```go func main() { // Create a custom round tripper for fine-grained HTTP control // options include proxy, tls, etc proxyURL, _ := url.Parse("http://my-proxy:8080") customRoundTripper := &http.Transport{ TLSClientConfig: &tls.Config{ MinVersion: tls.VersionTLS12, }, MaxIdleConns: 10, IdleConnTimeout: 30 * time.Second, DisableCompression: false, DisableKeepAlives: false, MaxIdleConnsPerHost: 5, Proxy: http.ProxyURL(proxyURL), // optional } creds := salesforce.Creds{ // ... your credentials } // Initialize with custom round tripper sf, err := salesforce.Init(creds, salesforce.WithRoundTripper(customRoundTripper), salesforce.WithAPIVersion("v64.0"), ) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Authenticate with Salesforce using Init Source: https://context7.com/k-capehart/go-salesforce/llms.txt The Init function creates an authenticated Salesforce client. The authentication flow is determined by the populated fields in the Creds struct. Supported flows include Client Credentials, Username-Password, JWT Bearer, and direct Access Token. Optional functional options can be provided for custom client configuration. ```go package main import ( "fmt" "log" "time" "github.com/k-capehart/go-salesforce/v3" ) func main() { // Client Credentials Flow (server-to-server) sf, err := salesforce.Init(salesforce.Creds{ Domain: "https://myorg.my.salesforce.com", ConsumerKey: "3MVG9...", ConsumerSecret: "ABC123...", }) if err != nil { log.Fatal(err) } // Username-Password Flow sf, err = salesforce.Init(salesforce.Creds{ Domain: "https://myorg.my.salesforce.com", Username: "user@example.com", Password: "mypassword", SecurityToken: "TOKEN123", ConsumerKey: "3MVG9...", ConsumerSecret: "ABC123...", }) if err != nil { log.Fatal(err) } // JWT Bearer Flow (certificate-based) sf, err = salesforce.Init(salesforce.Creds{ Domain: "https://myorg.my.salesforce.com", Username: "user@example.com", ConsumerKey: "3MVG9...", ConsumerRSAPem: "-----BEGIN RSA PRIVATE KEY-----\n...", }) if err != nil { log.Fatal(err) } // Access Token Flow (bring your own token) sf, err = salesforce.Init(salesforce.Creds{ Domain: "https://myorg.my.salesforce.com", AccessToken: "00D...", }) if err != nil { log.Fatal(err) } // With custom configuration options sf, err = salesforce.Init(salesforce.Creds{ Domain: "https://myorg.my.salesforce.com", ConsumerKey: "3MVG9...", ConsumerSecret: "ABC123...", }, salesforce.WithAPIVersion("v61.0"), salesforce.WithBatchSizeMax(100), salesforce.WithBulkBatchSizeMax(5000), salesforce.WithBulkPollTimeout(5*time.Minute), salesforce.WithCompressionHeaders(true), salesforce.WithValidateAuthentication(true), salesforce.WithTagName("salesforce"), salesforce.WithBulkQueryMaxRecords(500), ) if err != nil { log.Fatal(err) } fmt.Println("Auth flow:", sf.GetAuthFlow()) fmt.Println("API version:", sf.GetAPIVersion()) fmt.Println("Instance URL:", sf.GetInstanceUrl()) fmt.Println("Access token:", sf.GetAccessToken()) } ``` -------------------------------- ### Query Salesforce with Relationship Fields Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Demonstrates how to query fields from related Salesforce objects, such as accessing `Account.Name` from a `Contact` object. Ensure your Go structs mirror the relationship structure. ```go type Account struct { Name string } type Contact struct { Id string Account Account } contacts := []Contact{} sf.Query("SELECT Id, Account.Name FROM Contact", &contacts) ``` -------------------------------- ### Initialize Salesforce Client with JWT Bearer Flow Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Use this for the JWT Bearer Flow. Ensure DOMAIN, USERNAME, CONSUMER_KEY, and CONSUMER_RSA_PEM are defined. ```go sf, err := salesforce.Init(salesforce.Creds{ Domain: DOMAIN, Username: USERNAME, ConsumerKey: CONSUMER_KEY, ConsumerRSAPem: CONSUMER_RSA_PEM, }) ``` -------------------------------- ### Run Code Formatting Checks Source: https://github.com/k-capehart/go-salesforce/blob/main/CONTRIBUTING.md Execute this command to ensure your code adheres to the project's formatting standards. ```bash make fmt ``` -------------------------------- ### Initialize Salesforce Client with Custom HTTP Transport Source: https://context7.com/k-capehart/go-salesforce/llms.txt Configure the Salesforce client with a custom HTTP transport, allowing for advanced settings like TLS configuration, connection pooling, and timeouts. Ensure the provided credentials are valid. ```go import ( "crypto/tls" "net/http" "time" "github.com/k-capehart/go-salesforce/v3" ) // WithRoundTripper — custom HTTP transport (proxy, TLS config, connection pooling) sf, err := salesforce.Init(creds, salesforce.WithRoundTripper(&http.Transport{ TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12}, MaxIdleConns: 10, IdleConnTimeout: 30 * time.Second, MaxIdleConnsPerHost: 5, }), ) ``` -------------------------------- ### Configuration Struct Definition Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Defines the configuration options for the Salesforce client, including API version, timeouts, and HTTP client settings. ```go type configuration struct { compressionHeaders bool apiVersion string batchSizeMax int bulkBatchSizeMax int httpClient *http.Client roundTripper http.RoundTripper shouldValidateAuthentication bool httpTimeout time.Duration tagName string } ``` -------------------------------- ### Accessing Salesforce Client Configuration Source: https://github.com/k-capehart/go-salesforce/blob/main/HTTP_CLIENT_CONFIG.md Retrieve the current HTTP client and other configuration values from an initialized Salesforce client instance using getter methods. ```go sf, _ := salesforce.Init(creds) // Get the configured HTTP client client := sf.GetHTTPClient() // Get other configuration values apiVersion := sf.GetAPIVersion() batchSizeMax := sf.GetBatchSizeMax() bulkBatchSizeMax := sf.GetBulkBatchSizeMax() compressionEnabled := sf.GetCompressionHeaders() ``` -------------------------------- ### Initialize Salesforce Client with HTTP Timeout Source: https://context7.com/k-capehart/go-salesforce/llms.txt Set an overall HTTP client timeout for Salesforce operations. The default timeout is 120 seconds. ```go // WithHTTPTimeout — overall HTTP client timeout (default: 120s) sf, err = salesforce.Init(creds, salesforce.WithHTTPTimeout(30 * time.Second), ) ``` -------------------------------- ### Enable Local Testing with go.mod Replace Source: https://github.com/k-capehart/go-salesforce/blob/main/CONTRIBUTING.md Use this `replace` directive in your module's `go.mod` file to test local changes against the go-salesforce library. ```go replace github.com/k-capehart/go-salesforce/v3 => /path_to_local_fork/ ``` -------------------------------- ### Custom Salesforce Tag Name Source: https://context7.com/k-capehart/go-salesforce/llms.txt Initialize the Salesforce client with `salesforce.WithTagName("yourTagName")` to use a custom tag name for field mapping. ```go sf, _ := salesforce.Init(creds, salesforce.WithTagName("sf")) type Lead struct { Company string `sf:"Company"` Email string `sf:"Email"` } ``` -------------------------------- ### Default HTTP Client Configuration Source: https://github.com/k-capehart/go-salesforce/blob/main/HTTP_CLIENT_CONFIG.md This is the default HTTP client configuration used by the library when no custom round tripper is provided. It includes settings for timeout and transport. ```go { Timeout: 120 * time.Second, Transport: &http.Transport{ MaxIdleConns: 10, IdleConnTimeout: 30 * time.Second, DisableCompression: false, }, } ``` -------------------------------- ### Inspect Salesforce Client Configuration Source: https://context7.com/k-capehart/go-salesforce/llms.txt Retrieve current configuration values from an initialized Salesforce client, such as API version, maximum batch sizes, and compression settings. This is useful for debugging and understanding the client's state. ```go // Inspect current configuration fmt.Println(sf.GetAPIVersion()) // "v63.0" fmt.Println(sf.GetBatchSizeMax()) // 200 fmt.Println(sf.GetBulkBatchSizeMax()) // 10000 fmt.Println(sf.GetCompressionHeaders()) // false client := sf.GetHTTPClient() // *http.Client fmt.Println(sf.GetBulkQueryMaxRecords()) // -1 (use server default) ``` -------------------------------- ### Make HTTP Request to Salesforce Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Use this method to make generic HTTP calls to the Salesforce API. It requires the HTTP method, URI, and an optional JSON body. Custom headers can be added using RequestOption. ```go resp, err := sf.DoRequest(http.MethodGet, "/limits", nil) if err != nil { panic(err) } respBody, err := io.ReadAll(resp.Body) if err != nil { panic(err) } fmt.Println(string(respBody)) ``` -------------------------------- ### Bulk Insert from File — InsertBulkFile Source: https://context7.com/k-capehart/go-salesforce/llms.txt `InsertBulkFile` reads a CSV file and creates Bulk API v2 insert jobs from its contents. ```APIDOC ## InsertBulkFile ### Description Reads a CSV file and creates Bulk API v2 insert jobs from its contents. ### Method POST (Assumed, for initiating bulk job) ### Endpoint /services/data/vXX.X/jobs/ingest (Assumed, for Bulk API v2 ingest jobs) ### Parameters #### Path Parameters - **objectType** (string) - Required - The API name of the object to insert records into. #### Query Parameters - **filePath** (string) - Required - The path to the CSV file containing the records. - **batchSize** (integer) - Optional - The number of records per batch (default 10,000). - **waitForResults** (boolean) - Optional - If true, the operation blocks until all jobs complete. ### Request Body (Not applicable, data is read from file) ### Response #### Success Response (200) - **jobIds** ([]string) - A list of job IDs created for the bulk insert operation. ### Response Example ```go jobIds, err := sf.InsertBulkFile("Contact", "data/new_contacts.csv", 10000, false) // ... ``` ```json { "jobIds": ["7503t000002ABCBAA", "7503t000002ABCDBA", ...] } ``` ``` -------------------------------- ### Salesforce Struct Definition Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Defines the main Salesforce client struct, holding authentication and configuration details. ```go type Salesforce struct { auth *authentication config configuration } ``` -------------------------------- ### GetInstanceUrl Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Retrieves the current session's Instance URL. ```APIDOC ## GetInstanceUrl ### Description Returns the current session's Instance URL as a string. ### Method `func (sf *Salesforce) GetInstanceUrl() string` ### Endpoint N/A (Method on Salesforce struct) ### Parameters None ### Request Example ```go url := sf.GetInstanceUrl() ``` ### Response #### Success Response (200) - `string`: The current session's Instance URL. #### Response Example `"https://myslug.my.salesforce.com"` ``` -------------------------------- ### Bulk Query Export (Struct) — QueryStructBulkExport Source: https://context7.com/k-capehart/go-salesforce/llms.txt `QueryStructBulkExport` accepts a go-soql struct, generates the query, and exports results to a CSV file. ```APIDOC ## QueryStructBulkExport ### Description Accepts a go-soql struct, generates the SOQL query, and exports results to a CSV file. ### Method POST (Assumed, for initiating bulk job) ### Endpoint /services/data/vXX.X/jobs/query (Assumed, for Bulk API v2 query jobs) ### Parameters #### Request Body - **queryStruct** (object) - Required - A struct defining the query using `soql` tags. - **outputFilePath** (string) - Required - The path to the CSV file where results will be saved. ### Request Example ```go type AccountFields struct { Id string `soql:"selectColumn,fieldName=Id" json:"Id"` Name string `soql:"selectColumn,fieldName=Name" json:"Name"` Industry string `soql:"selectColumn,fieldName=Industry" json:"Industry"` } type AccountQuery struct { SelectClause AccountFields `soql:"selectClause,tableName=Account"` } err := sf.QueryStructBulkExport(AccountQuery{SelectClause: AccountFields{}}, "output/accounts.csv") ``` ### Response #### Success Response (200) Indicates the job was successfully initiated. The actual data is written to the specified file. ### Response Example (No direct response body example provided for job initiation, focus is on file output) ``` -------------------------------- ### SOQL Query Source: https://context7.com/k-capehart/go-salesforce/llms.txt Executes a SOQL query string and automatically handles pagination for all result pages, decoding them into a provided Go slice. ```APIDOC ## SOQL Query — `Query` `Query` executes a SOQL query string and decodes all result pages into a provided Go slice. Pagination (`nextRecordsUrl`) is handled automatically. ```go type Contact struct { Id string FirstName string LastName string Email string Account struct { Name string } } contacts := []Contact{} err := sf.Query( "SELECT Id, FirstName, LastName, Email, Account.Name FROM Contact WHERE LastName = 'Smith' LIMIT 100", &contacts, ) if err != nil { log.Fatal(err) } for _, c := range contacts { fmt.Printf("%s %s <%s> — Account: %s\n", c.FirstName, c.LastName, c.Email, c.Account.Name) } // Output: John Smith — Account: Acme Corp ``` ``` -------------------------------- ### Run Tests with HTML Output Source: https://github.com/k-capehart/go-salesforce/blob/main/CONTRIBUTING.md Run tests and generate an HTML report for test coverage and output. Note that Codecov may not count partial lines. ```bash make test-ouput ``` -------------------------------- ### Insert a Single SObject Record Source: https://context7.com/k-capehart/go-salesforce/llms.txt Create a new SObject record in Salesforce. The function returns a `SalesforceResult` which includes the new record's ID upon success. Handle potential errors and check the `Success` field in the result. ```go type Lead struct { FirstName string LastName string Company string Email string } result, err := sf.InsertOne("Lead", Lead{ FirstName: "Tony", LastName: "Stark", Company: "Stark Industries", Email: "tony@stark.com", }) if err != nil { log.Fatal(err) } if result.Success { fmt.Println("Created Lead ID:", result.Id) // Output: Created Lead ID: 00Q3t000001XzMEEA0 } else { for _, e := range result.Errors { fmt.Println("Error:", e.Message, e.StatusCode) } } ``` -------------------------------- ### Perform SOQL Query Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Executes a SOQL query and decodes the response into a provided struct. The `sObject` parameter should be a pointer to a slice of a custom struct type representing a Salesforce Object. ```go type Contact struct { Id string LastName string } contacts := []Contact{} err := sf.Query("SELECT Id, LastName FROM Contact WHERE LastName = 'Lee'", &contacts) ``` -------------------------------- ### Bulk Update from File Source: https://context7.com/k-capehart/go-salesforce/llms.txt `UpdateBulkFile` reads a CSV file (must contain an `Id` column) and performs bulk updates. ```APIDOC ## UpdateBulkFile ### Description Reads a CSV file (must contain an `Id` column) and performs bulk updates. ### Method Signature `sf.UpdateBulkFile(objectType string, filePath string, concurrency int, useParallel bool) ([]string, error)` ### Parameters - `objectType` (string): The Salesforce object type (e.g., "Contact"). - `filePath` (string): The path to the CSV file containing the records to update. Must include an `Id` column. - `concurrency` (int): The maximum number of jobs to run concurrently. - `useParallel` (bool): Whether to use parallel processing. ### Request Example ```csv // data/update_contacts.csv: // Id,Title,Department // 0033t000003xABCAAM,Senior Engineer,Engineering // 0033t000003xDEFAAM,Product Manager,Product ``` ```go jobIds, err := sf.UpdateBulkFile("Contact", "data/update_contacts.csv", 10000, false) if err != nil { log.Fatal(err) } fmt.Println("Bulk update job IDs:", jobIds) ``` ### Response - `[]string`: A slice of job IDs. - `error`: An error if the operation fails. ``` -------------------------------- ### Composite Insert — `InsertComposite` Source: https://context7.com/k-capehart/go-salesforce/llms.txt Inserts records via composite subrequests, allowing up to 25 subrequests per HTTP call, each with a specified batch size. The `allOrNone` parameter controls whether the entire operation rolls back on any single record failure. ```go type Contact struct { FirstName string LastName string } // 25 subrequests × 200 records = up to 5000 records in one HTTP call contacts := make([]Contact, 500) for i := range contacts { contacts[i] = Contact{FirstName: fmt.Sprintf("User%d", i), LastName: "Test"} } results, err := sf.InsertComposite("Contact", contacts, 200, true) // allOrNone=true if err != nil { log.Fatal(err) } fmt.Printf("Inserted: %d, HasErrors: %v\n", len(results.Results), results.HasSalesforceErrors) ``` -------------------------------- ### Export Query Results to CSV using QueryBulkExport Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Performs a SOQL query and exports the results directly to a specified CSV file. This is suitable for large datasets when direct file output is desired. ```go err := sf.QueryBulkExport("SELECT Id, FirstName, LastName FROM Contact", "data/export.csv") ``` -------------------------------- ### Update Salesforce Record with Partial Data Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Update a Salesforce record using `UpdateOne`. Note that uninitialized or zero/null fields in the provided struct will be treated as null values by Salesforce, potentially overwriting existing data. ```go type Contact struct { Id string LastName string FirstName string } contact := Contact{ Id: "003Dn00000pEYQSIA4", LastName: "Banner", } err = sf.UpdateOne("Contact", contact) // will update the FirstName of the contact to an empty string "" ``` -------------------------------- ### Nested Structs for Salesforce Relationships Source: https://context7.com/k-capehart/go-salesforce/llms.txt Map nested structs to Salesforce relationship fields using `salesforce:"Account.,inline"` for inline expansion in bulk queries. ```go type ContactWithAccount struct { Id string `salesforce:"Id"` AccountName struct { Name string } `salesforce:"Account.,inline"` } ``` -------------------------------- ### Insert Collection of Records — `InsertCollection` Source: https://context7.com/k-capehart/go-salesforce/llms.txt Inserts a slice of records in batches, with a maximum of 200 records per batch. Partial successes are committed, and results include per-record success/failure details. ```go type Contact struct { FirstName string LastName string Email string } contacts := []Contact{ {FirstName: "Steve", LastName: "Rogers", Email: "steve@avengers.com"}, {FirstName: "Natasha", LastName: "Romanoff", Email: "nat@avengers.com"}, {FirstName: "Bruce", LastName: "Banner", Email: "bruce@avengers.com"}, } results, err := sf.InsertCollection("Contact", contacts, 200) if err != nil { log.Fatal(err) } fmt.Printf("Has errors: %v\n", results.HasSalesforceErrors) for i, r := range results.Results { if r.Success { fmt.Printf("Contact[%d] created: %s\n", i, r.Id) } else { fmt.Printf("Contact[%d] failed: %s\n", i, r.Errors[0].Message) } } ``` -------------------------------- ### Update Salesforce Leads with Assignment Rule Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Updates a list of Lead records and assigns them using a specified assignment rule. The `records` parameter should be a slice of structs (e.g., `Lead`) containing at least the 'Id' field. Batch size is configurable. ```go type Lead struct { Id string LastName string Company string } ``` ```go leads := []Lead{ { Id: "00QDn0000024r6FMAQ", LastName: "Grant", Company: "The Avengers", }, } jobIds, err := sf.UpdateBulkAssign("Lead", leads, 100, true, "01QDn00000112FHMAY") ``` -------------------------------- ### Execute SOQL Query and Decode Results Source: https://context7.com/k-capehart/go-salesforce/llms.txt Perform a SOQL query and automatically decode all paginated results into a Go slice. Ensure the target struct matches the queried fields. Errors during the query or decoding will be returned. ```go type Contact struct { Id string FirstName string LastName string Email string Account struct { Name string } } contacts := []Contact{} err := sf.Query( "SELECT Id, FirstName, LastName, Email, Account.Name FROM Contact WHERE LastName = 'Smith' LIMIT 100", &contacts, ) if err != nil { log.Fatal(err) } for _, c := range contacts { fmt.Printf("%s %s <%s> — Account: %s\n", c.FirstName, c.LastName, c.Email, c.Account.Name) } // Output: John Smith — Account: Acme Corp ``` -------------------------------- ### Query Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Executes a SOQL query against Salesforce and decodes the results into a provided struct. ```APIDOC ## Query ### Description Performs a SOQL query given a query string and decodes the response into the given struct. ### Method `func (sf *Salesforce) Query(query string, sObject any) error` ### Endpoint N/A (Method on Salesforce struct) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - `query` (string) - Required - A SOQL query string. - `sObject` (any) - Required - A pointer to a slice of a custom struct type representing a Salesforce Object to decode the results into. ### Request Example ```go type Contact struct { Id string LastName string } contacts := []Contact{} err := sf.Query("SELECT Id, LastName FROM Contact WHERE LastName = 'Lee'", &contacts) ``` ### Response #### Success Response (200) - `error`: Returns `nil` if the query is successful. #### Response Example None explicitly provided, but implies successful execution if no error is returned. ``` -------------------------------- ### Bulk Query Export — QueryBulkExport Source: https://context7.com/k-capehart/go-salesforce/llms.txt `QueryBulkExport` runs a SOQL query via Bulk API v2 and writes all results to a CSV file, automatically handling result pagination. ```APIDOC ## QueryBulkExport ### Description Runs a SOQL query via Bulk API v2 and writes all results to a CSV file, automatically handling result pagination. ### Method POST (Assumed, for initiating bulk job) ### Endpoint /services/data/vXX.X/jobs/query (Assumed, for Bulk API v2 query jobs) ### Parameters #### Query Parameters - **soqlQuery** (string) - Required - The SOQL query to execute. - **outputFilePath** (string) - Required - The path to the CSV file where results will be saved. ### Request Body (Not applicable for initiating query job, parameters are in URL or headers) ### Response #### Success Response (200) Indicates the job was successfully initiated. The actual data is written to the specified file. ### Response Example (No direct response body example provided for job initiation, focus is on file output) ``` // File contents (CSV): // Id,FirstName,LastName,Email,CreatedDate // 0033t000003xABCAAM,Tony,Stark,tony@stark.com,2024-01-15T09:00:00.000+0000 // ... ``` ``` -------------------------------- ### Bulk Update from CSV File Source: https://context7.com/k-capehart/go-salesforce/llms.txt Performs bulk updates by reading records from a CSV file. The CSV must contain an 'Id' column. ```go // data/update_contacts.csv: // Id,Title,Department // 0033t000003xABCAAM,Senior Engineer,Engineering // 0033t000003xDEFAAM,Product Manager,Product jobIds, err := sf.UpdateBulkFile("Contact", "data/update_contacts.csv", 10000, false) if err != nil { log.Fatal(err) } fmt.Println("Bulk update job IDs:", jobIds) ``` -------------------------------- ### Bulk Query Export with Struct to CSV Source: https://context7.com/k-capehart/go-salesforce/llms.txt Exports query results to a CSV file using Bulk API v2, with the SOQL query defined by a Go struct. Ensure the output directory exists. ```go type AccountFields struct { Id string `soql:"selectColumn,fieldName=Id" json:"Id"` Name string `soql:"selectColumn,fieldName=Name" json:"Name"` Industry string `soql:"selectColumn,fieldName=Industry" json:"Industry"` } type AccountQuery struct { SelectClause AccountFields `soql:"selectClause,tableName=Account"` } err := sf.QueryStructBulkExport(AccountQuery{SelectClause: AccountFields{}}, "output/accounts.csv") if err != nil { log.Fatal(err) } fmt.Println("Accounts exported to output/accounts.csv") ``` -------------------------------- ### Perform SOQL Query with QueryStruct Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Execute a SOQL query using a Go struct that defines the query structure and criteria. The results are decoded into a provided slice of structs. ```go soqlStruct := ContactSoqlQuery{ SelectClause: Contact{}, WhereClause: ContactQueryCriteria{ LastName: "Lee", }, } contacts := []Contact{} err := sf.QueryStruct(soqlStruct, &contacts) ``` -------------------------------- ### Credentials Struct Definition Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Defines the structure for holding Salesforce authentication credentials, supporting various authentication methods. ```go type Creds struct { Domain string Username string Password string SecurityToken string ConsumerKey string ConsumerSecret string ConsumerRSAPem string AccessToken string } ``` -------------------------------- ### WithHeader Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Creates a `RequestOption` to add a custom header to an HTTP request made via `DoRequest`. ```APIDOC ## WithHeader ### Description Creates a request option that sets a custom header on the HTTP request. ### Method Signature `func WithHeader(key, value string) RequestOption` ### Parameters - `key` (string) - Required - The name of the header. - `value` (string) - Required - The value of the header. ### Example (Single Header) ```go // Use If-Modified-Since for efficient caching resp, err := sf.DoRequest("GET", "/sobjects/Account/describe", nil, salesforce.WithHeader("If-Modified-Since", "Wed, 21 Oct 2015 07:28:00 GMT")) if err != nil { panic(err) } if resp.StatusCode == 304 { fmt.Println("Data not modified, using cached version") } ``` ### Example (Multiple Headers) ```go // Multiple custom headers resp, err := sf.DoRequest("GET", "/sobjects", nil, salesforce.WithHeader("If-Modified-Since", "Wed, 21 Oct 2015 07:28:00 GMT"), salesforce.WithHeader("Accept-Language", "en-US")) ``` ``` -------------------------------- ### Query Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Executes a raw SOQL query string and decodes the response into a provided Go struct. This is useful for complex queries or when the go-soql struct approach is not preferred. ```APIDOC ## Handling Relationship Queries When querying Salesforce objects, it's common to access fields that are related through parent-child or lookup relationships. For instance, querying `Account.Name` with related `Contact` might look like this: ### Method Signature `sf.Query(soqlString string, sObject any) error` ### Example Usage ```go type Account struct { Name string } type Contact struct { Id string Account Account } contacts := []Contact{} sf.Query("SELECT Id, Account.Name FROM Contact", &contacts) ``` ``` -------------------------------- ### Iterate Query Results using QueryBulkIterator Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Performs a SOQL query and returns an IteratorJob to decode data iteratively. This is efficient for processing large result sets without loading everything into memory at once. ```go type Contact struct { Id string `json:"Id" salesforce:"Id"` FirstName string `json:"FirstName" salesforce:"FirstName"` LastName string `json:"LastName" salesforce:"LastName"` } it, err := sf.QueryBulkIterator("SELECT Id, FirstName, LastName FROM Contact") if err != nil { panic(err) } for it.Next() { var data []Contact if err := it.Decode(&data); err != nil { panic(err) } fmt.Println(data) } if err := it.Error(); err != nil { panic(err) } ``` -------------------------------- ### Bulk Query Iterator — QueryBulkIterator Source: https://context7.com/k-capehart/go-salesforce/llms.txt `QueryBulkIterator` runs a bulk SOQL query and returns an `IteratorJob` for streaming results in pages, decoded directly into typed Go slices. ```APIDOC ## QueryBulkIterator ### Description Runs a bulk SOQL query and returns an `IteratorJob` for streaming results in pages, decoded directly into typed Go slices. Useful for processing large datasets without loading all records into memory. ### Method POST (Assumed, for initiating bulk job) ### Endpoint /services/data/vXX.X/jobs/query (Assumed, for Bulk API v2 query jobs) ### Parameters #### Query Parameters - **soqlQuery** (string) - Required - The SOQL query to execute. ### Request Body (Not applicable for initiating query job, parameters are in URL or headers) ### Response #### Success Response (200) - **iteratorJob** (IteratorJob) - An iterator object to fetch results in pages. ### Response Example ```go type Contact struct { Id string `salesforce:"Id"` FirstName string `salesforce:"FirstName"` LastName string `salesforce:"LastName"` Email string `salesforce:"Email"` } it, err := sf.QueryBulkIterator("SELECT Id, FirstName, LastName, Email FROM Contact") // ... loop through it.Next() and it.Decode(&page) ``` ``` -------------------------------- ### Default Salesforce Struct Tagging Source: https://context7.com/k-capehart/go-salesforce/llms.txt Use the `salesforce:"FieldAPIName"` tag to map Go struct fields to Salesforce API fields for encoding and decoding. ```go type Contact struct { Id string `salesforce:"Id"` ExternalId string `salesforce:"ExternalId__c"` FullName string `salesforce:"Full_Name__c"` CreatedAt time.Time `salesforce:"CreatedDate"` // Parsed from Salesforce ISO 8601 format } ``` -------------------------------- ### InsertBulkFile Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Inserts a collection of Salesforce records from a CSV file using the Bulk API v2. It returns a list of Job IDs for the operations. ```APIDOC ## InsertBulkFile ### Description Inserts a collection of salesforce records from a csv file using Bulk API v2, returning a list of Job IDs ### Method `func (sf *Salesforce) InsertBulkFile(sObjectName string, filePath string, batchSize int, waitForResults bool) ([]string, error)` ### Parameters - `sObjectName` (string): API name of Salesforce object - `filePath` (string): path to a csv file containing salesforce data - `batchSize` (int): `1 <= batchSize <= 10000` - `waitForResults` (bool): denotes whether to wait for jobs to finish ### Request Example ```go jobIds, err := sf.InsertBulkFile("Contact", "data/avengers.csv", 1000, false) ``` ### Request Body `data/avengers.csv` ```csv FirstName,LastName Tony,Stark Steve,Rogers Bruce,Banner ``` ``` -------------------------------- ### Export Query Results using Struct with QueryStructBulkExport Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Performs a SOQL query defined by a Go struct and exports the data to a CSV file. Use this method when you want to leverage Go structs for query definition and validation. ```go soqlStruct := ContactSoqlQuery{ SelectClause: ContactSoql{}, } err := sf.QueryStructBulkExport(soqlStruct, "data/export2.csv") ``` -------------------------------- ### Bulk Insert with Assignment Rule — InsertBulkAssign Source: https://context7.com/k-capehart/go-salesforce/llms.txt `InsertBulkAssign` inserts Lead or Case records and assigns them via a Salesforce Assignment Rule. ```APIDOC ## InsertBulkAssign ### Description Inserts Lead or Case records and assigns them via a Salesforce Assignment Rule. ### Method POST (Assumed, for initiating bulk job) ### Endpoint /services/data/vXX.X/jobs/ingest (Assumed, for Bulk API v2 ingest jobs) ### Parameters #### Path Parameters - **objectType** (string) - Required - The API name of the object to insert (Lead or Case). #### Query Parameters - **batchSize** (integer) - Optional - The number of records per batch. - **waitForResults** (boolean) - Optional - If true, the operation blocks until all jobs complete. - **assignmentRuleId** (string) - Required - The ID of the assignment rule to use. ### Request Body - **records** ([]object) - Required - A list of records to insert. ### Request Example ```go type Lead struct { LastName string Company string Email string } leads := []Lead{ {LastName: "Parker", Company: "Daily Bugle", Email: "peter@dailybugle.com"}, } jobIds, err := sf.InsertBulkAssign("Lead", leads, 100, true, "01QDn00000112FHMAY") ``` ### Response #### Success Response (200) - **jobIds** ([]string) - A list of job IDs created for the bulk insert operation. ### Response Example ```json { "jobIds": ["7503t000002ABCDAA", "7503t000002ABCDBA", ...] } ``` ``` -------------------------------- ### Insert Bulk Records with Assignment Rule Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Inserts Lead or Case records using the Bulk API v2 with a specified assignment rule. Requires the object name, records, batch size, wait status, and assignment rule ID. ```go type Lead struct { LastName string Company string } ``` ```go leads := []Lead{ { LastName: "Spector", Company: "The Avengers", }, } jobIds, err := sf.InsertBulkAssign("Lead", leads, 100, true, "01QDn00000112FHMAY") ``` -------------------------------- ### Upsert Bulk Leads with Assignment Rule Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Upserts a list of Lead records using the Bulk API v2, assigning them via a specified rule. Requires the Lead object name, external ID field name, record data, batch size, and assignment rule ID. ```go leads := []Lead{ { LeadExternalId__c: "MK3", LastName: "Lockley", Company: "The Avengers", }, } jobIds, err := sf.UpsertBulkAssign("Lead", "LeadExternalId__c", leads, 100, true, "00QDn0000024r6FMAQ") ``` -------------------------------- ### Insert Bulk Records from File Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Inserts Salesforce records from a CSV file using the Bulk API v2. Provide the object name, file path, batch size, and whether to wait for results. ```csv FirstName,LastName Tony,Stark Steve,Rogers Bruce,Banner ``` ```go jobIds, err := sf.InsertBulkFile("Contact", "data/avengers.csv", 1000, false) ``` -------------------------------- ### Insert Bulk Records from File with Assignment Rule Source: https://github.com/k-capehart/go-salesforce/blob/main/README.md Inserts Lead or Case records from a CSV file using the Bulk API v2 with a specified assignment rule. Requires the object name, file path, batch size, wait status, and assignment rule ID. ```csv FirstName,LastName,Company Tony,Stark,The Avengers Steve,Rogers,The Avengers Bruce,Banner,The Avengers ``` ```go jobIds, err := sf.InsertBulkFileAssign("Lead", "data/avengers.csv", 1000, false, "01QDn00000112FHMAY") ``` -------------------------------- ### Make Raw HTTP Request Source: https://context7.com/k-capehart/go-salesforce/llms.txt Makes arbitrary authenticated HTTP calls to Salesforce REST API endpoints. Returns the raw http.Response for custom parsing. Use WithHeader to add custom headers. ```go import ( "io" "net/http" "github.com/k-capehart/go-salesforce/v3" ) // GET /limits resp, err := sf.DoRequest(http.MethodGet, "/limits", nil) if err != nil { log.Fatal(err) } body, _ := io.ReadAll(resp.Body) fmt.Println(string(body)) // GET with custom headers (e.g., conditional request caching) resp, err = sf.DoRequest( http.MethodGet, "/sobjects/Account/describe", nil, salesforce.WithHeader("If-Modified-Since", "Wed, 21 Oct 2024 07:28:00 GMT"), salesforce.WithHeader("Accept-Language", "en-US"), ) if err != nil { log.Fatal(err) } if resp.StatusCode == http.StatusNotModified { fmt.Println("Not modified — use cached version") } else { body, _ = io.ReadAll(resp.Body) fmt.Println(string(body)) } // POST a custom payload payload := []byte(`{"subject": "Test", "status": "New"}`) resp, err = sf.DoRequest(http.MethodPost, "/sobjects/Case", payload) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Bulk Insert with Assignment Rule Source: https://context7.com/k-capehart/go-salesforce/llms.txt Inserts Lead or Case records using Bulk API v2 and assigns them via a specified Salesforce Assignment Rule. Specify the object type, records, batch size, wait for results, and the assignment rule ID. ```go type Lead struct { LastName string Company string Email string } leads := []Lead{ {LastName: "Parker", Company: "Daily Bugle", Email: "peter@dailybugle.com"}, } jobIds, err := sf.InsertBulkAssign("Lead", leads, 100, true, "01QDn00000112FHMAY") if err != nil { log.Fatal(err) } fmt.Println("Leads assigned via rule, jobs:", jobIds) ```