Function Signature
Description
Creates a new database if it doesn’t already exist. This function is useful for setting up a fresh database before running migrations. Database creation behavior varies by database type.Parameters
The database connection URL. The database name specified in the URL will be created:
- PostgreSQL:
postgres://user:password@host:port/database_name?sslmode=disable - MySQL:
mysql://root:password@localhost:3306/database_name - MariaDB:
mariadb://root:password@localhost:3307/database_name - SQLite:
sqlite://./database.sqlite(file is created automatically) - LibSQL: Should be created using the LibSQL/Turso interface
Authentication token for LibSQL/Turso databases. Use
None for other database types.Name of the table that will be used to track migrations. This parameter is stored for future migration operations.
Path to the directory that will contain migration files. Example:
"./migrations".Name of the schema dump file that will be used for future migrations. Example:
"schema.sql".Timeout in seconds to wait for the database server to be ready. Use
Some(30) for 30 seconds, or None for default timeout.Return Value
ReturnsResult<()> which:
- Returns
Ok(())if the database was created successfully or already exists - Returns
Errif there was a connection error or permission issue
Usage Example
PostgreSQL Example
MySQL Example
MariaDB Example
Database-Specific Behavior
PostgreSQL, MySQL, MariaDB
- Connects to the database server
- Creates the database if it doesn’t exist
- No error is returned if the database already exists
SQLite
- The database file is created automatically when you first run migrations
- This function primarily validates the connection parameters
- The file path specified in the URL is used for the database location
LibSQL/Turso
- Databases should be created using the LibSQL/Turso CLI or web interface
- This function validates the connection to an existing LibSQL database
- Use the Turso CLI:
turso db create <database-name>
Error Handling
The function may return errors in these cases:- Database server is unreachable
- Insufficient permissions to create databases
- Invalid database URL format
- Connection timeout (server not ready within
wait_timeout) - Database name contains invalid characters
Workflow Example
Typical workflow for setting up a new project:See Also
- drop_database - Drop a database
- migrate_database - Run migrations after creating the database
- new_migration - Create migration files