GithubHelp home page GithubHelp logo

codelicia / trineforce Goto Github PK

View Code? Open in Web Editor NEW
5.0 3.0 5.0 275 KB

A nice ✨ gambiarra ✨ to work with Salesforce SOQL Queries and Doctrine DBAL

License: MIT License

PHP 99.74% Makefile 0.26%
doctrine doctrine-dbal salesforce salesforce-developers

trineforce's Introduction

SOQL Doctrine DBAL

Salesforce Soql Doctrine Driver allows you to write Soql queries and interact with a Salesforce instance using the Doctrine DBAL layer.

Now one can forget about Salesforce and have a nice repository/query object integration on one's architecture without hurting that much on the usual project structure.

Installation

Use composer to install this package as bellow:

$ composer require codelicia/trineforce

Configuration

If you are familiar with Doctrine, then you probably already know how to configure and use it. But some special configuration is required in order to make it work.

When creating a new Connection, you should also provide the configuration keys for salesforceInstance, consumerKey, consumerSecret and point to the right driverClass. The usual user and password are also required.

$config = new Configuration();
$connectionParams = [
    'salesforceInstance' => 'https://[SALESFORCE INSTANCE].salesforce.com',
    'apiVersion'         => 'v43.0',
    'user'               => '[email protected]',
    'password'           => 'salesforce-password',
    'consumerKey'        => '...',
    'consumerSecret'     => '...',
    'driverClass'        => \Codelicia\Soql\SoqlDriver::class,
    'wrapperClass'       => \Codelicia\Soql\ConnectionWrapper::class,
];

/** @var \Codelicia\Soql\ConnectionWrapper $conn */
$conn = DriverManager::getConnection($connectionParams, $config);
  • user provides the login, which is usually an email to access the salesforce instance.
  • password provides the corresponding password to the email provided on user.
  • salesforceInstance points to the url of the Salesforce instance.
  • apiVersion specify a salesforce API version to work with.
  • consumerKey provides the integration consumer key
  • consumerSecret provides the integration consumer secret
  • driverClass should points to \Codelicia\Soql\SoqlDriver::class
  • wrapperClass should points to \Codelicia\Soql\ConnectionWrapper::class

By setting up the wrapperClass, we can make use of a proper QueryBuild that allow JOIN in the Salesforce format.

When using the doctrine bundle and the dbal is configured through yaml the options should be passed in a different way for the validation that the bundle does.

doctrine:
    dbal:
        driver: soql
        user: '%env(resolve:SALESFORCE_USERNAME)%'
        password: '%env(resolve:SALESFORCE_PASSWORD)%'
        driver_class: '\Codelicia\Soql\SoqlDriver'
        wrapper_class: '\Codelicia\Soql\ConnectionWrapper'
        options:
            salesforceInstance: '%env(resolve:SALESFORCE_ENDPOINT)%'
            apiVersion: v56.0
            consumerKey: '%env(resolve:SALESFORCE_CLIENT_ID)%'
            consumerSecret: '%env(resolve:SALESFORCE_CLIENT_SECRET)%'

Using DBAL

Now that you have the connection set up, you can use Doctrine QueryBuilder to query some data as bellow:

$id = '0062X00000vLZDVQA4';

$sql = $conn->createQueryBuilder()
    ->select(['Id', 'Name', 'Status__c'])
    ->from('Opportunity')
    ->where('Id = :id')
    ->andWhere('Name = :name')
    ->setParameter('name', 'Pay as you go Opportunity')
    ->setParameter('id', $id)
    ->setMaxResults(1)
    ->execute();

var_dump($sql->fetchAll()); // All rest api result

or use the normal Connection#query() method.

Basic Operations

Here are some examples of basic CRUD operations.

Connection#insert()

Creating an Account with the Name of John:

$connection->insert('Account', ['Name' => 'John']);

Connection#delete()

Deleting an Account with the Id = 1234:

$connection->delete('Account', ['Id' => '1234']);

Connection#update()

Update an Account with the Name of Sr. John where the Id is 1234:

$connection->update('Account', ['Name' => 'Sr. John'], ['Id' => '1234']);

Be Transactional with Composite API

As salesforce released the composite api, it gave us the ability to simulate transactions as in a database. So, we can use the same Doctrine DBAL api that you already know to do transactional operations in your Salesforce instance.

$conn->beginTransaction();

$conn->insert('Account', ['Name' => 'John']);
$conn->insert('Account', ['Name' => 'Elsa']);

$conn->commit();

Or even, use the Connection#transactional() helper, as you prefer.

Referencing another Records

The composite api, also enables us to compose a structure data to be changed in one single request. So we can cross reference records as it fits our needs.

Let's see how to create an Account and a linked Contact to that Account in a single composite request.

$conn->transactional(static function () use ($conn) {

    $conn->insert('Account', ['Name' => 'John'], ['referenceId' => 'account']);
    $conn->insert('Contact', [
        'FirstName' => 'John',
        'LastName' => 'Contact',
        'AccountId' => '@{account.id}' // reference `Account` by its `referenceId`
    ]);

});

🚫 Known Limitations

As of today, we cannot consume a sObject using the queryBuilder to get all fields from the sObject. That is because Salesforce doesn't accept SELECT * as a valid query.

The workaround that issue is to do a GET request to specific resources, then can grab all data related to that resource.

$this->connection
    ->getNativeConnection() // : \GuzzleHttp\ClientInterface
    ->request(
        'GET',
        sprintf('/services/data/v40.0/sobjects/Opportunity/%s', $id)
    )
    ->getBody()
    ->getContents()
;

📈 Diagram

%%{init: {'sequence': { 'mirrorActors': false, 'rightAngles': true, 'messageAlign': 'center', 'actorFontSize': 20, 'actorFontWeight': 900, 'noteFontSize': 18, 'noteFontWeight': 600, 'messageFontSize': 20}}}%%
%%{init: {'theme': 'base', 'themeVariables': { 'actorBorder': '#D86613', 'activationBorderColor': '#232F3E', 'activationBkgColor': '#D86613','noteBorderColor': '#232F3E', 'signalColor': 'white', 'signalTextColor': 'gray', 'sequenceNumberColor': '#232F3E'}}}%%
sequenceDiagram
    autonumber
    Note left of ConnectionWrapper: Everything starts with <br/>the ConnectionWrapper.
    ConnectionWrapper->>QueryBuilder: createQueryBuilder()
    activate QueryBuilder
    alt 
        QueryBuilder->>QueryBuilder: execute() <br>Calls private executeQuery()<br>method
    end
    QueryBuilder->>+ConnectionWrapper: executeQuery()
    deactivate QueryBuilder
    ConnectionWrapper->>SoqlStatement: execute() 
    SoqlStatement->>+\Doctrine\DBAL\Driver\Result: execute()
    ConnectionWrapper->>+\Codelicia\Soql\DBAL\Result: new
    \Doctrine\DBAL\Driver\Result-->>\Codelicia\Soql\DBAL\Result: pass to
    \Codelicia\Soql\DBAL\Result-->>-ConnectionWrapper: returns
    ConnectionWrapper->>-SoqlStatement: fetchAll()
    SoqlStatement->>+\Codelicia\Soql\FetchDataUtility: fetchAll()
    \Codelicia\Soql\FetchDataUtility-->>+\GuzzleHttp\ClientInterface: send()
    Note right of \Codelicia\Soql\FetchDataUtility: Countable goes here?<br> before creating the Payload?
    \Codelicia\Soql\FetchDataUtility->>+\Codelicia\Soql\Payload: new
    \Codelicia\Soql\Payload-->>+SoqlStatement: returns

Author

trineforce's People

Contributors

allcontributors[bot] avatar dependabot-preview[bot] avatar dependabot[bot] avatar eher avatar malukenho avatar peter279k avatar renovate[bot] avatar rodrigoaguilera avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

trineforce's Issues

The Result constructor should not be extended in Codelicia\Soql\DBAL\Result

When clearing the cache of my app I get:

[info] User Deprecated: The "Doctrine\DBAL\Result::__construct()" method is considered internal The result can be only instantiated by {@see Connection} or {@see Statement}. It may change without further notice. You should not extend it from "Codelicia\Soql\DBAL\Result".

List alternative packages in the documentation

Summary

I was very happy to find this library on packagist to develop a salesforce integration but before that I stumbled upon
https://github.com/Kephson/php-salesforce-rest-api
that is not a a DBAL

Trineforce fits more my project needs and I don't have to worry about sanitizing the parameters for the queries since that is done by doctrine.

I also discovered an eloquent model for salesforce
https://github.com/roblesterjr04/EloquentSalesForce
but I don't want to use laravel for this particular project.

Describe the solution you'd like

My main goal is to make people aware of the alternatives so even if only the maintainer reads this issue is fine but I think it can be beneficial to have a little section in the readme that lists alternatives. I will propose the same on the other packages.

Fix issue when submitting queries through transactions

We have: private const SERVICE_COMPOSITE_URL = '/services/data/%s/composite';

But when used, "SERVICE_COMPOSITE_URL" is missing the tag replacement to have the API version actually inserted, which results in an invalid URL.

Handler array types when bind parameters

The following code should work out of the box

$this->client
            ->createQueryBuilder()
            ->select([
                'Id'
            ])
            ->from('Case')
             ->where('RecordType.Name IN (:recordTypeNames)')
            ->setParameter(
                'recordTypeNames',
                ['a', 'b', 'third' => 'c'],
                Types::TArray
            )
            ->execute()
            ->fetch();

Special url characters not used in Soql

When parameter contains url special character it's ignored in Soql:
`$phone = '+31612345678';

$sql = $conn->createQueryBuilder()
->select(['Contact.name','Contact.phone','Account.id', 'Account.name', 'Owner.email', 'Owner.name', 'Owner.id'])
->from('Contact')
->where('Phone = :phone')
->setParameter('phone', $phone, 'string')
->setMaxResults(1)
->execute();`

No results.

With urlencode in do_fetch
/** @return mixed[]|false */ private function doFetch() { // TODO: how to deal with different versions? MaybedriverOptions`?
$request = $this->connection->get('/services/data/v20.0/query?q=' . urlencode($this->statement));

    return json_decode($request->getBody()->getContents(), true);
}

`

One result

Make it possible to consume a sObject via GET request

As of today, we cannot consume a sObject without doing a SOQL query. But it still relevant to have a GET request to specific resources, as SOQL doesn't support * when querying fields, and via direct resource consumption we can grab all data related to a resource.

The Hacky way to do it right now is to get the configured GuzzleHttpClient and do the call directly.

$httpClient = $this->connection
    ->getWrappedConnection()
    ->getHttpClient();

$request    = $httpClient->request(
    'GET',
    sprintf('/services/data/v40.0/sobjects/Opportunity/%s', $id)
);

Fix examples in readme.md

I have been trying to use the examples to make my own queries but I haven't been able to use them verbatim.

If I try

        $stmt = $this->connection->createQueryBuilder()
            ->select(['AccountId', 'Name'])
            ->from('Contact')
            ->where('AccountId = :id')
            ->setParameter('id', '0013Y00002ZZLOzQAP')
            ->setMaxResults(1);

I get the following invalid SOQL query

SELECT AccountId, Name FROM Contact WHERE AccountId = :'0013Y00002ZZLOzQAP' LIMIT 1

Notice the colon before the AccountId string.
To get a proper SOQL query I need to use ->setParameter(':id', '0013Y00002ZZLOzQAP') with the colon.

Also trying to use positional parameters it seems like the index starts at 1 for positional parameter because of the use of
Doctrine\DBAL\Driver\OCI8\ConvertPositionalToNamedPlaceholders; in the SoqlStatement class.

When I read the docs the positional parameters usually start at 0 but not for this driver.
https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/query-builder.html

Is there a reason why there is a custom logic in this driver around parameters?

I'm not proposing a change in the readme yet because first I want to clarify the reasoning behind the current code.

Congratulations on a great piece of software.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

composer
composer.json
  • php ^8.1 || ^8.2
  • azjezz/psl ^2.7.0
  • doctrine/dbal ^3.6.6
  • doctrine/orm ^3.0.0
  • guzzlehttp/guzzle ^7.8.0
  • guzzlehttp/psr7 ^2.6.1
  • psr/http-message 2.0
  • doctrine/coding-standard ^12.0.0
  • infection/infection ^0.27.0
  • maglnet/composer-require-checker ^4.6.0
  • malukenho/mcbumpface ^1.2.0
  • phpunit/phpunit ^10.3.3
  • staabm/annotate-pull-request-from-checkstyle ^1.8.5
github-actions
.github/workflows/ci.yml
  • actions/checkout v4
  • shivammathur/setup-php v2
.github/workflows/release-on-milestone-closed.yml
  • actions/checkout v4
  • laminas/automatic-releases v1
  • laminas/automatic-releases v1
  • ubuntu 22.04

  • Check this box to trigger a request for Renovate to run again on this repository

Results of join queries should be countable

        $result = $this->connection
                       ->createQueryBuilder()
                       ->select(['Id'])
                       ->from('Account')
                       ->join('Opportunities', ['Id'])
                       ->where('ExternalId__c' = :externalId')
                       ->setParameter('externalId', $externalId)
                       ->execute()
                       ->fetchAll();

        var_dump($result);

This is the current result

 array(1) {
   [0]=>
   array(2) {
     ["Id"]=>
     string(18) "001w000001jEKBUMBA"
     ["Opportunities"]=>
     NULL
   }
 }

To be able to use count should be something like this

 array(1) {
   [0]=>
   array(2) {
     ["Id"]=>
     string(18) "001w000001jEKBUMBA"
     ["Opportunities"]=> []
   }
 }

Explore compatibility with the Doctrine ORM.

I would be great to define ORM objects that are configured to use this driver in the backend.

I have been researching this a bit and one of the initial obstacle is the lack of support for aliasing fields/columns in a SOQL query aka AS.

Has anyone tried before?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.