sobject

package
v2.0.1+incompatible Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2019 License: MIT Imports: 12 Imported by: 31

README

SObject APIs

back

The sobject package is an implementation of Salesforce APIs centered on SObject operations. These operations include:

  • Metadata
  • Describe
  • DML
    • Insert
    • Update
    • Upsert
    • Delete
  • Query
    • With Salesforce ID
    • With external ID
  • List of Deleted records
  • List of Updated records
  • Get Attachment body
  • Get Document body

As a reference, see Salesforce API documentation

Examples

The following are examples to access the APIs. It is assumed that a go-sfdc session has been created.

Metadata
sobjResources := sobject.NewResources(session)

metadata, err := sobjResources.Metadata("Account")

if err != nil {
	fmt.Printf("Error %s\n", err.Error())
	return
}

fmt.Println("Account Metadata")
fmt.Println("-------------------")
fmt.Printf("%+v\n", metadata)
Describe
sobjResources := sobject.NewResources(session)

describe, err := sobjResources.Describe("Account")

if err != nil {
	fmt.Printf("Error %s\n", err.Error())
	return
}

fmt.Println("Account Describe")
fmt.Println("-------------------")
fmt.Printf("%+v\n", describe)
DML Insert
type dml struct {
	sobject       string
	fields        map[string]interface{}
}

func (d *dml) SObject() string {
	return d.sobject
}
func (d *dml) Fields() map[string]interface{} {
	return d.fields
}


sobjResources := sobject.NewResources(session)

dml := &dml{
	sobject: "Account",
	fields: map[string]interface{}{
		"Name":            "Test Account",
		"MyUID__c":        "AccExID222",
		"MyCustomText__c": "My fun text",
		"Phone":           "9045551212",
	},
}

insertValue, err := sobjResources.Insert(dml)

if err != nil {
	fmt.Printf("Insert Error %s\n", err.Error())
	return
}

fmt.Println("Account")
fmt.Println("-------------------")
fmt.Printf("%+v\n", insertValue)
DML Update
type dml struct {
	sobject       string
	fields        map[string]interface{}
	id            string
}

func (d *dml) SObject() string {
	return d.sobject
}
func (d *dml) Fields() map[string]interface{} {
	return d.fields
}
func (d *dml) ID() string {
	return d.id
}


sobjResources := sobject.NewResources(session)

dml := &dml{
	sobject: "Account",
}

dml.id = "Account Salesforce ID"
dml.fields["Phone"] = "6065551212"
dml.fields["MyCustomText__c"] = "updated text"

err = sobjResources.Update(dml)

if err != nil {
	fmt.Printf("Update Error %s\n", err.Error())
	fmt.Println()
	return
}

fmt.Println("Account Updated")
fmt.Println("-------------------")

DML Upsert
type dml struct {
	sobject       string
	fields        map[string]interface{}
	id            string
	externalField string
}

func (d *dml) SObject() string {
	return d.sobject
}
func (d *dml) Fields() map[string]interface{} {
	return d.fields
}
func (d *dml) ID() string {
	return d.id
}
func (d *dml) ExternalField() string {
	return d.externalField
}

sobjResources := sobject.NewResources(session)

dml := &dml{
	sobject: "Account",
}
dml.id = "AccExID345"
dml.externalField = "MyUID__c"
dml.fields["Name"] = "Upsert Update"

upsertValue, err := sobjResources.Upsert(dml)

if err != nil {
	fmt.Printf("Upsert Error %s\n", err.Error())
	return
}

fmt.Println("Account Upsert")
fmt.Println("-------------------")
fmt.Printf("%+v\n", upsertValue)
DML Delete
type dml struct {
	sobject       string
	id            string
}

func (d *dml) SObject() string {
	return d.sobject
}
func (d *dml) ID() string {
	return d.id
}

sobjResources := sobject.NewResources(session)

dml := &dml{
	sobject: "Account",
	id:      "0012E00001oHQDNQA4",
}

err = sobjResources.Delete(dml)

if err != nil {
	fmt.Printf("Upsert Error %s\n", err.Error())
	return
}

fmt.Println("Account Deleted")

Query: With Salesforce ID

Return all SObject fields.

type query struct {
	sobject string
	id      string
	fields  []string
}

func (q *query) SObject() string {
	return q.sobject
}
func (q *query) ID() string {
	return q.id
}
func (q *query) Fields() []string {
	return q.fields
}

sobjResources := sobject.NewResources(session)

query := &query{
	sobject: "Account",
	id:      "Account Salesforce ID",
}

record, err := sobjResources.Query(query)
if err != nil {
	fmt.Printf("Query Error %s\n", err.Error())
	return
}

fmt.Println("Account Query")
fmt.Println("-------------------")
fmt.Printf("%+v\n", record)

Return specific SObject fields.

type query struct {
	sobject string
	id      string
	fields  []string
}

func (q *query) SObject() string {
	return q.sobject
}
func (q *query) ID() string {
	return q.id
}
func (q *query) Fields() []string {
	return q.fields
}

sobjResources := sobject.NewResources(session)

query := &query{
	sobject: "Account",
	id:      "Account Salesforce ID",
	fields: []string{
		"Name",
		"MyUID__c",
		"Phone",
		"MyCustomText__c",
	},
}

record, err := sobjResources.Query(query)
if err != nil {
	fmt.Printf("Query Error %s\n", err.Error())
	return
}

fmt.Println("Account Query")
fmt.Println("-------------------")
fmt.Printf("%+\nv", record)

Query: With External ID

Return all SObject fields.

type query struct {
	sobject  string
	id       string
	external string
	fields   []string
}

func (q *query) SObject() string {
	return q.sobject
}
func (q *query) ID() string {
	return q.id
}
func (q *query) Fields() []string {
	return q.fields
}
func (q *query) ExternalField() string {
	return q.external
}

sobjResources := sobject.NewResources(session)

query := &query{
	sobject:  "Account",
	id:       "AccExID234",
	external: "MyUID__c",
}

record, err := sobjResources.ExternalQuery(query)
if err != nil {
	fmt.Printf("Query Error %s\n", err.Error())
	return
}

fmt.Println("Account Query")
fmt.Println("-------------------")
fmt.Printf("%+v\n", record)

Return specific SObject fields.

type query struct {
	sobject  string
	id       string
	external string
	fields   []string
}

func (q *query) SObject() string {
	return q.sobject
}
func (q *query) ID() string {
	return q.id
}
func (q *query) Fields() []string {
	return q.fields
}
func (q *query) ExternalField() string {
	return q.external
}

sobjResources := sobject.NewResources(session)

query := &query{
	sobject:  "Account",
	id:       "AccExID234",
	external: "MyUID__c",
	fields: []string{
		"Name",
		"Phone",
		"MyCustomText__c",
	},
}

record, err := sobjResources.ExternalQuery(query)
if err != nil {
	fmt.Printf("Query Error %s\n", err.Error())
	return
}

fmt.Println("Account Query")
fmt.Println("-------------------")
fmt.Printf("%+v\n", record)
List of Deleted Records
sobjResources := sobject.NewResources(session)

deletedRecords, err := sobjResources.DeletedRecords("Account", time.Now().Add(time.Hour*-12), time.Now())
if err != nil {
	fmt.Printf("Deleted Records Error %s\n", err.Error())
	return
}

fmt.Println("Deleted Account Records")
fmt.Println("-------------------")
fmt.Printf("%+v\n", deletedRecords)
List of Updated Records
sobjResources := sobject.NewResources(session)

updatedRecords, err := sobjResources.UpdatedRecords("Account", time.Now().Add(time.Hour*-12), time.Now())
if err != nil {
	fmt.Printf("Deleted Records Error %s\n", err.Error())
	return
}

fmt.Println("Updated Account Records")
fmt.Println("-------------------")
fmt.Printf("%+v\n", updatedRecords)

Get Attachment and Document Content
sobjResources := sobject.NewResources(session)

attachment, err := sobjResources.GetContent("Attachment ID", sobject.AttachmentType)
if err != nil {
	fmt.Printf("Error %s\n", err.Error())
	return
}

document, err := sobjResources.GetContent("Document ID", sobject.DocumentType)
if err != nil {
	fmt.Printf("Error %s\n", err.Error())
	return
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ActionOverride

type ActionOverride struct {
	IsAvailableInTouch bool   `json:"isAvailableInTouch"`
	FormFactor         string `json:"formFactor"`
	Name               string `json:"name"`
	PageID             string `json:"pageId"`
	URL                string `json:"url"`
}

ActionOverride describes the objects overrides.

type ChildRelationship

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

ChildRelationship describes the child relationship of the SObject.

type ContentType

type ContentType string

ContentType is indicator of the content type in Salesforce blob.

const (
	// AttachmentType is the content blob from the Salesforce Attachment record.
	AttachmentType ContentType = "Attachment"
	// DocumentType is the content blob from the Salesforce Document record.
	DocumentType ContentType = "Document"
)

type DeletedRecords

type DeletedRecords struct {
	Records         []deletedRecord `json:"deletedRecords"`
	EarliestDateStr string          `json:"earliestDateAvailable"`
	LatestDateStr   string          `json:"latestDateCovered"`
	EarliestDate    time.Time       `json:"-"`
	LatestDate      time.Time       `json:"-"`
}

DeletedRecords is the return structure listing the deleted records.

type Deleter

type Deleter interface {
	SObject() string
	ID() string
}

Deleter provides the parameters needed to delete a record.

SObject is the Salesforce table name. An example would be Account or Custom__c.

ID is the Salesforce ID to be deleted.

type DescribeValue

type DescribeValue struct {
	Activateable         bool                `json:"activateable"`
	CompactLayoutable    bool                `json:"compactLayoutable"`
	Createable           bool                `json:"createable"`
	Custom               bool                `json:"custom"`
	CustomSetting        bool                `json:"customSetting"`
	Deletable            bool                `json:"deletable"`
	DeprecatedAndHidden  bool                `json:"deprecatedAndHidden"`
	FeedEnabled          bool                `json:"feedEnabled"`
	HasSubtypes          bool                `json:"hasSubtypes"`
	IsSubType            bool                `json:"isSubtype"`
	Layoutable           bool                `json:"layoutable"`
	Mergeable            bool                `json:"mergeable"`
	MRUEnabled           bool                `json:"mruEnabled"`
	Queryable            bool                `json:"queryable"`
	Replicateable        bool                `json:"replicateable"`
	Retrieveable         bool                `json:"retrieveable"`
	SearchLayoutable     bool                `json:"searchLayoutable"`
	Searchable           bool                `json:"searchable"`
	Triggerable          bool                `json:"triggerable"`
	Undeletable          bool                `json:"undeletable"`
	Updateable           bool                `json:"updateable"`
	KeyPrefix            string              `json:"keyPrefix"`
	Label                string              `json:"label"`
	LabelPural           string              `json:"labelPlural"`
	Name                 string              `json:"name"`
	NetworkScopeFielName string              `json:"networkScopeFieldName"`
	Listviewable         interface{}         `json:"listviewable"`
	LookupLayoutable     interface{}         `json:"lookupLayoutable"`
	URLs                 ObjectURLs          `json:"urls"`
	ActionOverrides      []ActionOverride    `json:"actionOverrides"`
	ChildRelationships   []ChildRelationship `json:"childRelationships"`
	Fields               []Field             `json:"fields"`
	RecordTypeInfos      []RecordTypeInfo    `json:"recordTypeInfos"`
	SupportedScopes      []SupportedScope    `json:"supportedScopes"`
	NamedLayoutInfos     []interface{}       `json:"namedLayoutInfos"`
}

DescribeValue is a structure that is returned from the from the Salesforce API SObject describe.

type ExternalQuerier

type ExternalQuerier interface {
	Querier
	ExternalField() string
}

ExternalQuerier is the interface used to query a SObject from Salesforce using an external ID.

SObject is the table object in Salesforce, like Account.

ID is the external ID of the table object to retrieve.

Fields is the fields to be returned. If the field array is empty, the all of the fields will be returned.

ExternalField is the external field on the sobject.

type Field

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

Field describes the SOBject's fields.

type InsertValue

type InsertValue struct {
	Success bool         `json:"success"`
	ID      string       `json:"id"`
	Errors  []sfdc.Error `json:"errors"`
}

InsertValue is the value that is returned when a record is inserted into Salesforce.

type Inserter

type Inserter interface {
	SObject() string
	Fields() map[string]interface{}
}

Inserter provides the parameters needed insert a record.

SObject is the Salesforce table name. An example would be Account or Custom__c.

Fields are the fields of the record that are to be inserted. It is the callers responsbility to provide value fields and values.

type MetadataValue

type MetadataValue struct {
	ObjectDescribe ObjectDescribe           `json:"objectDescribe"`
	RecentItems    []map[string]interface{} `json:"recentItems"`
}

MetadataValue is the response from the SObject metadata API.

type ObjectDescribe

type ObjectDescribe struct {
	Activatable         bool       `json:"activateable"`
	Creatable           bool       `json:"createable"`
	Custom              bool       `json:"custom"`
	CustomSetting       bool       `json:"customSetting"`
	Deletable           bool       `json:"deletable"`
	DeprecatedAndHidden bool       `json:"deprecatedAndHidden"`
	FeedEnabled         bool       `json:"feedEnabled"`
	HasSubtype          bool       `json:"hasSubtypes"`
	IsSubtype           bool       `json:"isSubtype"`
	KeyPrefix           string     `json:"keyPrefix"`
	Label               string     `json:"label"`
	LabelPlural         string     `json:"labelPlural"`
	Layoutable          bool       `json:"layoutable"`
	Mergeable           bool       `json:"mergeable"`
	MruEnabled          bool       `json:"mruEnabled"`
	Name                string     `json:"name"`
	Queryable           bool       `json:"queryable"`
	Replicateable       bool       `json:"replicateable"`
	Retrieveable        bool       `json:"retrieveable"`
	Searchable          bool       `json:"searchable"`
	Triggerable         bool       `json:"triggerable"`
	Undeletable         bool       `json:"undeletable"`
	Updateable          bool       `json:"updateable"`
	URLs                ObjectURLs `json:"urls"`
}

ObjectDescribe is the SObject metadata describe.

type ObjectURLs

type ObjectURLs struct {
	CompactLayouts   string `json:"compactLayouts"`
	RowTemplate      string `json:"rowTemplate"`
	ApprovalLayouts  string `json:"approvalLayouts"`
	DefaultValues    string `json:"defaultValues"`
	ListViews        string `json:"listviews"`
	Describe         string `json:"describe"`
	QuickActions     string `json:"quickActions"`
	Layouts          string `json:"layouts"`
	SObject          string `json:"sobject"`
	UIDetailTemplate string `json:"uiDetailTemplate"`
	UIEditTemplate   string `json:"uiEditTemplate"`
	UINewRecord      string `json:"uiNewRecord"`
}

ObjectURLs is the URL for the SObject metadata.

type PickListValue

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

PickListValue describes the SObject's field picklist values.

type Querier

type Querier interface {
	SObject() string
	ID() string
	Fields() []string
}

Querier is the interface used to query a SObject from Salesforce.

SObject is the table object in Salesforce, like Account.

ID is the Salesforce ID of the table object to retrieve.

Fields is the fields to be returned. If the field array is empty, the all of the fields will be returned.

type RecordTypeInfo

type RecordTypeInfo struct {
	Active                   bool          `json:"active"`
	Available                bool          `json:"available"`
	DefaultRecordTypeMapping bool          `json:"defaultRecordTypeMapping"`
	Master                   bool          `json:"master"`
	Name                     string        `json:"name"`
	RecordTypeID             string        `json:"recordTypeId"`
	DeveloperName            string        `json:"developerName"`
	URLs                     RecordTypeURL `json:"urls"`
}

RecordTypeInfo describes the SObjects record types assocaited with it.

type RecordTypeURL

type RecordTypeURL struct {
	Layout string `json:"layout"`
}

RecordTypeURL contains the record type's URLs.

type Resources

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

Resources is the structure for the Salesforce APIs for SObjects.

func NewResources

func NewResources(session session.ServiceFormatter) (*Resources, error)

NewResources forms the Salesforce SObject resource structure. The session formatter is required to form the proper URLs and authorization header.

func (*Resources) Delete

func (r *Resources) Delete(deleter Deleter) error

Delete will delete an existing Salesforce record.

func (*Resources) DeletedRecords

func (r *Resources) DeletedRecords(sobject string, startDate, endDate time.Time) (DeletedRecords, error)

DeletedRecords returns a list of records that have been deleted from a date range.

func (*Resources) Describe

func (r *Resources) Describe(sobject string) (DescribeValue, error)

Describe retrieves the SObject's describe.

func (*Resources) ExternalQuery

func (r *Resources) ExternalQuery(querier ExternalQuerier) (*sfdc.Record, error)

ExternalQuery returns a SObject record using an external ID field.

func (*Resources) GetContent

func (r *Resources) GetContent(id string, content ContentType) ([]byte, error)

GetContent returns the blob from a content SObject.

func (*Resources) Insert

func (r *Resources) Insert(inserter Inserter) (InsertValue, error)

Insert will create a new Salesforce record.

func (*Resources) Metadata

func (r *Resources) Metadata(sobject string) (MetadataValue, error)

Metadata retrieves the SObject's metadata.

func (*Resources) Query

func (r *Resources) Query(querier Querier) (*sfdc.Record, error)

Query returns a SObject record using the Salesforce ID.

func (*Resources) Update

func (r *Resources) Update(updater Updater) error

Update will update an existing Salesforce record.

func (*Resources) UpdatedRecords

func (r *Resources) UpdatedRecords(sobject string, startDate, endDate time.Time) (UpdatedRecords, error)

UpdatedRecords returns a list of records that have been updated from a date range.

func (*Resources) Upsert

func (r *Resources) Upsert(upserter Upserter) (UpsertValue, error)

Upsert will upsert an existing or new Salesforce record.

type SupportedScope

type SupportedScope struct {
	Label string `json:"label"`
	Name  string `json:"name"`
}

SupportedScope describes the supported scope.

type UpdatedRecords

type UpdatedRecords struct {
	Records       []string  `json:"ids"`
	LatestDateStr string    `json:"latestDateCovered"`
	LatestDate    time.Time `json:"-"`
}

UpdatedRecords is the return structure listing the updated records.

type Updater

type Updater interface {
	Inserter
	ID() string
}

Updater provides the parameters needed to update a record.

SObject is the Salesforce table name. An example would be Account or Custom__c.

ID is the Salesforce ID that will be updated.

Fields are the fields of the record that are to be inserted. It is the callers responsbility to provide value fields and values.

type UpsertValue

type UpsertValue struct {
	Inserted bool
	InsertValue
}

UpsertValue is the value that is return when a record as been upserted into Salesforce.

Upsert will return two types of values, which are indicated by Inserted. If Inserted is true, then the InsertValue is popluted.

type Upserter

type Upserter interface {
	Updater
	ExternalField() string
}

Upserter provides the parameters needed to upsert a record.

SObject is the Salesforce table name. An example would be Account or Custom__c.

ID is the External ID that will be updated.

ExternalField is the external ID field.

Fields are the fields of the record that are to be inserted. It is the callers responsbility to provide value fields and values.

Directories

Path Synopsis
Package collections is the implementation of the SObject Collections API.
Package collections is the implementation of the SObject Collections API.

Jump to

Keyboard shortcuts

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