Yii Database (yiisoft/db)

repository·master·Indexed 42 days ago

https://github.com/yiisoft/db

A framework-agnostic database abstraction layer (DAO) providing a unified API for interacting with MSSQL, MySQL, MariaDB, Oracle, PostgreSQL, and SQLite. It features a powerful query builder, command execution system for DDL and DML, schema metadata inspection, and support for database-agnostic quoting and table prefixing.

Tokens
44.1K
Snippets
156
Records
183
Agent score
52%

What's inside Yii Database

  1. Overview of Yii DB components

    master

    Yii DB is a DAO (Data Access Object) layer providing an object-oriented API for relational databases. It is designed to be database-agnostic and extensible.

    Core Components:

    • Connection: Manages the link to the database (supports MSSQL, MySQL, MariaDB, Oracle, PostgreSQL, and SQLite).
    • Command: Represents an SQL statement to be executed (supports DDL and DML).
    • Query Builder: A tool for constructing complex SQL statements programmatically.
    • Schema: Provides metadata inspection (table names, column names, etc.) and supports schema caching.
    • Logger & Profiler: Optional tools for monitoring and debugging queries.
  2. Use CompositeExpression to combine multiple SQL expressions

    master

    The Yiisoft\Db\Expression\CompositeExpression class allows you to combine multiple expressions into a single expression using a specified separator. This is particularly useful for complex ORDER BY clauses or building dynamic WHERE conditions.

    Key Behaviors:

    • Separator: Expressions are joined using a separator. If no separator is provided, a space ( ) is used by default.
    • Parameter Merging: Parameters from nested expressions are automatically collected and merged into the composite expression.
    • Ordering: Expressions are processed in the exact order they are provided in the array.
    • Security Warning: String expressions are not escaped. Avoid passing raw user input directly into string expressions to prevent SQL injection.
    use Yiisoft\Db\Expression\CompositeExpression;
    use Yiisoft\Db\Expression\Expression;
    use Yiisoft\Db\Expression\Value\ColumnName;
    
    // Example 1: Using a space as default separator
    new CompositeExpression([new ColumnName('id'), 'DESC']);
    
    // Example 2: Using a custom separator
    new CompositeExpression(['x = 1', 'y = 2'], ' AND ');
  3. Oracle Date and Time Formats

    master

    The Oracle driver automatically configures the session to use ISO 8601 date and time formats immediately after opening a connection. This ensures correct conversion of date and time values retrieved from the database. The driver executes the following SQL to set the session parameters:

    ALTER SESSION SET
        NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SSXFF'
        NLS_TIMESTAMP_TZ_FORMAT = 'YYYY-MM-DD HH24:MI:SSXFFTZH:TZM'
        NLS_TIME_FORMAT = 'HH24:MI:SSXFF'
        NLS_TIME_TZ_FORMAT = 'HH24:MI:SSXFFTZH:TZM'
        NLS_DATE_FORMAT = 'YYYY-MM-DD'
  4. Quote table and column names for database agnosticism

    master

    To write database-agnostic SQL that works across different DBMS (which have different quoting rules), use Yii DB's special quoting syntax:

    • [[column name]]: Encloses a column name in double square brackets to ensure it is quoted correctly.
    • {{%table name}}: Encloses a table name in double curly brackets. The % character is replaced by the configured table prefix.

    Yii DB automatically converts these constructs into the appropriate quoted identifiers for your specific database driver.

    use Yiisoft//Db/Connection/ConnectionInterface;
    
    /** @var ConnectionInterface $db */
    
    // This generates valid SQL for any supported database
    $result = $db->createCommand('SELECT COUNT([[id]]) FROM {{%employee}}')->queryScalar();
  5. Handle string values in Function Expressions using Value

    master

    When using function expression classes, the library treats string values as column names by default. To ensure a string is treated as a literal value rather than a column name, you must wrap it in a Value object.

    Exception: If a string contains a parenthesis (, it is treated as a raw SQL expression. To avoid ambiguity and ensure correct quoting, always use Value for literal strings.

    Example: new Longest(new Value('short'), 'column_name') renders as LONGEST('short', "column_name").

    use Yiisoft\Db\Expression\Value\Value;
    use Yiisoft\Db\Expression\Function\Longest;
    
    new Longest(new Value('short'), 'column_name');
  6. Upgrade from 1.x to 2.x: Constraint Changes

    master

    Constraint handling has been simplified. The generic Constraint class has been removed.

    Existing constraints have been renamed and moved to a more direct naming convention:

    • CheckConstraint $\rightarrow$ Check
    • DefaultValueConstraint $\rightarrow$ DefaultValue
    • ForeignKeyConstraint $\rightarrow$ ForeignKey
    • IndexConstraint $\rightarrow$ Index

    Implementation Note: Properties are now public readonly and must be initialized via the constructor. All previous methods have been removed; use the constructor for initialization and public properties to retrieve values.

  7. Use SQL expressions in queries and commands

    master

    The library provides classes implementing Yiisoft\Db\Expression\ExpressionInterface to represent complex SQL expressions. These expressions can be passed into various methods of Yiisoft\Db\Query\QueryInterface and Yiisoft\Db\Command\CommandInterface to inject raw or structured SQL logic instead of simple values.

    Common integration points include:

    • QueryInterface: select(), where(), having(), orderBy(), etc.
    • CommandInterface: insert(), update(), upsert(), etc.
  8. Upgrade from 1.x to 2.x: Column Schema and Types

    master

    The schema system has been refactored for better type safety and object-oriented usage.

    ColumnSchemaInterface (now ColumnInterface)

    Renamed to ColumnInterface and moved to Yiisoft//Db/Schema/Column. Key changes:

    • getName() can return string|null.
    • Added withName(), check(), getCheck(), reference(), getReference(), notNull(), null(), isUnique(), and hasDefaultValue() for method chaining.
    • Removed getPrecision() and getPhpType().
    • All AbstractColumn properties (except $type) are now passed via the constructor.

    Specialized Column Classes

    Each data type now has a dedicated class in the Yiisoft//Db/Schema/Column namespace:

    • BooleanColumn (boolean)
    • BitColumn (bit)
    • IntegerColumn (tinyint, smallint, integer, bigint)
    • BigIntColumn (out-of-range integers)
    • DoubleColumn (float, double, decimal, money)
    • StringColumn (char, string, text)
    • BinaryColumn (binary)
    • DateTimeColumn (timestamp, datetime, time, date)
    • ArrayColumn (array)
    • StructuredColumn (PostgreSQL composite types)
    • JsonColumn (json)
  9. Use Expression for raw SQL constructs

    master

    The Yiisoft\Db\Expression\Expression class allows you to include raw SQL fragments in your queries that do not require escaping or quoting. This is essential for using database functions (like NOW()), operators, or specific SQL constructs that the standard query builder methods do not support directly.

    use Yiisoft\Db\Expression\Expression;
    
    // Using a database function
    new Expression('NOW()');
    
    // Using column identifiers and operators
    new Expression('[[column1]] + [[column2]]');
  10. How schema caching works in yiisoft/db

    master
    To improve ORM performance, yiisoft/db uses Schema objects to retrieve database structure information. Instead of querying the database server every time, the Schema stores this information in a SchemaCache. When the Schema needs metadata, it first checks the cache to avoid unnecessary database roundtrips.
  11. Difference between Query and QueryBuilder

    master

    In the yiisoft/db package, there is a distinction between Yiisoft\Db\Query\Query and Yiisoft\Db\QueryBuilder\QueryBuilder:

    • Yiisoft\Db\Query\Query: This is the primary class intended for end-user use. It provides a high-level, fluent interface to represent SQL statements. When you call an execution method (like all()), it implicitly invokes the QueryBuilder.
    • Yiisoft\Db\QueryBuilder\QueryBuilder: This is the underlying engine responsible for the heavy lifting. It translates the abstract representation from Query into specific, DBMS-dependent SQL statements (e.g., handling the specific syntax for SELECT, FROM, WHERE, etc., for your specific database driver).
  12. Use Object format for advanced query building

    master

    The Object format uses specific condition classes to define logic. This is the most powerful method and is used when building custom abstractions. Condition objects are immutable and store data that a ConditionBuilder later transforms into SQL.

    Internally, other formats (string, hash, operator) are converted to this object format. You can mix formats by passing objects into andWhere() or where().

    Mapping of Operators to Classes:

    • AND $\rightarrow$ Yiisoft\Db\QueryBuilder\Condition\AndX
    • OR $\rightarrow$ Yiisoft\Db\QueryBuilder\Condition\OrX
    • NOT $\rightarrow$ Yiisoft\Db\QueryBuilder\Condition\Not
    • IN / NOT IN $\rightarrow$ Yiisoft\Db\QueryBuilder\Condition\In
    • BETWEEN / NOT BETWEEN $\rightarrow$ Yiisoft\Db\QueryBuilder\Condition\Between
    • ARRAY OVERLAPS $\rightarrow$ Yiisoft\Db\QueryBuilder\Condition\ArrayOverlaps
    • JSON OVERLAPS $\rightarrow$ Yiisoft\Db\QueryBuilder\Condition\JsonOverlaps
    use Yiisoft\Db\QueryBuilder\Condition\In;
    use Yiisoft\Db\QueryBuilder\Condition\OrX;
    use Yiisoft\Db\Query\Query;
    
    $query->andWhere(
        new OrX([
            new In('type', 'in', $types),
            ['like', 'name', '%good%'],
            'disabled=false',
        ]),
    );