VOOZH about

URL: https://deepwiki.com/MahoCommerce/maho/14.5-database-adapter-interface

⇱ Database Adapter Interface | MahoCommerce/maho | DeepWiki


Loading...
Last indexed: 15 May 2026 (ea8ab8)
Menu

Database Adapter Interface

Purpose and Scope

This page documents Maho's database adapter interface and its implementations that provide a robust, modern database abstraction layer. At its core, Maho uses Doctrine DBAL 4.x as the database abstraction engine, encapsulated in adapter classes implementing Maho\Db\Adapter\AdapterInterface. This system supports multiple database platforms while exposing a consistent API for data access, query building, transaction management, and schema operations.

Supported database platforms currently include:

  • MySQL / MariaDB via the pdo_mysql driver.
  • PostgreSQL via the pdo_pgsql driver.
  • SQLite via the pdo_sqlite driver.

These platforms are supported with dedicated PDO adapter classes extending an abstract base adapter providing platform-agnostic logic.

This interface and implementation enable multi-platform compatibility of Maho’s resource models and collections without requiring application code changes per database.


Architecture Overview

The database adapter interface acts as a bridge between Maho's high-level model/resource architecture and the low-level Doctrine DBAL connection.

Layered Architecture Diagram


Diagram: Maho Database Adapter Layer Integration

  • Mage_Core_Model_Abstract (models) and Maho\Data\Collection\Db rely on resource classes in Mage_Core_Model_Resource_Abstract and Mage_Core_Model_Resource_Db_Abstract.
  • Resource classes obtain read/write adapters implementing AdapterInterface.
  • The AbstractPdoAdapter forms the base implementation, relying on Doctrine DBAL’s Connection.
  • The Maho\Db\Select class wraps Doctrine's query builder, offering an intuitive query builder interface.
  • Platform-specific adapters (Mysql, Pgsql, Sqlite) implement platform nuances relating to driver name, SQL modes, connection options, and dialect quirks.

Core Interface: Maho\Db\Adapter\AdapterInterface

The AdapterInterface declares constants and method signatures required by all database adapters, ensuring a uniform API. It provides constants used for creating index types, defining foreign key actions, and standard date formats while prescribing:

  • Methods to obtain configuration and access the Doctrine connection.
  • Query execution and fetch methods.
  • Transaction control methods (beginTransaction, commit, rollBack).
  • Query builder provisioning (select() returns Maho\Db\Select).
  • Utility functions supporting SQL generation.

Platform Implementations Comparison

FeatureMySQL AdapterPostgreSQL AdapterSQLite Adapter
Driver Namepdo_mysqlpdo_pgsqlpdo_sqlite
Quote CharacterBacktick `Double quotes "Double quotes "
Statement Class\Maho\Db\Statement\Pdo\Mysql\Maho\Db\Statement\Pdo\Pgsql\Maho\Db\Statement\Pdo\Sqlite
DDL Cache PrefixDB_PDO_MYSQL_DDLDB_PDO_PGSQL_DDLDB_PDO_SQLITE_DDL

Platform-specific classes primarily override initialization details (eg., driver name, connection options, SQL dialects).


Key Adapter Methods

MethodReturn TypeDescription
getConfig()arrayReturns the adapter configuration array.
getConnection()\Doctrine\DBAL\ConnectionReturns the underlying Doctrine DBAL connection object.
select()Maho\Db\SelectReturns a new query builder instance.
beginTransaction()selfInitiates a database transaction with nesting support.
commit()selfCommits the current transaction, honoring nesting.
rollBack()selfRolls back the current transaction, aborting all nesting.
fetchAll()arrayExecutes a query and fetches all results as an array.
query()StatementExecutes a raw SQL query, returns a statement.

The detailed method implementations provide facilities such as safely quoting identifiers (tables, columns) and value binding with parameterized queries.


SQL Helper Methods: Cross-Platform

Maho exposes adapter methods to emit platform-specific SQL constructs with a unified interface:

HelperPurposeExample SQL (MySQL / PgSQL / SQLite)
getConcatSql(columns, separator)Concatenates strings with separatorCONCAT_WS(sep, cols...) / `col1
getCheckSql(condition, truePart, falsePart)Emulates IF conditionalsIF(cond, truePart, falsePart) / CASE WHEN cond THEN ... ELSE ... END
getIfNullSql(expr, fallback)Returns fallback for NULL expressionsIFNULL(expr, fallback) / COALESCE(expr, fallback)


Date and Interval Arithmetic Support

Date/time interval units are represented with constants such as INTERVAL_SECOND, INTERVAL_MINUTE, etc., mapped internally to platform-specific units.

  • PostgreSQL uses units such as SECOND, MINUTE, HOUR, DAY, MONTH, YEAR.
  • SQLite supports its strftime function with units like 'seconds', 'minutes', 'hours', 'days', 'months', and 'years'.

Adapters internally translate these units to support cross-platform SQL generation.


Transaction Handling

Maho's database adapter supports nested transactions with an internal counter. This pattern preserves consistent transaction semantics regardless of whether the underlying driver supports true nested transactions.

Transaction Lifecycle


  • Only starting the first transaction calls the real DB transaction begin.
  • Nested transaction calls increment the counter without calling DB.
  • Commit decrements the counter; the last commit triggers the actual DB commit.
  • If rollBack() is called at any nesting level, the entire transaction is rolled back immediately, and the counter resets to zero, preventing partial commits.

Schema and DDL Operations

Maho's database abstraction supports schema-level operations via data definition language (DDL) manipulations integrated with Doctrine DBAL’s schema API.

Cross-Engine Consistency in Date/Time Fields

A key modernization is converting MySQL-only TIMESTAMP columns to DATETIME:

  • TIMESTAMP columns are converted to DATETIME because:
    • DATETIME supports a wider year range (1000-9999).
    • It avoids MySQL’s implicit timezone conversions, enhancing cross-DB consistency.
  • Default CURRENT_TIMESTAMP is preserved only if explicitly present; others are dropped.
  • ON UPDATE CURRENT_TIMESTAMP clauses are removed from schema for consistency.
  • This conversion is MySQL-specific and applied in a schema upgrade script [app/code/core/Mage/Core/sql/maho_setup/maho-26.5.0.php].

SQLite Enhancements: Custom Functions

Because SQLite lacks several MySQL/PostgreSQL built-in functions, the SQLite adapter registers custom user-defined functions:

  • REGEXP: Uses PHP's preg_match to support regex matching in SQL queries.
  • GREATEST and LEAST: Emulated using PHP's max() and min() for scalar argument lists.

This ensures compatibility of queries using these functions regardless of platform.


CLI Integration for Database Access

Maho CLI commands provide convenient utilities to interact directly with the database using configured credentials:

db:connect

  • Opens an interactive shell (like mysql, psql, or sqlite3) using credentials from Maho’s configuration.
  • Maps to respective system clients depending on the database engine [lib/MahoCLI/Commands/DBConnect.php].

db:query

  • Allows executing arbitrary SQL queries via CLI.
  • Internally dispatches to the appropriate command line client with connection data, facilitating quick SQL execution.
  • Supports the three main platforms and fails gracefully on unsupported engines [lib/MahoCLI/Commands/DBQuery.php].

Summary

Maho's Database Adapter Interface provides:

  • A unified, object-oriented interface for database access built atop Doctrine DBAL.
  • Support for three major database engines with adapter classes catering to each engine's dialect and features.
  • A platform-agnostic query builder via Maho\Db\Select.
  • Nested transaction support via internal counting.
  • Cross-platform-compatible SQL helper method implementations.
  • Schema upgrade automation to align schema with multi-DB conventions.
  • Custom SQLite function provision for feature parity.
  • Tight integration with CLI tools for database access and query execution.

These design choices modernize Maho's data layer for reliability, maintainability, and extensibility across diverse deployment environments.


Sources