salesforce

package module
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 1, 2022 License: BSD-3-Clause Imports: 15 Imported by: 0

README

README

A partial go implementation of Salesforce's Lightning Platform REST API that provides create, update, delete, upsert and query commands to access/modify salesforce database tables.

Tables are modified using the SObject interface{}. Structs representing table field data that implement the SObject interface maybe created using the genpkgs module.

Example

Create a Private Key and Self-Signed Digital Certificate

ctx := context.Background()
var contactID = "0141S0000009bv2QAA"
var contact salesforce.SObject = <your def package>.Contact{....}

sv, err := jwt.ServiceFromFile(ctx, cfg.SFCredentialFile, nil)
if err != nil {
    log.Fatalf("%v", err)
}
sv.Update(ctx, contact, contactID)

### Explain single operation, collection and batch ###

* create self-signed cert
* upload to SF
* sample config

### Create Object Definitions as struct ###

* demo gen config file

Documentation

Overview

Package salesforce implements data access, creation and updating routines for the Salesforce Rest API https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_rest.htm

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrZeroRecords = errors.New("must have at least 1 record")

ErrZeroRecords indicates a zero length SObject slice is passed to collection func

Functions

func RegisterSObjectTypes

func RegisterSObjectTypes(sobjs ...SObject)

RegisterSObjectTypes catalogs the type of the SObject structs. The Any type uses these registrations to unmarshal a salesforce response into the appropriate type.

Types

type ActionOverride

type ActionOverride struct {
	FormFactor           string `json:"formFactor,omitempty"`
	IsIsAvailableInTouch bool   `json:"isAvailableInTouch,omitempty"`
	Name                 string `json:"name,omitempty"`
	PageID               string `json:"pageID,omitempty"`
	URL                  string `json:"url,omitempty"`
}

ActionOverride provides details about an action that replaces the default action pages for an object. For example, an object could be configured to replace the new/create page with a custom page. https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_describesobjects_describesobjectresult.htm

type Address

type Address struct {
	GeocodeAccuracy string  `json:"geocodeAccuracy,omitempty"` //	Accuracy level of the geocode for the address. For example, this field is known as MailingGeocodeAccuracy on Contact.
	City            string  `json:"city,omitempty"`            // The city detail for the address. For example, this field is known as MailingCity on Contact.
	CountryCode     string  `json:"country,omitempty"`         // The ISO country code for the address. For example, this field is known as MailingCountryCode on Contact. CountryCode is always available on compound address fields, whether or not state and country picklists are enabled in your organization.
	Latitude        float64 `json:"latitude,omitempty"`        // Used with Longitude to specify the precise geolocation of the address. For example, this field is known as MailingLatitude on Contact.
	Longitude       float64 `json:"longitude,omitempty"`       // Used with Latitude to specify the precise geolocation of the address. For example, this field is known as MailingLongitude on Contact.
	PostalCode      string  `json:"postalCode,omitempty"`      // The postal code for the address. For example, this field is known as MailingPostalCode on Contact.
	StateCode       string  `json:"state,omitempty"`           // The ISO state code for the address. For example, this field is known as MailingStateCode on Contact. StateCode is always available on compound address fields, whether or not state and country picklists are enabled in your organization.
	Street          string  `json:"street,omitempty"`          // textarea
}

Address is describes structure of the Address type. Field names differ depending on the object. Convert to and from map[string]interface{} with specific routines

func ToAddress

func ToAddress(prefix string, ix map[string]interface{}) *Address

ToAddress converts a map[string]interface{} to an Address value. The prefix parameter allows mapping of map fields to Address fields.

func (Address) ToMap

func (a Address) ToMap(nm string, omitempty bool) map[string]interface{}

ToMap creates a map that may be used to update address type. nm is the prefix for the field names.

type Any

type Any struct {
	SObject
}

Any is used to unmarshal an SObject json for undetermined objects.

func (*Any) UnmarshalJSON

func (a *Any) UnmarshalJSON(b []byte) error

UnmarshalJSON uses the attributes data to determine the SObject type the registered structs. SObject

type Attributes

type Attributes struct {
	Type string `json:"type,omitempty"`
	URL  string `json:"url,omitempty"`
	Ref  string `json:"referenceId,omitempty"`
}

Attributes data returned with each query record

type BatchBody

type BatchBody struct {
	AllOrNone bool      `json:"allOrNone,omitempty"`
	Records   []SObject `json:"records,omitempty"`
}

BatchBody is the body of a collection Create,Update,Upsert

type BatchLogFunc

type BatchLogFunc func(context.Context, int, []SObject, []OpResponse) error

BatchLogFunc is passed the corresponding SObjects and OpResponses created and returned from a salesforce batch. The int value is the number of records previously processed. Context is the context passed to the composite call. Returning a non-nil error halts the composite call.

type Binary

type Binary []byte

Binary handles base64Binary type

func (Binary) MarshalJSON

func (b Binary) MarshalJSON() ([]byte, error)

MarshalJSON handles outputting json of base64Binary. Empty value outputs null, a nil ptr is omitted with omitempty.

func (*Binary) UnmarshalJSON

func (b *Binary) UnmarshalJSON(buff []byte) error

UnmarshalJSON does null handling during json decode,

type BulkQuery

type BulkQuery struct {
	Query string `json:"query,omitempty"`
	// Valid delimiters
	// COMMA (,) default
	// BACKQUOTE—backquote character (`)
	// CARET—caret character (^)
	// COMMA—comma character (,)
	// PIPE—pipe character (|)
	// SEMICOLON—semicolon character (;)
	// TAB—tab character
	ColumnDelimiter string `json:"columnDelimiter,omitempty"` // COMMA default
	// Valid line breaks
	// LF default
	// CRLF carriage return character followed by a linefeed character
	LineEnding string `json:"lineEnding,omitempty"`
}

BulkQuery is passed to QueryCreateJob. Query is processed by the job

type ChildRef

type ChildRef struct {
	CascadeDelete       bool          `json:"cascadeDelete,omitempty"`
	ChildSObject        interface{}   `json:"childSObject,omitempty"`
	DeprecatedAndHidden bool          `json:"deprecatedAndHidden,omitempty"`
	Field               string        `json:"field,omitempty"`
	JunctionIDListNames []string      `json:"junctionIdListNames,omitempty"`
	JunctionReferenceTo []interface{} `json:"junctionReferenceTo,omitempty"`
	RelationshipName    *string       `json:"relationshipName,omitempty"`
	RestrictedDelete    bool          `json:"restrictedDelete,omitempty"`
}

ChildRef describes sobject details https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_describesobjects_describesobjectresult.htm Scroll down for ChildRef definition

type Date

type Date string

Date handles the json marshaling and unmarshaling of SF date type which is a string of format yyyy-mm-dd

func TmToDate

func TmToDate(tm *time.Time) *Date

TmToDate converts a time.Time to a Date pointer with zero time value

func (*Date) Display

func (d *Date) Display(format string) string

Display allows different formatting of *Date and displays nils and empty strings

func (Date) MarshalText

func (d Date) MarshalText() ([]byte, error)

MarshalText handles outputting json of date. Empty value outputs null, a nil ptr is omitted with omitempty.

func (*Date) Time

func (d *Date) Time() *time.Time

Time converts the string to a time.Time value

func (*Date) UnmarshalText

func (d *Date) UnmarshalText(b []byte) error

UnmarshalText does null handling during json decode,

type Datetime

type Datetime string

Datetime handles the json marshaling and unmarshaling of SF datetime type which a string of iso 8061 format yyyy-mm-ddThh:mm:ss.sss+0000

func TmToDatetime

func TmToDatetime(tm *time.Time) *Datetime

TmToDatetime converts a time.Time to DateTime

func (*Datetime) MarshalText

func (d *Datetime) MarshalText() ([]byte, error)

MarshalText handles outputting json of date. Empty value outputs null, a nil ptr is omitted with omitempty.

func (*Datetime) Time

func (d *Datetime) Time() *time.Time

Time converts the string to a time.Time value

func (*Datetime) UnmarshalText

func (d *Datetime) UnmarshalText(b []byte) error

UnmarshalText does null handling during json decode,

type DeleteID

type DeleteID string

DeleteID allows a string to be used as an SObject

func (DeleteID) SObjectName

func (d DeleteID) SObjectName() string

SObjectName simply return definition name

func (DeleteID) WithAttr

func (d DeleteID) WithAttr(ref string) SObject

WithAttr just returns object as it is not a struct

type DeletedRecord

type DeletedRecord struct {
	http.HandlerFunc
	ID          string   `json:"id,omitempty"`
	DeletedDate Datetime `json:"deletedDate,omitempty"`
}

DeletedRecord contains the id and delete date of a deleted record

type Error

type Error struct {
	StatusCode string   `json:"statusCode,omitempty"`
	Message    string   `json:"message,omitempty"`
	Fields     []string `json:"fields,omitempty"`
}

Error is the error response for most calls

type Field

type Field struct {
	Aggregatable                 bool            `json:"aggregatable,omitempty"`
	AiPredictionField            bool            `json:"aiPredictionField,omitempty"`
	AutoNumber                   bool            `json:"autoNumber,omitempty"`
	ByteLength                   int             `json:"byteLength,omitempty"`
	Calculated                   bool            `json:"calculated,omitempty"`
	CalculatedFormula            interface{}     `json:"calculatedFormula,omitempty"`
	CascadeDelete                bool            `json:"cascadeDelete,omitempty"`
	CaseSensitive                bool            `json:"caseSensitive,omitempty"`
	CompoundFieldName            interface{}     `json:"compoundFieldName,omitempty"`
	ControllerName               interface{}     `json:"controllerName,omitempty"`
	Createable                   bool            `json:"createable,omitempty"`
	Custom                       bool            `json:"custom,omitempty"`
	DefaultedOnCreate            bool            `json:"defaultedOnCreate,omitempty"`
	DefaultValueFormula          interface{}     `json:"defaultValueFormula,omitempty"`
	DefaultValue                 interface{}     `json:"defaultValue,omitempty"`
	DependentPicklist            bool            `json:"dependentPicklist,omitempty"`
	DeprecatedAndHidden          bool            `json:"deprecatedAndHidden,omitempty"`
	Digits                       int             `json:"digits,omitempty"`
	DisplayLocationInDecimal     bool            `json:"displayLocationInDecimal,omitempty"`
	Encrypted                    bool            `json:"encrypted,omitempty"`
	ExternalID                   bool            `json:"externalId,omitempty"`
	ExtraTypeInfo                interface{}     `json:"extraTypeInfo,omitempty"`
	Filterable                   bool            `json:"filterable,omitempty"`
	FilteredLookupInfo           interface{}     `json:"filteredLookupInfo,omitempty"`
	FormulaTreatNullNumberAsZero bool            `json:"formulaTreatNullNumberAsZero,omitempty"`
	Groupable                    bool            `json:"groupable,omitempty"`
	HighScaleNumber              bool            `json:"highScaleNumber,omitempty"`
	HTMLFormatted                bool            `json:"htmlFormatted,omitempty"`
	IDLookup                     bool            `json:"idLookup,omitempty"`
	InlineHelpText               string          `json:"inlineHelpText,omitempty"`
	Label                        string          `json:"label,omitempty"`
	Length                       int             `json:"length,omitempty"`
	Mask                         string          `json:"mask,omitempty"`
	MaskType                     string          `json:"maskType,omitempty"`
	NameField                    bool            `json:"nameField,omitempty"`
	NamePointing                 bool            `json:"namePointing,omitempty"`
	Name                         string          `json:"name,omitempty"`
	Nillable                     bool            `json:"nillable,omitempty"`
	Permissionable               bool            `json:"permissionable,omitempty"`
	PicklistValues               []PickListValue `json:"picklistValues,omitempty"`
	PolymorphicForeignKey        bool            `json:"polymorphicForeignKey,omitempty"`
	Precision                    int             `json:"precision,omitempty"`
	QueryByDistance              bool            `json:"queryByDistance,omitempty"`
	ReferenceTargetField         string          `json:"referenceTargetField,omitempty"`
	ReferenceTo                  []string        `json:"referenceTo,omitempty"`
	RelationshipName             string          `json:"relationshipName,omitempty"`
	RelationshipOrder            int             `json:"relationshipOrder,omitempty"`
	RestrictedDelete             bool            `json:"restrictedDelete,omitempty"`
	RestrictedPicklist           bool            `json:"restrictedPicklist,omitempty"`
	Scale                        int             `json:"scale,omitempty"`
	SearchPrefilterable          bool            `json:"searchPrefilterable,omitempty"`
	SoapType                     string          `json:"soapType,omitempty"`
	Sortable                     bool            `json:"sortable,omitempty"`
	Type                         string          `json:"type,omitempty"`
	Unique                       bool            `json:"unique,omitempty"`
	Updateable                   bool            `json:"updateable,omitempty"`
	WriteRequiresMasterRead      bool            `json:"writeRequiresMasterRead,omitempty"`
}

Field defines a field of an sobject https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_describesobjects_describesobjectresult.htm Scroll down for Field definition

type GetDeletedResponse

type GetDeletedResponse struct {
	DeletedRecords        []DeletedRecord `json:"deletedRecords,omitempty"`
	EarliestDateAvailable Datetime        `json:"earliestDateAvailable,omitempty"`
	LatestDateCovered     Datetime        `json:"latestDateCovered,omitempty"`
}

GetDeletedResponse contains a list of deleted ids

type GetUpdatedResponse

type GetUpdatedResponse struct {
	IDs               []string `json:"ids,omitempty"`
	LatestDateCovered Datetime `json:"latestDateCovered,omitempty"`
}

GetUpdatedResponse contains a list of updated ids

type HTTPBody

type HTTPBody struct {
	Rdr           io.ReadCloser
	ContentType   string
	ContentLength int64
}

HTTPBody allows salesforce calls to be returned as a stream rather than a decoded json object.

type Job

type Job struct {
	APIVersion             float64 `json:"apiVersion,omitempty"`
	AssignmentRuleID       string  `json:"assignmentRuleId,omitempty"`
	ColumnDelimiter        string  `json:"columnDelimiter,omitempty"`
	ConcurrencyMode        string  `json:"concurrencyMode,omitempty"`
	ContentType            string  `json:"contentType,omitempty"`
	ContentURL             string  `json:"contentURL,omitempty"`
	CreatedByID            string  `json:"createdById,omitempty"`
	CreatedDate            string  `json:"createdDate,omitempty"`
	ExternalIDFieldName    string  `json:"externalIdFieldName,omitempty"`
	ID                     string  `json:"id,omitempty"`
	JobType                string  `json:"jobType,omitempty"`
	LineEnding             string  `json:"lineEnding,omitempty"`
	NumberRecordsFailed    int     `json:"numberRecordsFailed"`
	NumberRecordsProcessed int     `json:"numberRecordsProcessed"`
	Object                 string  `json:"object,omitempty"`
	Operation              string  `json:"operation,omitempty"`
	State                  string  `json:"state,omitempty"`
	SystemModstamp         string  `json:"systemModstamp,omitempty"`
}

Job contains current state of a job and is returned from the CreateJob, CloseJob, GetJob and AbortJob methods

type JobDefinition

type JobDefinition struct {
	ExternalIDFieldName string `json:"externalIdFieldName,omitempty"`
	Object              string `json:"object,omitempty"`
	Operation           string `json:"operation,omitempty"`
	ConcurrencyMode     string `json:"concurrencyMode,omitempty"`
	ContentType         string `json:"contentType,omitempty"`
	LineEnding          string `json:"lineEnding,omitempty"`
	ColumnDelimiter     string `json:"columnDelimiter,omitempty"`
	AssignmentRuleID    string `json:"assignmentRuleId,omitempty"`
}

JobDefinition is the initialization data for a new bulk job

type JobList

type JobList struct {
	Done           bool   `json:"done,omitempty"`
	Records        []Job  `json:"records,omitempty"`
	NextRecordsURL string `json:"nextRecordsUrl,omitempty"`
}

JobList returns all job status

type Links struct {
	ApprovalLayouts  string `json:"approvalLayouts,omitempty"`
	CompactLayouts   string `json:"compactLayouts,omitempty"`
	DefaultValues    string `json:"defaultValues,omitempty"`
	Describe         string `json:"describe,omitempty"`
	Layouts          string `json:"layouts,omitempty"`
	Listviews        string `json:"listviews,omitempty"`
	QuickActions     string `json:"quickActions,omitempty"`
	RowTemplate      string `json:"rowTemplate,omitempty"`
	Sobject          string `json:"sobject,omitempty"`
	UIDetailTemplate string `json:"uiDetailTemplate,omitempty"`
	UIEditTemplate   string `json:"uiEditTemplate,omitempty"`
	UINewRecord      string `json:"uiNewRecord,omitempty"`
}

Links lists all sobject links

type LogError

type LogError struct {
	Index      int     `json:"index"`
	ExternalID string  `json:"external_id,omitempty"`
	Errors     []Error `json:"errors,omitempty"`
}

LogError used to report individual record errors

type NullValue

type NullValue struct{}

NullValue represents a sent or received null in json

type OpResponse

type OpResponse struct {
	ID          string  `json:"id"`
	Success     bool    `json:"success"`
	Errors      []Error `json:"errors"`
	Created     bool    `json:"created,omitempty"`
	RecordIndex int     `json:"-"`
	SObject     SObject `json:"-"`
}

OpResponse is returned for each record of and Update, Upsert and Insert

func (OpResponse) SObjectValue

func (or OpResponse) SObjectValue(ix interface{}) error

SObjectValue attempts to assign the response SObject to the ix pointer. See example.

var cx Contact err := or.SObjectValue(&cx)

type OpResponses

type OpResponses []OpResponse

OpResponses is a slice of OpResponse records

func (OpResponses) Errors

func (oprs OpResponses) Errors(startIndex int, sobjects []SObject) []OpResponse

Errors returns unsuccessful OpResponses

type PickListValue

type PickListValue struct {
	Active       bool        `json:"active,omitempty"`
	DefaultValue bool        `json:"defaultValue,omitempty"`
	Label        string      `json:"label,omitempty"`
	ValidFor     interface{} `json:"validFor,omitempty"`
	Value        string      `json:"value,omitempty"`
}

PickListValue describes l

type QueryResponse

type QueryResponse struct {
	TotalSize      int          `json:"totalSize,omitempty"`
	Done           bool         `json:"done,omitempty"`
	NextRecordsURL string       `json:"nextRecordsUrl,omitempty"`
	Records        *RecordSlice `json:"records"`
}

QueryResponse is the base response for a query

type RecordMap

type RecordMap map[string]interface{}

RecordMap is created during an Any.JSONUnmarshal when the record type is not registered

func (RecordMap) SObjectName

func (m RecordMap) SObjectName() string

SObjectName returns the attributes type value

func (RecordMap) WithAttr

func (m RecordMap) WithAttr(ref string) SObject

WithAttr set the attributes value

type RecordSlice

type RecordSlice struct {
	// contains filtered or unexported fields
}

RecordSlice wraps pointer to the result slice allowing custom unmarshaling that adds rows through multiple next record calls

func NewRecordSlice

func NewRecordSlice(results interface{}) (*RecordSlice, error)

NewRecordSlice creates a RecordSlice pointer based upon *[]<struct> of the results parameter; error created when result is an invalid type

func (RecordSlice) MarshalJSON

func (rs RecordSlice) MarshalJSON() ([]byte, error)

MarshalJSON marshals the value in resultsVal

func (*RecordSlice) UnmarshalJSON

func (rs *RecordSlice) UnmarshalJSON(b []byte) error

UnmarshalJSON creates a temporary slice for unmarshaling a call. This temp slice is then appended to the resultsVal

type RecordTypeInfo

type RecordTypeInfo struct {
	Active                   bool              `json:"active,omitempty"`
	Available                bool              `json:"available,omitempty"`
	DefaultRecordTypeMapping bool              `json:"defaultRecordTypeMapping,omitempty"`
	DeveloperName            string            `json:"developerName,omitempty"`
	Layout                   map[string]string `json:"layout,omitempty"`
	Master                   bool              `json:"master,omitempty"`
	Name                     string            `json:"name,omitempty"`
	RecordTypeID             string            `json:"recordTypeId,omitempty"`
	Urls                     Links             `json:"urls,omitempty"`
}

RecordTypeInfo for sobject

type SObject

type SObject interface {
	SObjectName() string
	WithAttr(string) SObject
}

SObject is a struct used for Create, Update and Delete operations

type SObjectDefinition

type SObjectDefinition struct {
	Activateable          bool             `json:"activateable,omitempty"`
	ActionOverrides       []ActionOverride `json:"actionOverrides"`
	AssociateEntityType   *string          `json:"associateEntityType,omitempty"`
	AssociateParentEntity string           `json:"associateParentEntity,omitempty"`
	ChildRelationships    []ChildRef       `json:"childRelationships,omitempty"`
	CompactLayoutable     bool             `json:"compactLayoutable,omitempty"`
	Createable            bool             `json:"createable,omitempty"`
	Custom                bool             `json:"custom,omitempty"`
	CustomSetting         bool             `json:"customSetting,omitempty"`
	DeepCloneable         bool             `json:"deepCloneable,omitempty"`
	DefaultImplementation interface{}      `json:"defaultImplementation,omitempty"`
	Deletable             bool             `json:"deletable,omitempty"`
	DeprecatedAndHidden   bool             `json:"deprecatedAndHidden,omitempty"`
	ExtendedBy            interface{}      `json:"extendedBy,omitempty"`
	ExtendsInterfaces     interface{}      `json:"extendsInterfaces,omitempty"`
	FeedEnabled           bool             `json:"feedEnabled,omitempty"`
	Fields                []Field          `json:"fields,omitempty"`
	HasSubtypes           bool             `json:"hasSubtypes,omitempty"`
	ImplementedBy         interface{}      `json:"implementedBy,omitempty"`
	ImplementsInterfaces  interface{}      `json:"implementsInterfaces,omitempty"`
	IsInterface           bool             `json:"isInterface,omitempty"`
	IsSubtype             bool             `json:"isSubtype,omitempty"`
	KeyPrefix             string           `json:"keyPrefix,omitempty"`
	LabelPlural           string           `json:"labelPlural,omitempty"`
	Label                 string           `json:"label,omitempty"`
	Layoutable            bool             `json:"layoutable,omitempty"`
	Listviewable          interface{}      `json:"listviewable,omitempty"`
	LookupLayoutable      interface{}      `json:"lookupLayoutable,omitempty"`
	Mergeable             bool             `json:"mergeable,omitempty"`
	MruEnabled            bool             `json:"mruEnabled,omitempty"`
	NamedLayoutInfos      []interface{}    `json:"namedLayoutInfos,omitempty"`
	Name                  string           `json:"name,omitempty"`
	NetworkScopeFieldName interface{}      `json:"networkScopeFieldName,omitempty"`
	Queryable             bool             `json:"queryable,omitempty"`
	RecordTypeInfos       []RecordTypeInfo `json:"recordTypeInfos,omitempty"`
	Replicateable         bool             `json:"replicateable,omitempty"`
	Retrieveable          bool             `json:"retrieveable,omitempty"`
	Searchable            bool             `json:"searchable,omitempty"`
	SearchLayoutable      bool             `json:"searchLayoutable,omitempty"`
	SobjectDescribeOption string           `json:"sobjectDescribeOption,omitempty"`
	SupportedScopes       []Scope          `json:"supportedScopes,omitempty"`
	Triggerable           bool             `json:"triggerable,omitempty"`
	Undeletable           bool             `json:"undeletable,omitempty"`
	Updateable            bool             `json:"updateable,omitempty"`
	Urls                  Links            `json:"urls,omitempty"`
}

SObjectDefinition describes a salesforce SObject https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_describesobjects_describesobjectresult.htm

type Scope

type Scope struct {
	Label string `json:"label,omitempty"`
	Name  string `json:"name,omitempty"`
}

Scope describes an sobject scope

type Service

type Service struct {
	BaseURL *url.URL
	CF      ctxclient.Func
	// contains filtered or unexported fields
}

Service handles creation, authorization and execution of REST Api calls via its methods

func New

func New(host string, version string, ts oauth2.TokenSource) *Service

New creates a salesforce service. The host should be in the format <mydomain>.my.salesforce.com. For a fuller explanation, see the URI section of https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_rest_resources.htm The cf parameter must return an *http.Client to that authorizes eacha call.

Example (Fromtoken)
tk := &oauth2.Token{
	AccessToken: "valid token from somewhere",
}
sv := salesforce.New("<instance url>", "<version>", oauth2.StaticTokenSource(tk))
var recs []Contact
if err := sv.Query(context.Background(), "SELECT Id FROM Contact", &recs); err != nil {
	log.Fatalf("query error: %v", err)
}
log.Printf("total recs = %d", len(recs))
Output:

Example (Password)
// The example uses username/password entries to authorize the new service. More details may be found at:
// https://help.salesforce.com/s/articleView?id=sf.remoteaccess_oauth_username_password_flow.htm&type=5

cfg := &clientcredentials.Config{
	ClientID:     "<clientID>",
	ClientSecret: "<clientSecret>",
	TokenURL:     "https://login.salesforce.com/services/oauth2/token",
	EndpointParams: map[string][]string{
		"grant_type": {"<password>"},
		"username":   {"<username>"},
		"password":   {"<password>" + "<securityToken>"},
	},
}
sv := salesforce.New("<instance url>", "<version>", cfg.TokenSource(nil))
var recs []Contact
if err := sv.Query(context.Background(), "SELECT Id FROM Contact", &recs); err != nil {
	log.Fatalf("query error: %v", err)
}
log.Printf("total recs = %d", len(recs))
Output:

func (*Service) AbortJob

func (sv *Service) AbortJob(ctx context.Context, jobID string) (*Job, error)

AbortJob stops job processing https://developer.salesforce.com/docs/atlas.en-us.api_bulk_v2.meta/api_bulk_v2/close_job.htm

func (*Service) Call

func (sv *Service) Call(ctx context.Context, path, method string, body interface{}, result interface{}) error

Call performs all api operations. All other service operations call this func, so rarely should there be a need to use directly.

If path begins with "/", it will be used as an absolute path otherwise it is appended to the service's base path. body may be nil, io.Reader or an interface{}. An interface{} is marshaled as json. result must be a pointer to an expected result type.

Example
ctx := context.Background()
sv, err := jwt.ServiceFromFile(ctx, credentialFilename, nil)
if err != nil {
	log.Fatalf("%v", err)
}
// retrieve contact records
var records []Contact
var qry = "SELECT Id, Name FROM Contact WHERE MailingPostalCode = '80907'"
if err := sv.Query(ctx, qry, &records); err != nil {
	log.Fatalf("query error %v", err)
}

var updateRecs []salesforce.SObject

// prepare updates
for _, c := range records {
	c.DoNotCall = true
	updateRecs = append(updateRecs)
}

opResponses, err := sv.UpdateRecords(ctx, false, updateRecs)
if err != nil {
	log.Fatalf("update error %v", err)
}
// loop through responses looking for errors
for i, r := range opResponses {
	if !r.Success {
		contact, _ := updateRecs[i].(Contact)
		log.Printf("%s %s %v", contact.ContactID, contact.Name, r.Errors)
	}
}
Output:

func (*Service) CloseJob

func (sv *Service) CloseJob(ctx context.Context, jobID string) (*Job, error)

CloseJob starts job processing https://developer.salesforce.com/docs/atlas.en-us.api_bulk_v2.meta/api_bulk_v2/close_job.htm

func (*Service) CompositeCall

func (sv *Service) CompositeCall(ctx context.Context, allOrNone bool, path, method string, recs []SObject) ([]OpResponse, error)

CompositeCall updates/inserts/upserts all records in batches based upon the Service batch size (generally 200).

func (*Service) CreateJob

func (sv *Service) CreateJob(ctx context.Context, jd *JobDefinition) (*Job, error)

CreateJob is the beginning of a batch job https://developer.salesforce.com/docs/atlas.en-us.api_bulk_v2.meta/api_bulk_v2/create_job.htm

func (*Service) CreateRecords

func (sv *Service) CreateRecords(ctx context.Context, allOrNone bool, recs []SObject) ([]OpResponse, error)

CreateRecords inserts records from recs. Salesforce will return an error for any record that has a RecordID set. The OpResponses will contain the new RecordIDs. https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_composite_sobjects_collections_create.htm

func (*Service) DeleteRecords

func (sv *Service) DeleteRecords(ctx context.Context, allOrNone bool, ids []string) ([]OpResponse, error)

DeleteRecords deletes a list sobject from the list of ids https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_composite_sobjects_collections_delete.htm

func (*Service) DeleteRelatedRecord

func (sv *Service) DeleteRelatedRecord(ctx context.Context, sobjectName, id, relationship string) error

DeleteRelatedRecord with detatch the record on the the defined relationship for one to one relationships. Scroll the Example using DELETE to delete a relationship record section. https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_relationship_traversal.htm#dome_relationship_traversal

func (*Service) Describe

func (sv *Service) Describe(ctx context.Context, name string) (*SObjectDefinition, error)

Describe returns all fields of an SObject along with top level metadata https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_sobject_describe.htm

func (*Service) Get

func (sv *Service) Get(ctx context.Context, result interface{}, id string, flds ...string) error

Get retrieves values of a single record identified by sf ID. The result parameterf must be a pointer to an SObject https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_get_field_values.htm

func (*Service) GetAttachment

func (sv *Service) GetAttachment(ctx context.Context, sobjectName, id string) (*HTTPBody, error)

GetAttachment retrieves a binary file from an attachment sobject https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_sobject_blob_retrieve.htm

func (*Service) GetByExternalID

func (sv *Service) GetByExternalID(ctx context.Context, result interface{}, externalIDField, externalID string, flds ...string) error

GetByExternalID retrieves values of a single record identified by external ID. The result parameter must be a pointer to an SObject https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/using_resources_retrieve_with_externalid.htm

func (*Service) GetDeletedRecords

func (sv *Service) GetDeletedRecords(ctx context.Context, sobjectName string, start, end time.Time) (*GetDeletedResponse, error)

GetDeletedRecords returns a list of ids for records deleted in the time range https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_get_deleted.htm

func (*Service) GetRelatedRecords

func (sv *Service) GetRelatedRecords(ctx context.Context, result interface{}, sobjectName, id, relationship string, fields ...string) error

GetRelatedRecords retrieves related records from an SObject's defined relationship. result should be a pointer to a single SObject record when the relationship is one to one, otherwise use a pointer to a slice of a specific SObject. If no relationship exists in a one to one relationship, a 404 error is returned. A one to many relationship will return an empty slice. https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_sobject_relationships.htm

func (*Service) GetUpdatedRecords

func (sv *Service) GetUpdatedRecords(ctx context.Context, sobjectName string, start, end time.Time) (*GetUpdatedResponse, error)

GetUpdatedRecords returns a list of ids for records updated in the time range https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_get_updated.htm

func (*Service) Instance

func (sv *Service) Instance() string

Instance returns the serviced instance

func (*Service) ListJobs

func (sv *Service) ListJobs(ctx context.Context, nextURL string) (*JobList, error)

ListJobs returns all jobs status. nextURL should be empty on first call and use the nextRecordsURL from the returned JobList https://developer.salesforce.com/docs/atlas.en-us.api_bulk_v2.meta/api_bulk_v2/get_all_jobs.htm

func (*Service) MaxBatchSize

func (sv *Service) MaxBatchSize() int

MaxBatchSize returns the batchSize property and used to limit batch sizes

func (*Service) ObjectList

func (sv *Service) ObjectList(ctx context.Context) ([]SObjectDefinition, error)

ObjectList returns all objects with top level metadata https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_describeGlobal.htm

func (*Service) Query

func (sv *Service) Query(ctx context.Context, qry string, results interface{}) error

Query executes the query. All results are decoded into the results parameter that must be of the form *[]<struct>. To set the f https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_query.htm

func (*Service) QueryAll

func (sv *Service) QueryAll(ctx context.Context, qry string, results interface{}) error

QueryAll executes the query that will include filtering on deleted records https://developer.salesforce.com/docs/atlas.en-us.232.0.api_rest.meta/api_rest/dome_queryall.htm

func (*Service) QueryCreateJob

func (sv *Service) QueryCreateJob(ctx context.Context, bulkQuery BulkQuery, queryAll bool) (*Job, error)

QueryCreateJob runs a query in a job. To include deleted records, set queryAll to true. https://developer.salesforce.com/docs/atlas.en-us.api_bulk_v2.meta/api_bulk_v2/query_create_job.htm

func (*Service) RetrieveRecords

func (sv *Service) RetrieveRecords(ctx context.Context, results interface{}, ids []string, fields ...string) error

RetrieveRecords returns sobjects rows pointed to by the passed ids, results must be a pointer to a slice of types implementing SObject interface. If retrieving SObjects of different types, have the results be a *[]GenericSObject and read the objest' Attributes.Type field to identify the object type. https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_composite_sobjects_collections_retrieve.htm

func (*Service) Update

func (sv *Service) Update(ctx context.Context, rec SObject, id string) error

Update updates a row. ID must not be set on the rec. https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_update_fields.htm

func (*Service) UpdateRecords

func (sv *Service) UpdateRecords(ctx context.Context, allOrNone bool, recs []SObject) ([]OpResponse, error)

UpdateRecords update records from recs. The each record must set the Salesforce RecordID for the object. https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_composite_sobjects_collections_update.htm

func (*Service) UpdateRelatedRecord

func (sv *Service) UpdateRelatedRecord(ctx context.Context, updateRecord SObject, sobjectName, id, relationship string) error

UpdateRelatedRecord updates the record attached to the defined relationship. Do not in the Id in the passed SObject. Scroll down to the Example of using PATCH to update a relationship record. https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_relationship_traversal.htm#dome_relationship_traversal

func (*Service) UploadJobData

func (sv *Service) UploadJobData(ctx context.Context, job string, rdr io.Reader) error

UploadJobData sends csv stream to SF. If rdr is an io.Closer, function will close stream. https://developer.salesforce.com/docs/atlas.en-us.api_bulk_v2.meta/api_bulk_v2/upload_job_data.htm

func (*Service) UploadJobDataFile

func (sv *Service) UploadJobDataFile(ctx context.Context, job string, fileName string) error

UploadJobDataFile sends csv file to SF https://developer.salesforce.com/docs/atlas.en-us.api_bulk_v2.meta/api_bulk_v2/upload_job_data.htm

func (*Service) Upsert

func (sv *Service) Upsert(ctx context.Context, rec SObject, externalIDField, externalID string) (*OpResponse, error)

Upsert inserts/updates a row using an external id https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_upsert.htm

func (*Service) UpsertRecords

func (sv *Service) UpsertRecords(ctx context.Context, allOrNone bool, externalIDField string, recs []SObject) ([]OpResponse, error)

UpsertRecords updates/inserts records based upon the external id field. All recs must be of the same Object Type. https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_composite_sobjects_collections_upsert.htm

func (*Service) WithAcceptContentType

func (sv *Service) WithAcceptContentType(accept, contentType string) *Service

WithAcceptContentType replaces default accept and contentType headers with passed values. Use when needing to set/receive other than applicaton/json such text/csv or text/xml. Empty strings in accept or contentType parameters assume existing values.

func (*Service) WithBatchSize

func (sv *Service) WithBatchSize(batchSz int) *Service

WithBatchSize returns a service that uses batchSz to regulate batches from query and collection update operations. Queries use the setting to set the Sforce-Query-Options header which deteremines the number of records returned per batch. The maximum number of returned rows is 2000 and minimum is 200. If batch size is set to less than 200, query operations will 200 as the batch size. Collection updates use the setting to determine the maximum number of update records per call, and the maximum setting is 200. If the batch size setting is greater than 200, batch calls will use 200 as the setting. https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/headers_queryoptions.htm?search_text=batchSize

func (*Service) WithCtxClientFunc

func (sv *Service) WithCtxClientFunc(f ctxclient.Func) *Service

WithCtxClientFunc returns a service that uses the ctxclient.Func to provide authorizing client

func (*Service) WithLogger

func (sv *Service) WithLogger(blf BatchLogFunc) *Service

WithLogger returns a new service that uses the passed BatchLogFunc in composite calls to review OpResponses after each batch allowing as processed logging instead of waiting for the end and reviewing every OpResponse

func (*Service) WithMaxrows

func (sv *Service) WithMaxrows(maxrows int) *Service

WithMaxrows sets the max total rows returned for a query (not the rows in a batch for composite functions)

func (*Service) WithURL

func (sv *Service) WithURL(newURL string) *Service

WithURL creates a new service that uses the passed URL as the prefix for calls. Created to allow testing with httptest

type Time

type Time string

Time handles the json marshaling and unmarshaling of SF time type

func (Time) MarshalText

func (t Time) MarshalText() ([]byte, error)

MarshalText handles outputting json of time. Empty value outputs null, a nil ptr is omitted with omitempty.

func (*Time) UnmarshalText

func (t *Time) UnmarshalText(b []byte) error

UnmarshalText does null handling during json decode,

Directories

Path Synopsis
jwt
Package genpkgs is a library for creating packages to describe the queryable sobjects in a salesforce instance.
Package genpkgs is a library for creating packages to describe the queryable sobjects in a salesforce instance.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL