{"id":13404921,"url":"https://github.com/utopia-php/database","last_synced_at":"2026-04-02T19:13:51.671Z","repository":{"id":37013771,"uuid":"331726515","full_name":"utopia-php/database","owner":"utopia-php","description":"Lite \u0026 fast micro PHP database abstraction library that is **easy to use**.","archived":false,"fork":false,"pushed_at":"2026-03-31T05:07:24.000Z","size":15437,"stargazers_count":74,"open_issues_count":41,"forks_count":54,"subscribers_count":6,"default_branch":"main","last_synced_at":"2026-03-31T05:44:40.958Z","etag":null,"topics":["hacktoberfest","utopia-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/utopia-php.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","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}},"created_at":"2021-01-21T19:03:47.000Z","updated_at":"2026-03-30T23:40:54.000Z","dependencies_parsed_at":"2023-09-27T14:30:09.424Z","dependency_job_id":"409749b5-cc25-410b-add3-c70c0faa86c4","html_url":"https://github.com/utopia-php/database","commit_stats":{"total_commits":1412,"total_committers":22,"mean_commits":64.18181818181819,"dds":0.7471671388101984,"last_synced_commit":"b592ab1bab9d7412cf5b756fdcdf850c03b1470d"},"previous_names":[],"tags_count":372,"template":false,"template_full_name":null,"purl":"pkg:github/utopia-php/database","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/utopia-php%2Fdatabase","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/utopia-php%2Fdatabase/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/utopia-php%2Fdatabase/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/utopia-php%2Fdatabase/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/utopia-php","download_url":"https://codeload.github.com/utopia-php/database/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/utopia-php%2Fdatabase/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31314157,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-02T12:59:32.332Z","status":"ssl_error","status_checked_at":"2026-04-02T12:54:48.875Z","response_time":89,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"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":["hacktoberfest","utopia-framework"],"created_at":"2024-07-30T19:01:53.255Z","updated_at":"2026-04-02T19:13:51.651Z","avatar_url":"https://github.com/utopia-php.png","language":"PHP","funding_links":[],"categories":["PHP"],"sub_categories":[],"readme":"# Utopia Database\n\n[![Build Status](https://travis-ci.org/utopia-php/database.svg?branch=master)](https://travis-ci.com/utopia-php/database)\n![Total Downloads](https://img.shields.io/packagist/dt/utopia-php/database.svg)\n[![Discord](https://img.shields.io/discord/564160730845151244?label=discord)](https://appwrite.io/discord)\n\nUtopia framework database library is simple and lite library for managing application persistency using multiple database adapters. This library is aiming to be as simple and easy to learn and use. This library is maintained by the [Appwrite team](https://appwrite.io).\n\nAlthough this library is part of the [Utopia Framework](https://github.com/utopia-php/framework) project it is dependency free, and can be used as standalone with any other PHP project or framework.\n\n## Getting Started\n\nInstall using composer:\n\n```bash\ncomposer require utopia-php/database\n```\n\n### Concepts\n\nA list of the utopia/php concepts and their relevant equivalent using the different adapters\n\n- **Database** - An instance of the utopia/database library that abstracts one of the supported adapters and provides a unified API for CRUD operation and queries on a specific schema or isolated scope inside the underlining database.\n- **Adapter** - An implementation of an underlying database engine that this library can support - below is a list of [supported databases](#supported-databases) and supported capabilities for each Database.\n- **Collection** - A set of documents stored on the same adapter scope. For SQL-based adapters, this will be equivalent to a table. For a No-SQL adapter, this will equivalent to a native collection.\n- **Document** - A simple JSON object that will be stored in one of the utopia/database collections. For SQL-based adapters, this will be equivalent to a row. For a No-SQL adapter, this will equivalent to a native document.\n- **Attribute** - A simple document attribute. For SQL-based adapters, this will be equivalent to a column. For a No-SQL adapter, this will equivalent to a native document field.\n- **Index** - A simple collection index used to improve the performance of your database queries.\n- **Permissions** - Using permissions, you can decide which roles have read, create, update and delete access for a specific document. The special attribute `$permissions` is used to store permission metadata for each document in the collection. A permission role can be any string you want. You can use `$authorization-\u003eaddRole()` to delegate new roles to your users, once obtained a new role a user would gain read, create, update or delete access to a relevant document.\n\n### Filters\n\nAttribute filters are functions that manipulate attributes before saving them to the database and after retrieving them from the database. You can add filters using the `Database::addFilter($name, $encode, $decode)` where `$name` is the name of the filter that we can add later to attribute `filters` array. `$encode` and `$decode` are the functions used to encode and decode the attribute, respectively. There are also instance-level filters that can only be defined while constructing the `Database` instance. Instance level filters override the static filters if they have the same name.\n\n### Custom Document Types\n\nThe database library supports mapping custom document classes to specific collections, enabling a domain-driven design approach. This allows you to create collection-specific classes (like `User`, `Post`, `Product`) that extend the base `Document` class with custom methods and business logic.\n\n```php\n// Define a custom document class\nclass User extends Document\n{\n    public function getEmail(): string\n    {\n        return $this-\u003egetAttribute('email', '');\n    }\n\n    public function isAdmin(): bool\n    {\n        return $this-\u003egetAttribute('role') === 'admin';\n    }\n}\n\n// Register the custom type\n$database-\u003esetDocumentType('users', User::class);\n\n// Now all documents from 'users' collection are User instances\n$user = $database-\u003egetDocument('users', 'user123');\n$email = $user-\u003egetEmail(); // Use custom methods\nif ($user-\u003eisAdmin()) {\n    // Domain logic\n}\n```\n\n**Benefits:**\n- ✅ Domain-driven design with business logic in domain objects\n- ✅ Type safety with IDE autocomplete for custom methods\n- ✅ Code organization and encapsulation\n- ✅ Fully backwards compatible\n\n### Reserved Attributes\n\n- `$id` - the document unique ID, you can set your own custom ID or a random UID will be generated by the library.\n- `$createdAt` - the document creation date, this attribute is automatically set when the document is created.\n- `$updatedAt` - the document update date, this attribute is automatically set when the document is updated.\n- `$collection` - an attribute containing the name of the collection the document is stored in.\n- `$permissions` - an attribute containing an array of strings. Each string represent a specific action and role. If your user obtains that role for that action they will have access for this document.\n\n### Attribute Types\n\nThe database document interface only supports primitives types (`strings`, `integers`, `floats`, and `booleans`) translated to their native database types for each of the relevant database adapters. Complex types like arrays or objects will be encoded to JSON strings when stored and decoded back when fetched from their adapters.\n\n### Supported Databases\n\nBelow is a list of supported databases, and their compatibly tested versions alongside a list of supported features and relevant limits.\n\n| Adapter  | Status | Version |\n|----------|--------|---------|\n| MariaDB  | ✅      | 10.5    |\n| MySQL    | ✅      | 8.0     |\n| Postgres | ✅      | 13.0    |\n| SQLite   | ✅      | 3.38    |\n\n` ✅  - supported `\n\n` 🛠  - work in progress`\n\n### Limitations \n\n#### MariaDB, MySQL, Postgres, SQLite\n- ID max size can be 255 bytes\n- ID can only contain [^A-Za-z0-9] and symbols `_` `-`\n- Document max size is 65535 bytes\n- Collection can have a max of 1017 attributes\n- Collection can have a max of 64 indexes\n- Index value max size is 768 bytes. Values over 768 bytes are truncated\n- String max size is 4294967295 characters\n- Integer max size is 4294967295 \n\n#### MongoDB\n- ID max size can be 255 bytes\n- ID can only contain [^A-Za-z0-9] and symbols `_` `-`\n- Document can have unrestricted size\n- Collection can have unrestricted amount of attributes \n- Collection can have a max of 64 indexes\n- Index value can have unrestricted size\n- String max size is 2147483647 characters \n- Integer max size is 4294967295 \n\n## Usage\n\n### Connecting to a Database \n\n#### MariaDB\n\n```php\nrequire_once __DIR__ . '/vendor/autoload.php';\n\nuse PDO;\nuse Utopia\\Database\\Database;\nuse Utopia\\Cache\\Cache;\nuse Utopia\\Cache\\Adapter\\Memory;\nuse Utopia\\Database\\Adapter\\MariaDB;\n\n$dbHost = 'mariadb';\n$dbPort = '3306';\n$dbUser = 'root';\n$dbPass = 'password';\n$pdoConfig = [\n    PDO::ATTR_TIMEOUT =\u003e 3, // Seconds\n    PDO::ATTR_PERSISTENT =\u003e true,\n    PDO::ATTR_DEFAULT_FETCH_MODE =\u003e PDO::FETCH_ASSOC,\n    PDO::ATTR_ERRMODE =\u003e PDO::ERRMODE_EXCEPTION,\n    PDO::ATTR_EMULATE_PREPARES =\u003e true,\n    PDO::ATTR_STRINGIFY_FETCHES =\u003e true,\n];\n\n$pdo = new PDO(\"mysql:host={$dbHost};port={$dbPort};charset=utf8mb4\", $dbUser, $dbPass, $pdoConfig);\n\n$cache = new Cache(new Memory()); // or use any cache adapter you wish\n\n$database = new Database(new MariaDB($pdo), $cache);\n```\n\n#### MySQL\n\n```php\nrequire_once __DIR__ . '/vendor/autoload.php';\n\nuse PDO;\nuse Utopia\\Database\\Database;\nuse Utopia\\Cache\\Cache;\nuse Utopia\\Cache\\Adapter\\Memory;\nuse Utopia\\Database\\Adapter\\MySQL;\n\n$dbHost = 'mysql';\n$dbPort = '3306';\n$dbUser = 'root';\n$dbPass = 'password';\n$pdoConfig = [\n    PDO::ATTR_TIMEOUT =\u003e 3, // Seconds\n    PDO::ATTR_PERSISTENT =\u003e true,\n    PDO::ATTR_DEFAULT_FETCH_MODE =\u003e PDO::FETCH_ASSOC,\n    PDO::ATTR_ERRMODE =\u003e PDO::ERRMODE_EXCEPTION,\n    PDO::ATTR_EMULATE_PREPARES =\u003e true,\n    PDO::ATTR_STRINGIFY_FETCHES =\u003e true,\n];\n\n$pdo = new PDO(\"mysql:host={$dbHost};port={$dbPort};charset=utf8mb4\", $dbUser, $dbPass, $pdoConfig);\n\n$cache = new Cache(new Memory()); // or use any cache adapter you wish\n\n$database = new Database(new MySql($pdo), $cache);\n```\n\n#### Postgres\n\n```php\nrequire_once __DIR__ . '/vendor/autoload.php';\n\nuse PDO;\nuse Utopia\\Database\\Database;\nuse Utopia\\Cache\\Cache;\nuse Utopia\\Cache\\Adapter\\Memory;\nuse Utopia\\Database\\Adapter\\Postgres;\n\n$dbHost = 'postgres';\n$dbPort = '5432';\n$dbUser = 'root';\n$dbPass = 'password';\n$pdoConfig = [\n    PDO::ATTR_TIMEOUT =\u003e 3, // Seconds\n    PDO::ATTR_PERSISTENT =\u003e true,\n    PDO::ATTR_DEFAULT_FETCH_MODE =\u003e PDO::FETCH_ASSOC,\n    PDO::ATTR_ERRMODE =\u003e PDO::ERRMODE_EXCEPTION,\n    PDO::ATTR_EMULATE_PREPARES =\u003e true,\n    PDO::ATTR_STRINGIFY_FETCHES =\u003e true,\n];\n\n$pdo = new PDO(\"pgsql:host={$dbHost};port={$dbPort};charset=utf8mb4\", $dbUser, $dbPass, $pdoConfig);\n\n$cache = new Cache(new Memory()); // or use any cache adapter you wish\n\n$database = new Database(new Postgres($pdo), $cache);\n```\n\n#### SQLite\n\n```php\nrequire_once __DIR__ . '/vendor/autoload.php';\n\nuse PDO;\nuse Utopia\\Database\\Database;\nuse Utopia\\Cache\\Cache;\nuse Utopia\\Cache\\Adapter\\Memory;\nuse Utopia\\Database\\Adapter\\SQLite;\n\n$dbPath = '/path/to/database.sqlite';\n$pdoConfig = [\n    PDO::ATTR_TIMEOUT =\u003e 3, // Seconds\n    PDO::ATTR_PERSISTENT =\u003e true,\n    PDO::ATTR_DEFAULT_FETCH_MODE =\u003e PDO::FETCH_ASSOC,\n    PDO::ATTR_ERRMODE =\u003e PDO::ERRMODE_EXCEPTION,\n    PDO::ATTR_EMULATE_PREPARES =\u003e true,\n    PDO::ATTR_STRINGIFY_FETCHES =\u003e true,\n];\n\n$pdo = new PDO(\"sqlite:{$dbPath}\", $pdoConfig);\n\n$cache = new Cache(new Memory()); // or use any cache adapter you wish\n\n$database = new Database(new SQLite($pdo), $cache);\n```\n\n#### MongoDB\n\n```php\nrequire_once __DIR__ . '/vendor/autoload.php';\n\nuse Utopia\\Database\\Database;\nuse Utopia\\Cache\\Cache;\nuse Utopia\\Cache\\Adapter\\Memory;\nuse Utopia\\Database\\Adapter\\Mongo;\nuse Utopia\\Mongo\\Client; // from utopia-php/mongo\n\n$dbHost = 'mongo';\n$dbPort = 27017; \n$dbUser = 'root';\n$dbPass = 'password';\n$dbName = 'dbName';\n\n$mongoClient = new Client($dbName, $dbHost, $dbPort, $dbUser, $dbPass, true);\n\n$cache = new Cache(new Memory()); // or use any cache adapter you wish\n\n$database = new Database(new Mongo($mongoClient), $cache);\n```\n\n### Database Methods\n\n```php\n\n// Get namespace\n$database-\u003egetNamespace();\n\n// Sets namespace that prefixes all collection names\n$database-\u003esetNamespace(\n    namespace: 'namespace'\n);\n\n// Get default database\n$database-\u003egetDatabase();\n\n// Sets default database\n$database-\u003esetDatabase(\n    name: 'dbName'\n);\n\n// Creates a new database. \n// Uses default database as the name.\n$database-\u003ecreate();\n\n// Returns an array of all databases\n$database-\u003elist();\n\n// Delete database\n$database-\u003edelete(\n    name: 'mydb'\n);\n\n// Ping database it returns true if the database is alive\n$database-\u003eping();\n\n// Check if database exists\n$database-\u003eexists(\n    database: 'mydb'\n); \n\n// Check if collection exists\n$database-\u003eexists(\n    database: 'mydb',\n    collection: 'users'\n); \n\n// Listen to events\n\n// Event Types\nDatabase::EVENT_ALL\nDatabase::EVENT_DATABASE_CREATE,\nDatabase::EVENT_DATABASE_LIST,\nDatabase::EVENT_COLLECTION_CREATE,\nDatabase::EVENT_COLLECTION_LIST,\nDatabase::EVENT_COLLECTION_READ,\nDatabase::EVENT_ATTRIBUTE_CREATE,\nDatabase::EVENT_ATTRIBUTE_UPDATE,\nDatabase::EVENT_INDEX_CREATE,\nDatabase::EVENT_DOCUMENT_CREATE,\nDatabase::EVENT_DOCUMENT_UPDATE,\nDatabase::EVENT_DOCUMENT_READ,\nDatabase::EVENT_DOCUMENT_FIND,\nDatabase::EVENT_DOCUMENT_COUNT,\nDatabase::EVENT_DOCUMENT_SUM,\nDatabase::EVENT_DOCUMENT_INCREASE,\nDatabase::EVENT_DOCUMENT_DECREASE,\nDatabase::EVENT_INDEX_DELETE,\nDatabase::EVENT_DOCUMENT_DELETE,\nDatabase::EVENT_ATTRIBUTE_DELETE,\nDatabase::EVENT_COLLECTION_DELETE,\nDatabase::EVENT_DATABASE_DELETE,\n\n$database-\u003eon(\n    Database::EVENT_ALL, \n    function($event, $data) {\n        // Do something\n    }\n);\n\n// Get Database Adapter\n$database-\u003egetAdapter();\n\n// Get List of keywords that cannot be used\n$database-\u003egetKeywords();\n```\n\n### Collection Methods\n\n```php\n// Creates two new collection named '$namespace_$collectionName' with attribute names '_id', '_uid', '_createdAt', '_updatedAt', '_permissions' \n// The second collection is named '$namespace_$collectionName_perms' with attribute names '_id', '_type', '_permission', '_document'\n$database-\u003ecreateCollection(\n    id: 'users'\n);\n\n// Create collection with attributes and indexes\n$attributes = [\n     new Document([\n         '$id' =\u003e ID::unique(),\n         '$permissions' =\u003e [\n            Permission::read(Role::any()),\n            Permission::update(Role::any()),\n            Permission::delete(Role::any())\n         ],\n         'name' =\u003e 'Jhon', \n         'age'  =\u003e  20\n     ]),\n     new Document([\n         '$id' =\u003e ID::unique(),\n         '$permissions' =\u003e [\n            Permission::read(Role::any()),\n            Permission::update(Role::any()),\n            Permission::delete(Role::any())\n         ],\n         'name' =\u003e 'Doe', \n         'age'  =\u003e  34\n     ]),\n]\n\n$indexes = [\n     new Document([\n            '$id' =\u003e ID::unique(),\n            'type' =\u003e Database::INDEX_KEY,\n            'attributes' =\u003e ['name'],\n            'lengths' =\u003e [256],\n            'orders' =\u003e ['ASC'],\n        ]),\n     new Document([\n            '$id' =\u003e ID::unique(),\n            'type' =\u003e Database::INDEX_KEY,\n            'attributes' =\u003e ['name', 'age'],\n            'lengths' =\u003e [128, 128],\n            'orders' =\u003e ['ASC'],\n        ])\n];\n\n$database-\u003ecreateCollection(\n    id: 'users', \n    attributes: $attributes, \n    indexes: $indexes\n);\n\n// Update Collection Permissions\n$database-\u003eupdateCollection(\n    id: 'users',\n    permissions: [\n        Permission::read(Role::any()),\n        Permission::update(Role::any()),\n        Permission::delete(Role::any())\n    ],\n    documentSecurity: true\n);\n\n// Get Collection\n$database-\u003egetCollection(\n    id: 'users'\n);\n\n// List Collections\n$database-\u003elistCollections(\n    limit: 25, \n    offset: 0\n);\n\n// Deletes the two collections named 'namespace_$collectionName' and 'namespace_$collectionName_perms'\n$database-\u003edeleteCollection(\n    id: 'users'\n);\n\n// Delete cached documents of a collection\n$database-\u003epurgeCachedCollection(\n    collection: 'users'\n);\n```\n\n### Attribute Methods\n\n```php\n// Data types\nDatabase::VAR_STRING      \nDatabase::VAR_INTEGER\nDatabase::VAR_FLOAT\nDatabase::VAR_BOOLEAN  \nDatabase::VAR_DATETIME\n\n\n// Creates a new attribute named '$attributeName' in the '$namespace_$collectionName' collection.\n$database-\u003ecreateAttribute(\n    collection: 'movies',\n    id: 'name',\n    type:  Database::VAR_STRING,\n    size: 128, \n    required: true\n);\n\n// New attribute with optional parameters\n$database-\u003ecreateAttribute(\n    collection: 'movies', \n    id: 'genres',\n    type: Database::VAR_STRING, \n    size: 128, \n    required: true, \n    default: null, \n    signed: true, \n    array: false, \n    format: null, \n    formatOptions: [], \n    filters: []\n);\n\n// Updates the attribute named '$attributeName' in the '$namespace_$collectionName' collection.\n$database-\u003e updateAttribute(\n    collection: 'movies', \n    id: 'genres',\n    type: Database::VAR_STRING, \n    size: 128, \n    required: true, \n    default: null, \n    signed: true, \n    array: false, \n    format: null, \n    formatOptions: [], \n    filters: []\n);\n\n// Update the required status of an attribute\n$database-\u003eupdateAttributeRequired(\n    collection: 'movies', \n    id: 'genres',\n    required: true\n);\n\n// Update the attribute format\n$database-\u003eupdateAttributeFormat(\n    collection: 'movies', \n    id: 'genres',\n    format: null,\n);\n\n// Update the attribute format options\n$database-\u003eupdateAttributeFormatOptions(\n    collection: 'movies', \n    id: 'genres',\n    formatOptions: []\n);\n\n// Update the attribute filters\n$database-\u003eupdateAttributeFilters(\n    collection: 'movies', \n    id: 'genres',\n    filters: []\n);\n\n// Update the default value of an attribute\n$database-\u003eupdateAttributeDefault(\n    collection: 'movies', \n    id: 'genres',\n    default: 'sci-fi'\n);\n\n// Check if attribute can be added to a collection\n$collection = $database-\u003egetCollection('movies');\n\n$attribute = new Document([\n    '$id' =\u003e ID::unique(),\n    'type' =\u003e Database::VAR_INTEGER,\n    'size' =\u003e 256,\n    'required' =\u003e true,\n    'default' =\u003e null,\n    'signed' =\u003e true,\n    'array' =\u003e false,\n    'filters' =\u003e [],\n]);\n\n$database-\u003echeckAttribute(\n    collection: $collection,\n    attribute: $attribute\n);\n\n// Get Adapter attribute limit\n$database-\u003egetLimitForAttributes(); // if 0 then no limit\n\n// Get Adapter index limit\n$database-\u003egetLimitForIndexes(); \n\n// Renames the attribute from old to new in the '$namespace_$collectionName' collection.\n$database-\u003erenameAttribute(\n    collection: 'movies',\n    old: 'genres', \n    new: 'genres2'\n);\n\n// Deletes the attribute in the '$namespace_$collectionName' collection.\n$database-\u003edeleteAttribute(\n    collection: 'movies', \n    id: 'genres'\n);\n```\n\n### Index Methods\n\n```php\n// Index types\nDatabase::INDEX_KEY,                 \nDatabase::INDEX_FULLTEXT\nDatabase::INDEX_UNIQUE\nDatabase::INDEX_SPATIAL\nDatabase::INDEX_ARRAY\n\n// Insertion Order                                 \nDatabase::ORDER_ASC\nDatabase::ORDER_DESC\n   \n\n// Creates a new index named '$indexName' in the '$namespace_$collectionName' collection.\n// Note: The size for the index will be taken from the size of the attribute\n$database-\u003ecreateIndex(\n    collection: 'movies', \n    id: 'index1', Database::INDEX_KEY, \n    attributes: ['name', 'genres'], \n    lengths: [128,128], \n    orders: [Database::ORDER_ASC, Database::ORDER_DESC]\n);\n\n// Rename index from old to new in the '$namespace_$collectionName' collection.\n$database-\u003erenameIndex(\n    collection: 'movies', \n    old: 'index1', \n    new: 'index2'\n);\n\n// Deletes the index in the '$namespace_$collectionName' collection.\n$database-\u003edeleteIndex(\n    collection: 'movies', \n    id: 'index2'\n);\n``` \n\n### Relationship Methods\n\n```php\n// Relationship types\nDatabase::RELATION_ONE_TO_ONE\nDatabase::RELATION_ONE_TO_MANY\nDatabase::RELATION_MANY_TO_ONE\nDatabase::RELATION_MANY_TO_MANY\n\n// Creates a relationship between the two collections with the default reference attributes\n$database-\u003ecreateRelationship(\n    collection: 'movies', \n    relatedCollection: 'users', \n    type: Database::RELATION_ONE_TO_ONE,\n    twoWay: true\n);\n\n\n// Create a relationship with custom reference attributes\n$database-\u003ecreateRelationship(\n    collection: 'movies', \n    relatedCollection: 'users', \n    type: Database::RELATION_ONE_TO_ONE, \n    twoWay: true, \n    id: 'movies_id', \n    twoWayKey: 'users_id'\n); \n\n// Relationship onDelete types\nDatabase::RELATION_MUTATE_CASCADE, \nDatabase::RELATION_MUTATE_SET_NULL,\nDatabase::RELATION_MUTATE_RESTRICT,\n\n// Update the relationship with the default reference attributes\n$database-\u003eupdateRelationship(\n    collection: 'movies', \n    id: 'users', \n    onDelete: Database::RELATION_MUTATE_CASCADE\n); \n\n// Update the relationship with custom reference attributes\n$database-\u003eupdateRelationship(\n    collection: 'movies', \n    id: 'users', \n    onDelete: Database::RELATION_MUTATE_CASCADE, \n    newKey: 'movies_id', \n    newTwoWayKey: 'users_id', \n    twoWay: true\n);\n\n// Delete the relationship with the default or custom reference attributes\n$database-\u003edeleteRelationship(\n    collection: 'movies', \n    id: 'users'\n);\n```\n\n### Document Methods\n\n```php\nuse Utopia\\Database\\Document;             \nuse Utopia\\Database\\Helpers\\ID;\nuse Utopia\\Database\\Helpers\\Permission;\nuse Utopia\\Database\\Helpers\\Role;\n\n// Id helpers\nID::unique(padding: 12)        // Creates an id of length 7 + padding\nID::custom(id: 'my_user_3235')  \n\n// Role helpers\nRole::any()\nRole::guests()\nRole::user(\n    identifier: ID::unique()\n    status: 'active' //optional\n)    \nRole::users()\nRole::team(\n    identifier: ID::unique()\n)\nRole::team(\n    identifier: ID::unique()\n    dimension: '123'  //team:id/dimension\n)\nRole::label(\n    identifier: 'admin'\n)\nRole::members(\n    identifier: ID::unique()\n)\n\n\n\n// Permission helpers\nPermission::read(Role::any()),\nPermission::create(Role::user(ID::unique())),\nPermission::update(Role::user(ID::unique(padding: 23))),\nPermission::delete(Role::user(ID::custom(id: 'my_user_3235')))\n\n// To create a document\n$document = new Document([\n    '$permissions' =\u003e [\n        Permission::read(Role::any()),\n        Permission::create(Role::user(ID::custom('1x'))),\n        Permission::update(Role::user(ID::unique(12))),\n        Permission::delete(Role::user($customId)),\n    ],\n    '$id' =\u003e ID::unique(),\n    'name' =\u003e 'Captain Marvel',\n    'director' =\u003e 'Anna Boden \u0026 Ryan Fleck',\n    'year' =\u003e 2019,\n    'price' =\u003e 25.99,\n    'active' =\u003e true,\n    'genres' =\u003e ['science fiction', 'action', 'comics'],\n]);\n\n$document = $database-\u003ecreateDocument(\n    collection: 'movies', \n    document: $document\n);\n\n// Get which collection a document belongs to\n$document-\u003egetCollection();\n\n// Get document id\n$document-\u003egetId();\n\n// Check whether document in empty\n$document-\u003eisEmpty();\n\n// Increase an attribute in a document \n$database-\u003eincreaseDocumentAttribute(\n    collection: 'movies', \n    id: $document-\u003egetId(),\n    attribute: 'name', \n    value: 24,\n    max: 100\n);\n\n// Decrease an attribute in a document\n$database-\u003edecreaseDocumentAttribute(\n    collection: 'movies', \n    id: $document-\u003egetId(),\n    attribute: 'name', \n    value: 24, \n    min: 100\n);\n\n// Update the value of an attribute in a document\n\n// Set types\nDocument::SET_TYPE_ASSIGN, // Assign the new value directly\nDocument::SET_TYPE_APPEND, // Append the new value to end of the array\nDocument::SET_TYPE_PREPEND // Prepend the new value to start of the array\nNote: Using append/prepend with an attribute which is not an array, it will be set to an array containing the new value.\n\n$document-\u003esetAttribute(key: 'name', 'Chris Smoove')\n         -\u003esetAttribute(key: 'age', 33, Document::SET_TYPE_ASSIGN);\n\n$database-\u003eupdateDocument(\n    collection: 'users', \n    id: $document-\u003egetId(), \n    document: $document\n);         \n\n// Update the permissions of a document\n$document-\u003esetAttribute('$permissions', Permission::read(Role::any()), Document::SET_TYPE_APPEND)\n         -\u003esetAttribute('$permissions', Permission::create(Role::any()), Document::SET_TYPE_APPEND)\n         -\u003esetAttribute('$permissions', Permission::update(Role::any()), Document::SET_TYPE_APPEND)\n         -\u003esetAttribute('$permissions', Permission::delete(Role::any()), Document::SET_TYPE_APPEND)\n\n$database-\u003eupdateDocument(\n    collection: 'users', \n    id: $document-\u003egetId(), \n    document: $document\n);\n\n// Info regarding who has permission to read, create, update and delete a document\n$document-\u003egetRead(); // returns an array of roles that have permission to read the document\n$document-\u003egetCreate(); // returns an array of roles that have permission to create the document\n$document-\u003egetUpdate(); // returns an array of roles that have permission to update the document\n$document-\u003egetDelete(); // returns an array of roles that have permission to delete the document\n\n// Get document with all attributes\n$database-\u003egetDocument(\n    collection: 'movies', \n    id: $document-\u003egetId()\n); \n\n// Get document with a sub-set of attributes\n$database-\u003egetDocument(\n    collection: 'movies', \n    id: $document-\u003egetId(), \n    queries: [\n        Query::select(['name', 'director', 'year'])\n    ]\n);\n\n// Find documents \n\n// Query Types\nQuery::equal(attribute: \"...\", values: [\"...\", \"...\"]),\nQuery::notEqual(attribute: \"...\", value: \"...\"),\nQuery::lessThan(attribute: \"...\", value: 100),\nQuery::lessThanEqual(attribute: \"...\", value: 1000),\nQuery::greaterThan(attribute: \"...\", value: 1000),\nQuery::greaterThanEqual(attribute: \"...\", value: ...),  \nQuery::contains(attribute: \"...\", values: [\"...\", \"...\"]),\nQuery::between(attribute: \"...\", start: 100, end: 1000),\nQuery::search(attribute: \"...\", value: \"...\"),\nQuery::select(attributes: [\"...\", \"...\"]),\nQuery::orderDesc(attribute: \"...\"),\nQuery::orderAsc(attribute: \"...\"),\nQuery::isNull(attribute: \"...\"),\nQuery::isNotNull(attribute: \"...\"),\nQuery::startsWith(attribute: \"...\", value: \"...\"),\nQuery::endsWith(attribute: \"...\", value: \"...\"),\nQuery::limit(value: 35),\nQuery::offset(value: 0),\n\n$database-\u003efind(\n    collection: 'movies', \n    queries:  [\n        Query::equal(attribute: 'name', values: ['Captain Marvel']),\n        Query::notEqual(attribute: 'year', value: 2019)\n    ], \n    timeout: 1 //timeout is optional\n);  \n\n// Find a document \n$database-\u003efindOne(\n    collection: 'movies', \n    queries:  [\n        Query::equal(attribute: 'name', values: ['Captain Marvel']),\n        Query::lessThan(attribute: 'year', value: 2019)\n    ]\n);  \n\n// Get count of documents \n$database-\u003ecount(\n    collection: 'movies', \n    queries:  [\n        Query::equal(attribute: 'name', values: ['Captain Marvel']),\n        Query::greaterThan(attribute: 'year', value: 2019)\n    ], \n    max: 1000 // Max is optional\n);\n\n// Get the sum of an attribute from all the documents\n$database-\u003esum(\n    collection: 'movies', \n    attribute: 'price', \n    queries:  [\n        Query::greaterThan(attribute: 'year', value: 2019)\n    ],\n    max: null // max = null means no limit\n); \n\n// Delete a document\n$database-\u003edeleteDocument(\n    collection: 'movies', \n    id: $document-\u003egetId()\n);\n\n// Delete a cached document\nNote: Cached Documents or Collections are automatically deleted when a document or collection is updated or deleted \n$database-\u003epurgeCachedDocument(\n    collection: 'movies', \n    id: $document-\u003egetId()\n);\n\n```\n\n## System Requirements\n\nUtopia Framework requires PHP 8.0 or later. We recommend using the latest PHP version whenever possible.\n\n## Contributing\n\nThank you for considering contributing to the Utopia Framework! \nCheck out the [CONTRIBUTING.md](https://github.com/utopia-php/database/blob/main/CONTRIBUTING.md) file for more information.\n\n## Copyright and License\n\nThe MIT License (MIT) [http://www.opensource.org/licenses/mit-license.php](http://www.opensource.org/licenses/mit-license.php)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Futopia-php%2Fdatabase","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Futopia-php%2Fdatabase","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Futopia-php%2Fdatabase/lists"}