Code Monkey home page Code Monkey logo

db-mysql's Introduction

Yii MySQL

Yii Database MySQL and MariaDB driver


Latest Stable Version Total Downloads rector codecov StyleCI type-coverage

MySQL driver for Yii Database allows developers to access and interact with MySQL and MariaDB databases. It provides a set of classes and methods for connecting to a MySQL and MariaDB database, executing SQL queries, and managing data within the database. The package is designed to be easy to use and integrate, and supports a wide range of MySQL, MariaDB features and functions. It also includes support for transactions, database schema management, and error handling.

It is used in Yii Framework but can be used separately.

Support version

PHP MySQL/MariaDB Version CI-Actions
8.1-8.3 5.7-8.0/10.4-10.10 build ansi-mode Mutation testing badge static analysis

Installation

The package could be installed with Composer:

composer require yiisoft/db-mysql

Documentation

Check the documentation to learn about usage

If you need help or have a question, the Yii Forum is a good place for that. You may also check out other Yii Community Resources.

License

The Yii Database MySQL and MariaDB driver is free software. It is released under the terms of the BSD License. Please see LICENSE for more information.

Maintained by Yii Software.

Support the project

Open Collective

Follow updates

Official website Twitter Telegram Facebook Slack

db-mysql's People

Contributors

arhell avatar cebe avatar darkdef avatar dependabot-preview[bot] avatar dependabot[bot] avatar devanych avatar fantom409 avatar fcaldarelli avatar hiqsol avatar luizcmarin avatar machour avatar mister-42 avatar roxblnfk avatar rustamwin avatar samdark avatar stylecibot avatar terabytesoftw avatar tigrov avatar viktorprogger avatar vjik avatar xepozz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

db-mysql's Issues

Dependabot can't resolve your PHP dependency files

Dependabot can't resolve your PHP dependency files.

As a result, Dependabot couldn't update your dependencies.

The error Dependabot encountered was:

Your requirements could not be resolved to an installable set of packages.
  Problem 1
    - Installation request for yiisoft/view ^3.0@dev -> satisfiable by yiisoft/view[3.0.x-dev].
    - yiisoft/view 3.0.x-dev requires psr/event-dispatcher-implementation 1.0.0 -> no matching package found.
  Problem 2
    - Installation request for yiisoft/yii-web ^3.0@dev -> satisfiable by yiisoft/yii-web[3.0.x-dev].
    - yiisoft/yii-web 3.0.x-dev requires psr/http-factory-implementation 1.0 -> no matching package found.

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://getcomposer.org/doc/04-schema.md#minimum-stability> for more details.
 - It's a private package and you forgot to add a custom repository to find it

Read <https://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.

If you think the above is an error on Dependabot's side please don't hesitate to get in touch - we'll do whatever we can to fix it.

View the update logs.

MySQL loadColumnSchema: determine boolean columns

The method loadColumnSchema determines a column as a boolean only if db type is 'BIT(1)'.
https://github.com/yiisoft/yii2/blob/master/framework/db/mysql/Schema.php#L160

At the same time Schema::TYPE_BOOLEAN maps on 'tinyint(1)' for MySQL.
https://github.com/yiisoft/yii2/blob/master/framework/db/mysql/QueryBuilder.php#L41

The method loadColumnSchema for MS SQL is implemented in the right way. It considers both TINYINT(1) and BIT(1) types.
https://github.com/yiisoft/yii2/blob/master/framework/db/mssql/Schema.php#L203

I propose to change the line 160 in mysql/Schema.php to make it corresponding to the same method for MS SQL. After that the data types mapping will be proper.

if ($column->size === 1 && ($type === 'tinyint' || $type === 'bit')) {

This issue isn't theoretical. I created a migration with boolean column. Then I used gii to generate CRUD. But it generates a textField for boolean colums (not checkbox!). And it's not a gii fault, it's all about implementation of loadColumnSchema method for MySQL.

Schema::TYPE_TEXT is too short in MySQL

Schema::TYPE_TEXT converts to TEXT in MySQL. This is just 64K, which is not a lot. Unless it's in strict mode, MySQL will truncate anything longer when inserting, and not throw an error (it'll throw a warning, but you'll have to look in the mysql server log).
You can use MEDIUMTEXT and LONGTEXT for your fields, but that only works in MySQL, and not in Postgre and Sqlite for example (where TEXT is long enough), so if you're writing portable code, you can't just use 'MEDIUMTEXT'.
It's also likely that most developers will just use Yii's schema types, without knowing that the data is limited to 64K.

I see several possible solutions to this:

  1. Adding Schema::TYPE_MEDIUMTEXT and Schema::TYPE_LONGTEXT, similar to how we have TYPE_INTEGER and TYPE_BIGINT. This probably breaks BC, because custom QueryBuilders will be missing these types, and it also makes the typeMap more bloated, just because of a quirk in MySQL (unlike bigint, which is present in other databases). A developer using Postgre might not even care, since they won't have problems with TYPE_TEXT. I don't think this is a good solution.
  2. Changing \yii\db\mysql\QueryBuilder::$typeMap[Schema::TYPE_TEXT] to 'MEDIUMTEXT' or 'LONGTEXT'. This adds 1 or 2 extra bytes per field per row, which can add up if you have a lot of rows, but in typical use cases shouldn't matter much. It's better to have a safe default, and let those who know the trade-offs optimize it. This change would cause inconsistency in existing databases (fields that were created before the change would remain TEXT, new ones would become MEDIUMTEXT, while rebuilding the database using the new version would create all MEDIUMTEXT).
  3. Making the default configurable. You could have a setting that determines globally what Schema::TYPE_TEXT will be converted to in MySQL. You could default this to 'TEXT' for BC, but I think it would be a good idea to default it to 'MEDIUMTEXT' (maybe in Yii 2.1?).

I'm going to change the default to MEDIUMTEXT for my projects, overwriting the typeMap in mysql\QueryBuilder. Unfortunately, the query builder is not created using Yii::createObject, so I can't use DI to do this, and I'll have to extend both \yii\db\mysql\Schema and \yii\db\mysql\QueryBuilder, then overwrite the db connection's schemaMap (and I can't change just the mysql schema in the application configuration, I have to replace the whole thing). This is really inconvenient. Is there a better way to do this? I can use DI to replace the Schema at least.

update irc link

What steps will reproduce the problem?

http=>https

What is the expected result?

What do you get instead?

Additional info

Q A
Version 1.0.?
PHP version
Operating system

Prevent auto increment of primary key on duplicate values when `upsert()`

When attempting to upsert() duplicate values the autoincrement primary key will be incremented even if no duplicates are inserted.

$columns = ['unique_field' => 'unique value', 'field' => 'value'];
$command->upsert('table_name', $columns, false)->execute();

Generated query:

INSERT IGNORE INTO table_name (unique_field, field) VALUES ('unique value', 'value')

This can be solved by generating query without IGNORE

INSERT INTO table_name (unique_field, field)
SELECT 'unique value', 'value'
FROM DUAL
WHERE NOT EXISTS(
    SELECT 1
    FROM table_name
    WHERE unique_field = 'unique value'
)

Type blob is generated instead of binary Mysql 8.0

The field type binary(16) is converted to the blob type. MySQL 8.0 also has a binary type.

Example

$b->createTable('urls', [
    'id' => $b->bigPrimaryKey()->unsigned(),
    'hash' => $b->binary(16)->notNull()->comment('md5 from url')->asString(), // md5 binary
    'url' => $b->text()->notNull(),
    'create' => $b->timestamp()->notNull()->defaultExpression('CURRENT_TIMESTAMP')
]);

Result:

CREATE TABLE urls (
    id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    hash blob NOT NULL COMMENT 'md5 from url',
    url text NOT NULL,
    create timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP
);

Support MySQL datatype SET

A MySQL SET datatype should be mapped to an array. This would make it much easier to use in forms, e.g. in a checkboxList(). For now as a developer I have to write getter/setter which do the conversion between a csv string and an array.

public function getUserCountries()
{
    return explode(',', $this->user_countries);
}
public function setUserCountries($value)
{
    $this->user_countries = is_array($value) ? implode(',', $value) : '';
}

Funding

  • You can sponsor this specific effort via a Polar.sh pledge below
  • We receive the pledge once the issue is completed & verified
Fund with Polar

Dependabot can't resolve your PHP dependency files

Dependabot can't resolve your PHP dependency files.

As a result, Dependabot couldn't update your dependencies.

The error Dependabot encountered was:

Your requirements could not be resolved to an installable set of packages.
  Problem 1
    - Installation request for yiisoft/db-mysql No version set (parsed as 1.0.0) -> satisfiable by yiisoft/db-mysql[No version set (parsed as 1.0.0)].
    - yiisoft/db 3.0.x-dev requires yiisoft/db-mysql ^3.0@dev -> satisfiable by yiisoft/db-mysql[3.0.x-dev].
    - Can only install one of: yiisoft/db-mysql[3.0.x-dev, No version set (parsed as 1.0.0)].
    - Installation request for yiisoft/db ^3.0@dev -> satisfiable by yiisoft/db[3.0.x-dev].

If you think the above is an error on Dependabot's side please don't hesitate to get in touch - we'll do whatever we can to fix it.

View the update logs.

Cannot save other value in tinyint(1) other than 0 or 1 on mariadb

What steps will reproduce the problem?

Example code:

        $model = new Model($this->connection);// $connection is instance of Yiisoft\Db\Connection\ConnectionInterface
        $model->type = 5;
        $model->status = 4;
        $model->created_at = date('Y-m-d h:i:s');
        $model->updated_at = date('Y-m-d h:i:s');
        $model->save();
        $identifier = $model->primaryKey;
        $cmd = $this->connection->createCommand('SELECT * FROM ' . $model->tableName() . ' WHERE id = :id', [
            'id' => $identifier
        ]);
        $cmd->execute();
        var_dump($cmd->queryAll());

Example schema of model:

CREATE TABLE `model` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `type` tinyint(1) unsigned NOT NULL,
  `status` tinyint(1) unsigned NOT NULL DEFAULT 0 COMMENT '0: disable, 1: pending, 2: active, 3: error',
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

What is the expected result?

array(1) { [0]=> array(9) { ["id"]=> string(1) "4" ["type"]=> string(1) "5"  ["status"]=> string(1) "4" ["created_at"]=> string(19) "2023-01-29 03:24:48" ["updated_at"]=> string(19) "2023-01-29 03:24:48" } } 

What do you get instead?

array(1) { [0]=> array(9) { ["id"]=> string(1) "4" ["type"]=> string(1) "1"  ["status"]=> string(1) "1" ["created_at"]=> string(19) "2023-01-29 03:24:48" ["updated_at"]=> string(19) "2023-01-29 03:24:48" } } 

Additional info

Q A
Version 1.0.?
PHP version 8.1.14
MariaDB version 10.3.37
Operating system Linux Mint 20.3

Flag $emulatePrepare - false by default

Need set default value for $emulatePrepare = false
And removing all multi statement queries (with support special Stringable object for multi statement queries in resetSequence and other cases from query builders)

Restore connection if closed

What steps will reproduce the problem?

Need to use yii-runner-roadrunner or infinity loop service. After some time, db close connection and next query raise exception.

What is the expected result?

When I try to work with DB, I expect success exec.

What do you get instead?

Exception, in mysql:

{
  "type": "Yiisoft\\Db\\Exception\\IntegrityException",
  "message": "SQLSTATE[HY000]: General error: 2006 MySQL server has gone away\nThe SQL being executed was: SELECT * FROM `user` WHERE (`ex_id`=8) AND (`type_id`=1)",
  "code": 0,
  "file": "/home/babl/chat-backend/vendor/yiisoft/db/src/Exception/ConvertException.php",
  "line": 41,
  "trace": [
    {
      "file": "/home/babl/chat-backend/vendor/yiisoft/db/src/Driver/Pdo/AbstractPdoCommand.php",
      "line": 212,
      "function": "run",
      "class": "Yiisoft\\Db\\Exception\\ConvertException",
      "type": "->"
    },
    {
      "file": "/home/babl/chat-backend/vendor/yiisoft/db/src/Command/AbstractCommand.php",
      "line": 590,
      "function": "internalExecute",
      "class": "Yiisoft\\Db\\Driver\\Pdo\\AbstractPdoCommand",
      "type": "->"
    },
    {
      "file": "/home/babl/chat-backend/vendor/yiisoft/db/src/Driver/Pdo/AbstractPdoCommand.php",
      "line": 268,
      "function": "queryInternal",
      "class": "Yiisoft\\Db\\Command\\AbstractCommand",
      "type": "->"
    },
    {
      "file": "/home/babl/chat-backend/vendor/yiisoft/db/src/Command/AbstractCommand.php",
      "line": 460,
      "function": "queryInternal",
      "class": "Yiisoft\\Db\\Driver\\Pdo\\AbstractPdoCommand",
      "type": "->"
    },
    {
      "file": "/home/babl/chat-backend/vendor/yiisoft/db/src/Query/Query.php",
      "line": 538,
      "function": "queryOne",
      "class": "Yiisoft\\Db\\Command\\AbstractCommand",
      "type": "->"
    },
    {
      "file": "/home/babl/chat-backend/vendor/yiisoft/active-record/src/ActiveQuery.php",
      "line": 369,
      "function": "one",
      "class": "Yiisoft\\Db\\Query\\Query",
      "type": "->"
    }
]}
......

Additional info

Q A
Version dev-master
PHP version 8.3
Operating system Debian GNU/Linux

schema cache dependency with last updated migration

What steps will reproduce the problem?

Currently (yii2), can only bind the schema update to cache time.

  • large cache TTL -> notice the change slow
  • small cache TTL -> unnecessary check and slow query times

I suggest that the date of the last change to the migration table be used optionally:

  • large cache ttl
  • small check time
  • instantly reload schema
Q A
Version 1.0.0 under development
PHP version -
Operating system -

update src folder links

What steps will reproduce the problem?

http=>https

What is the expected result?

What do you get instead?

Additional info

Q A
Version 1.0.?
PHP version
Operating system

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.