{"id":20180760,"url":"https://github.com/webfiori/database","last_synced_at":"2026-05-11T09:56:46.282Z","repository":{"id":37740949,"uuid":"305740824","full_name":"WebFiori/database","owner":"WebFiori","description":"Database abstraction layer of WebFiori framework.","archived":false,"fork":false,"pushed_at":"2025-09-29T16:32:51.000Z","size":1737,"stargazers_count":5,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-09-29T17:13:39.492Z","etag":null,"topics":["database","hacktoberfest","mysql","php","webfiori-framework"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/WebFiori.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null},"funding":{"custom":["https://paypal.me/IbrahimBinAlshikh","https://www.buymeacoffee.com/ibrahimdev"],"ko_fi":"ibrahimdev"}},"created_at":"2020-10-20T14:48:24.000Z","updated_at":"2025-09-29T16:28:27.000Z","dependencies_parsed_at":"2023-02-01T10:30:36.921Z","dependency_job_id":"af749b98-3d85-4ace-86a8-d1b7a927dae3","html_url":"https://github.com/WebFiori/database","commit_stats":{"total_commits":531,"total_committers":2,"mean_commits":265.5,"dds":0.03578154425612057,"last_synced_commit":"ba067f3ece4b6678d7d9adfbc66969adfd73c14b"},"previous_names":[],"tags_count":72,"template":false,"template_full_name":null,"purl":"pkg:github/WebFiori/database","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WebFiori%2Fdatabase","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WebFiori%2Fdatabase/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WebFiori%2Fdatabase/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WebFiori%2Fdatabase/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/WebFiori","download_url":"https://codeload.github.com/WebFiori/database/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WebFiori%2Fdatabase/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279000855,"owners_count":26082951,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-09T02:00:07.460Z","response_time":59,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["database","hacktoberfest","mysql","php","webfiori-framework"],"created_at":"2024-11-14T02:32:50.766Z","updated_at":"2026-05-11T09:56:46.262Z","avatar_url":"https://github.com/WebFiori.png","language":"PHP","funding_links":["https://paypal.me/IbrahimBinAlshikh","https://www.buymeacoffee.com/ibrahimdev","https://ko-fi.com/ibrahimdev"],"categories":[],"sub_categories":[],"readme":"# Webfiori Database Abstraction Layer\n\nDatabase abstraction layer of WebFiori framework.\n\n\u003cp style=\"text-align: center\"\u003e\n  \u003ca href=\"https://github.com/WebFiori/database/actions\"\u003e\n    \u003cimg alt=\"PHP 8 Build Status\" src=\"https://github.com/WebFiori/database/actions/workflows/php85.yaml/badge.svg?branch=main\"\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://codecov.io/gh/WebFiori/database\"\u003e\n    \u003cimg alt=\"CodeCov\" src=\"https://codecov.io/gh/WebFiori/database/branch/main/graph/badge.svg?token=cDF6CxGTFi\" /\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://sonarcloud.io/dashboard?id=WebFiori_database\"\u003e\n      \u003cimg alt=\"Quality Checks\" src=\"https://sonarcloud.io/api/project_badges/measure?project=WebFiori_database\u0026metric=alert_status\" /\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://github.com/WebFiori/database/releases\"\u003e\n      \u003cimg alt=\"Version\" src=\"https://img.shields.io/github/release/WebFiori/database.svg?label=latest\" /\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://packagist.org/packages/webfiori/database\"\u003e\n      \u003cimg alt=\"Downloads\" src=\"https://img.shields.io/packagist/dt/webfiori/database?color=light-green\"\u003e\n  \u003c/a\u003e\n\u003c/p\u003e\n\n## Content \n\n* [Supported PHP Versions](#supported-php-versions)\n* [Supported Databases](#supported-databases)\n* [Features](#features)\n* [Installation](#installation)\n* [Usage](#usage)\n  * [Connecting to Database](#connecting-to-database)\n  * [Running Basic SQL Queries](#running-basic-sql-queries)\n  * [Building Database Structure](#building-database-structure)\n  * [Repository Pattern](#repository-pattern)\n  * [Active Record Pattern](#active-record-pattern)\n  * [Entity Generation](#entity-generation)\n  * [Database Migrations](#database-migrations)\n  * [Database Seeders](#database-seeders)\n  * [Performance Monitoring](#performance-monitoring)\n  * [Transactions](#transactions)\n\n## Supported PHP Versions\n|                                                                                           Build Status                                                                                            |\n|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|\n| \u003ca target=\"_blank\" href=\"https://github.com/WebFiori/database/actions/workflows/php81.yaml\"\u003e\u003cimg src=\"https://github.com/WebFiori/database/actions/workflows/php81.yaml/badge.svg?branch=main\"\u003e\u003c/a\u003e |\n| \u003ca target=\"_blank\" href=\"https://github.com/WebFiori/database/actions/workflows/php82.yaml\"\u003e\u003cimg src=\"https://github.com/WebFiori/database/actions/workflows/php82.yaml/badge.svg?branch=main\"\u003e\u003c/a\u003e |\n| \u003ca target=\"_blank\" href=\"https://github.com/WebFiori/database/actions/workflows/php83.yaml\"\u003e\u003cimg src=\"https://github.com/WebFiori/database/actions/workflows/php83.yaml/badge.svg?branch=main\"\u003e\u003c/a\u003e |\n| \u003ca target=\"_blank\" href=\"https://github.com/WebFiori/database/actions/workflows/php84.yaml\"\u003e\u003cimg src=\"https://github.com/WebFiori/database/actions/workflows/php84.yaml/badge.svg?branch=main\"\u003e\u003c/a\u003e |\n| \u003ca target=\"_blank\" href=\"https://github.com/WebFiori/database/actions/workflows/php85.yaml\"\u003e\u003cimg src=\"https://github.com/WebFiori/database/actions/workflows/php85.yaml/badge.svg?branch=main\"\u003e\u003c/a\u003e |\n\n## Supported Databases\n- MySQL\n- MSSQL\n\n## Features\n* Building your database structure within PHP\n* Fast and easy to use query builder\n* Database abstraction which makes it easy to migrate your system to different DBMS\n* Repository pattern with `AbstractRepository` for clean data access\n* Active Record pattern support for rapid development\n* PHP 8 attributes for table definitions\n* Database migrations and seeders\n* Performance monitoring and query analysis\n* Entity generation for object-relational mapping\n* Transaction support with automatic rollback\n\n## Installation\nTo install the library using composer, add following dependency to `composer.json`: `\"webfiori/database\":\"*\"`\n\n## Usage\n\n### Connecting to Database\n\nConnecting to a database is simple. First step is to define database connection information using the class `ConnectionInfo`. Later, the instance can be used to establish a connection to the database using the class `Database`.\n\n```php\nuse WebFiori\\Database\\ConnectionInfo;\nuse WebFiori\\Database\\Database;\n\n$connection = new ConnectionInfo('mysql', 'root', '123456', 'testing_db');\n$database = new Database($connection);\n```\n\n### Running Basic SQL Queries\n\nFor every query, the table must be specified using `Database::table(string $tblName)`. The method returns an `AbstractQuery` instance with methods for building queries:\n\n* `insert(array $cols)`: Construct an insert query.\n* `select(array $cols)`: Construct a select query.\n* `update(array $cols)`: Construct an update query.\n* `delete()`: Construct a delete query.\n* `where($col, $val)`: Adds a condition to the query.\n\nAfter building the query, call `execute()` to run it.\n\n```php\n// Insert\n$database-\u003etable('posts')-\u003einsert([\n    'title' =\u003e 'Super New Post',\n    'author' =\u003e 'Me'\n])-\u003eexecute();\n\n// Select\n$resultSet = $database-\u003etable('posts')\n    -\u003eselect()\n    -\u003ewhere('author', 'Ibrahim')\n    -\u003eexecute();\n\nforeach ($resultSet as $record) {\n    echo $record['title'];\n}\n\n// Update\n$database-\u003etable('posts')-\u003eupdate([\n    'title' =\u003e 'Updated Title',\n])-\u003ewhere('id', 1)-\u003eexecute();\n\n// Delete\n$database-\u003etable('posts')-\u003edelete()-\u003ewhere('id', 1)-\u003eexecute();\n```\n\n### Building Database Structure\n\nDefine database structure in PHP code using blueprints:\n\n```php\nuse WebFiori\\Database\\ColOption;\nuse WebFiori\\Database\\DataType;\n\n$database-\u003ecreateBlueprint('users')-\u003eaddColumns([\n    'id' =\u003e [\n        ColOption::TYPE =\u003e DataType::INT,\n        ColOption::PRIMARY =\u003e true,\n        ColOption::AUTO_INCREMENT =\u003e true\n    ],\n    'name' =\u003e [\n        ColOption::TYPE =\u003e DataType::VARCHAR,\n        ColOption::SIZE =\u003e 100\n    ],\n    'email' =\u003e [\n        ColOption::TYPE =\u003e DataType::VARCHAR,\n        ColOption::SIZE =\u003e 150\n    ]\n]);\n\n// Create the table\n$database-\u003etable('users')-\u003ecreateTable()-\u003eexecute();\n```\n\n### Repository Pattern\n\nThe `AbstractRepository` class provides a clean way to handle data access with separation between entities and database logic.\n\n#### Creating an Entity\n\n```php\nclass Product {\n    public ?int $id = null;\n    public string $name;\n    public float $price;\n}\n```\n\n#### Creating a Repository\n\n```php\nuse WebFiori\\Database\\Repository\\AbstractRepository;\n\nclass ProductRepository extends AbstractRepository {\n    protected function getTableName(): string {\n        return 'products';\n    }\n\n    protected function getIdField(): string {\n        return 'id';\n    }\n\n    protected function toEntity(array $row): object {\n        $product = new Product();\n        $product-\u003eid = (int) $row['id'];\n        $product-\u003ename = $row['name'];\n        $product-\u003eprice = (float) $row['price'];\n        return $product;\n    }\n\n    protected function toArray(object $entity): array {\n        return [\n            'id' =\u003e $entity-\u003eid,\n            'name' =\u003e $entity-\u003ename,\n            'price' =\u003e $entity-\u003eprice\n        ];\n    }\n}\n```\n\n#### Using the Repository\n\n```php\n$repo = new ProductRepository($database);\n\n// Create\n$product = new Product();\n$product-\u003ename = 'Widget';\n$product-\u003eprice = 29.99;\n$repo-\u003esave($product);\n\n// Read\n$product = $repo-\u003efindById(1);\n$allProducts = $repo-\u003efindAll();\n\n// Update\n$product-\u003eprice = 24.99;\n$repo-\u003esave($product);\n\n// Delete\n$repo-\u003edeleteById(1);\n\n// Pagination\n$page = $repo-\u003epaginate(page: 1, perPage: 20);\n```\n\n### Active Record Pattern\n\nFor rapid development, you can merge entity and repository into a single model class:\n\n```php\nuse WebFiori\\Database\\Attributes\\Column;\nuse WebFiori\\Database\\Attributes\\Table;\nuse WebFiori\\Database\\DataType;\nuse WebFiori\\Database\\Repository\\AbstractRepository;\n\n#[Table(name: 'articles')]\nclass Article extends AbstractRepository {\n    #[Column(type: DataType::INT, primary: true, autoIncrement: true)]\n    public ?int $id = null;\n\n    #[Column(type: DataType::VARCHAR, size: 200)]\n    public string $title = '';\n\n    #[Column(type: DataType::TEXT)]\n    public string $content = '';\n\n    protected function getTableName(): string { return 'articles'; }\n    protected function getIdField(): string { return 'id'; }\n    \n    protected function toEntity(array $row): object {\n        $article = new self($this-\u003edb);\n        $article-\u003eid = (int) $row['id'];\n        $article-\u003etitle = $row['title'];\n        $article-\u003econtent = $row['content'];\n        return $article;\n    }\n\n    protected function toArray(object $entity): array {\n        return [\n            'id' =\u003e $entity-\u003eid,\n            'title' =\u003e $entity-\u003etitle,\n            'content' =\u003e $entity-\u003econtent\n        ];\n    }\n}\n```\n\nUsage:\n\n```php\n// Create and save\n$article = new Article($database);\n$article-\u003etitle = 'Hello World';\n$article-\u003econtent = 'My first article';\n$article-\u003esave();\n\n// Query\n$all = $article-\u003efindAll();\n$one = $article-\u003efindById(1);\n\n// Update\n$article-\u003etitle = 'Updated Title';\n$article-\u003esave();\n\n// Delete\n$article-\u003edeleteById();\n\n// Reload from database\n$fresh = $article-\u003ereload();\n```\n\n### Entity Generation\n\nGenerate entity classes from table blueprints:\n\n```php\n$blueprint = $database-\u003egetTable('users');\n\n$generator = $blueprint-\u003egetEntityGenerator('User', __DIR__, 'App\\\\Entity');\n$generator-\u003egenerate();\n```\n\n### Database Migrations\n\nVersion control your database schema changes:\n\n```php\nuse WebFiori\\Database\\Schema\\AbstractMigration;\n\nclass CreateUsersTable extends AbstractMigration {\n    public function up(Database $db): void {\n        $db-\u003ecreateBlueprint('users')-\u003eaddColumns([\n            'id' =\u003e [ColOption::TYPE =\u003e DataType::INT, ColOption::PRIMARY =\u003e true, ColOption::AUTO_INCREMENT =\u003e true],\n            'name' =\u003e [ColOption::TYPE =\u003e DataType::VARCHAR, ColOption::SIZE =\u003e 100]\n        ]);\n        $db-\u003etable('users')-\u003ecreateTable()-\u003eexecute();\n    }\n    \n    public function down(Database $db): void {\n        $db-\u003eraw(\"DROP TABLE users\")-\u003eexecute();\n    }\n}\n```\n\nRun migrations:\n\n```php\nuse WebFiori\\Database\\Schema\\SchemaRunner;\n\n$runner = new SchemaRunner($connectionInfo);\n$runner-\u003ediscoverFromPath(__DIR__ . '/migrations', 'App\\\\Migrations');\n$runner-\u003ecreateSchemaTable();\n$runner-\u003eapply();\n```\n\n### Database Seeders\n\nPopulate your database with sample data:\n\n```php\nuse WebFiori\\Database\\Schema\\AbstractSeeder;\n\nclass UsersSeeder extends AbstractSeeder {\n    public function run(Database $db): void {\n        $db-\u003etable('users')-\u003einsert([\n            'name' =\u003e 'Administrator',\n            'email' =\u003e 'admin@example.com'\n        ])-\u003eexecute();\n    }\n}\n```\n\n### Performance Monitoring\n\nTrack and analyze query performance:\n\n```php\nuse WebFiori\\Database\\Performance\\PerformanceOption;\n\n$database-\u003esetPerformanceConfig([\n    PerformanceOption::ENABLED =\u003e true,\n    PerformanceOption::SLOW_QUERY_THRESHOLD =\u003e 50\n]);\n\n// Execute queries...\n\n$analyzer = $database-\u003egetPerformanceMonitor()-\u003egetAnalyzer();\necho \"Total queries: \" . $analyzer-\u003egetQueryCount();\necho \"Slow queries: \" . $analyzer-\u003egetSlowQueryCount();\n```\n\n### Transactions\n\nExecute multiple operations as a single unit:\n\n```php\n$database-\u003etransaction(function (Database $db) {\n    $db-\u003etable('users')-\u003einsert(['name' =\u003e 'John'])-\u003eexecute();\n    $db-\u003etable('profiles')-\u003einsert([\n        'user_id' =\u003e $db-\u003egetLastInsertId(),\n        'bio' =\u003e 'Developer'\n    ])-\u003eexecute();\n});\n```\n\n## Examples\n\nSee the [examples](examples/) directory for complete working examples:\n\n- [01-basic-connection](examples/01-basic-connection/) - Database connections\n- [02-basic-queries](examples/02-basic-queries/) - CRUD operations\n- [03-table-blueprints](examples/03-table-blueprints/) - Table structures\n- [04-entity-mapping](examples/04-entity-mapping/) - Entity generation\n- [05-transactions](examples/05-transactions/) - Transaction handling\n- [06-migrations](examples/06-migrations/) - Schema migrations\n- [07-seeders](examples/07-seeders/) - Data seeding\n- [08-performance-monitoring](examples/08-performance-monitoring/) - Query analysis\n- [09-multi-result-queries](examples/09-multi-result-queries/) - Stored procedures\n- [10-attribute-based-tables](examples/10-attribute-based-tables/) - PHP 8 attributes\n- [11-repository-pattern](examples/11-repository-pattern/) - Repository pattern\n- [12-clean-architecture](examples/12-clean-architecture/) - Domain separation\n- [13-pagination](examples/13-pagination/) - Pagination techniques\n- [14-active-record-model](examples/14-active-record-model/) - Active Record pattern\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwebfiori%2Fdatabase","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwebfiori%2Fdatabase","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwebfiori%2Fdatabase/lists"}