PHPackages                             genesis/sql-data-mods - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Testing &amp; Quality](/categories/testing)
4. /
5. genesis/sql-data-mods

ActiveBehat-extension[Testing &amp; Quality](/categories/testing)

genesis/sql-data-mods
=====================

SQL/PDO extension - extending capabilities provided by the original SQL API extension.

4.20.0(5y ago)39.8k[13 issues](https://github.com/forceedge01/sql-data-mods/issues)[2 PRs](https://github.com/forceedge01/sql-data-mods/pulls)MITPHPPHP ~5.5|~7.0

Since Dec 22Pushed 3y ago1 watchersCompare

[ Source](https://github.com/forceedge01/sql-data-mods)[ Packagist](https://packagist.org/packages/genesis/sql-data-mods)[ RSS](/packages/genesis-sql-data-mods/feed)WikiDiscussions master Synced 3w ago

READMEChangelogDependencies (7)Versions (57)Used By (0)

SQL Data Mods (Behat Extension) [ ![Codeship Status for forceedge01/sql-api-wrapper](https://camo.githubusercontent.com/3c27d557a351de9145dd0edbda19edde60cfde1db12a3676f06e3bcc01735c2a/68747470733a2f2f6170702e636f6465736869702e636f6d2f70726f6a656374732f39363330323231302d616434352d303133352d373263362d3536663030343033343334642f7374617475733f6272616e63683d6d6173746572)](https://app.codeship.com/projects/257181)
===========================================================================================================================================================================================================================================================================================================================================================================================================================

[](#sql-data-mods-behat-extension--)

Need fixture data but seed causing headaches? Create fixture seed data on the fly, keep them visible in your scenarios, auto generate data and deal with complex data relationships.

**Find example usage in the features folder.**

Release details:
----------------

[](#release-details)

Major: Allow multiple data sources to be defined.

Minor:

- Allow uniqueColumn to be specified from the step definition rather than assuming first column.
- Get count through dataMod::count() call, truncate call now made public.
- Inject domain mod based defaults through to data mods.
- Fail aid integration if FailureContext is enabled for suite.
- Constants for confusing string values used around data mods.
- Simplified traits to provide alternate syntax of declarations.

Patch:

- Fix count step defintion to not create additional record.
- Revised english for additional fixture step defintion.

Tools provided by this package:
-------------------------------

[](#tools-provided-by-this-package)

- Define more than one data source i.e mssql, mysql etc.
- DataModSQLContext - Use your data mods directly with step defintions provided by this class. Just register with the behat.yml file and you are good to go.
- Decorated API BaseProvider Class - for advanced and easy integration with data modules.
- DataRetriever class - Retrieve data in a robust way and make a solid foundation for your test framework quickly.
- CLI commands to facilitate debugging.
- Auto generation of data mod files with or without database support.

CLI Commands:
-------------

[](#cli-commands)

Debug sql only:

- To view sql statements executed by the extension use `--debug-sql` flag.

Debug all:

- To view all activity along with executed statements use `--debug-sql-all` flag.

Generate data mod:

- To generate a simple base data mod use `--dm-generate ` flag.
- To generate with database support use `--dm-generate= --dm-connection=` flag.
- You may want to explore the `--dm-path` and `--dm-namespace` flags from the help menu as well.

DataModSQLContext
-----------------

[](#datamodsqlcontext)

```
# Insert single entry for a datamod.
Given I have a "User" fixture
# OR with specific data
Given I have a "User" fixture with the following data set:
| name  | Wahab Qureshi              |
| email | its.inevitable@hotmail.com |

# Insert multiple entries for a datamod.
Given I have multiple "User" fixtures with the following data sets:
| name           | email                       |
| Wahab Qureshi  | its.inevitable@hotmail.com  |
| Sabhat Qureshi | next-gen-coder@hotmail.com  |
| Jawad Qureshi  | to-be-coder@hotmail.com     |
| Another name   | [Users.Email\|Name:Another] |
```

The last value in the list above uses an external reference to fetch the value to be inserted. You can find out more about this by reading the 'Referencing foreign table values' topic in the behat-sql-extension extension. We do need to escape the pipe character in this call so it doesn't result in a syntax error when using table nodes.

The createFixture call will attempt to delete the existing record before it creates another one so you always end up with a fresh copy. As easy as it sounds, foreign key constraints may not let that happen. In cases like these you can disable foreign key checks on the test database (most of the time you won't need to do this).

Installation
------------

[](#installation)

```
composer require --dev genesis/sql-data-mods

```

Sample configurating in the behat.yml file:

```
default:
    suites:
        default:
            contexts:
                - Genesis\SQLExtensionWrapper\DataModSQLContext:
                    debug: false # 1 for all debug, 2 for only SQL queries.
                    userUniqueRef: aq # Optional
    extensions:
        Genesis\SQLExtensionWrapper\Extension:
            connections:
                mysql:
                    engine: mysql # mssql, pgsql, sqlite...
                    host: '%MYSQL_HOST%' # Resolve environment variable
                    port: 3306
                    dbname: mydb_mysql
                    username: root
                    password: root
                    schema: myschema
                    prefix: dev_
                mssql:
                    engine: mssql # mssql, pgsql, sqlite...
                    host: '%MSSQL_HOST%' # Resolve environment variable
                    port: 1433
                    dbname: mydb_mssql
                    username: root
                    password: root
                    schema: myschema
                    prefix: dev_
            dataModMapping: # Optional
                "*": \QuickPack\DataMod\ # Configure path for all data mods using *.
                "User": \QuickPack\DataMod\User\User # Configure single data mod.
            domainModMapping: # Optional
                "*": \QuickPack\DomainMod\
                "User": \QuickPack\DomainMod\User\User
            FailAid: # If behat-fail-aid is enabled.
                output:
                  enabled: true
                  select: true
                  insert: true
                  update: true
                  delete: true
```

debug - Turns debugging on off. userUniqueRef: Appends the string onto first column of data provided to the fixture step definitions if its a string. This is so every user has its own unique data if multiple users are targeting a single database. connections: Your database connection details. dataModMapping: The autoloading namespace reference to your dataMods. (Optional) domainModMapping: The autoloading namespace reference of your domainMods. (Optional)

Please note: The extension expects you to have your dataMods located in the `features/bootstrap/DataMod` folder. If you have a different mapping to this, you will have to define your autoload strategy in the composer.json file or manually require the files in. You can set the mapping in php like so:

You can register the context file through php as well.

```
use Behat\Testwork\Hook\Scope\BeforeSuiteScope;
use Genesis\SQLExtensionWrapper\DataModSQLContext;
use Genesis\SQLExtensionWrapper\BaseProvider;

class FeatureContext
{
    /**
     * @BeforeSuite
     */
    public static function loadDataModSQLContext(BeforeSuiteScope $scope)
    {
        BaseProvider::setCredentials([
            'mssql' => [
                'engine' => 'dblib',
                'name' => 'databaseName',
                'schema' => 'dbo',
                'prefix' => 'dev_',
                'host' => 'myhost',
                'port' => '1433',
                'username' => 'myUsername',
                'password' => 'myPassword'
            ]
        ]);

        // Default path is \\DataMod\\ which points to features/DataMod/, override this way.
        DataModSQLContext::setDataModMapping([
            '*' => '\\Custom\\DataMod\\'
        ]);

        DataModSQLContext::setDomainModMapping([
            '*' => '\\Custom\\DomainMod\\'
        ]);

        $scope->getEnvironment()->registerContextClass(
            DataModSQLContext::class,
            ['debug' => false]
        );
    }
}
```

BaseProvide Class
-----------------

[](#baseprovide-class)

The wrapper provides with powerful tools around the [behat-sql-extension](https://github.com/forceedge01/behat-sql-extension) API class. Methods provided:

- createFixture(array $data = \[\], string $uniqueColumn = null) // Recreates a record for fresh usage. Overridable from data mod.
- getSingle(array $where) // Returns a single record defined by the mapping.
- getColumn(string $column, array $where) // Returns a single column value from the database.
- getValue(string $key) // Get key value based on mapping.
- truncate() // Truncates a table.
- subSelect(string $column, array $where) // Provides the ability to sub select a column for any query.
- rawSubSelect(string $table, string $column, array $where) // Provides the ability to sub select a column for any query without a data mod.
- saveSession(string $primaryKey) // Save the current session for later re-use.
- restoreSession() // Restore the session saved by saveSession.
- getRequiredData(array $data, string $key, boolean $format) // Extended: Extracts value from an array.
- getOptionalData(array $data, string $key, mixed $default = null, boolean $format = false) // Extended: Optional value from an array, provide default otherwise.
- getFieldMapping(string $key) // Extended: Get field mapping provided in the getDataMapping method.
- getKeyword(string $key) // Get the keyword for mapped key.

Note: All methods provided by the wrapper are static, because they have a global state - we don't need to instantiate this wrapper.

Example usage
-------------

[](#example-usage)

Creating a DataMod to use in your context files. This is as easy as just extending the BaseProvider class from your dataMods.

```
# User.php
