# Marten > Marten is a batteries-included web framework for Crystal. This file contains the guides for the version under development. The guide index is at https://martenframework.com/docs/llms.txt. These guides are the in-development guides at https://martenframework.com/docs/next/. The latest stable guides are at https://martenframework.com/docs/. The generated API reference for this version is at https://martenframework.com/docs/api/dev/. # Prologue Source: https://martenframework.com/docs/next/ Welcome to the Marten documentation! **Marten** is a batteries-included web framework for Crystal. It provides a consistent and extensible set of tools for building complete web applications without reinventing the wheel. ## Getting started Are you new to the Marten web framework? The following resources will help you get started: * The [installation guide](https://martenframework.com/docs/next/getting-started/installation) will help you install Crystal and the Marten CLI * The [tutorial](https://martenframework.com/docs/next/getting-started/tutorial) will help you discover the main features of the framework by creating a simple web application * [Coming from Django?](https://martenframework.com/docs/next/getting-started/from-django) and [Coming from Rails?](https://martenframework.com/docs/next/getting-started/from-rails) map familiar concepts to Marten if you already know those frameworks * [Why Marten?](https://martenframework.com/docs/next/the-marten-project/why-marten) compares Marten to other Crystal frameworks and helps you decide whether it is a good fit for your project ## Browsing the documentation The Marten documentation contains multiple pages and references that don't necessarily serve the same purpose. To help you browse this documentation, here is an overview of the different sorts of content you might encounter: * **Topic-specific guides** discuss the key concepts of the framework. They provide explanations and useful information about things like [models](https://martenframework.com/docs/next/models-and-databases), [handlers](https://martenframework.com/docs/next/handlers-and-http), and [templates](https://martenframework.com/docs/next/templates) * **Reference pages** provide a curated technical reference of the framework APIs * **How-to guides** document how to solve common problems when working with the framework. Those can cover things like deployments, app development, etc Additionally, an automatically-generated [API reference](https://martenframework.com/docs/api/dev/index.html) is also available to dig into Marten's internals. # Getting Started Source: https://martenframework.com/docs/next/getting-started If you are new to Marten or to web development, the following resources will help you get started. ## Guides - [Installation](https://martenframework.com/docs/next/getting-started/installation) - [Tutorial](https://martenframework.com/docs/next/getting-started/tutorial) - [Coming from Django?](https://martenframework.com/docs/next/getting-started/from-django) - [Coming from Rails?](https://martenframework.com/docs/next/getting-started/from-rails) # Installation Source: https://martenframework.com/docs/next/getting-started/installation This guide will help you get started in order to install Marten and its dependencies. Let's get started! ## Install Crystal Marten is a Crystal web framework; as such Crystal must be installed on your system. There are many ways to install Crystal, but we'll only highlight what we think are the most common ones here for the sake of simplicity: using Homebrew (macOS or Linux) or the APT package manager (Ubuntu, Debian). Please refer to the official [Crystal installation guide](https://crystal-lang.org/install/) if these methods don't work for you. ### Using Homebrew On macOS or Linux, Crystal can be installed using [Homebrew](https://brew.sh/) (also known as Linuxbrew) by running the following command: ```bash brew install crystal ``` ### Using APT On Ubuntu, Debian or any other Linux distribution using the APT package manager, Crystal can be installed by running the following command: ```bash curl -fsSL https://crystal-lang.org/install.sh | sudo bash ``` ### Using pacman On ArchLinux and derivates you can install Crystal and the `shards` command line tool through Pacman: ```bash sudo pacman -S crystal shards ``` ## Install a database Marten officially supports **MariaDB**, **MySQL**, **PostgreSQL**, and **SQLite3** databases. New Marten projects will use a SQLite database by default: this lightweight serverless database application is usually already pre-installed on most of the existing operating systems, which makes it an ideal candidate for a development or a testing database. As such, if you choose to use SQLite for your new Marten project, you can very probably skip this section. Marten also has built-in support for PostgreSQL, MariaDB, and MySQL. Please refer to the applicable official documentation to install your database of choice: * [PostgreSQL Installation Guide](https://wiki.postgresql.org/wiki/Detailed_installation_guides) * [MariaDB Installation Guide](https://mariadb.com/kb/en/getting-installing-and-upgrading-mariadb) * [MySQL Installation Guide](https://dev.mysql.com/doc/refman/8.0/en/installing.html) * [SQLite Installation Guide](https://www.tutorialspoint.com/sqlite/sqlite_installation.htm) Each database necessitates the use of a dedicated shard (a package of Crystal code). If you're just beginning with the framework or planning to follow the [tutorial](https://martenframework.com/docs/next/getting-started/tutorial), there's no immediate need to install these shards. However, if you intend to employ other databases like MariaDB, MySQL, or PostgreSQL, you may need to install database-specific shards. You can find instructions on how to do this in the [Configure database backends](https://martenframework.com/docs/next/development/how-to/configure-database-backends) section. ## Install Marten The next step is to install the Marten CLI. This tool will let you easily generate new Marten projects or applications. ### Using Homebrew On macOS or Linux, Marten can be installed using [Homebrew](https://brew.sh/) (also known as Linuxbrew) by running the following commands: ```bash brew tap martenframework/marten brew trust martenframework/marten brew install marten ``` ### Using AUR on ArchLinux and derivates Assuming you use some AUR helper (`yay` in this example) it will be as simple as: ```bash yay -S marten ``` Once the installation is complete, you should be able to use the `marten` command: ```bash marten -v ``` ### From the sources Marten can be installed from the sources by running the following commands: ```bash git clone https://github.com/martenframework/marten cd marten shards install crystal build src/marten_cli.cr -o bin/marten mv bin/marten /usr/local/bin ``` Once the above steps are done, you should be able to verify that the `marten` command works as expected by running: ```bash marten -v ``` ## Next steps _Congrats! You’re in._ You can now move on to the [introduction tutorial](https://martenframework.com/docs/next/getting-started/tutorial). # Tutorial Source: https://martenframework.com/docs/next/getting-started/tutorial This guide will walk you through the creation of a simple weblog application, which will help you learn the basics of the Marten web framework. It is designed for beginners who want to get started by creating a Marten web project, so no prior experience with the framework is required. :::tip Already familiar with Django or Rails? You may find it helpful to skim [Coming from Django?](https://martenframework.com/docs/next/getting-started/from-django) or [Coming from Rails?](https://martenframework.com/docs/next/getting-started/from-rails) first, then come back here to build something hands-on. ::: ## Requirements This guide assumes that [Crystal and the Marten CLI are properly installed already](https://martenframework.com/docs/next/getting-started/installation). You can verify that the Marten CLI is properly installed by running the following command: ```bash marten -v ``` This should output the version of your Marten installation. ## What is Marten? Marten is a web application framework written in the Crystal programming language. It is designed to make developing web applications easy and fun; and it does so by making some assumptions regarding the common needs that developers may encounter when building web applications. ## Creating a project Creating a project is the first thing to do in order to start working on a Marten web application. This creation process can be done through the use of the `marten` command, and it will ensure that the basic structure of a Marten project is properly generated. This can be achieved from the command line, where you can run the following command to create your first Marten project: ```bash marten new project myblog ``` The above command will create a `myblog` directory inside your current directory. This new folder should have the following content: ``` myblog/ ├── config │   ├── initializers │   ├── settings │   │   ├── base.cr │   │   ├── development.cr │   │   ├── production.cr │   │   └── test.cr │   └── routes.cr ├── spec │   └── spec_helper.cr ├── src │   ├── assets │   ├── emails │   ├── handlers │   ├── migrations │   ├── models │   ├── schemas │   ├── templates │   ├── cli.cr │   ├── project.cr │   └── server.cr ├── .editorconfig ├── .gitignore ├── AGENTS.md ├── manage.cr ├── seed.cr └── shard.yml ``` These files and folders are described below: | Path | Description | | ----------- | ----------- | | config/ | Contains the configuration of the project. This includes environment-specific Marten configuration settings, initializers, and web application routes. | | spec/ | Contains the project specs, allowing you to test your application. | | src/ | Contains the source code of the application. By default this folder will include a `project.cr` file (where all dependencies - including Marten itself - are required), a `server.cr` file (which starts the Marten web server), a `cli.cr` file (where migrations and CLI-related abstractions are required), and `assets`, `emails`, `handlers`, `migrations`, `models`, `schemas`, and `templates` folders. | | .editorconfig | Regular `.editorconfig` which file defines basic indentation coding styles for Crystal. | | .gitignore | Regular `.gitignore` file which tells git the files and directories that should be ignored. | | AGENTS.md | Instructions for coding agents: the Marten version, links to the matching guides, project layout, generators, and how to run specs. | | manage.cr | This file defines a CLI that lets you interact with your Marten project in order to perform various actions (e.g. running database migrations, collecting assets, etc). | | seed.cr | This file can be used to define logics for populating your project's database with initial or default data. | | shard.yml | The standard [shard.yml](https://crystal-lang.org/reference/the_shards_command/index.html) file, that lists the dependencies that are required to build your application. | Now that the project structure is created, you can change into the `myblog` directory (if you haven't already) in order to install the project dependencies by running the following command: ```bash shards install ``` :::info Marten projects are organized around the concept of "apps". A Marten app is a set of abstractions (usually defined under a unique folder) that contributes specific behaviours to a project. For example, apps can provide [models](https://martenframework.com/docs/next/models-and-databases) or [handlers](https://martenframework.com/docs/next/handlers-and-http). They allow to separate a project into a set of logical and reusable components. Another interesting benefit of apps is that they can be extracted and distributed as external shards. This pattern allows third-party libraries to easily contribute models, migrations, handlers, or templates to other projects. The use of apps is activated by simply adding app classes to the [`installed_apps`](https://martenframework.com/docs/next/development/reference/settings#installed_apps) setting. By default, when creating a new project through the use of the [`new`](https://martenframework.com/docs/next/development/reference/management-commands#new) command, no explicit app will be created nor installed. This is because each Marten project comes with a default "main" app that corresponds to your standard `src` folder. Models, migrations, or other classes defined in this folder are associated with the main app by default, unless they are part of another explicitly defined application. As projects grow in size and scope, it is generally encouraged to start thinking in terms of apps and how to split models, handlers, or features across multiple apps depending on their intended responsibilities. Please refer to [Applications](https://martenframework.com/docs/next/development/applications) to learn more about applications and how to structure your projects using them. ::: ## Running the development server Now that you have a fully functional web project, you can start a development server by using the following command: ```bash marten serve ``` This will start a Marten development server. To verify that it's working as expected, you can open a browser and navigate to [http://localhost:8000](http://localhost:8000). When doing so, you should be greeted by the Marten "welcome" page: ![Marten welcome page](https://martenframework.com/docs/img/getting-started/tutorial/marten_welcome_page.png) :::info Your project development server will automatically be available on the internal IP at port 8000. The server port and IP can be changed easily by modifying the `config/settings/development.cr` file: ```crystal Marten.configure :development do |config| config.debug = true config.host = "localhost" config.port = 3000 end ``` ::: Once started, the development server will watch your project source files and will automatically recompile them when they are updated; it will also take care of restarting your project server. As such, you don't have to manually restart the server when making changes to your application source files. ## Writing a first handler Let's start by creating the first handler for your project. To do so, create a `src/handlers/home_handler.cr` file with the following content: ```crystal title="src/handlers/home_handler.cr" class HomeHandler < Marten::Handler def get respond("Hello World!") end end ``` Handlers are classes that process a web request in order to produce a web response. This response can be rendered HTML content or a redirection for example. In the above example, the `HomeHandler` handler explicitly processes a `GET` HTTP request and returns a very simple `200 OK` response containing a short text. But in order to access this handler via a browser, it is necessary to map it to a URL route. To do so, you can edit the `config/routes.cr` file as follows: ```crystal title="config/routes.cr" Marten.routes.draw do // highlight-next-line path "/", HomeHandler, name: "home" // highlight-next-line if Marten.env.development? path "#{Marten.settings.assets.url}", Marten::Handlers::Defaults::Development::ServeAsset, name: "asset" path "#{Marten.settings.media_files.url}", Marten::Handlers::Defaults::Development::ServeMediaFile, name: "media_file" end end ``` The `config/routes.cr` file was automatically created earlier when you initialized the project structure. By using the `#path` method you wired the `HomeHandler` into the routes configuration. The `#path` method accepts three arguments: * the first argument is the route pattern, which is a string like `/foo/bar`. When Marten needs to resolve a route, it starts at the beginning of the routes array and compares each of the configured routes until it finds a matching one * the second argument is the handler class associated with the specified route. When a request URL is matched to a specific route, Marten executes the handler that is associated with it * the last argument is the route name. This is an identifier that can later be used in your codebase to generate the full URL for a specific route, and optionally inject parameters in it Now if you go to [http://localhost:8000](http://localhost:8000), you will get the `Hello World!` response that is generated by the handler you just wrote. :::tip Multiple routes can map to the same handler class if necessary. ::: :::info Please refer to [Routing](https://martenframework.com/docs/next/handlers-and-http/routing) to learn more about Marten's routing mechanism. ::: ## Creating the Article model [Models](https://martenframework.com/docs/next/models-and-databases/introduction) are classes that define what data can be persisted and manipulated by a Marten application. They explicitly specify fields and rules that map to database tables and columns. Model records can be queried and interacted with through a mechanism called [Query sets](https://martenframework.com/docs/next/models-and-databases/queries). Let's define an `Article` model, which is the linchpin of any weblog application. To do set, let's create a `src/models/article.cr` file with the following content: ```crystal title="src/models/article.cr" class Article < Marten::Model field :id, :big_int, primary_key: true, auto: true field :title, :string, max_size: 255 field :content, :text end ``` As you can see, Marten models are defined as subclasses of the `Marten::Model` base class, and they explicitly define "fields" through the use of a `field` macro. In its current state, our `Article` model contains the following three fields: * `id` is a big integer that will hold the unique identifier of an article (primary key of the underlying table record) * `title` is a string column (`VARCHAR(255)`) that will hold the title of an article * `content` is a text column (`TEXT`) that will hold the textual content of an article ## Generating and running migrations Our `Article` model above is defined but is not "applied" at the database level yet. In order to create the corresponding table and columns, we will need to generate a [migration](https://martenframework.com/docs/next/models-and-databases/migrations) for it. Marten provides a migrations mechanism that is designed to be automatic: this means that migrations will be automatically derived from your model definitions. This allows to ensure that the definition of your model and its fields (and underlying columns) is done in one place only, which helps keep your project DRY. In order to generate the migration file for the model we created previously, all we need to do is to run the following Marten command: ```shell marten genmigrations ``` This will output something along those lines: ```shell Generating migrations for app 'main': › Creating [src/migrations/202208072015231_create_main_article_table.cr]... DONE ○ Create main_article table ``` The `genmigrations` command is a way to tell Marten to introspect your project in order to identify whether you added, removed, or modified models. The changes identified by this command are persisted in migration files (living under `migrations/` folders in each Marten application), that you can run later on in order to apply them at the database level. Now that we have generated a migration file for our `Article` model, we can apply it at the database level by running the following command: ```shell marten migrate ``` Which will output the following content: ```shell Running migrations: › Applying main_202208072015231_create_main_article_table... DONE ``` The `migrate` command will identify all the migration files that weren't applied to your database yet, and will run them one by one. By doing so, Marten will ensure that the changes you made to your model definitions are applied at the database level, in the corresponding tables. :::info Please refer to [Migrations](https://martenframework.com/docs/next/models-and-databases/migrations) to learn more about migrations. ::: :::note For new projects, Marten uses a SQLite database by default. In our case, if we look at the `config/settings/base.cr` file, we can see that the current database configuration looks something like this: ```crystal config.database do |db| db.backend = :sqlite db.name = Path["myblog.db"].expand end ``` An SQLite database is a good choice in order to try Marten and experiment with it (since SQLite is already pre-installed on most systems). That being said, if you need to use another database backend (for example, PostgreSQL, MariaDB, or MySQL), feel free to have a look at the [databases configuration reference](https://martenframework.com/docs/next/development/reference/settings#database-settings). ::: ## Interacting with model records Now that our `Article` model table has been created at the database level, let's try to make use of the Marten ORM to create and query article records. To do so, we can launch an instance of the [Crystal playground](https://crystal-lang.org/reference/master/using_the_compiler/index.html#crystal-play) as follows: ```shell marten play ``` You should be able to navigate to [http://localhost:8080](http://localhost:8080) and see a Crystal editor containing the following snippet: ```crystal require "./src/project" # Setup the project. Marten.setup # Write your code here. ``` These lines basically require your project dependencies and ensure that Marten is properly set up. You should keep those in the editor when playing with the following examples. Each of the following snippets is assumed to be copied/pasted below the previous one. The output of these examples is highlighted next to the `# =>` comment line. Let's start by initializing a new `Article` object: ```crystal article = Article.new(title: "My article", content: "This is my article.") # => # ``` As you can see, by using `#new`, we are initializing a new `Article` object by specifying its field values (`title` and `content`). It should be noted that so far, the object is only _initialized_ and is not saved to the database yet (this is why `id` is set to `nil` in the above snippet). In order to persist the new object at the database level, you can make use of the `#save` method: ```crystal article.save # => true ``` The output of the `#save` method is a boolean indicating the result of the object validation: in our case, `true` means that the `Article` object was successfully validated and that the corresponding record was created at the database level. Now if we inspect the `article` object again, we should observe that an `id` has been set for the record at hand: ```crystal article # => # ``` If we want to fetch this record from the database again, we can use the [`#get`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#get) method and specify the identifier value of the record we want to retrieve. For example: ```crystal article = Article.get(id: 1) # => # ``` Now we can try to retrieve all the `Article` records that we currently have in the database. This is done by calling the `#all` method on the `Article` model: ```crystal Article.all # => ]> ``` This method returns an `Article::QuerySet` object, which is commonly referred to as a "query set". A query set is a representation of records collections from the database that can be filtered, and iterated over. The `Article::QuerySet` class, automatically generated for the `Article` model, is a subclass of `Marten::DB::Query::Set`. :::info Please refer to [Queries](https://martenframework.com/docs/next/models-and-databases/queries) to learn more about Marten's querying capabilities. ::: ## Showing a list of articles Let's revisit our initial implementation of the `HomeHandler` handler we defined [earlier](#writing-a-first-handler). Since we are building a weblog application, it would make sense to display a list of all our `Article` objects on the index page. To do so, let's update the existing `src/handlers/home_handler.cr` file with the following content: ```crystal title="src/handlers/home_handler.cr" class HomeHandler < Marten::Handler def get render("home.html", context: { articles: Article.all }) end end ``` The `#render` method that is used above allows to return an HTTP response whose content is generated by rendering a specific [template](https://martenframework.com/docs/next/templates). The template can be rendered by specifying a context hash or a named tuple. In our case the template context contains an `articles` key that maps to a query set of all the `Article` records. Now if you start the Marten development server again and then try to access the home page ([http://localhost:8000](http://localhost:8000)), you should get an error stating that the `home.html` template does not exist. This is normal: we need to create it. Templates provide a convenient way for defining the presentation logic of a web application. They allow to write HTML content that is rendered dynamically by using variables that you specify in a "template context". This rendering process can involve model records or any other variables you define. Let's define the expected template for our home handler by creating a `src/templates/home.html` file with the following content: ```html title="src/templates/home.html" {% extend "base.html" %} {% block content %}

My blog

Articles:

    {% for article in articles %}
  • {{ article.title }}
  • {% endfor %}
{% endblock %} ``` As you can see, Marten's templating system relies on variables that are surrounded by **`{{`** and **`}}`**. Each variable can involve lookups in order to access specific object attributes. In the above example `{{ article.title }}` means that the `title` attribute of the `article` variable should be outputted. Method-calling is done by using statements (also called "template tags") delimited by **`{%`** and **`%}`**. Such statements can involve for loops, if conditions, etc. In the above example we are using a for loop to iterate over the `Article` records in the `articles` query set that is "passed" to the template context in our `HomeHandler` handler. :::info Please refer to [Templates](https://martenframework.com/docs/next/templates/introduction) to learn more about Marten's templating system. ::: :::info What about the `extend` and `block` tags in the previous snippet? These tags allow to "extend" a "base" template that usually contains the layout of an application (`base.html` in the above snippet) and to explicitly define the contents of the "blocks" that are expected by this base template. New marten projects are created with a simple `base.html` template that defines a very basic HTML document, whose body is filled with the content of a `content` block. This is why templates in this tutorial extend a `base.html` and override the content of the `content` block. You can learn more about these capabilities in [Template inheritance](https://martenframework.com/docs/next/templates/introduction#template-inheritance). ::: If you go back to the home page ([http://localhost:8000](http://localhost:8000)), you should be able to see a list of article titles corresponding to all the `Article` records you created previously. We have now pieced together the main components of the Marten web framework (Models, Handlers, Templates). When accessing the home page of our application, the following steps are taken care of by the framework: 1. the browser issues a GET request to `http://localhost:8000` 2. the Marten web application that is currently running receives the request 3. the Marten routing system maps the path of the incoming request to the `HomeHandler` handler 4. the handler is initialized and executed, which involves fetching all the `Article` records 5. the handler renders the `home.html` template and returns a `200 OK` response containing the rendered content 6. the Marten server sends the response with the HTML content back to the browser ## Showing a single article We presently have a handler that lists all the existing `Article` records, but it would be nice to be able to actually see the content of each article individually. To do so, let's create a new `src/handlers/article_detail_handler.cr` handler file with the following content: ```crystal title="src/handlers/article_detail_handler.cr" class ArticleDetailHandler < Marten::Handler def get render("article_detail.html", context: { article: Article.get!(id: params["pk"]) }) rescue Marten::DB::Errors::RecordNotFound raise Marten::HTTP::Errors::NotFound.new("Article not found") end end ``` Like in the previous example, we will be relying on the `#render` method to render a template and return the corresponding HTTP response. But this time we will be retrieving a specific record whose parameter will be specified in a `pk` route parameter. :::note You will note that we are making use of the `#get!` method to retrieve the model record in the above example. This method behaves similarly to the `#get` method we saw earlier, but it will raise a "record not found" exception if no record can be found for the specified parameters. In that case we can "rescue" this error in order to raise an "Not Found" HTTP exception that will result in a 404 response to be returned. ::: Let's now map this handler to a new route by adding the following line to the `config/routes.cr` file: ```crystal title="config/routes.cr" Marten.routes.draw do path "/", HomeHandler, name: "home" // highlight-next-line path "/article/", ArticleDetailHandler, name: "article_detail" if Marten.env.development? path "#{Marten.settings.assets.url}", Marten::Handlers::Defaults::Development::ServeAsset, name: "asset" path "#{Marten.settings.media_files.url}", Marten::Handlers::Defaults::Development::ServeMediaFile, name: "media_file" end end ``` As you can see above, the new route we mapped to the `ArticleDetailHandler` handler requires a `pk` - _primary key_ - integer (`int`) parameter. Route parameters are defined using angle brackets, and the name of the parameter and its type are separated by a `:` character (`` format). Obviously, we also need to define the `article_detail.html` template. To do so, let's create a `src/templates/article_detail.html` with the following content: ```html title="src/templates/article_detail.html" {% extend "base.html" %} {% block content %}

{{ article.title }}

{{ article.content }}

{% endblock %} ``` Now if you try to access [http://localhost:8000/article/1](http://localhost:8000/article/1), you will be able to see the content of the `Article` record with ID 1. There is something missing though: the home page does not link to the "detail" page of each article. To remediate this, we can modify the `src/templates/home.html` template file as follows: ```html title="src/templates/home.html" {% extend "base.html" %} {% block content %}

My blog

Articles:

    {% for article in articles %} // highlight-next-line
  • // highlight-next-line {{ article.title }} // highlight-next-line ‐ View // highlight-next-line
  • {% endfor %}
{% endblock %} ``` The `url` tag used in the above snippet allows to perform a reverse URL resolution. This allows to generate the final URL associated with a specific route name (the `article_detail` route name we defined earlier in this case). This reverse resolution can involve parameters if the considered route require ones. :::info Please refer to [Routing](https://martenframework.com/docs/next/handlers-and-http/routing) to learn more about Marten's routing system. ::: ## Creating a new article So far we only implemented support for "read" operations: we made it possible to list all the available articles in the home page, and we added the ability to see the content of a specific article in the "detail" page. The next step will be to make it possible to create new articles in order to populate our weblog. To do so, let's start by creating a new `src/schemas/article_schema.cr` schema file with the following content: ```crystal title="src/schemas/article_schema.cr" class ArticleSchema < Marten::Schema field :title, :string, max_size: 255 field :content, :string end ``` We just defined a "schema". Schemas are classes that define how input data should be serialized / deserialized, and validated. Schemas are usually used when processing web requests containing form data or pre-defined payloads. Like models, they contain a set of pre-defined fields that indicate what parameters are expected, what are their types, and how they should be validated. Let's see how we can use this schema in a handler. In this light, let's create a new `src/handlers/article_create_handler.cr` file: ```crystal title="src/handlers/article_create_handler.cr" class ArticleCreateHandler < Marten::Handler @schema : ArticleSchema? def get render("article_create.html", context: { schema: schema }) end def post if schema.valid? article = Article.new(schema.validated_data) article.save! redirect(reverse("home")) else render("article_create.html", context: { schema: schema }, status: 422) end end private def schema @schema ||= ArticleSchema.new(request.data) end end ``` This handler is able to handle both GET and POST requests: * when the incoming request is a GET, it will simply render the `article_create.html` template, and initialize the schema (instance of `ArticleSchema`) with any data currently present in the request object (which is returned by the `#request` method). This schema object is made available to the template context * when the incoming request is a POST, it will initialize the schema and try to see if it is valid considering the incoming data. If it's valid, then the new `Article` record will be created using the schema's validated data, and the user will be redirect to the home page. Otherwise, the `article_create.html` template will be rendered again with the invalid schema in the associated context In the above snippet, we make use of `#redirect` in order to indicate that we want to return a 302 Found HTTP response, and we generate the redirection URL by performing a reverse resolution of the `home` route we introduced earlier by using the `#reverse` method (which is similar to the `url` template tag we encountered in the previous section). We can now create the `article_create.html` template file with the following content: ```html title="src/templates/article_create.html" {% extend "base.html" %} {% block content %}

Create a new article

{% for error in schema.title.errors %}

{{ error.message }}

{% endfor %}
{% for error in schema.content.errors %}

{{ error.message }}

{% endfor %}
{% endblock %} ``` As you can see, the above snippet defines a form that includes two fields: one for the `title` schema field and the other one for the `content` schema field. Each schema field can be errored depending on the result of a validation, and this is why specific field errors are (optionally) displayed as well. :::tip What about the hidden CSRF token input? The `csrftoken` input in the above example is mandatory because every unsafe request (eg. POST) is automatically protected by a CSRF (Cross-Site Request Forgeries) check. Please refer to [Cross-Site Request Forgery protection](https://martenframework.com/docs/next/security/csrf) to learn more about this. ::: Finally, we need to map the `ArticleCreateHandler` handler to a proper route. We can do this by editing the `config/routes.cr` file as follows: ```crystal title="config/routes.cr" Marten.routes.draw do path "/", HomeHandler, name: "home" // highlight-next-line path "/article/create", ArticleCreateHandler, name: "article_create" path "/article/", ArticleDetailHandler, name: "article_detail" if Marten.env.development? path "#{Marten.settings.assets.url}", Marten::Handlers::Defaults::Development::ServeAsset, name: "asset" path "#{Marten.settings.media_files.url}", Marten::Handlers::Defaults::Development::ServeMediaFile, name: "media_file" end end ``` Now if you open your browser at [http://localhost:8000/article/create](http://localhost:8000/article/create), you should be able to see a very rough form allowing to create a new `Article` record and to redirect to it. Obviously, we still need to a link somewhere in our application to be able to easily access the article creation form. In this light, we can modify the `home.html` template file as follows: ```html title="src/templates/home.html" {% extend "base.html" %} {% block content %}

My blog

// highlight-next-line Create new article

Articles:

    {% for article in articles %}
  • {{ article.title }} ‐ View
  • {% endfor %}
{% endblock %} ``` :::info Please refer to [Schemas](https://martenframework.com/docs/next/schemas/introduction) to learn more about schemas. ::: ## Updating an article Now that we are able to create new `Article` records, let's add the ability to update existing records. To do so, we will implement a handler that works similarly to the `ArticleCreateHandler` handler we defined earlier: it should be able to process GET requests in order to display an "update" form, and it should validate the incoming data (and update the right record) when POST requests are submitted through an HTML form. In this light, let's define the `src/handlers/article_update_handler.cr` file with the following content: ```crystal title="src/handlers/article_update_handler.cr" class ArticleUpdateHandler < Marten::Handler @article : Article? @schema : ArticleSchema? def get render("article_update.html", context: { article: article, schema: schema }) end def post if schema.valid? article.update!(schema.validated_data) redirect(reverse("home")) else render("article_update.html", context: { article: article, schema: schema }, status: 422) end end private def article @article ||= Article.get!(id: params["pk"]) rescue Marten::DB::Errors::RecordNotFound raise Marten::HTTP::Errors::NotFound.new("Article not found") end private def initial_schema_data Marten::Schema::DataHash{ "title" => article.title, "content" => article.content } end private def schema @schema ||= ArticleSchema.new(request.data, initial: initial_schema_data) end end ``` Here the `#get` and `#post` method implementations look similar to what was introduced for the `ArticleCreateHandler` handler. The main difference is that a specific `Article` record needs to be retrieved. Moreover the `ArticleSchema` schema is initialized with some "initial data" (`Marten::Schema::DataHash` hash-like object) that corresponds to the current `title` and `content` field values of the considered record. When a valid schema is processed, instead of creating a new record, we simply update the considered one through the use of the `#update!` method. We can now create the `article_update.html` template file with the following content: ```html title="src/templates/article_update.html" {% extend "base.html" %} {% block content %}

Update article "{{ article.title }}"

{% for error in schema.title.errors %}

{{ error.message }}

{% endfor %}
{% for error in schema.content.errors %}

{{ error.message }}

{% endfor %}
{% endblock %} ``` As you can see, this looks very similar to what we did previously with the `article_create.html` template file. Let's now map the `ArticleUpdateHandler` handler to a proper route. We can do this by editing the `config/routes.cr` file as follows: ```crystal title="config/routes.cr" Marten.routes.draw do path "/", HomeHandler, name: "home" path "/article/create", ArticleCreateHandler, name: "article_create" path "/article/", ArticleDetailHandler, name: "article_detail" // highlight-next-line path "/article//update", ArticleUpdateHandler, name: "article_update" if Marten.env.development? path "#{Marten.settings.assets.url}", Marten::Handlers::Defaults::Development::ServeAsset, name: "asset" path "#{Marten.settings.media_files.url}", Marten::Handlers::Defaults::Development::ServeMediaFile, name: "media_file" end end ``` Now if you open your browser at [http://localhost:8000/article/1/update](http://localhost:8000/article/1/update), you should be able to see a very rough form allowing to update the `Article` record with ID 1. We can also add a link somewhere in the home page of the application to be able to easily access the update form for existing articles. In this light, we can modify the `home.html` template file as follows: ```html title="src/templates/home.html" {% extend "base.html" %} {% block content %}

My blog

Create new article

Articles:

    {% for article in articles %}
  • {{ article.title }} ‐ View // highlight-next-line ‐ Update
  • {% endfor %}
{% endblock %} ``` ## Deleting an article Finally, the last missing feature we could add is the ability to delete an article. To do so, let's introduce a handler that works as follows: when processing a GET request the handler will ask the user to confirm that they want to indeed delete the considered `Article` record, and when processing a POST request the handler will actually delete the record and then redirect to the home page of the application. In this light, let's define the `src/handlers/article_delete_handler.cr` file: ```crystal title="src/handlers/article_delete_handler.cr" class ArticleDeleteHandler < Marten::Handler @article : Article? def get render("article_delete.html", context: { article: article }) end def post article.delete redirect(reverse("home")) end private def article @article ||= Article.get!(id: params["pk"]) rescue Marten::DB::Errors::RecordNotFound raise Marten::HTTP::Errors::NotFound.new("Article not found") end end ``` In the above snippet, the `#get` method simply fetches the `Article` record by using the `pk` parameter value and renders the `article_delete.html` template (with the article in the associated context). The `#post` method fetches the `Article` record as well and deletes it before redirecting the user to the home page. Let's now create the `article_delete.html` template file with the following content: ```html title="src/templates/article_delete.html" {% extend "base.html" %} {% block content %}

Delete article "{{ article.title }}"

Are you sure?

{% endblock %} ``` This template simply asks the user for confirmation and displays a confirmation button embedded in a form to issue the POST request that will actually delete the record. Let's now map the `ArticleDeleteHandler` handler to a proper route. We can do this by editing the `config/routes.cr` file as follows: ```crystal title="config/routes.cr" Marten.routes.draw do path "/", HomeHandler, name: "home" path "/article/create", ArticleCreateHandler, name: "article_create" path "/article/", ArticleDetailHandler, name: "article_detail" path "/article//update", ArticleUpdateHandler, name: "article_update" // highlight-next-line path "/article//delete", ArticleDeleteHandler, name: "article_delete" if Marten.env.development? path "#{Marten.settings.assets.url}", Marten::Handlers::Defaults::Development::ServeAsset, name: "asset" path "#{Marten.settings.media_files.url}", Marten::Handlers::Defaults::Development::ServeMediaFile, name: "media_file" end end ``` Now if you open your browser at [http://localhost:8000/article/1/delete](http://localhost:8000/article/1/delete), you should be able to see a the confirmation page allowing to delete the `Article` record with ID 1. We can also add a link somewhere in the home page of the application to be able to easily access the delete confirmation page for existing articles. In this light, we can modify the `home.html` template file as follows: ```html title="src/templates/home.html" {% extend "base.html" %} {% block content %}

My blog

Create new article

Articles:

    {% for article in articles %}
  • {{ article.title }} ‐ View ‐ Update // highlight-next-line ‐ Delete
  • {% endfor %}
{% endblock %} ``` ## Refactoring: using template partials The templates used for creating and updating an article look the same: they both make use of the same schema in order to create or update articles. It would be interesting to be able to reuse this form for both templates. This is where template "partials" came in handy: these are template snippets that can be easily "included" into other templates to avoid duplications of code. Let's create a `src/templates/partials/article_form.html` partial with the following content: ```html title="src/templates/partials/article_form.html"
{% for error in schema.title.errors %}

{{ error.message }}

{% endfor %}
{% for error in schema.content.errors %}

{{ error.message }}

{% endfor %}
``` This partial template contains the exact same form that we used in the creation and update templates. Let's now make use of this partial in the `src/templates/article_create.html` and `src/templates/article_update.html` templates by leveraging the [`include`](https://martenframework.com/docs/next/templates/reference/tags#include) template tag: ```html title="src/templates/article_create.html" {% extend "base.html" %} {% block content %}

Create a new article

{% include "partials/article_form.html" %} {% endblock %} ``` ```html title="src/templates/article_update.html" {% extend "base.html" %} {% block content %}

Update article "{{ article.title }}"

{% include "partials/article_form.html" %} {% endblock %} ``` As you can see, the creation and update templates are now much more simple. :::tip The `include` template tag provides additional options like the ability to assign variables that are specific to the included template. Please refer to the [`include` template tag reference](https://martenframework.com/docs/next/templates/reference/tags#include) to learn more about this mechanism. ::: ## Refactoring: using generic handlers The handlers we implemented previously map to common web development use cases: retrieving data from the database - from a specific URL parameter - and displaying it, listing multiple objects, creating or updating records, etc. These use cases are so frequently encountered that Marten provides a set of "generic handlers" that allow to easily implement them. These generic handlers take care of these common patterns so that developers don't end up reimplementing the wheel. We could definitely leverage these generic handlers as part of our weblog application. In this light, let's start with the `HomeHandler` class we implemented earlier: this handler essentially retrieves all the `Article` records and makes this list available to the `home.html` template. This pattern is enabled by the [`Marten::Handlers::RecordList`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordList.html) generic handler. In order to use it, let's modify the `src/handlers/home_handler.cr` file as follows: ```crystal title="src/handlers/home_handler.cr" class HomeHandler < Marten::Handlers::RecordList model Article template_name "home.html" list_context_name "articles" end ``` In the above snippet we use a few class methods in order to define how the handler should behave: `#model` allows to define the model class that should be used to retrieve the record, `#template_name` allows to define the name of the template to render, and `#list_context_name` allows to define the name of the record list variable in the template context. Let's continue with the `ArticleDetailHandler` class: this handler retrieves a specific `Article` record from a `pk` route parameter, and "renders" it using a specific template. This pattern is enabled by the [`Marten::Handlers::RecordDetail`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordDetail.html) generic handler. In order to use it, let's modify the `src/handlers/article_detail_handler.cr` file as follows: ```crystal title="src/handlers/article_detail_handler.cr" class ArticleDetailHandler < Marten::Handlers::RecordDetail model Article template_name "article_detail.html" record_context_name "article" end ``` In order to configure how the handler should behave, we make use of a few class methods here as well: `#model` allows to define the model class of the record that should be retrieved, `#template_name` defines the template to render, and `#record_context_name` defines the name of the record variable in the template context. Now let's look at the `ArticleCreateHandler` class: this class displays a form when processing GET requests, and it validates a schema that is used to create a specific record when processing POST requests. This exact pattern is enabled by the [`Marten::Handlers::RecordCreate`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordCreate.html) generic handler. In order to use it, we can modify the `src/handlers/article_create_handler.cr` file as follows: ```crystal title="src/handlers/article_create_handler.cr" class ArticleCreateHandler < Marten::Handlers::RecordCreate model Article schema ArticleSchema template_name "article_create.html" success_route_name "home" end ``` Here, `#model` allows to define the model class to use to create the new record, `#schema` is the schema class that should be used to validated the incoming data, `#template_name` defines the name of the template to render, and `#success_route_name` is the name of the route to redirect to after a successful record creation. We can now look at the `ArticleUpdateHandler` class: this class retrieves a specific record and displays a form when processing GET requests, and it validates a schema whose data is used to update the record when processing POST requests. This pattern is enabled by the [`Marten::Handlers::RecordUpdate`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordUpdate.html) generic handler. Let's use it and let's modify the `src/handlers/article_update_handler.cr` file as follows: ```crystal title="src/handlers/article_update_handler.cr" class ArticleUpdateHandler < Marten::Handlers::RecordUpdate model Article schema ArticleSchema template_name "article_update.html" success_route_name "home" record_context_name "article" end ``` Here, `#model` allows to define the model class to use to retrieve and update the record, `#schema` is the schema class that should be used to validated the incoming data, `#template_name` defines the name of the template to render, `#success_route_name` is the name of the route to redirect to after a successful record update, and `#record_context_name` is the name of the record variable in the template context. Finally, let's look at the `ArticleDeleteHandler` class: this handler renders a template when processing GET requests, and performs the deletion of the considered record when processing POST requests. This pattern is provided by the [`Marten::Handlers::RecordDelete`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordDelete.html) generic handler. In order to use it, let's modify the `src/handlers/article_delete_handler.cr` file as follows: ```crystal title="src/handlers/article_delete_handler.cr" class ArticleDeleteHandler < Marten::Handlers::RecordDelete model Article template_name "article_delete.html" success_route_name "home" record_context_name "article" end ``` In order to configure how the handler should behave, we make use of a few class methods here as well: `#model` allows to define the model class of the record that should be retrieved and deleted, `#template_name` defines the template to render, and `#success_route_name` defines the name of the route to redirect to once the record is deleted. Now if you go to your application again at [http://localhost:8000](http://localhost:8000), you will notice that everything is working like it used to do before we introduced these changes (but with less code!). :::info Please refer to [Generic handlers](https://martenframework.com/docs/next/handlers-and-http/generic-handlers) to learn more about generic handlers. ::: ## What's next? As part of this tutorial, we covered the main features of the Marten web framework by implementing a very simple application: * we learned to define [models](https://martenframework.com/docs/next/models-and-databases) in order to interact with the database * we learned to create [handlers](https://martenframework.com/docs/next/handlers-and-http) and to map URLs to these in order to process HTTP requests * we learned to render [templates](https://martenframework.com/docs/next/templates) in order to define the presentation logic of an application Now that you've experimented with these core concepts of the framework, you should not hesitate to update the application we just created in order to experiment further and add new features to it. The Marten documentation also contains plenty of additional guides allowing you to keep exploring and learning more about other areas of the framework. These may be useful depending on the specific needs of your application: [Testing](https://martenframework.com/docs/next/development/testing), [Applications](https://martenframework.com/docs/next/development/applications), [Security](https://martenframework.com/docs/next/security), [Internationalization](https://martenframework.com/docs/next/i18n), etc. # Coming from Django? Source: https://martenframework.com/docs/next/getting-started/from-django If you already know [Django](https://www.djangoproject.com/), many Marten ideas will feel familiar. Marten follows a similar Model, Handler, and Template structure and borrows conventions from Django's apps, migrations, templates, and generic views. It is [not a port](https://martenframework.com/docs/next/the-marten-project/why-marten#familiar-ideas-designed-for-crystal) of Django though; it is designed around Crystal's type system and compilation model. This guide maps Django concepts to their Marten equivalents. For a hands-on introduction, you can continue with the [tutorial](https://martenframework.com/docs/next/getting-started/tutorial) once you have completed [installation](https://martenframework.com/docs/next/getting-started/installation). ## Concept map | Django | Marten | Learn more | | --- | --- | --- | | Model | [`Marten::Model`](https://martenframework.com/docs/next/models-and-databases/introduction) | ORM, validations, callbacks | | View (function or class-based) | [Handler](https://martenframework.com/docs/next/handlers-and-http/introduction) | Request processing | | Template (Django template language) | [Marten templates](https://martenframework.com/docs/next/templates/introduction) | Django-inspired syntax | | `urls.py` | [`config/routes.cr`](https://martenframework.com/docs/next/handlers-and-http/routing) | Route maps and reverse URLs | | Form / `ModelForm` | [Schema](https://martenframework.com/docs/next/schemas/introduction) | Input validation in handlers | | Generic class-based views | [Generic handlers](https://martenframework.com/docs/next/handlers-and-http/generic-handlers) | List, detail, create, update, delete | | `QuerySet` | [Query set](https://martenframework.com/docs/next/models-and-databases/queries) | Filtering, ordering, aggregation | | Migrations | [Migrations](https://martenframework.com/docs/next/models-and-databases/migrations) | Auto-generated with `genmigrations` | | `manage.py` | [`marten` CLI](https://martenframework.com/docs/next/development/management-commands) | Project management commands | | `settings.py` | [`config/settings/`](https://martenframework.com/docs/next/development/settings) | Per-environment configuration | | `INSTALLED_APPS` | [`installed_apps`](https://martenframework.com/docs/next/development/reference/settings#installed_apps) | Applications and reusable apps | | Middleware | [Middleware](https://martenframework.com/docs/next/handlers-and-http/middlewares) | Request/response pipeline | | `django.contrib.auth` | [Authentication](https://martenframework.com/docs/next/authentication/introduction) | Optional `--with-auth` app | | `django.contrib.sessions` | [Sessions](https://martenframework.com/docs/next/handlers-and-http/sessions) | Persisted between requests (cookie store by default) | | `django.contrib.messages` | [Flash store](https://martenframework.com/docs/next/handlers-and-http/introduction#using-the-flash-store) | One-request messages | | Translation / i18n | [Internationalization](https://martenframework.com/docs/next/i18n/introduction) | YAML locales via crystal-i18n | | `send_mail` | [Emailing](https://martenframework.com/docs/next/emailing/introduction) | Email classes and backends | | `cache` framework | [Caching](https://martenframework.com/docs/next/caching/introduction) | Cache stores | | `static` / `collectstatic` | [Assets](https://martenframework.com/docs/next/assets/introduction) | Collected with `collectassets` | ## What works differently ### Crystal comes first Marten is a Crystal framework. Even when APIs look Django-like, you will write Crystal code with static typing, compile-time checks, macros, and native compilation. If Crystal is new to you, you may want to skim the [Crystal language reference](https://crystal-lang.org/reference/) alongside this documentation. ### Handlers, not views In Django, "views" process requests and return responses. In Marten, this role is filled by [handlers](https://martenframework.com/docs/next/handlers-and-http/introduction). A handler is a class that receives a request and returns a response. HTTP verbs map to methods such as `#get` and `#post`, or to an overridden `#dispatch` method. [Handler callbacks](https://martenframework.com/docs/next/handlers-and-http/callbacks) can be used for logic that would otherwise live in a view's `dispatch` method or in middleware. ### Schemas instead of forms User input is usually validated through [schemas](https://martenframework.com/docs/next/schemas/introduction) rather than Django forms. Schemas define fields and validation rules, and handlers bind them to incoming request data. They are not model-bound like `ModelForm` classes; model-level validation still lives on [models](https://martenframework.com/docs/next/models-and-databases/validations). ### No built-in admin Django's automatic admin interface has no direct equivalent in Marten. You can build admin-style interfaces with handlers, templates, and generic handlers, or integrate a dedicated frontend. ### Dependencies and packaging Python packages map to [Crystal shards](https://crystal-lang.org/reference/the_shards_command/) declared in `shard.yml`. Reusable Marten functionality is often packaged as [applications](https://martenframework.com/docs/next/development/applications), which play a similar role to Django apps distributed as installable packages. Unlike `INSTALLED_APPS`, the main application associated with the `src/` folder is always available implicitly; only additional applications need to be listed in [`installed_apps`](https://martenframework.com/docs/next/development/reference/settings#installed_apps). ### Compile-time feedback Many mistakes surface at compile time rather than at runtime. This is usually a good thing: the compiler can catch issues early when refactoring models, handlers, and schemas. ## Where to go next * The [installation guide](https://martenframework.com/docs/next/getting-started/installation) will help you install Crystal and the Marten CLI * The [Applications](https://martenframework.com/docs/next/development/applications) guide explains how projects and apps are organized * The [models](https://martenframework.com/docs/next/models-and-databases/introduction) and [handlers](https://martenframework.com/docs/next/handlers-and-http/introduction) guides cover the core request and data flow * The [tutorial](https://martenframework.com/docs/next/getting-started/tutorial) will walk you through building a small application * [Why Marten?](https://martenframework.com/docs/next/the-marten-project/why-marten) compares Marten to other Crystal frameworks Please refer to [Acknowledgements](https://martenframework.com/docs/next/the-marten-project/acknowledgments#django) for a deeper look at Marten's Django lineage. # Coming from Rails? Source: https://martenframework.com/docs/next/getting-started/from-rails If you already know [Ruby on Rails](https://rubyonrails.org/), Marten will feel familiar in spirit. It provides a convention-oriented structure, models with validations and callbacks, migrations, and a batteries-included backend toolkit. Marten also draws from [Django](https://martenframework.com/docs/next/the-marten-project/acknowledgments#django) in areas like templates and applications. It is [not a port](https://martenframework.com/docs/next/the-marten-project/why-marten#familiar-ideas-designed-for-crystal) of Rails though; it is designed around Crystal. This guide maps Rails concepts to their Marten equivalents. For a hands-on introduction, you can continue with the [tutorial](https://martenframework.com/docs/next/getting-started/tutorial) once you have completed [installation](https://martenframework.com/docs/next/getting-started/installation). ## Concept map | Rails | Marten | Learn more | | --- | --- | --- | | ActiveRecord model | [`Marten::Model`](https://martenframework.com/docs/next/models-and-databases/introduction) | ORM, validations, callbacks | | Controller | [Handler](https://martenframework.com/docs/next/handlers-and-http/introduction) | Request processing | | View (ERB/Haml) | [Marten templates](https://martenframework.com/docs/next/templates/introduction) | Django-inspired syntax, not ERB | | `routes.rb` | [`config/routes.cr`](https://martenframework.com/docs/next/handlers-and-http/routing) | Route maps and reverse URLs | | Strong parameters / form objects | [Schema](https://martenframework.com/docs/next/schemas/introduction) | Input validation in handlers | | Scaffold / resourceful routing | [Generic handlers](https://martenframework.com/docs/next/handlers-and-http/generic-handlers) | List, detail, create, update, delete | | `ActiveRecord::Relation` | [Query set](https://martenframework.com/docs/next/models-and-databases/queries) | Filtering, ordering, aggregation | | Migrations | [Migrations](https://martenframework.com/docs/next/models-and-databases/migrations) | Auto-generated with `genmigrations` | | `bin/rails` | [`marten` CLI](https://martenframework.com/docs/next/development/management-commands) | Project management commands | | `config/application.rb` / environments | [`config/settings/`](https://martenframework.com/docs/next/development/settings) | Per-environment configuration | | Engine | [Application](https://martenframework.com/docs/next/development/applications) | Reusable app packaged as a shard | | Rack middleware | [Middleware](https://martenframework.com/docs/next/handlers-and-http/middlewares) | Request/response pipeline | | Authentication (eg. Devise) | [Authentication](https://martenframework.com/docs/next/authentication/introduction) | Optional `--with-auth` app | | `session` | [Sessions](https://martenframework.com/docs/next/handlers-and-http/sessions) | Persisted between requests (cookie store by default) | | `flash` | [Flash store](https://martenframework.com/docs/next/handlers-and-http/introduction#using-the-flash-store) | One-request messages | | I18n | [Internationalization](https://martenframework.com/docs/next/i18n/introduction) | YAML locales via crystal-i18n | | Action Mailer | [Emailing](https://martenframework.com/docs/next/emailing/introduction) | Email classes and backends | | `Rails.cache` | [Caching](https://martenframework.com/docs/next/caching/introduction) | Cache stores | | Asset pipeline / Propshaft | [Assets](https://martenframework.com/docs/next/assets/introduction) | Collected with `collectassets` | | Generators | [Generators](https://martenframework.com/docs/next/development/generators) | Models, handlers, schemas, etc. | ## What works differently ### Crystal, not Ruby Crystal's syntax is Ruby-inspired, which can ease the transition, but Marten applications are compiled Crystal programs. You get static typing, compile-time checks, and native binaries. Types and nilability are explicit, and the compiler is part of your day-to-day feedback loop. ### Handlers, not controllers Rails controllers map to Marten [handlers](https://martenframework.com/docs/next/handlers-and-http/introduction). Handlers receive a request object and return a response. You can use `#get`, `#post`, and other HTTP verb methods, or override `#dispatch`, instead of defining action methods on a controller. [Handler callbacks](https://martenframework.com/docs/next/handlers-and-http/callbacks) replace much of what you might otherwise do with `before_action`. ### Schemas instead of strong parameters Request data is usually validated through [schemas](https://martenframework.com/docs/next/schemas/introduction) rather than strong parameters or ActiveModel form objects. Schemas declare fields and rules; handlers initialize and validate them against incoming data. Model validations remain on [models](https://martenframework.com/docs/next/models-and-databases/validations). ### Templates are not ERB Marten templates use a [Django-inspired language](https://martenframework.com/docs/next/templates/introduction) with tags, filters, and auto-escaping. They are not ERB templates. The mental model is closer to Django templates than to Rails views. ### No built-in admin Marten has no equivalent to tools like Rails Admin or ActiveAdmin out of the box. Admin interfaces are built with handlers and templates. ### Dependencies and packaging Gems map to [Crystal shards](https://crystal-lang.org/reference/the_shards_command/) declared in `shard.yml`. Reusable features are packaged as Marten [applications](https://martenframework.com/docs/next/development/applications), which play a similar role to Rails engines. Application routes can be [included](https://martenframework.com/docs/next/handlers-and-http/routing#defining-included-routes) in the main routes map under a common prefix. The main application associated with the `src/` folder is always available implicitly; only additional applications need to be listed in [`installed_apps`](https://martenframework.com/docs/next/development/reference/settings#installed_apps). ### Frontend is your choice Marten is [backend-oriented](https://martenframework.com/docs/next/the-marten-project/why-marten#backend-oriented-by-choice). It does not prescribe a JavaScript bundler or SPA architecture. You can use server-rendered templates, a separate frontend, or whichever frontend toolchain best fits your project. ## Where to go next * The [installation guide](https://martenframework.com/docs/next/getting-started/installation) will help you install Crystal and the Marten CLI * The [Applications](https://martenframework.com/docs/next/development/applications) guide explains how projects and apps are organized * The [models](https://martenframework.com/docs/next/models-and-databases/introduction) and [handlers](https://martenframework.com/docs/next/handlers-and-http/introduction) guides cover the core request and data flow * The [tutorial](https://martenframework.com/docs/next/getting-started/tutorial) will walk you through building a small application * [Why Marten?](https://martenframework.com/docs/next/the-marten-project/why-marten) compares Marten to other Crystal frameworks Please refer to [Acknowledgements](https://martenframework.com/docs/next/the-marten-project/acknowledgments#ruby-on-rails) for a deeper look at Marten's Rails lineage. # Models and databases Source: https://martenframework.com/docs/next/models-and-databases Models define what data can be persisted and manipulated by a Marten application. They explicitly specify fields and rules that map to database tables and columns. ## Guides - [Introduction](https://martenframework.com/docs/next/models-and-databases/introduction) - [Queries](https://martenframework.com/docs/next/models-and-databases/queries) - [Relationships](https://martenframework.com/docs/next/models-and-databases/relationships) - [Validations](https://martenframework.com/docs/next/models-and-databases/validations) - [Callbacks](https://martenframework.com/docs/next/models-and-databases/callbacks) - [Migrations](https://martenframework.com/docs/next/models-and-databases/migrations) - [Transactions](https://martenframework.com/docs/next/models-and-databases/transactions) - [Raw SQL](https://martenframework.com/docs/next/models-and-databases/raw-sql) - [Multiple databases](https://martenframework.com/docs/next/models-and-databases/multiple-databases) ## How-to's - [Create custom model fields](https://martenframework.com/docs/next/models-and-databases/how-to/create-custom-model-fields) - [Create custom field predicates](https://martenframework.com/docs/next/models-and-databases/how-to/create-custom-field-predicates) ## Reference - [Model fields](https://martenframework.com/docs/next/models-and-databases/reference/fields) - [Table options](https://martenframework.com/docs/next/models-and-databases/reference/table-options) - [Query set](https://martenframework.com/docs/next/models-and-databases/reference/query-set) - [Migration operations](https://martenframework.com/docs/next/models-and-databases/reference/migration-operations) # Introduction to models Source: https://martenframework.com/docs/next/models-and-databases/introduction Models define what data can be persisted and manipulated by a Marten application. They explicitly specify fields and rules that map to database tables and columns. As such, they correspond to the layer of the framework that is responsible for representing business data and logic. ## Basic model definition Marten models must be defined as subclasses of the [`Marten::Model`](https://martenframework.com/docs/api/dev/Marten/DB/Model.html) base class; they explicitly define "fields" through the use of the `field` macro. These classes and fields map to database tables and columns that can be queried through the use of an automatically-generated database access API (see [Queries](https://martenframework.com/docs/next/models-and-databases/queries) for more details). For example, the following code snippet defines a simple `Article` model: ```crystal class Article < Marten::Model field :id, :big_int, primary_key: true, auto: true field :title, :string, max_size: 255 field :content, :text end ``` In the above example, `id`, `title`, and `content` are fields of the `Article` model. Each of these fields map to a database column in a table whose name is automatically inferred from the model name (and its associated application). If it was to be manually created using plain SQL, the `Article` model would correspond to the following statement (using the PostgreSQL syntax): ```sql CREATE TABLE myapp_articles ( "id" bigserial NOT NULL PRIMARY KEY, "title" varchar(255) NOT NULL, "content" text NOT NULL ); ``` ## Models and installed apps A model's application needs to be explicitly added to the list of installed applications for the considered project. Indeed, Marten requires projects to explicitly declare the applications they are using in the `installed_apps` configuration option. Model tables and migrations will only be created/applied for model classes that are provided by _installed apps_. For example, if the above `Article` model was associated with a `MyApp` application class, it would be possible to ensure that it is used by ensuring that the `installed_app` configuration option is as follows: ```crystal Marten.configure do |config| config.installed_apps = [ MyApp, # other apps... ] end ``` ## Model fields Model classes must define _fields_. Fields allow to specify the attributes of a model and they map to actual database columns. They are defined through the use of the `field` macro. For example: ```crystal class Author < Marten::Model field :id, :big_int, primary_key: true, auto: true field :first_name, :string, max_size: 255 field :last_name, :string, max_size: 255 end class Article < Marten::Model field :id, :big_int, primary_key: true, auto: true field :title, :string, max_size: 255 field :content, :text field :author, :many_to_one, to: Author end ``` ### Field ID and field type Every field in a model class must contain two mandatory positional arguments: a field identifier and a field type. The field identifier is used by Marten in order to determine the name of the corresponding database column. This identifier is also used to generate the Crystal bindings that allow you to interact with field values through getters and setters. The field type determines a few other things: * the type of the corresponding database column (for example `INTEGER`, `TEXT`, etc) * the getter and setter methods that are generated for the field in the model class * how field values are actually validated Marten provides numerous built-in field types that cover common web development needs. The complete list of supported fields is covered in the [model fields reference](https://martenframework.com/docs/next/models-and-databases/reference/fields). :::note It is possible to write custom model fields and use them in your model definitions. See [How to create custom model fields](https://martenframework.com/docs/next/models-and-databases/how-to/create-custom-model-fields) for more details. ::: ### Common field options In addition to their identifiers and types, fields can take keyword arguments that allow to further configure their behaviors and how they map to database columns. Most of the time those additional keyword arguments are optional, but they can be mandatory depending on the considered field type. Some of these optional field arguments are shared across all the available fields. Below is a list of the ones you'll encounter most frequently. #### `null` The `null` argument allows defining whether a field is allowed to store `NULL` values in the database. The default value for this argument is `false`. #### `blank` The `blank` argument allows defining whether a field is allowed to receive blank values from a validation perspective. The fields with `blank: false` that receive blank values will make their associated model record validation fail. The default value for this argument is `false`. #### `default` The `default` argument allows defining a default value for a given field. The default value for this argument is `nil`. #### `unique` The `unique` argument allows defining that values for a specific field must be unique throughout the associated table. The default value for this argument is `false`. ### Mandatory primary key All Marten models must define one (and only one) primary key field. This primary key field will usually be an `int` or a `big_int` field using the `primary_key: true` and `auto: true` arguments, like in the following example: ```crystal class MyModel < Marten::Model field :id, :big_int, primary_key: true, auto: true end ``` It should be noted that the primary key can correspond to any other field type. For example, your primary key could correspond to an `uuid` field: ```crystal class MyModel < Marten::Model field :id, :uuid, primary_key: true after_initialize :initialize_id def initialize_id @id ||= UUID.random end end ``` ### Relationships Marten provides special fields allowing to define the three most common types of database relationships: many-to-many, many-to-one, and one-to-one. #### Many-to-one relationships Many-to-one relationships can be defined through the use of [`many_to_one`](https://martenframework.com/docs/next/models-and-databases/reference/fields#many_to_one) fields. This special field type requires the use of a special `to` argument in order to specify the model class to which the current model is related. For example, an `Article` model could have a many-to-one field towards an `Author` model. In such case, an `Article` record would only have one associated `Author` record, but every `Author` record could be associated with many `Article` records: ```crystal class Author < Marten::Model # ... end class Article < Marten::Model # ... field :author, :many_to_one, to: Author end ``` :::tip It is possible to define recursive relationships by leveraging the `self` keyword. For example, if you want to define a many-to-one relationship field that targets that same model, you can do so easily by using `self` as the value for the `to` argument: ```crystal class TreeNode < Marten::Model # ... field :parent, :many_to_one, to: self end ``` ::: :::info Please refer to [Many-to-one relationships](https://martenframework.com/docs/next/models-and-databases/relationships#many-to-one-relationships) to learn more about this type of model relationship. ::: #### One-to-one relationships One-to-one relationships can be defined through the use of [`one_to_one`](https://martenframework.com/docs/next/models-and-databases/reference/fields#one_to_one) fields. This special field type requires the use of a special `to` argument in order to specify the model class to which the current model is related. For example, a `User` model could have a one-to-one field towards a `Profile` model. In such case, the `User` model could only have one associated `Profile` record, and the reverse would be true as well (a `Profile` record could only have one associated `User` record). In fact, a one-to-one field is really similar to a many-to-one field, but with an additional unicity constraint: ```crystal class Profile < Marten::Model # ... end class User < Marten::Model # ... field :profile, :one_to_one, to: Profile end ``` :::info Please refer to [One-to-one relationships](https://martenframework.com/docs/next/models-and-databases/relationships#one-to-one-relationships) to learn more about this type of model relationship. ::: #### Many-to-many relationships Many-to-many relationships can be defined through the use of [`many_to_many`](https://martenframework.com/docs/next/models-and-databases/reference/fields#many_to_many) fields. This special field type requires the use of a special `to` argument in order to specify the model class to which the current model is related. For example, an `Article` model could have a many-to-many field towards a `Tag` model. In such case, an `Article` record could have many associated `Tag` records, and every `Tag` record could be associated with many `Article` records as well: ```crystal class Tag < Marten::Model # ... end class Article < Marten::Model # ... field :tags, :many_to_many, to: Tag end ``` :::info Please refer to [Many-to-many relationships](https://martenframework.com/docs/next/models-and-databases/relationships#many-to-many-relationships) to learn more about this type of model relationship. ::: ### Timestamps Marten lets you easily add automatic `created_at` / `updated_at` [`date_time`](https://martenframework.com/docs/next/models-and-databases/reference/fields#date_time) fields to your models by leveraging the [`#with_timestamp_fields`](https://martenframework.com/docs/api/dev/Marten/DB/Model/Table.html#with_timestamp_fields-macro) macro: ```crystal class Article < Marten::Model // highlight-next-line with_timestamp_fields field :id, :big_int, primary_key: true, auto: true field :title, :string, max_size: 255 end ``` The `created_at` field is populated with the current time when new records are created while the `updated_at` field is refreshed with the current time whenever records are updated. Note that using [`#with_timestamp_fields`](https://martenframework.com/docs/api/dev/Marten/DB/Model/Table.html#with_timestamp_fields-macro) is technically equivalent as defining two `created_at` and `updated_at` [`date_time`](https://martenframework.com/docs/next/models-and-databases/reference/fields#date_time) fields as follows: ```crystal class Article < Marten::Model // highlight-next-line field :created_at, :date_time, auto_now_add: true // highlight-next-line field :updated_at, :date_time, auto_now: true field :id, :big_int, primary_key: true, auto: true field :title, :string, max_size: 255 end ``` ## Multifields indexes and unique constraints Single model fields can be indexed or associated with a unique constraint _individually_ by leveraging the [`index`](https://martenframework.com/docs/next/models-and-databases/reference/fields#index) and [`unique`](https://martenframework.com/docs/next/models-and-databases/reference/fields#unique) field options. That being said, it is sometimes necessary to configure multifields indexes or unique constraints. ### Multifields indexes Multifields indexes can be configured in a model by leveraging the [`#db_index`](https://martenframework.com/docs/api/dev/Marten/DB/Model/Table/ClassMethods.html#db_index(name%3AString|Symbol%2Cfield_names%3AArray(String)|Array(Symbol))%3ANil-instance-method) class method. This method requires an index name argument as well as an array of targeted field names. For example: ```crystal class Person < Marten::Model field :id, :int, primary_key: true, auto: true field :first_name, :string, max_size: 50 field :last_name, :string, max_size: 50 db_index :person_full_name_index, field_names: [:first_name, :last_name] end ``` ### Multifields unique constraints Multifields unique constraints can be configured in a model by leveraging the [`#db_unique_constraint`](https://martenframework.com/docs/api/dev/Marten/DB/Model/Table/ClassMethods.html#db_unique_constraint(name%3AString|Symbol%2Cfield_names%3AArray(String)|Array(Symbol))%3ANil-instance-method) class method. This method requires an index name argument as well as an array of targeted field names. For example: ```crystal class Booking < Marten::Model field :id, :int, primary_key: true, auto: true field :room, :string, max_size: 50 field :date, :date, max_size: 50 db_unique_constraint :booking_room_date_constraint, field_names: [:room, :date] end ``` The above constraint ensures that each room can only be booked for each date. ## CRUD operations CRUD stands for **C**reate, **R**ead, **U**pdate, and **D**elete. Marten provides a set of methods and tools allowing applications to read and manipulate data stored in model tables. ### Create Model records can be created through the use of the `#new` and `#create` methods. The `#new` method will simply initialize a new model record that is not persisted in the database. The `#create` method will initialize the new model record using the specified attributes and persist it to the database. For example, it would be possible to create a new `Article` model record by specifying its `title` and `content` attribute values through the use of the `#create` method as follows: ```crystal Article.create(title: "My article", content: "Learn how to build web apps with Marten!") ``` The same `Article` record could be initialized (but not saved!) through the use of the `new` method as follows: ```crystal Article.new(title: "My article", content: "Learn how to build web apps with Marten!") ``` It should be noted that field values can be assigned after a model instance has been initialized. For example, the previous example is equivalent to the following snippet: ```crystal article = Article.new article.title = "My article" article.content = "Learn how to build web apps with Marten!" ``` A model instance that was initialized like in the previous example will not be persisted to the database automatically. In this situation, it is possible to ensure that the corresponding record is created in the database by using the `#save` method (`article.save`). Finally it should be noted that both `#create` and `#new` support an optional block that will receive the initialized model record. This allows to initialize attributes or to call additional methods on the record being initialized: ```crystal Article.create do |article| article.title = "My article" article.content = "Learn how to build web apps with Marten!" end ``` ### Read Marten models provide a powerful API allowing to read and query records. This is achieved by constructing "query sets". A query set is a representation of records collections from the database that can be filtered. For example, it is possible to return a collection of all the `Article` model records using: ```crystal Article.all ``` It is possible to retrieve a specific record matching a set of filters (for example the value of an identifier) by using: ```crystal Article.get(id: 42) ``` Finally the following snippet showcases how to filter `Article` records by title and to sort them by creation date in reverse chronological order: ```crystal Article.filter(name: "My article").order("-created_at") ``` Please head over to the [Model queries](https://martenframework.com/docs/next/models-and-databases/queries) guide in order to learn more about model querying capabilities. ### Update Once a model record has been retrieved from the database, it is possible to update it by modifying its attributes and calling the `#save` method: ```crystal article = Article.get(id: 42) article.title = "Updated!" article.save ``` Marten also provide the ability to update the records that are targeted by a specific query set through the use of the `#update` method, like in the following example: ```crystal Article.filter(title: "My article").update(title: "Updated!") ``` #### Updating specific columns If you need to update only specific columns without running validations or callbacks, you can use the `#update_columns` or `#update_columns!` methods: ```crystal article = Article.get(id: 42) article.update_columns(title: "Updated!") ``` These methods are useful when you want to efficiently update a subset of fields without triggering the full save lifecycle. The `#update_columns!` variant will raise an error if called on a new (unsaved) record: ```crystal article = Article.new article.update_columns!(title: "New article") # Raises Marten::DB::Errors::UnmetSaveCondition ``` :::caution The `#update_columns` and `#update_columns!` methods bypass model validations and lifecycle callbacks (such as `before_update`, `after_update`, etc.). Use them with caution and only when you're certain that skipping these checks is safe for your application. ::: ### Delete Once a model record has been retrieved from the database, it is possible to delete it by using the `#delete` method: ```crystal article = Article.get(id: 42) article.delete ``` Marten also provide the ability to delete the records that are targeted by a specific query set through the use of the `#delete` method, like in the following example: ```crystal Article.filter(title: "My article").delete ``` ## Validations Marten lets you specify how to validate model records before they are persisted to the database. These validation rules can be inherited from the fields in your model depending on the options you used (for example fields using `blank: false` will make the associated record validation fail if the field value is blank). They can also be explicitly specified in your model class, which is useful if you need to implement custom validation logics. For example: ```crystal class User < Marten::Model field :id, :big_int, primary_key: true, auto: true field :name, :string, max_size: 255 validate :validate_name private def validate_name errors.add(:name, "Name must not be less than 3 characters!") if name && name!.size < 3 end end ``` Most of the methods presented above that actually persist model records to the database (like `#create` or `#save`) run these validation rules. This means that they will automatically validate the considered records before propagating any changes to the database. It should be noted that in the event that a record is invalid, these methods will return `false` to indicate that the considered object is invalid (and they will return `true` if the object is valid). The `#create` and `#save` methods also have bang counterparts (`#create!` and `#save!`) that will explicitly raise a validation error in case of invalid records: ```crystal article = Article.new article.save # => false article.save! # => Unhandled exception: Record is invalid (Marten::DB::Errors::InvalidRecord) ``` Please head over to the [Model validations](https://martenframework.com/docs/next/models-and-databases/validations) guide in order to learn more about model validations. ## Inheritance Model classes can inherit from each other. This allows you to easily reuse the field definitions and table attributes of a parent model within a child model. Presently, the Marten web framework allows [abstract model inheritance](#abstract-model-inheritance) (which is useful in order to reuse shared model fields and patterns over multiple child models without having a database table created for the parent model) and [multi-table inheritance](#multi-table-inheritance). ### Abstract model inheritance You can define abstract model classes by leveraging [Crystal's abstract type mechanism](https://crystal-lang.org/reference/syntax_and_semantics/virtual_and_abstract_types.html). Doing so allows to easily reuse model field definitions, table properties, and custom logics within child models. In this situation, the parent's model does not contribute any table to the considered database. For example: ```crystal abstract class Person < Marten::Model field :id, :big_int, primary_key: true, auto: true field :name, :string, max_size: 255 field :email, :string, max_size: 255 end class Student < Person field :grade, :string, max_size: 15 end ``` The `Student` model will have four model fields in total (`id`, `name`, `email`, and `grade`). Moreover, all the methods of the parent model fields will be available on the child model. It should be noted that in this case the `Person` model cannot be used like a regular model: for example, trying to query records will return an error since no table is actually associated with the abstract model. Since it is an [abstract type](https://crystal-lang.org/reference/syntax_and_semantics/virtual_and_abstract_types.html), the `Student` class can't be instantiated either. ### Multi table inheritance Marten also supports another form of model inheritance, where each model in the hierarchy is a concrete model (i.e., a model that is not abstract). In this situation, each model can be used/queried individually and has its own associated table. The framework upholds "links" between each model that uses multi table inheritance and its parent models in order to ensure that the relational structure and inheritance hierarchy are accurately maintained. For example, let's consider the following models: ```crystal class Person < Marten::Model field :id, :big_int, primary_key: true, auto: true field :first_name, :string, max_size: 100 field :last_name, :string, max_size: 100 end class Employee < Person field :company_name, :string, max_size: 100 end ``` All the fields defined in the `Person` model will be accessible when interacting with records of the `Employee` model, despite the fact that the data itself is stored in distinct tables. This means that it will be possible to filter `Employee` records using fields defined in the `Person` model, and to interact with the corresponding attributes when manipulating the obtained model instances: ```crystal employee = Employee.filter(first_name: "John").first! employee.first_name # => "John" ``` Initializing or creating `Employee` records will also work as you would expect if all the fields were defined in the `Employee` model class: ```crystal employee = Employee.create!( first_name: "John", last_name: "Doe", company_name: "Super org" ) ``` Additionally, it's important to note that attempting to filter or retrieve `Person` records will return `Person` instances. When manipulating a parent model instance, it is possible to get a child model record by calling the `#` method - with `child_model` being the downcased version of the child model name. For example: ```crystal person = Person.filter(first_name: "John").first! person.employee # => # ``` You should note that if the `Person` record is not an employee, then calling `#employee` will return `nil`. :::note It's important to note that when retrieving and filtering model records that utilize multi-table inheritance (such as child model records), there will be added join operations within the underlying SQL queries. These joins are necessary to assemble the complete data from various related tables, potentially affecting the overall query performance. ::: ## Callbacks It is possible to define callbacks in your model in order to bind methods and logics to specific events in the life cycle of your model records. For example, it is possible to define callbacks that run before a record gets created, or before it is destroyed. Please head over to the [Model callbacks](https://martenframework.com/docs/next/models-and-databases/callbacks) guide in order to learn more about model callbacks. ## Migrations When working with models, it is necessary to ensure that any changes made to model definitions are applied at the database level. This is achieved through the use of migrations. Marten provides a migrations mechanism that is designed to be automatic: this means that migrations will be automatically generated from your model definitions when you run a dedicated command (the `genmigrations` command). Please head over to [Model migrations](https://martenframework.com/docs/next/models-and-databases/migrations) in order to learn more about migrations generations and the associated workflows. # Querying model records Source: https://martenframework.com/docs/next/models-and-databases/queries Once [models are properly defined](https://martenframework.com/docs/next/models-and-databases/introduction), it is possible to leverage the querying API in order to interact with model records. This API lets you build what is commonly referred to as "query sets": that is, representations of records collections that can be read, filtered, updated, or deleted. This documents covers the main features of the [query set API](https://martenframework.com/docs/next/models-and-databases/reference/query-set). Most of the examples used to illustrate these features will refer to the following models: ```crystal class City < Marten::Model field :id, :big_int, primary_key: true, auto: true field :name, :string, max_size: 255 field :population, :int, null: true, blank: true end class Author < Marten::Model field :id, :big_int, primary_key: true, auto: true field :first_name, :string, max_size: 255 field :last_name, :string, max_size: 255 field :hometown, :foreign_key, to: City, blank: true, null: true end class Article < Marten::Model field :id, :big_int, primary_key: true, auto: true field :title, :string, max_size: 255 field :subtitle, :string, max_size: 255, blank: true, null: true field :content, :text field :author, :many_to_one, to: Author, related: :articles end ``` ## Creating new records New model records can be created through the use of the `#new` and `#create` methods. The `#new` method will simply initialize a new model record that is not persisted in the database. The `#create` method will initialize the new model record using the specified attributes and then persist it to the database. For example, it is possible to create a new `Author` model record by specifying their `first_name` and `last_name` attribute values through the use of the `create` method like this: ```crystal Author.create(first_name: "John", last_name: "Doe") ``` The same `Author` record could be initialized (but not saved!) through the use of the `new` method as follows: ```crystal Author.new(first_name: "John", last_name: "Doe") ``` In the previous example the model instance will not be persisted to the database automatically. In order to explicitly save it to the database it is possible to use the `#save` method: ```crystal author = Author.new(first_name: "John", last_name: "Doe") # not persisted yet! author.save # the author is now persisted to the database! ``` Finally, it should be noted that both `#create` and `#new` support an optional block that will receive the initialized model record. This allows to initialize attributes or to call additional methods on the record being initialized: ```crystal Author.create do |author| author.first_name = "John" author.last_name = "Doe" end ``` :::caution Model records will be validated before being saved to the database. If this validation fails, both the `#create` and `#save` methods will silently fail: `#create` will return the invalid model instance while `#save` will return `false`. The `#create` and `#save` methods also have bang counterparts (`#create!` and `#save!`) that will explicitly raise a validation error (`Marten::DB::Errors::InvalidRecord`) in case of an invalid record. Please refer to [Validations](https://martenframework.com/docs/next/models-and-databases/validations) in order to learn more about model validations. ::: ## Basic querying capabilities In order to interact with a collection of model records, it is necessary to construct a "query set". A query set represents a collection of model records in the database. It can have filters, be paginated, etc. Unless a specific "write" operation is performed on such query sets, they will usually be mapped to a standard `SELECT` statement where filters are converted to `WHERE` clauses. Query sets can be forged from a specific model by using methods such `#all`, `#filter`, or `#exclude` (those are described below). One of the key characteristics of query sets is that they are **lazily evaluated**: defining a query set will usually not involve any database operation. Additionally, most methods provided by query sets also return new query set objects. Query sets are only translated to SQL queries hitting the underlying database when records need to be extracted or manipulated by the considered codebase. For example, filters can be chained on a query set without it being evaluated. The query set is only evaluated when the actual records need to be displayed or when it becomes necessary to interact with them: ```crystal qset = Article.filter(title__startswith: "Top") # the query set is not evaluated qset = qset.filter(author__first_name: "John") # the query set is not evaluated puts qset # the query set is evaluated ``` In the above example, the two filters are simply chained without these resulting in database hits. The query set is only evaluated when the actual records need to be printed. Query sets are **iterable**: they provide the ability to iterate over the resulting records (which will also force the query set to be evaluated when this happens): ```crystal qset = Article.filter(title__startswith: "Top") # the query set is not evaluated qset.each { |article| puts article } # the query set is evaluated ``` ### Querying all records Retrieving all the records of a specific model can be achieved through the use of the `#all` method: ```crystal Author.all ``` "All records" does not necessarily mean all the records in the considered table. For example, `#all` can be chained to an existing query set that was filtered (which is usually unnecessary since this does not alter the resulting records): ```crystal Author.filter(first_name: "John").all ``` ### Filtering specific records Filtering records is achieved through the use of the `#filter` method. The `#filter` method requires one or many predicate keyword arguments (in the format described in [Field predicates](#field-predicates)). For example: ```crystal Author.filter(first_name: "John") ``` The above query set will return `Author` records whose first name is "John". It’s possible to filter records using multiple filters. For example, the following queries are equivalent: ```crystal Author.filter(first_name: "John").filter(last_name: "Doe") Author.filter(first_name: "John", last_name: "Doe") ``` By default, filters involving multiple parameters like in the above examples always produce SQL queries whose parameters are "AND"ed together. More complex queries (eg. using AND, OR, XOR, or NOT conditions) can be achieved through the use of the `q` DSL (which is described in [Complex filters with `q` expressions](#complex-filters-with-q-expressions)), as outlined by the following examples: ```crystal # Get Author records with either "Bob" or "Alice" as first name Author.filter { q(first_name: "Bob") | q(first_name: "Alice") } # Get Author records whose first names are not "John" Author.filter { -q(first_name: "Alice") } ``` Marten also has the option to filter query sets using [raw SQL predicates](https://martenframework.com/docs/next/models-and-databases/raw-sql#filtering-with-raw-sql-predicates). This is useful when you want to leverage the flexibility of SQL for specific conditions, but still want Marten to handle the column selection and query building for the rest of the query. To use raw SQL predicates, can specify a string containing the predicate with optional parameters to the `#filter` query set method: ```crystal Author.filter("first_name = :first_name", first_name: "John") Author.filter("first_name = ?", "John") Author.filter { q("first_name = :first_name", first_name: "John") } ``` ### Excluding specific records Excluding records is achieved through the use of the `#exclude` method. This method provides exactly the same API as the [`#filter`](#filtering-specific-records) method outlined previously. It requires one or many predicate keyword arguments (in the format described in [Field predicates](#field-predicates)). For example: ```crystal Author.exclude(first_name: "John") Author.exclude(first_name: "John").exclude(last_name: "Doe") Author.exclude(first_name: "John", last_name: "Doe") Author.exclude { q(first_name: "Bob") | q(first_name: "Alice") } ``` ### Retrieving a specific record Retrieving a specific record is achieved through the use of the `#get` method, which requires one or many predicate keyword arguments (in the format described in [Field predicates](#field-predicates)). For example: ```crystal Author.get(id: 1) Author.get(first_name: "John") ``` If the record is not found, `nil` will be returned. It should be noted that a bang version of this method also exists: `#get!`. This alternative method raises a `Marten::DB::Errors::RecordNotFound` error if the record is not found. Regardless of the method used, if multiple records are found for the passed predicates, a `Marten::DB::Errors::MultipleRecordsFound` error is raised. It is also possible to chain a `#get` call on a query set that was already filtered: ```crystal Author.filter(first_name: "John").get(id: 42) ``` A record can also be retrieved with a raw SQL predicate. For example: ```crystal Author.get("id=?", 42) Author.get("id=:id", id: 42) ``` ### Retrieving the first or last record The `#first` and `#last` methods can be used to retrieve the first or last record for a given query set. ```crystal Author.filter(first_name: "John").first Author.filter(first_name: "John").last ``` If the considered query set is empty, the returned value will be `nil`. It should be noted that these methods have a bang equivalent (`#first!` and `#last!`) that both raise a `NilAssertionError` if the query set is empty. ### Field predicates Field predicates allow to define filters that are applied to a given query set. They map to `WHERE` clauses in the produced SQL queries. For example: ```crystal Article.filter(title__icontains: "top") ``` Will translate to a SQL query like the following one (using PostgreSQL's syntax): ```sql SELECT * FROM articles WHERE title LIKE UPPER("top") ``` Field predicates always contain a mandatory field name (`title` in the previous example) and an optional predicate type (`icontains` in the previous example). The field name and the predicate type are always separated by a double underscore notation (`__`). This notation (`__`) is used as the keyword argument name while the argument value is used to define the value to use to perform the filtering. :::tip The field name can correspond to any of the fields defined in the model being filtered. For `many_to_one` or `one_to_one` fields, it's possible to append a `_id` at the end of the field name to explicitly filter on the raw ID of the related record: ```crystal Article.all.filter(author_id: 42) ``` ::: Marten support numerous predicate types, which are all documented in the [field predicates reference](https://martenframework.com/docs/next/models-and-databases/reference/query-set#field-predicates). Implementing custom field predicates is also a possibility that is documented in [Create custom field predicates](https://martenframework.com/docs/next/models-and-databases/how-to/create-custom-field-predicates). The ones that you'll encounter most frequently are outlined below: #### `exact` The `exact` field predicate can be used for "exact" matches: only records whose field values exactly match the specified value will be returned. This is the default predicate type, and it's not necessary to specify it when filtering model records. As such, the two following examples are equivalent: ```crystal Author.filter(first_name: "John") Author.filter(first_name__exact: "John") ``` #### `iexact` This field predicate can be used for case insensitive matches. For example, the following filter would return `Article` records whose titles are `Test`, `TEST` or `test`: ```crystal Article.filter(title__iexact: "test") ``` #### `contains` This field predicate can be used to filter strings that should contain a specific value. For example: ```crystal Article.filter(title__contains: "top") ``` A case insensitive equivalent (`icontains`) is also available. ### Field transformations Field transformations allow to apply transformations to field values before they are used in a query set when filtering records with [predicates](#field-predicates). They map to SQL functions in the produced SQL queries. For example: ```crystal Article.filter(released_on__year: 2022) ``` Will allow to filter `Article` records whose `released_on` field values are associated with the year 2022, with the transformation of the datetime field to an integer representing the year being performed at the SQL level. Most of the [field predicates](#field-predicates) can be used in combination with field transformations. For example: ```crystal Article.filter(released_on__year__gt: 2022) ``` Please refer to the [field transformations reference](https://martenframework.com/docs/next/models-and-databases/reference/query-set#field-transformations) for more details on the available field transformations. ## Advanced querying capabilities ### Complex filters with `q` expressions As mentioned previously, field predicates expressed as keyword arguments will use an AND operator in the produced `WHERE` clauses. In order to produce conditions using other operators, it is necessary to use `q` expressions. In order to produce such expressions, methods like `#filter`, `#exclude`, or `#get` can receive a block allowing to define complex conditions. Inside of this block, a `#q` method can be used in order to define conditions nodes that can be combined together using the following operators: * `&` in order to perform a logical "AND" * `|` in order to perform a logical "OR" * `^` in order to perform a logical "XOR" * `-` in order to perform a logical negation For example, the following snippet will return all the `Article` records whose title starts with "Top" or "10": ```crystal Article.filter { q(title__startswith: "Top") | q(title__startswith: "10") } ``` Using this approach, it is possible to produce complex conditions by combining `q()` expressions with the `&`, `|`, `^`, and `-` operators. Parentheses can also be used to group statements: ```crystal Article.filter { (q(title__startswith: "Top") | q(title__startswith: "10")) & -q(author__first_name: "John") } ``` Finally it should be noted that you can define many field predicates _inside_ `q()` expressions. When doing so, the field predicates will be "AND"ed together: ```crystal Article.filter { q(title__startswith: "Top") & -q(author__first_name: "John", author__last_name: "Doe") } ``` ### Filtering relations The double underscores notation described previously (`__`) can also be used to filter based on related model fields. For example, in the considered models definitions, we have an `Article` model which defines a relation (`many_to_one` field) to the `Author` model through the `author` field. The `Author` model itself also defines a relation to a `City` record through the `hometown` field. Given this data model, we could easily retrieve `Article` records whose author's first name is "John" with the following query set: ```crystal Article.filter(author__first_name: "John") ``` We could even retrieve all the `Article` records whose author are located in "Montréal" with the following query set: ```crystal Article.filter(author__hometown__name: "Montreal") ``` And obviously, the above query sets could also be used along with more specific field predicate types. For example: ```crystal Author.filter(author__hometown__name__startswith: "New") ``` When doing “deep filtering” like this, related model tables are automatically "joined" at the SQL level to perform the query (inner joins or left outer joins are used depending on the nullability of the filtered fields). It is worth noting that this filtering capability also works for [many-to-many relationships](https://martenframework.com/docs/next/models-and-databases/relationships#many-to-many-relationships) and reverse relations. For example, assuming that the `Article` model defines a `tags` [many-to-many](https://martenframework.com/docs/next/models-and-databases/reference/fields#many_to_many) field towards a hypothetical `Tag` model, the following query would be possible: ```crystal Article.filter(tags__label: "crystal") ``` ### Pre-selecting relations with joins It is also possible to explicitly define that a specific query set must "join" a set of relations. This can result in nice performance improvements since this can help reduce the number of SQL queries performed for a given codebase. This is achieved through the use of the [`#join`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#join) method: ```crystal author_1 = Author.filter(first_name: "John") puts author_1.hometown # DB hit to retrieve the associated City record author_2 = Author.join(:hometown).filter(first_name: "John") puts author_2.hometown # No additional DB hit ``` The double underscores notations can also be used in the context of joins. For example: ```crystal # The associated Author and City records will be selected and fully initialized # with the selected Article record. Article.join(:author__hometown).get(id: 42) ``` Finally, it is worth mentioning that many relations can be specified to [`#join`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#join). For example: ```crystal Article.join(:author__hometown, :edited_by) ``` :::info Please note that the [`#join`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#join) query set method can only be used on [many-to-one](https://martenframework.com/docs/next/models-and-databases/relationships#many-to-one-relationships) relationships, [one-to-one](https://martenframework.com/docs/next/models-and-databases/relationships#one-to-one-relationships) relationships, and reverse one-to-one relations. For multi-valued relations, please consider [pre-fetching records](#pre-fetching-relations). ::: ### Pre-fetching relations While [pre-selecting relations with joins](#pre-selecting-relations-with-joins) can result in performance improvements (and help in reducing the number of SQL queries) by performing joins at the SQL level, is also possible to _pre-fetch relations_ using the [`#prefetch`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#prefetch) method. Both methods serve a common purpose, aiming to alleviate N+1 issues commonly encountered when accessing related objects. However, their strategies diverge in approach: * When using [`#join`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#join), the specified relationships are followed and each record returned by the considered query set has the corresponding related objects already selected and populated. The performance improvements are achieved by reducing the number of SQL queries since related records are retrieved by creating an SQL join and by including their fields in the main SELECT statement. Because of this, [`#join`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#join) can only be used on single-valued relationships: [many-to-one](https://martenframework.com/docs/next/models-and-databases/relationships#many-to-one-relationships) relationships, [one-to-one](https://martenframework.com/docs/next/models-and-databases/relationships#one-to-one-relationships) relationships, and reverse one-to-one relations. * When using [`#prefetch`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#prefetch), the records corresponding to the specified relationships will be prefetched in single batches and each record returned by the original query set will have the corresponding related objects already selected and populated. As such, [`#prefetch`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#prefetch) can be used with any kind of relationship: [many-to-one](https://martenframework.com/docs/next/models-and-databases/relationships#many-to-one-relationships) relationships, [one-to-one](https://martenframework.com/docs/next/models-and-databases/relationships#one-to-one-relationships) relationships, [many-to-many](https://martenframework.com/docs/next/models-and-databases/relationships#many-to-many-relationships) relationships, and all types of reverse relations. For example, assuming that a `Post` model defines a `tags` many-to-many field: ```crystal posts_1 = Post.all.to_a # hits the database to retrieve the related "tags" (many-to-many relation) puts posts_1[0].tags.to_a posts_2 = Post.all.prefetch(:tags).to_a # doesn't hit the database since the related "tags" relation was already prefetched puts posts_2[0].tags.to_a ``` The double underscores notations can also be used when pre-fetching relations. In this situation, the records targeted by the original query set will be decorated with the prefetched records, and those records will be decorated with the following prefetched records. For example: ```crystal # The associated Book and BookGenres records will be pre-fetched and fully initialized # at the Author and Book records levels. Author.prefetch(:books__genres) ``` Finally, it is worth mentioning that multiple relations can be specified to [`#prefetch`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#prefetch). For example: ```crystal Author.prefetch(:books__genres, :publisher) ``` ### Pagination Marten provides a pagination mechanism that you can leverage in order to easily iterate over records that are split across several pages of data. This works as follows: each query set object lets you generate a "paginator" (instance of [`Marten::DB::Query::Paginator`](https://martenframework.com/docs/api/dev/Marten/DB/Query/Paginator.html)) from a given page size (the number of records you would like on each page). You can then use this paginator in order to request specific pages, which gives you access to the corresponding records and to some additional pagination metadata. For example: ```crystal query_set = Article.filter(published: true) paginator = query_set.paginator(10) paginator.page_size # => 10 paginator.pages_count # => 6 paginator.total_count # => 60 # Retrieve the first page and iterate over the underlying records page = paginator.page(1) page.each { |article| puts article } page.number # 1 page.previous_page? # => false page.previous_page_number # => nil page.next_page? # => true page.next_page_number # => 2 page.total_count # => 60 ``` As you can see, paginator objects let you request specific pages by providing a page number (1-indexed!) to the [`#page`](https://martenframework.com/docs/api/dev/Marten/DB/Query/Paginator.html#page(number%3AInt)-instance-method) method. Such pages are instances of [`Marten::DB::Query::Page`](https://martenframework.com/docs/api/dev/Marten/DB/Query/Page.html) and give you the ability to easily iterate over the corresponding records. They also give you the ability to retrieve some pagination-related information (eg. about the previous and next pages by leveraging the [`#previous_page?`](https://martenframework.com/docs/api/dev/Marten/DB/Query/Page.html#previous_page%3F-instance-method), [`#previous_page_number`](https://martenframework.com/docs/api/dev/Marten/DB/Query/Page.html#previous_page_number-instance-method), [`#next_page?`](https://martenframework.com/docs/api/dev/Marten/DB/Query/Page.html#next_page%3F-instance-method), and [`#next_page_number`](https://martenframework.com/docs/api/dev/Marten/DB/Query/Page.html#next_page_number-instance-method) methods). ## Updating records Once a model record has been retrieved from the database, it is possible to update it by modifying its attributes and calling the `#save` method (already mentioned previously): ```crystal article = Article.get(id: 42) article.title = "Updated!" article.save ``` It is also possible to update records through the use of query sets. To do so, the `#update` method can be chained to a pre-defined query set in order to update all the resulting records: ```crystal Article.filter(title: "My article").update(title: "Updated!") ``` When calling the `#update` method like in the previous example, the update is done at the SQL level (using a regular `UPDATE` SQL statement) and the method returns the number of impacted records. As such it's important to remember that records updated like this won't be instantiated or validated before the update, and that no callbacks will be executed for them. ## Deleting records Single model records that have been retrieved from the database can be deleted by using the `#delete` method: ```crystal article = Article.get(id: 42) article.delete ``` Marten also provide the ability to delete the records that are targeted by a specific query set through the use of the `#delete` method, like in the following example: ```crystal Article.filter(title: "My article").delete ``` By default, related objects that are associated with the deleted records will also be deleted by following the deletion strategy defined in each relation field (`on_delete` option, see the [reference](https://martenframework.com/docs/next/models-and-databases/reference/fields#on_delete) for more details). The method always returns the number of deleted records. ## Scopes Scopes allow for the pre-definition of specific filtered query sets, which can be easily applied to model classes and model query sets. When defining such scopes, all the query set capabilities that were covered previously (such as [filtering records](#filtering-specific-records), [excluding records](#excluding-specific-records), etc) can be leveraged. ### Defining scopes Scopes can be defined through the use of the [`#scope`](https://martenframework.com/docs/api/dev/Marten/DB/Model/Querying.html#scope(name%2C%26block)-macro) macro. This macro expects a scope name (string literal or symbol) as first argument and requires a block where the query set filtering logic is defined. For example: ```crystal class Post < Marten::Model field :id, :big_int, primary_key: true, auto: true field :title, :string, max_size: 255 field :is_published, :bool, default: false field :created_at, :date_time // highlight-next-line scope :published { filter(is_published: true) } // highlight-next-line scope :unpublished { filter(is_published: false) } // highlight-next-line scope :recent { filter(created_at__gt: 1.year.ago) } end ``` Considering the above model definition, it is possible to get published posts by using the following method call: ```crystal Post.published # => Post::QuerySet [...]> ``` Similarly, retrieving all published posts from a query set object can be accomplished by calling the `#published` method on the query set object: ```crystal query_set = Post.all query_set.published # => Post::QuerySet [...]> ``` Because of this capability, it is important to note that scopes can technically be chained. For example, the following snippet will return all the published posts that were created less than one year ago: ```crystal Post.published.recent # => Post::QuerySet [...]> ``` ### Defining scopes with arguments If needed, you can define scopes that require arguments. To accomplish this, simply include the required arguments within the scope block. For example: ```crystal class Post < Marten::Model field :id, :big_int, primary_key: true, auto: true field :title, :string, max_size: 255 field :author, :many_to_one, to: Author // highlight-next-line scope :by_author_id { |author_id| filter(author_id: author_id) } end ``` Scopes that require arguments can be used in the same way as argument-free scopes; they can be called on model classes or model query sets: ```crystal Post.by_author_id(42) # => Post::QuerySet [...]> query_set = Post.all query_set.by_author_id(42) # => Post::QuerySet [...]> ``` ### Defining default scopes By default, querying all model records returns unfiltered query sets. However, you can define a default scope to automatically apply a specific filter to all queries for that model. This ensures that certain criteria are consistently enforced without the need to explicitly include a specific filter in every query. Default scopes can be defined through the use of the [`#default_scope`](https://martenframework.com/docs/api/dev/Marten/DB/Model/Querying.html#default_scope-macro) macro. This macro requires a block where the query set filtering logic is defined. For example: ```crystal class Post < Marten::Model field :id, :big_int, primary_key: true, auto: true field :title, :string, max_size: 255 field :is_published, :bool, default: false field :created_at, :date_time // highlight-next-line default_scope { filter(is_published: true) } end ``` ### Disabling scoping It is worth mentioning that unscoped model records are always accessible through the use of the [`#unscoped`](https://martenframework.com/docs/api/dev/Marten/DB/Model/Querying/ClassMethods.html#unscoped-instance-method) class method. This is especially useful if your model defines a default scope and you need to override it for certain queries. For example: ```crystal class Post < Marten::Model field :id, :big_int, primary_key: true, auto: true field :title, :string, max_size: 255 field :is_published, :bool, default: false field :created_at, :date_time // highlight-next-line default_scope { filter(is_published: true) } end ``` Considering, the above model definition, you can retrieve all the `Post` records by bypassing the default scope with: ```crystal Post.unscoped # => Post::QuerySet [...]> ``` ## Aggregations The previous sections have covered the ways to filter and order model records. However, there are times when you need to retrieve calculated values that summarize or aggregate collections of objects. This section describes how to generate and return aggregate values using Marten's query API. When considering aggregations, we can usually consider two main use cases: * Returning a single calculated value from a given query set. * Annotating a query set with additional aggregated data that can be filtered on and that is made available for each record in the query set. ### Returning a single aggregated value #### Counting objects The most basic aggregation is counting the number of objects in a query set. This can be done by using the [`#count`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#count) method. For example: ```crystal Article.all.count # returns the number of article records Article.all.count(:subtitle) # returns the number of articles where the subtitle is not null Article.filter(title__startswith: "Top").count # returns the number of articles whose title start with "Top" ``` #### Summing values The [`#sum`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#sum) method returns the sum of the values of a given model field. For example: ```crystal City.all.sum(:population) # returns the sum of the population values of all cities ``` #### Calculating averages The [`#average`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#average) method returns the average of the values of a given model field. For example: ```crystal City.all.average(:population) # returns the average of the population values of all cities ``` #### Calculating minimum and maximum values The [`#minimum`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#minimum) and [`#maximum`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#maximum) methods return the minimum and maximum values of a given model field across a query set, respectively. For example: ```crystal City.all.minimum(:population) # returns the minimum population value of all cities City.all.maximum(:population) # returns the maximum population value of all cities ``` ### Annotating query sets with aggregated data The previous sections have covered the ways to retrieve a single aggregated value from a given query set. However, sometimes you will need to "retain" the aggregated values for each record in the query set (possibly for further filtering or for making use of the aggregated values when dealing with individual records). This can be achieved by using the [`#annotate`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#annotate) method. This method requires the use of a block that will be used to define the aggregated value for each record in the query set. For example: ```crystal query_set = Author.all.annotate { count(:articles) } ``` All the types of aggregation methods covered previously can be used within the block. For example: | Aggregation method | Description | |---------------------|-------------| | `count` | Counts the number of records | | `sum` | Returns the sum of the values of a given field | | `average` | Returns the average of the values of a given field | | `minimum` | Returns the minimum value of a given field | | `maximum` | Returns the maximum value of a given field | For example: ```crystal Author.all.annotate { count(:articles) } Author.all.annotate { sum(:articles__score) } Author.all.annotate { average(:articles__score) } Author.all.annotate { minimum(:articles__score) } Author.all.annotate { maximum(:articles__score) } ``` #### Accessing annotated values Once an annotated query set has been retrieved, it is possible to access the annotated values for each record by using the [`#annotations`](https://martenframework.com/docs/api/dev/Marten/DB/Model.html#annotations%3AHash(String%2CBool|File|Float32|Float64|Int32|Int64|JSON%3A%3AAny|JSON%3A%3ASerializable|Marten%3A%3ADB%3A%3AField%3A%3AFile%3A%3AFile|Marten%3A%3AHTTP%3A%3AUploadedFile|String|Symbol|Time|Time%3A%3ASpan|UUID|Nil)-instance-method) method. This method returns a hash where the keys are the names of the annotated fields and the values are the annotated values. For example: ```crystal annotated_query_set = Author.all.annotate { count(:articles) } annotated_query_set.each do |author| puts author.annotations["articles_count"] end ``` It is worth mentioning that the annotation names are generated by concatenating the field or relation name with the annotation type. For example, the annotation name for the `count` annotation on the `articles` reverse relation is `articles_count`, unless [an alias name is specified](#specifying-an-alias-name-for-an-annotation). #### Specifying multiple annotations It is also possible to specify multiple annotations at once when using the [`#annotate`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#annotate) method. This can be achieved by calling the method multiple times or by defining the block over multiple lines. For example, the following two query sets are equivalent: ```crystal query_set_1 = Author.all .annotate { count(:articles) } .annotate { sum(:articles__score) } query_set_2 = Article.all.annotate do count(:articles) sum(:articles__score) end ``` #### Specifying an alias name for an annotation It is also possible to specify an alias name for an annotation by using the `#as` method. This can be achieved by calling the annotation method with the alias name specified with the `alias_name` argument or by calling the `#alias` method on the annotation object itself. For example, the following two query sets are equivalent: ```crystal query_set_1 = Author.all.annotate { count(:articles, alias_name: :my_ann) } query_set_2 = Author.all.annotate { count(:articles).alias(:my_ann) } ``` In the previous examples, the annotation value will be available under the `my_ann` key instead of the default `articles_count` one when [accessing the annotated values](#accessing-annotated-values). #### Computing distinct annotations It is also possible to compute distinct annotations by specifying the `distinct: true` argument to the annotation method or by calling the `#distinct` method on the annotation object itself. For example, the following two query sets are equivalent: ```crystal query_set_1 = Author.all.annotate { sum(:articles__score, distinct: true) } query_set_2 = Author.all.annotate { sum(:articles__score).distinct } ``` In the previous examples, the annotation value will be computed by summing the distinct values of the `score` field. #### Ordering by annotated values It is possible to order the records of a query set by an annotated value by using the [`#order`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#order) method. To do so, you can simply specify the aliases of the annotated values you want to order by. For example: ```crystal Author.all.annotate { count(:articles) }.order(:articles_count) Author.all.annotate { count(:articles) }.order("-articles_count") ``` #### Filtering on annotated values To filter on annotated values, you can use the [`#filter`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#filter) method and use the aliases of the annotated values you want to filter on. For example: ```crystal Author.all.annotate { count(:articles) }.filter(articles_count__gt: 10) Author .filter(first_name: "John") .annotate { count(:articles) } .filter(articles_count__gt: 10) ``` :::warning Filtering on annotated values is an experimental feature. All database backends supported by Marten allow filtering on annotated values as long as those filters are applied separately from filters targeting other fields. If you want to combine filters in a single `#filter` call that targets both annotated values and other fields, you should note that this is only supported by the PostgreSQL and SQLite backends at the moment. ::: # Relationships Source: https://martenframework.com/docs/next/models-and-databases/relationships Marten offers a powerful and intuitive solution for defining the three most common types of database relationships (many-to-one, one-to-one, and many-to-many) through the use of [model fields](https://martenframework.com/docs/next/models-and-databases/introduction#model-fields). By leveraging these special fields, developers can enhance their application's data modeling and streamline data access. ## Many-to-one relationships Many-to-one relationships can be defined through the use of [`many_to_one`](https://martenframework.com/docs/next/models-and-databases/reference/fields#many_to_one) fields. This special field type requires the utilization of the [`to`](https://martenframework.com/docs/next/models-and-databases/reference/fields#to-1) argument, allowing to explicitly define the target model class associated with the current model. For example, an `Article` model could have a many-to-one field towards an `Author` model. In such case, an `Article` record would only have one associated `Author` record, but every `Author` record could be associated with many `Article` records: ```crystal class Author < Marten::Model field :id, :big_int, primary_key: true, auto: true field :full_name, :string, max_size: 128 end class Article < Marten::Model field :id, :big_int, primary_key: true, auto: true field :title, :string, max_size: 128 // highlight-next-line field :author, :many_to_one, to: Author end ``` ### Interacting with related records Like for any other [model fields](https://martenframework.com/docs/next/models-and-databases/introduction#model-fields), Marten automatically generates getters and setters allowing to interact with the field's value. With the above snippet, it would be possible to access the `Author` record associated with a specific `Article` record by leveraging the `#author` and `#author=` methods. For example: ```crystal # Create two authors author_1 = Author.create!(full_name: "Foo Bar") author_2 = Author.create!(full_name: "John Doe") # Create an article article = Article.create!(title: "First article", author: author_1) article.author!.id # => 1 article.author # => # # Change the article author article.author = author_2 article.save! article.author!.id # => 2 article.author # => # ``` :::tip Note that you can also access the related record's ID directly without actually loading it by leveraging the `#_id` method (which corresponds to the actual name of the column used to persist the reference to the related record's primary key in the model table). For instance, using the model definitions provided earlier, you could perform the following operation: ```crystal author = Author.create!(full_name: "Foo Bar") article = Article.create!(title: "First article", author: author) article.author_id # => 1 ``` ::: ### Backward relations By default, [`many_to_one`](https://martenframework.com/docs/next/models-and-databases/reference/fields#many_to_one) fields do not establish a backward relation. This means that you cannot directly retrieve records that target a specific related record starting from the related record itself. For instance, by default, it is not possible to retrieve all the `Article` records associated with a specific `Author` record. To enable this capability, you need to make use of the [`related`](https://martenframework.com/docs/next/models-and-databases/reference/fields#related-1) argument when defining your [`many_to_one`](https://martenframework.com/docs/next/models-and-databases/reference/fields#many_to_one) field. For instance, we could modify the previous model definitions as follows in order to define an `articles` backward relation and to let `Author` records expose their related `Article` records: ```crystal class Author < Marten::Model field :id, :big_int, primary_key: true, auto: true field :full_name, :string, max_size: 128 end class Article < Marten::Model field :id, :big_int, primary_key: true, auto: true field :title, :string, max_size: 128 // highlight-next-line field :author, :many_to_one, to: Author, related: :articles end ``` When the [`related`](https://martenframework.com/docs/next/models-and-databases/reference/fields#related-1) argument is used, a method will be automatically created on the targeted model by using the chosen argument's value. For example, this means that all the `Article` records associated with a specific `Author` record will be accessible through the use of the `Author#articles` method: ```crystal # Create two authors author_1 = Author.create!(full_name: "Foo Bar") author_2 = Author.create!(full_name: "John Doe") # Create articles article_1 = Article.create!(title: "First article", author: author_1) article_2 = Article.create!(title: "Second article", author: author_2) article_3 = Article.create!(title: "Third article", author: author_1) # List the first author's articles author_1.articles.to_a # [#, # #] # Create an article associated with the first author article_4 = author_1.articles.create!(title: "Fourth article") article_4.author # => # ``` :::tip The method generated for the backward relation returns a [query set](https://martenframework.com/docs/next/models-and-databases/queries) that you can use to further filter the list of records. For example: ```crystal author.articles.filter(title__startswith: "Top") ``` ::: ### Deletion strategy When defining [`many_to_one`](https://martenframework.com/docs/next/models-and-databases/reference/fields#many_to_one) fields, it is highly advisable to specify a deletion strategy for the associated relation. This configuration determines the behavior of records with many-to-one fields when one of the records referred to by such fields gets deleted. Such behavior can be configured by leveraging the [`on_delete`](https://martenframework.com/docs/next/models-and-databases/reference/fields#on_delete) argument when defining [`many_to_one`](https://martenframework.com/docs/next/models-and-databases/reference/fields#many_to_one) fields. This argument allows specifying the deletion strategy to adopt when a related record (one that is targeted by the [`many_to_one`](https://martenframework.com/docs/next/models-and-databases/reference/fields#many_to_one) field) is deleted. This argument accepts the following values (expressed as symbols): * `:do_nothing`: This is the default strategy. With this strategy, Marten won't do anything to ensure that records referencing the record being deleted are deleted or updated. If the database enforces referential integrity (which will be the case for foreign key fields), this means that deleting a record could result in database errors. * `:cascade`: This strategy can be used to perform cascade deletions. When deleting a record, Marten will try to first destroy the other records that reference the object being deleted. * `:protect`: This strategy allows explicitly preventing the deletion of records if they are referenced by other records. This means that attempting to delete a "protected" record will result in a `Marten::DB::Errors::ProtectedRecord` error. * `:set_null`: This strategy will set the reference column to `null` when the related record is deleted. For example, we could modify our previous model definition so that `Article` records are cascade-deleted if the associated `Author` records are destroyed: ```crystal class Author < Marten::Model field :id, :big_int, primary_key: true, auto: true field :full_name, :string, max_size: 128 end class Article < Marten::Model field :id, :big_int, primary_key: true, auto: true field :title, :string, max_size: 128 // highlight-next-line field :author, :many_to_one, to: Author, related: :articles, on_delete: :cascade end ``` With this change, if we try to delete an `Author` record, we should notice that the associated `Article` records are deleted as well: ```crystal # Create two authors author_1 = Author.create!(full_name: "Foo Bar") author_2 = Author.create!(full_name: "John Doe") # Create articles article_1 = Article.create!(title: "First article", author: author_1) article_2 = Article.create!(title: "Second article", author: author_2) article_3 = Article.create!(title: "Third article", author: author_1) # Delete the first author author_1.delete article_1.reload # => raises Marten::DB::Errors::RecordNotFound ``` ## One-to-one relationships One-to-one relationships can be defined through the use of [`one_to_one`](https://martenframework.com/docs/next/models-and-databases/reference/fields#one_to_one) fields. This special field type requires the utilization of the [`to`](https://martenframework.com/docs/next/models-and-databases/reference/fields#to-2) argument, allowing to explicitly define the target model class associated with the current model. For example, a `User` model could have a one-to-one field towards a `Profile` model. In such case, the `User` model could only have one associated `Profile` record, and the reverse would be true as well (a `Profile` record could only have one associated `User` record): ```crystal class Profile < Marten::Model field :id, :big_int, primary_key: true, auto: true field :full_name, :string, max_size: 128 end class User < Marten::Model field :id, :big_int, primary_key: true, auto: true field :email, :email // highlight-next-line field :profile, :one_to_one, to: Profile end ``` :::info A one-to-one field is really similar to a many-to-one field, but with an additional unicity constraint. ::: ### Interacting with related records Like for any other [model fields](https://martenframework.com/docs/next/models-and-databases/introduction#model-fields), Marten automatically generates getters and setters allowing to interact with the field's value. With the above snippet, it would be possible to access the `Profile` record associated with a specific `User` record by leveraging the `#profile` and `#profile=` methods. For example: ```crystal # Create two users user_1 = User.create!(email: "test1@example.com", profile: Profile.create!(full_name: "Foo Bar")) user_2 = User.create!(email: "test2@example.com", profile: Profile.create!(full_name: "John Doe")) # Access a user's profile user_1.profile!.id # => 1 user_1.profile # => # # Change a user's profile user_1.profile = Profile.create!(full_name: "New Profile") user_1.save! user_1.profile!.id # => 3 user_1.profile # => # ``` :::tip Like for [many-to-one relationships](#many-to-one-relationships), you can also access the related record's ID directly without actually loading it by leveraging the `#_id` method (which corresponds to the actual name of the column used to persist the reference to the related record's primary key in the model table). For instance, using the model definitions provided earlier, you could perform the following operation: ```crystal user = User.create!(email: "test1@example.com", profile: Profile.create!(full_name: "Foo Bar")) user.profile_id # => 1 ``` ::: ### Backward relations By default, [`one_to_one`](https://martenframework.com/docs/next/models-and-databases/reference/fields#one_to_one) fields do not establish a backward relation. This means that you cannot directly retrieve the record that targets a specific related record starting from the related record itself. For instance, by default, it is not possible to retrieve the `User` record associated with a specific `Profile` record. To enable this capability, you need to make use of the [`related`](https://martenframework.com/docs/next/models-and-databases/reference/fields#related-2) argument when defining your [`one_to_one`](https://martenframework.com/docs/next/models-and-databases/reference/fields#one_to_one) field. For instance, we could modify the previous model definitions as follows in order to define a `user` backward relation and to let `Profile` records expose their related `User` record: ```crystal class Profile < Marten::Model field :id, :big_int, primary_key: true, auto: true field :full_name, :string, max_size: 128 end class User < Marten::Model field :id, :big_int, primary_key: true, auto: true field :email, :email // highlight-next-line field :profile, :one_to_one, to: Profile, related: :user end ``` When the [`related`](https://martenframework.com/docs/next/models-and-databases/reference/fields#related-2) argument is used, a method will be automatically created on the targeted model by using the chosen argument's value. For example, this means that the `User` record associated with a specific `Profile` record will be accessible through the use of the `Profile#user` method: ```crystal # Create two profiles profile_1 = Profile.create!(full_name: "Foo Bar") profile_2 = Profile.create!(full_name: "John Doe") # Create two users user_1 = User.create!(email: "test1@example.com", profile: profile_1) user_2 = User.create!(email: "test2@example.com", profile: profile_2) # Get the first profile's user profile_1.user # => # ``` :::tip Note that in the previous example, `#user` could return `nil` if no `User` record is available for the considered profile. A nil-safe version of the related method is also automatically defined with the following name: `#!`. For example: ```crystal # Create two profiles profile_1 = Profile.create!(full_name: "Foo Bar") profile_2 = Profile.create!(full_name: "John Doe") # Create two users user_1 = User.create!(email: "test1@example.com", profile: profile_1) user_2 = User.create!(email: "test2@example.com", profile: profile_2) # Delete the first user user_1.delete # Get the first profile's user profile_1.user! # => raises Marten::DB::Errors::RecordNotFound ``` ::: ### Deletion strategy Like for [many-to-one relationships](#deletion-strategy), the deletion strategy to use for [`one_to_one`](https://martenframework.com/docs/next/models-and-databases/reference/fields#one_to_one) fields can be configured by leveraging the [`on_delete`](https://martenframework.com/docs/next/models-and-databases/reference/fields#on_delete-1) argument. This argument allows specifying the deletion strategy to adopt when a related record (one that is targeted by the [`many_to_one`](https://martenframework.com/docs/next/models-and-databases/reference/fields#many_to_one) field) is deleted. This argument accepts the following values (expressed as symbols): * `:do_nothing`: This is the default strategy. With this strategy, Marten won't do anything to ensure that the record referencing the record being deleted is deleted or updated. If the database enforces referential integrity (which will be the case for foreign key fields), this means that deleting a record could result in database errors. * `:cascade`: This strategy can be used to perform cascade deletions. When deleting a record, Marten will try to first destroy the other record that references the object being deleted. * `:protect`: This strategy allows explicitly preventing the deletion of the record if is is referenced by another record. This means that attempting to delete a "protected" record will result in a `Marten::DB::Errors::ProtectedRecord` error. * `:set_null`: This strategy will set the reference column to `null` when the related record is deleted. For example, we could modify our previous model definition so that a `User` record is cascade-deleted if the associated `Profile` records is destroyed: ```crystal class Profile < Marten::Model field :id, :big_int, primary_key: true, auto: true field :full_name, :string, max_size: 128 end class User < Marten::Model field :id, :big_int, primary_key: true, auto: true field :email, :email // highlight-next-line field :profile, :one_to_one, to: Profile, related: :user, on_delete: :cascade end ``` With this change, if we try to delete a `Profile` record, we should notice that the associated `User` records is deleted as well: ```crystal # Create two profiles profile_1 = Profile.create!(full_name: "Foo Bar") profile_2 = Profile.create!(full_name: "John Doe") # Create two users user_1 = User.create!(email: "test1@example.com", profile: profile_1) user_2 = User.create!(email: "test2@example.com", profile: profile_2) # Delete the first profile profile_1.delete user_1.reload # => raises Marten::DB::Errors::RecordNotFound ``` ## Many-to-many relationships Many-to-many relationships can be defined through the use of [`many_to_many`](https://martenframework.com/docs/next/models-and-databases/reference/fields#many_to_many) fields. This special field type requires the utilization of the [`to`](https://martenframework.com/docs/next/models-and-databases/reference/fields#to) argument, allowing to explicitly define the target model class associated with the current model. For example, an `Article` model could have a many-to-many field towards a `Tag` model. In such case, an `Article` record could have many associated `Tag` records, and every `Tag` record could be associated with many `Article` records as well: ```crystal class Tag < Marten::Model field :id, :big_int, primary_key: true, auto: true field :label, :string, max_size: 128 end class Article < Marten::Model field :id, :big_int, primary_key: true, auto: true field :title, :string, max_size: 128 // highlight-next-line field :tags, :many_to_many, to: Tag end ``` ### Interacting with related records [`many_to_many`](https://martenframework.com/docs/next/models-and-databases/reference/fields#many_to_many) fields exhibit unique characteristics compared to other relationship fields. When using [`many_to_many`](https://martenframework.com/docs/next/models-and-databases/reference/fields#many_to_many) fields in Marten, the framework generates a `#` getter method that returns a specialized [query set](https://martenframework.com/docs/next/models-and-databases/queries) that not only enables filtering of targeted records but also facilitates the dynamic addition and removal of records to/from the set. With the above snippet, it would be possible to access the `Tags` records associated with a specific `Article` record by leveraging the `#tags` method. For example: ```crystal # Create three tags tag_1 = Tag.create!(label: "Tag 1") tag_2 = Tag.create!(label: "Tag 2") tag_3 = Tag.create!(label: "Tag 3") # Create one article article = Article.create!(title: "My article") # Add one tag to the article article.tags.add(tag_1) article.tags.to_a # => [#] # Add two tags to the article article.tags.add(tag_2, tag_3) article.tags.to_a # => [#, # #, # #] # Filter the article's tags article.tags.filter(label: "Tag 1").to_a # => [#] # Remove a tag from the article's tags article.tags.remove(tag_2) article.tags.to_a # => [#, # #] # Clear the article's tags article.tags.clear ``` Take note of the utilization of the [`#add`](https://martenframework.com/docs/api/dev/Marten/DB/Query/ManyToManySet.html#add(*objs%3AM)-instance-method) and [`#remove`](https://martenframework.com/docs/api/dev/Marten/DB/Query/ManyToManySet.html#remove(*objs%3AM)%3ANil-instance-method) methods, facilitating the addition or removal of objects from the record's many-to-many collection of associated items. These methods are callable with single or multiple records as parameters, as well as with arrays of records for streamlined addition or removal. ### Backward relations By default, [`many_to_many`](https://martenframework.com/docs/next/models-and-databases/reference/fields#many_to_many) fields do not establish a backward relation. This means that you cannot directly retrieve records that target a specific related record starting from the related record itself. For instance, by default, it is not possible to retrieve all the `Article` records associated with a specific `Tag` record. To enable this capability, you need to make use of the [`related`](https://martenframework.com/docs/next/models-and-databases/reference/fields#related-1) argument when defining your [`many_to_many`](https://martenframework.com/docs/next/models-and-databases/reference/fields#many_to_many) field. For instance, we could modify the previous model definitions as follows in order to define an `articles` backward relation and to let `Tag` records expose their related `Article` records: ```crystal class Tag < Marten::Model field :id, :big_int, primary_key: true, auto: true field :label, :string, max_size: 128 end class Article < Marten::Model field :id, :big_int, primary_key: true, auto: true field :title, :string, max_size: 128 // highlight-next-line field :tags, :many_to_many, to: Tag, related: :articles end ``` When the [`related`](https://martenframework.com/docs/next/models-and-databases/reference/fields#related) argument is used, a method will be automatically created on the targeted model by using the chosen argument's value. For example, this means that all the `Article` records associated with a specific `Tag` record will be accessible through the use of the `Tag#articles` method: ```crystal # Create three tags tag_1 = Tag.create!(label: "Tag 1") tag_2 = Tag.create!(label: "Tag 2") tag_3 = Tag.create!(label: "Tag 3") # Create two articles article_1 = Article.create!(title: "First article") article_2 = Article.create!(title: "Second article") # Add tags to the articles article_1.tags.add(tag_1, tag_2) article_2.tags.add(tag_2, tag_3) # Retrieve the second tag's articles tag_2.articles.to_a # => [#, # #] tag_2.articles.filter(title: "First article").to_a # => [#] ``` ## Polymorphic relationships Polymorphic relationships can be defined through the use of [`polymorphic`](https://martenframework.com/docs/next/models-and-databases/reference/fields#polymorphic) fields. Those are useful when you want to store a reference to a record whose model can vary among a predefined set of possible types. This special field type requires the utilization of the [`to`](https://martenframework.com/docs/next/models-and-databases/reference/fields#to-3) argument, allowing to explicitly define the model classes that can be related to the model where the `polymorphic` field is defined. For example, a `Comment` model could have a polymorphic field towards an `Article` or a `Recipe` model. In such case, a `Comment` record could be associated with an `Article` or a `Recipe` record, and each of these models could have many associated `Comment` records: ```crystal class Article < Marten::Model field :id, :big_int, primary_key: true, auto: true field :title, :string, max_size: 128 end class Recipe < Marten::Model field :id, :big_int, primary_key: true, auto: true field :title, :string, max_size: 128 end class Comment < Marten::Model field :id, :big_int, primary_key: true, auto: true // highlight-next-line field :target, :polymorphic, to: [Article, Recipe] field :text, :text end ``` Under the hood, the framework keeps track of both the target object's primary key and its model type, allowing it to resolve the relationship dynamically when accessed. This means that polymorphic fields contribute two columns to the model table: `_type` and `_id`, where `field_name` is the name of the polymorphic field. The `_type` column is used to store the type of the related record (the class name of the related record), and the `_id` column is used to store the ID of the related record. In the previous example, the `Comment` model would have two columns named `target_type` and `target_id` because of the `target` polymorphic field. ### Interacting with related records Marten automatically generates getters and setters for polymorphic fields, allowing to interact with the field's value. On top of that, Marten also generates a set of methods allowing to access the related record based on its type as well as numerous helper methods. For example: ```crystal # Create an article article = Article.create!(title: "This is an article") # Create a recipe recipe = Recipe.create!(title: "This is a recipe") # Create a comment comment = Comment.create!(text: "This is a comment", target: article) # Regular getter methods comment.target # => # comment.target_type # => "Article" comment.target_id # => 1 # Type class getter method comment.target_class # => Article (or nil if no related record is set) comment.target_class! # => Article (or raise if no related record is set) # Predicate helper methods comment.article_target? # => true comment.recipe_target? # => false # Typed getters methods comment.article_target # => Returns the associated Recipe record if the targeted record is indeed a Recipe record (or nil otherwise) comment.article_target! # => Returns the associated Recipe record if the targeted record is indeed a Recipe record (or raise otherwise) # Type-specific model scopes (generated based on the specified type classes) Comment.with_article_target # => Returns all the comments associated with Article records Comment.with_recipe_target # => Returns all the comments associated with Recipe records ``` ### Backward relations By default, [`polymorphic`](https://martenframework.com/docs/next/models-and-databases/reference/fields#polymorphic) fields do not establish a backward relation. This means that you cannot directly retrieve records that target a specific related record starting from the related record itself. For instance, by default, it is not possible to retrieve all the `Comment` records associated with a specific `Article` or `Recipe` record. To enable this capability, you need to make use of the [`related`](https://martenframework.com/docs/next/models-and-databases/reference/fields#related-3) argument when defining your [`polymorphic`](https://martenframework.com/docs/next/models-and-databases/reference/fields#polymorphic) field. For instance, we could modify the previous model definitions as follows in order to define a `comments` backward relation and to let `Article` and `Recipe` records expose their related `Comment` records: ```crystal class Comment < Marten::Model field :id, :big_int, primary_key: true, auto: true // highlight-next-line field :target, :polymorphic, to: [Article, Recipe], related: :comments field :text, :text end ``` When the [`related`](https://martenframework.com/docs/next/models-and-databases/reference/fields#related-3) argument is used, a method will be automatically created on the targeted model by using the chosen argument's value. For example, this means that all the `Comment` records associated with a specific `Article` or `Recipe` record will be accessible through the use of the `Article#comments` or `Recipe#comments` methods: ```crystal # Create an article article = Article.create!(title: "This is an article") # Create a recipe recipe = Recipe.create!(title: "This is a recipe") # Create comments Comment.create!(text: "This is a comment", target: article) Comment.create!(text: "This is a comment", target: recipe) # Get the article's comments article.comments.to_a # => [#] # Get the recipe's comments recipe.comments.to_a # => [#] ``` :::tip The method generated for the backward relation returns a [query set](https://martenframework.com/docs/next/models-and-databases/queries) that you can use to further filter the list of records. For example: ```crystal article.comments.filter(text__startswith: "This is") ``` ::: ### Deletion strategy Like for [many-to-one relationships](#deletion-strategy), the deletion strategy to use for [`polymorphic`](https://martenframework.com/docs/next/models-and-databases/reference/fields#polymorphic) fields can be configured by leveraging the [`on_delete`](https://martenframework.com/docs/next/models-and-databases/reference/fields#on_delete-2) argument. This argument allows specifying the deletion strategy to adopt when a related record (one that is targeted by the [`polymorphic`](https://martenframework.com/docs/next/models-and-databases/reference/fields#polymorphic) field) is deleted. This argument accepts the following values (expressed as symbols): * `:do_nothing`: This is the default strategy. With this strategy, Marten won't do anything to ensure that records referencing the record being deleted are deleted or updated. Because polymorphic fields are not backed by a database foreign key, this means that related records can be left with a dangling type/ID pair. * `:cascade`: This strategy can be used to perform cascade deletions. When deleting a record, Marten will try to first destroy the other records that reference the object being deleted. * `:protect`: This strategy allows explicitly preventing the deletion of records if they are referenced by other records. This means that attempting to delete a "protected" record will result in a `Marten::DB::Errors::ProtectedRecord` error. * `:set_null`: This strategy will set both the `_id` and `_type` columns of the polymorphic field to `null` when the related record is deleted. For example, we could modify our previous model definition so that `Comment` records are cascade-deleted if the associated `Article` or `Recipe` records are destroyed: ```crystal class Comment < Marten::Model field :id, :big_int, primary_key: true, auto: true // highlight-next-line field :target, :polymorphic, to: [Article, Recipe], related: :comments, on_delete: :cascade field :text, :text end ``` ## Advanced topics ### Recursive relationships All the relationship fields mentioned previously support defining recursive relations, ie. relations that target the same model as the model defining the relation field. To do so, you can define a [`many_to_one`](https://martenframework.com/docs/next/models-and-databases/reference/fields#many_to_one), [`one_to_one`](https://martenframework.com/docs/next/models-and-databases/reference/fields#one_to_one), or [`many_to_many`](https://martenframework.com/docs/next/models-and-databases/reference/fields#many_to_many) field whose `to` argument is set to the `self` keyword. For example: ```crystal class TreeNode < Marten::Model field :id, :big_int, primary_key: true, auto: true field :label, :string, max_size: 128 // highlight-next-line field :parent, :many_to_one, to: self end ``` In the above snippet, the `TreeNode` model will have a relation to itself through the `parent` field. # Model validations Source: https://martenframework.com/docs/next/models-and-databases/validations Model instances _should_ be validated before being persisted to the database. As such models provide a convenient way to define validation rules through the use of model fields and through the use of a custom validation rules DSL. The underlying validation logics are completely database-agnostic, cannot be skipped (unless explicitly specified), and can be unit-tested easily. Validation rules can be inherited from the fields in your model depending on the options you used and the type of your fields (for example fields using `blank: false` will make the associated record validation fail if the field value is blank). They can also be explicitly specified in your model class, which is useful if you need to implement custom validation logics. ## Overview ### A short example Let's consider the following example: ```crystal class User < Marten::Model field :id, :big_int, primary_key: true, auto: true field :name, :string, max_size: 128, blank: false end ``` In the above snippet, a `User` model is defined and it is specified that the `name` field must be present (`blank: false`) and that the associated value cannot exceed 128 characters. Given these characteristics, it is possible to create `User` instances and to validate them through the use of the `#valid?` method: ```crystal user_1 = User.new user_1.valid? # => false user_2 = User.new(name: "0" * 200) user_2.valid? # => false user_3 = User.new(name: "John Doe") user_3.valid? # => true ``` As you can see in the above examples, the first two users are invalid because either the `name` is not specified or because its value exceeds the maximum characters limit. The last user is valid though because it has a `name` that is less than 128 characters. ### When does model validation happen? Model instances are validated when they are created or updated, before any values are persisted to the database. Methods like `#create` or `#save` automatically run validations. They return `false` to indicate that the considered object is invalid (and they return `true` if the object is valid). The `#create` and `#save` methods also have bang counterparts (`#create!` and `#save!`) that will explicitly raise a validation error (instance of `Marten::DB::Errors::InvalidRecord`) in case of invalid records. For example: ```crystal user = User.new user.save # => false user.save! # => Unhandled exception: Record is invalid (Marten::DB::Errors::InvalidRecord) ``` When validating model records, the validation rules that are inherited by fields will be executed first and then any custom validation rule defined in the model will be applied. ### Running model validations As mentioned previously, validation rules will be executed automatically when calling the `#create` or `#save` methods on a model record. It is also possible to manually verify whether a model instance is valid or not using the `#valid?` and `#invalid?` methods: ```crystal user = User.new user.valid? # => false user.invalid? # => true ``` ## Field validation rules As mentioned previously, fields can contribute validation rules to your models. These validation rules can be inherited: * from the field type itself: some fields will validate that values are of a specific type (for example a `uuid` field will not validate values that don't correspond to valid UUIDs) * from the field options you define (for example fields using `blank: true` accept empty values) Please refer to the [fields reference](https://martenframework.com/docs/next/models-and-databases/reference/fields) in order to learn more about the supported field types and their associated options. ## Custom validation rules Custom validate rules can be defined through the use of the `#validate` macro. This macro lets you configure the name of a validation method that should be called when a model instance is validated. Inside this method, you can implement any validation logic that you might require and add errors to your model instances if they are identified as invalid. For example: ```crystal class User < Marten::Model field :id, :big_int, primary_key: true, auto: true field :name, :string, max_size: 128, blank: false validate :validate_name_is_not_forbidden private def validate_name_is_not_forbidden errors.add(:name, "admin can't be used!") if name == "admin" end end ``` In the above snippet, a custom validation method ensures that the `name` of a `User` model instance can't be set to `"admin"`: if the name is set to `"admin"`, then a specific error (associated with the `name` attribute) is added to the model instance (which makes it invalid). ## Validation errors Methods like `#valid?` or `#invalid?` only let you know whether a model instance is valid or invalid. But you'll likely want to know exactly what are the actual errors or how to add new ones. As such, every model instance has an associated error set, which is an instance of [`Marten::Core::Validation::ErrorSet`](https://martenframework.com/docs/api/dev/Marten/Core/Validation/ErrorSet.html). ### Inspecting errors A model instance error set lets you access all the errors of a specific model instance. For example: ```crystal user = User.new user.valid? # => false user.errors.size # => 1 user.errors # => #]> ``` As you can see, the error set gives you the ability to know how many errors are affecting your model instance. Each error provides some additional information as well: * the associated field name (which can be `nil` if the error is global) * the error message * the error type, which is optional (`blank` in the previous example) You can also access the errors that are associated with a specific field very easily by using the `#[]` method: ```crystal user.errors[:name] # => [#] ``` Global errors (errors affecting the whole model instances or multiple fields at once) can be listed through the use of the `#global` method. ### Adding errors Errors can be added to an error set through the use of the `#add` method. This method takes a field name, a message, and an optional error type: ```crystal user.errors.add(:name, "Name is invalid") # error type is "invalid" user.errors.add(:name, "Name is invalid", type: :invalid_name) # error type is "invalid_name" ``` Global errors can be specified through the use of an alternative `#add` method that doesn't take a field name: ```crystal user.errors.add("User is invalid") # error type is "invalid" user.errors.add("User is invalid", type: :invalid_user) # error type is "invalid_user" ``` Validation errors can be serialized to JSON with the same representation used for [schema errors](https://martenframework.com/docs/next/schemas/validations#serializing-errors-as-json). Passing `user.errors` to a handler's [`#json`](https://martenframework.com/docs/next/handlers-and-http/introduction#json) helper returns an array of objects with `field`, `type`, and `message`. `field` is `null` when the error is global. ## Skipping validations Model validations can be explicitly skipped when using the `#save` or `#save!` methods. To do so, the `validate: false` argument can be used: ```crystal user = User.new user.save(validate: false) ``` :::caution It is generally not a good idea to skip validation that way. This technique should be used with caution! ::: # Model callbacks Source: https://martenframework.com/docs/next/models-and-databases/callbacks Models callbacks let you define logic that is triggered before or after a record's state alteration. They are methods that get called at specific stages of a record's lifecycle. For example, callbacks can be called when model instances are created, updated, or deleted. This documents covers the available callbacks and introduces you to the associated API, which you can use to define hooks in your models. ## Overview As stated above, callbacks are methods that will be called when specific events occur for a specific model instance. They need to be registered explicitly as part your model definitions. There are [many types of callbacks](#available-callbacks), and it is possible to register "before" or "after" callbacks for most of these types. Registering a callback is as simple as calling the right callback macro (eg. `#before_validation`) with a symbol of the name of the method to call when the callback is executed. For example: ```crystal class User < Marten::Model field :id, :big_int, primary_key: true, auto: true field :username, :string, max_size: 64, unique: true before_validation :ensure_username_is_downcased private def ensure_username_is_downcased self.username = username.try(&.downcase) end end ``` In the above snippet, a `before_validation` callback is registered to ensure that the `username` of a `User` instance is downcased before any validation. This technique of callback registration is shared by all types of callbacks. It should be noted that the order in which callback methods are registered for a given callback type (eg. `before_update`) matters: callbacks will be called in the order in which they were registered. ## Available callbacks ### `after_initialize` `after_initialize` callbacks are called right after a model instance is initialized. They will be called automatically when new model instances are initialized through the use of `new` or when records are retrieved from the database. ### `before_validation` and `after_validation` `before_validation` callbacks are called before running validation rules for a given model instance while `after_validation` callbacks are executed after. They can be used to sanitize model instance attributes for example. The use of methods like `#valid?` or `#invalid?`, or any other methods involving validations (`#save`, `#save!`, `#create`, or `#create!`), will trigger validation callbacks. See [Model validations](https://martenframework.com/docs/next/models-and-databases/validations) for more details. ### `before_create` and `after_create` `before_create` callbacks are called before a new record is inserted into the database. `after_create` callbacks are called after a new record has been created at the database level. The use of the `#save` method (or `#save!`) on a new model instance will trigger the execution of creation callbacks. The use of the `#create` / `#create!` methods will also trigger these callbacks. ### `before_update` and `after_update` `before_update` callbacks are called before an existing record is updated while `after_update` callbacks are called after. The use of the `#save` method (or `#save!`) on an existing model record will trigger the execution of update callbacks. ### `before_save` and `after_save` `before_save` callbacks are called before a record (existing or new) is saved to the database while `after_save` callbacks are called after. The use of the `#save` / `#save!` and the `#create` / `#create!` methods will trigger the execution of save callbacks. :::info `before_save` and `after_save` are called for both new and existing records. `before_save` callbacks are always executed _before_ `before_create` or `before_update` callbacks. `after_save` callbacks on the other hand are always executed _after_ `after_create` or `after_update` callbacks. ::: ### `before_delete` and `after_delete` `before_delete` callbacks are called before a record gets deleted while `after_delete` callbacks are called after. The use of the `#delete` method will trigger these callbacks. ### `after_commit` `after_commit` callbacks are called after a record is created, updated, or deleted, but only after the corresponding SQL transaction has been committed to the database (which isn't the case for other `after_*` callbacks - See [Transactions](https://martenframework.com/docs/next/models-and-databases/transactions) for more details). For example: ```crystal after_commit :do_something ``` As mentioned previously, by default such callbacks will run in the context of record creations, updates, and deletions. That being said it is also possible to associate these callbacks with one or more specific actions only by using the `on` argument. For example: ```crystal after_commit :do_something, on: :create # Will run after creations only after_commit :do_something, on: :update # Will run after updates only after_commit :do_something, on: :update # Will run after saves (creations or updates) only after_commit :do_something, on: :delete # Will run after deletions only after_commit :do_something_else, on: [:create, :delete] # Will run after creations and deletions only ``` The actions supported by the `on` argument are `create`, `update`, `save`, and `delete`. ### `after_rollback` `after_rollback` callbacks are called after a transaction is rolled back when a record is created, updated, or deleted. For example: ```crystal after_rollback :do_something ``` As mentioned previously, by default such callbacks will run in the context of record creations, updates, and deletions. That being said it is also possible to associate these callbacks with one or more specific actions only by using the `on` argument. For example: ```crystal after_rollback :do_something, on: :create # Will run after rolled back creations only after_rollback :do_something, on: :update # Will run after rolled back updates only after_rollback :do_something, on: :update # Will run after rolled back saves (creations or updates) only after_rollback :do_something, on: :delete # Will run after rolled back deletions only after_rollback :do_something_else, on: [:create, :delete] # Will run after rolled back creations and deletions only ``` The actions supported by the `on` argument are `create`, `update`, `save`, and `delete`. ## Methods that bypass callbacks Some model methods intentionally bypass callbacks for performance or specific use cases. The following methods do **not** trigger callbacks: * `#update_columns` and `#update_columns!` - These methods update specific columns directly in the database without running validations or any lifecycle callbacks. They are useful for performance-critical updates where you want to avoid the overhead of the full save lifecycle. If you need to update records while ensuring that callbacks are executed, use the standard `#save`, `#save!`, `#update`, or `#update!` methods instead. # Model migrations Source: https://martenframework.com/docs/next/models-and-databases/migrations Migrations ensure that any changes made to model definitions are applied at the database level. Marten's migrations mechanism is designed to be mostly automatic: migrations are generated from your model definitions when you run a dedicated command, after having introduced some changes to your model definitions. ## Overview Marten is able to automatically create migrations when you introduce changes to your models. For example, let's assume you just added a `hometown` string field to an existing `Author` model: ```crystal class Author < Marten::Model field :id, :big_int, primary_key: true, auto: true field :first_name, :string, max_size: 255 field :last_name, :string, max_size: 255 // highlight-next-line field :hometown, :string, max_size: 255, blank: true, null: true end ``` After introducing this change, you can run the `genmigrations` management command as follows: ```shell $ marten genmigrations Generating migrations for app 'blog': › Creating [src/blog/migrations/202206221856241_add_hometown_to_blog_author_table.cr]... DONE ○ Add hometown to blog_author table ``` When running this command, the table definition corresponding to your current model will be analyzed and compared to the equivalent table that is defined by your migration files. Depending on the result of this analysis, a new set of migration files will be generated in order to account for the changes that were made to the models. Generated migrations are saved under a `migrations` folder that lives in the local structure of every [application](https://martenframework.com/docs/next/development/applications). As a general rule of thumb, you should always look at what is actually generated by the `genmigrations` command. Indeed, the introspection capabilities of this command could be limited depending on what you are trying to achieve. In the above example, the generated migration file looks something like this: ```crystal # Generated by Marten 0.1.0 on 2022-06-22 18:56:24 -04:00 class Migration::Blog::V202206221856241 < Marten::Migration depends_on :blog, "202205290942181_previous_migration_name" def plan add_column :blog_author, :hometown, :string, max_size: 255, null: true end end ``` As you see, the migration explicitly depends on the previous migration for the considered application (`blog` in this case) and it defines a migration "plan" that involves adding a `hometown` string column to the `blog_author` table. We can then apply this migration to the database by running the `migrate` Marten command: ```shell $ marten migrate Running migrations: › Applying blog_202206221856241_add_hometown_to_blog_author_table... DONE ``` ## Available commands Marten provides a set of four commands allowing interacting with model migrations: * [`genmigrations`](https://martenframework.com/docs/next/development/reference/management-commands#genmigrations) allows generating migration files by looking for changes in your model definitions * [`migrate`](https://martenframework.com/docs/next/development/reference/management-commands#migrate) allows applying (or unapplying) migrations to your databases * [`listmigrations`](https://martenframework.com/docs/next/development/reference/management-commands#listmigrations) allows listing all the migrations for all your [installed applications](https://martenframework.com/docs/next/development/applications), and whether they have already been applied or not * [`resetmigrations`](https://martenframework.com/docs/next/development/reference/management-commands#resetmigrations) allows resetting multiple migrations into a single one ## DB connections specificities Migrations can be used with all the built-in database backends provided by Marten: PostgreSQL, MySQL, and SQlite. That being said, there are some key differences among those backends that you should be aware of when it comes to migrations. These differences stem from the fact that not all of these databases support schema alteration operations or DDL (Data Definition Language) transactions. PostgreSQL and SQLite support DDL transactions, but MySQL does *not* support them. As such, if a migration fails when being applied to a MySQL database, you might have to manually undo some of the operations in order to try again. Finally, it should be noted that SQLite does not support most schema alteration operations. Because of this, Marten will perform the following set of operations when applying model changes to a SQLite database: 1. create a new table corresponding to the new model definition 2. copy the data from the old table to the new one 3. delete the old table 4. rename the new one so that it matches the model's table name ## Migration files As presented in the [overview](#overview) section above, migration files are automatically generated by Marten by identifying changes in your model definitions (although migrations could be created and defined manually if needed). These files are persisted in a `migrations` folder inside each application's main directory. Migrations always inherit from the [`Marten::Migration`](https://martenframework.com/docs/api/dev/Marten/DB/Migration.html) base class. A basic migration will look something like this: ```crystal # Generated by Marten 0.1.0 on 2022-03-13 16:08:37 -04:00 class Migration::Main::V202203131608371 < Marten::Migration depends_on :users, "202203131607261_create_users_user_table" depends_on :main, "202203131604261_add_content_to_main_article_table" def plan add_column :main_article, :author_id, :reference, to_table: :users_user, to_column: :id, null: true end end ``` Each migration must define the following mandatory information: the migration's **dependencies** and the migration's **operations**. ### Dependencies Marten migrations can depend upon one another. As such, each migration generally defines one or many dependencies through the use of the [`#depends_on`](https://martenframework.com/docs/api/dev/Marten/DB/Migration.html#depends_on(app_name%3AString|Symbol%2Cmigration_name%3AString|Symbol)-class-method) class method, which takes an application label and a migration name as positional arguments. Migration dependencies are used to ensure that changes to a database are applied in the right order. For example, the previous migration is part of the `main` app and depends on two other migrations: first, it depends on the previous migration of the `main` app (`202203131604261_add_content_to_main_article_table`). Secondly, it depends on the `202203131607261_create_users_user_table` migration of the `users` app. This makes sense considering that the migration's only operation is adding an `author_id` foreign key targeting the `users_user` table to the `main_article` table: the dependency instructs Marten to first apply the `202203131607261_create_users_user_table` migration (which creates the `users_user` table) before applying the migration adding the new foreign key (since this foreign key requires the targeted table to exist first in order to be created properly). Again, migration dependencies are automatically identified and generated by Marten when you create migrations through the use of the [`genmigrations`](https://martenframework.com/docs/next/development/reference/management-commands#genmigrations) command. These dependencies are identified by looking at the DB relationships between the application for which migrations are generated for and the other installed applications. ### Operations Migrations must define operations to apply (or unapply) at the database level. Unless instructed otherwise, these operations are all executed within a single transaction for the backends that support DDL transactions (PostgreSQL and SQLite). When they are generated automatically, migrations will define a set of operations to execute as part of a `#plan` method. This method can define one or more operations. For example: ```crystal # Generated by Marten 0.1.0 on 2022-03-30 22:13:06 -04:00 class Migration::Press::V202203302213061 < Marten::Migration depends_on :press, "202203111822091_initial" def plan add_column :press_article, :rating, :int, null: true remove_column :press_article, :old_status end end ``` Migrations can be *applied* and *unapplied*. This means that when a migration is applied, all the operations defined in the `#plan` method will be executed in the order they were defined. But if the migration is unapplied, the exact same operation will be "reversed" in reverse order. In the previous example, the "plan" of the migration involves two operations: first, we are adding a new `rating` column to the `press_article` table and then we are removing an `old_status` column from the same table. If we were applying this migration, these two operations would be executed in this order. But if we were unapplying the migration, this means that we would first re-create the `old_status` column in the `press_article` table, and then we would remove the `rating` column from the `press_article` table. The bidirectional aspect of the `#plan` method can be leveraged for most migration use cases, but there could be situations where the operations involved when *applying* the migration differ from the operations involved when *unapplying* the migration. In such situations, forward operations can be defined in a `#forward` method while backward operations can be defined in a `#backward` method: ```crystal # Generated by Marten 0.1.0 on 2022-03-30 22:13:06 -04:00 class Migration::Press::V202203302213061 < Marten::Migration depends_on :press, "202203111822091_initial" def forward add_column :press_article, :rating, :int, null: true remove_column :press_article, :old_status end def backward # do something else end end ``` ## Generating migrations Generating migrations is possible through the use of the [`genmigrations`](https://martenframework.com/docs/next/development/reference/management-commands#genmigrations) management command. This command will scan the table definition corresponding to your current models and will compare it to the equivalent table that is defined by your migration files. Based on the result of this analysis, a new set of migrations will be created and persisted in your applications' `migrations` folders. :::info The `genmigrations` command can only create migrations for [installed applications](https://martenframework.com/docs/next/development/applications). If the command is not detecting the intended changes, make sure that your models are part of an installed application. ::: Running `marten genmigrations` will generate migrations for *all* of the models provided by your installed applications, but it is possible to restrict the generation to a specific application label by specifying an additional argument as follows: ```shell $ marten genmigrations my_app ``` Another useful command option is the `--empty` one, which allows generating an empty migration file (without any defined operations): ```shell $ marten genmigrations my_app --empty ``` ## Applying and unapplying migrations As mentioned previously, migrations can be applied by running the [`migrate`](https://martenframework.com/docs/next/development/reference/management-commands#migrate) management command. Running `marten migrate` will execute non-applied migrations for your installed applications. That being said, it is possible to ensure that only the migrations of a specific application are applied by specifying an additional argument as follows: ```shell $ marten migrate my_app ``` To unapply certain migrations (or to apply some of them up to a certain version only), it is possible to specify another argument corresponding to the version of a targeted migration. For example, we could unapply all the migrations after the `202203111821451` version for the `my_app` application by running: ```shell $ marten migrate my_app 202203111821451 ``` If you wish to unapply all the migrations of a specific application, you can do so by targeting the `zero` version: ```shell $ marten migrate my_app zero ``` Finally, it should be noted that it is possible to "fake" the fact that migrations are applied or unapplied by using the `--fake` command option. When doing so, only the fact that the migration was applied (or unapplied) will be registered, and no migration operations will be executed: ```shell $ marten migrate my_app 202203111821451 --fake ``` ## Transactions The operations of a migrations will be executed inside a single transaction by default unless this capability is not supported by the database backend (which is the case for MySQL). It is possible to disable this default behavior by using the [`#atomic`](https://martenframework.com/docs/api/dev/Marten/DB/Migration.html#atomic(atomic%3ABool)-class-method) method, in the migration class: ```crystal # Generated by Marten 0.1.0 on 2022-03-30 22:13:06 -04:00 class Migration::Press::V202203302213061 < Marten::Migration depends_on :press, "202203111822091_initial" atomic false def plan add_column :press_article, :rating, :int, null: true remove_column :press_article, :old_status end end ``` Concurrent index operations (`add_index` / `remove_index` with `concurrently: true`) cannot run inside a transaction. Marten raises if such an operation is used in an atomic migration; set `atomic false` in that case. See [`add_index`](https://martenframework.com/docs/next/models-and-databases/reference/migration-operations#add_index) and [`remove_index`](https://martenframework.com/docs/next/models-and-databases/reference/migration-operations#remove_index) for details. ## Data migrations Sometimes, it is necessary to write migrations that don't change the database schema but that actually write data to the database. This is often the case when backfilling column values for example. In order to do so, Marten provides the ability to run arbitrary code as part of migrations through the use of a special `#run_code` operation. For example, the following migration will run the `#run_forward_code` method when applying the migration, and it will run the `#run_backward_code` method when unapplying it: ```crystal # Generated by Marten 0.1.0 on 2022-03-30 22:13:06 -04:00 class Migration::Press::V202203302213061 < Marten::Migration depends_on :press, "202203111822091_initial" def plan run_code :run_forward_code, :run_backward_code end def run_forward_code # do something end def run_backward_code # do something end end ``` `#run_code` can be called with a single argument if you don't want to specify a "backward" method. The following migration is technically equivalent to the one in the previous example: ```crystal # Generated by Marten 0.1.0 on 2022-03-30 22:13:06 -04:00 class Migration::Press::V202203302213061 < Marten::Migration depends_on :press, "202203111822091_initial" def forward run_code :run_forward_code end def backward run_code :run_backward_code end def run_forward_code # do something end def run_backward_code # do something end end ``` :::info Data migration logics can't be defined as part of the `#forward` and `#backward` methods directly. Indeed, the `#plan`, `#forward`, and `#backward` methods don't actually do anything to the database: they simply build a plan of operations that Marten will use when applying or unapplying the migrations. That's why it is necessary to use the `#run_code` operation when defining data migrations. ::: It should be noted that one convenient way to start writing a data migration is to generate an empty migration skeleton for the targeted application: ```shell $ marten genmigrations my_app --empty ``` ## Executing custom SQL statements Sometimes the built-in migration operations that are provided by Marten might not be enough and you may want to run arbitrary SQL statements on the database as part of migrations. To do so, you can leverage the [`#execute`](https://martenframework.com/docs/next/models-and-databases/reference/migration-operations#execute) migration operation. This operation must be called with a forward statement string as first positional argument, and it can also take a second positional (and optional) argument in order to specify the statement to execute when unapplying the migration (which is only useful when defining a bidirectional operation inside the `#plan` method). For example: ```crystal # Generated by Marten 0.1.0 on 2022-03-30 22:13:06 -04:00 class Migration::Press::V202203302213061 < Marten::Migration depends_on :press, "202203111822091_initial" def plan execute("CREATE EXTENSION 'uuid-ossp';") end end ``` ## Resetting migrations When your application starts having a certain amount of migrations, it can become interesting to reset them. This means reducing all the existing migrations to a unique migration file. This can be achieved through the use of the [`resetmigrations`](https://martenframework.com/docs/next/development/reference/management-commands#resetmigrations) management command. For example, let's consider the following situation where we have three migrations under the `my_app` application: ```shell $ marten listmigrations [my_app] [✔] my_app_202203111821451_create_my_app_article_table [✔] my_app_202203111822091_add_status_to_my_app_article_table [✔] my_app_202204051755101_add_rating_to_my_app_article_table ``` Running the `resetmigrations` command will produce the following output: ```shell $ marten resetmigrations my_app Generating migrations for app 'my_app': › Creating [src/my_app/migrations/202206261646061_auto.cr]... DONE ○ Create my_app_article table ``` If we look at the generated migration, you will notice that it includes multiple calls to the [`#replaces`](https://martenframework.com/docs/api/dev/Marten/DB/Migration.html#replaces(app_name%3AString|Symbol%2Cmigration_name%3AString|Symbol)-class-method) class method: ```crystal # Generated by Marten 0.1.0 on 2022-06-26 16:46:06 -04:00 class Migration::MyApp::V202206261646061 < Marten::Migration replaces :my_app, "202203111821451_create_my_app_article_table" replaces :my_app, "202203111822091_add_status_to_my_app_article_table" replaces :my_app, "202204051755101_add_rating_to_my_app_article_table" def plan create_table :my_app_article do column :id, :big_int, primary_key: true, auto: true column :title, :string, max_size: 155 column :body, :text column :status, :string, max_size: 64, null: true column :rating, :int, null: true end end end ``` These `#replaces` method calls indicate the previous migrations that the current migration is replacing. This new migration can be committed to your project's repository. Then it can be applied like any other migration (even if the underlying database was already up to date with the latest migrations). The following migrations will use it as a dependency and will disregard all the migrations that were replaced. Later on, you can decide to remove the old migrations (the ones that were replaced by the new migration). But obviously, you should only do so after a certain while in order to give a chance to developers to apply all the latest migrations. :::warning The `resetmigrations` management command will not carry on `run_code` operations nor any other "manually" added operations. As a matter of fact, `resetmigrations` will simply look at your model definitions and try to recreate a new migration file from the beginning (without considering your old migration files). As such, if your database requires special `run_code` or `run_sql` operations, you should make sure that those are added as following migrations. ::: # Database transactions Source: https://martenframework.com/docs/next/models-and-databases/transactions Transactions are blocks whose underlying SQL statements are committed to the database as one atomic action only if they can complete without errors. Marten provides a few mechanisms to control how database transactions are performed and managed. ## The basics Transactions are essential in order to enforce database integrity. Whenever you are in a situation where you have more than one SQL operations that must be executed together or not at all, then you should consider wrapping all these operations in a dedicated transaction. Transaction blocks can be created by leveraging the `#transaction` method, which can be called either on [model records](https://martenframework.com/docs/api/dev/Marten/DB/Model/Connection.html#transaction(using%3ANil|String|Symbol%3Dnil%2C%26block)-instance-method) or [model classes](https://martenframework.com/docs/api/dev/Marten/DB/Model/Connection/ClassMethods.html#transaction(using%3ANil|String|Symbol%3Dnil%2C%26)-instance-method). For example: ```crystal MyModel.transaction do my_record.save! my_other_record.save! end ``` With the above snippet, both records will be saved _only_ if each save operation completes successfully (that is if no exception is raised). If an exception occurs as part of one of the save operations (eg. if one of the records is invalid), then no records will be saved. It should be noted that there is no difference between calling `#transaction` on [a model record](https://martenframework.com/docs/api/dev/Marten/DB/Model/Connection.html#transaction(using%3ANil|String|Symbol%3Dnil%2C%26block)-instance-method) or [a model class](https://martenframework.com/docs/api/dev/Marten/DB/Model/Connection/ClassMethods.html#transaction(using%3ANil|String|Symbol%3Dnil%2C%26)-instance-method). It's also worth mentioning that the models manipulated within a transaction block that result in SQL statements can be of different classes. For example, the following two transactions would be equivalent: ```crystal MyModel.transaction do MyModel.create!(foo: "bar") MyOtherModel.create!(foo: "bar") end MyOtherModel.transaction do MyModel.create!(foo: "bar") MyOtherModel.create!(foo: "bar") end ``` :::info When transaction blocks are nested, this results in all the database statements of the inner transaction to be added to the outer transaction. As such, there is only one "effective" transaction at any given time when transaction blocks are nested. ::: ## Automatic transactions Basic model operations such as [creating](https://martenframework.com/docs/next/models-and-databases/introduction#create), [updating](https://martenframework.com/docs/next/models-and-databases/introduction#update), or [deleting](https://martenframework.com/docs/next/models-and-databases/introduction#delete) records are automatically wrapped in a transaction. This helps in ensuring that any exception that is raised in the context of validations or as part of `after_*` [callbacks](https://martenframework.com/docs/next/models-and-databases/callbacks) (ie. `after_create`, `after_update`, `after_save`, and `after_delete`) will also roll back the current transaction. The consequence of this is that the changes you make to the database in these callbacks will not be "visible" until the transaction is complete. For example, this means that if you are triggering something (like an asynchronous job) that needs to leverage the changes introduced by a model operation, then you should probably not use the regular `after_*` callbacks. Instead, you should leverage [`after_commit`](https://martenframework.com/docs/next/models-and-databases/callbacks#after_commit) callbacks (which are the only callbacks that are triggered _after_ a model operation has been committed to the database). ## Exception handling and rollbacks As mentioned before, any exception that is raised from within a transaction block will result in the considered transaction being rolled back. Moreover, it should be noted that raised exceptions will also be propagated outside of the transaction block, which means that your codebase should catch these accordingly if applicable. If you need to roll back a transaction _manually_ from within a transaction itself while ensuring that no exception is propagated outside of the block, then you can make use of the [`Marten::DB::Errors::Rollback`](https://martenframework.com/docs/api/dev/Marten/DB/Errors/Rollback.html) exception: when this specific exception is raised from inside a transaction block, the transaction will be rolled back and the transaction block will return `false`. For example: ```crystal transaction_committed = MyModel.transaction do MyModel.create!(foo: "bar") MyOtherModel.create!(foo: "bar") raise Marten::DB::Errors::Rollback.new("Stop!") if should_rollback? end transaction_committed # => false ``` ## Pessimistic locking Marten supports pessimistic row locking via `SELECT ... FOR UPDATE`. This is useful when you need to prevent concurrent updates to the same record (for example when adjusting a balance or inventory count). ### Locking a query set The [`#lock`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#lock) query set method appends a `FOR UPDATE` clause to the generated SQL query. On database backends that support row locking, locked query sets **must** be evaluated inside a transaction (otherwise a `Marten::DB::Errors::UnmetQuerySetCondition` exception is raised): ```crystal Account.transaction do account = Account.lock.get!(id: account_id) account.balance -= 100 account.save! end ``` You can also request a custom locking clause (for example `FOR UPDATE NOWAIT` or `FOR SHARE`): ```crystal Account.transaction do account = Account.lock("FOR UPDATE NOWAIT").get!(id: account_id) # ... end ``` ### Locking a record If you already have a model instance, you can use [`#with_lock`](https://martenframework.com/docs/api/dev/Marten/DB/Model/Persistence.html#with_lock(lock%3ABool%7CString%3Dtrue%2Cusing%3ANil%7CString%7CSymbol%3Dnil%2C%26block)-instance-method) to open a transaction, reload the record with a row lock, and then run your updates: ```crystal account.with_lock do account.balance -= 100 account.save! end ``` `#with_lock` discards any in-memory attribute changes when it reloads the record (the same way [`#reload`](https://martenframework.com/docs/api/dev/Marten/DB/Model/Persistence.html#reload-instance-method) does). Apply your mutations inside the block after the lock has been acquired. If you are already inside a transaction, you can call [`#lock!`](https://martenframework.com/docs/api/dev/Marten/DB/Model/Persistence.html#lock!(lock%3ABool%7CString%3Dtrue%2Cusing%3ANil%7CString%7CSymbol%3Dnil)-instance-method) instead: ```crystal Account.transaction do account.lock! account.balance -= 100 account.save! end ``` Row locks are released automatically when the surrounding transaction is committed or rolled back. Both `#lock!` and `#with_lock` raise a `Marten::DB::Errors::UnmetSaveCondition` exception if they are called on a record that is not persisted. :::info SQLite does not support `SELECT ... FOR UPDATE`. On SQLite, the locking APIs still open a transaction and reload the record, but no database-level row lock is acquired. ::: # Performing raw SQL queries Source: https://martenframework.com/docs/next/models-and-databases/raw-sql Marten gives you the ability to execute raw SQL if the capabilities provided by [query sets](https://martenframework.com/docs/next/models-and-databases/queries) are not sufficient for the task at hand. When doing so, multiple solutions can be considered: you can either decide to perform raw queries that are mapped to actual model instances, or you can execute entirely custom SQL statements. ## Performing raw queries It is possible to perform raw SQL queries and expect to have the corresponding records mapped to actual model instances. This is possible by using the [`#raw`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#raw) query set method. For example, the following snippet would allow iterating over all the `Article` model records (by assuming that the corresponding database table is the `main_article` one): ```crystal Article.raw("select * from main_article").each do |article| # Do something with `article` record end ``` :::tip You need to know the name of the model table you are targeting to use the [`#raw`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#raw) query set method. Unless you have explicitly overridden this name by using the [`#db_table`](https://martenframework.com/docs/api/dev/Marten/DB/Model/Table/ClassMethods.html#db_table(db_table%3AString|Symbol)-instance-method) class method, the name of the model table is automatically generated by Marten using the following format: `_` (`model_name` being the underscore version of the model class name). ::: It should be noted that you can also "inject" parameters into your SQL query. To do so you have two options: either you specify these parameters as positional arguments, or you specify them as named arguments. Positional parameters must be specified using the `?` syntax while named parameters must be specified using the `:param` format. For example, the following query uses positional parameters: ```crystal Article.raw("SELECT * FROM articles WHERE title = ? and created_at > ?", "Hello World!", "2022-10-30") ``` And the following one uses named parameters: ```crystal Article.raw( "SELECT * FROM articles WHERE title = :title and created_at > :created_at", title: "Hello World!", created_at: "2022-10-30" ) ``` :::caution **Do not use string interpolations in your SQL queries!** You should never use string interpolations in your raw SQL queries as this would expose your code to SQL injection attacks (where attackers can inject and execute arbitrary SQL into your database). As such, never - ever - do something like that: ```crystal Article.raw("SELECT * FROM articles WHERE title = '#{title}'") ``` And instead, do something like that: ```crystal Article.raw("SELECT * FROM articles WHERE title = ?", title) ``` Also, note that the parameters are left **unquoted** in the raw SQL queries: this is very important as not doing it would expose your code to SQL injection vulnerabilities as well. Parameters are quoted automatically by the underlying database backend. ::: Finally, it should be noted that Marten does not validate the SQL queries you specify to the [`#raw`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#raw) query set method. It is the developer's responsibility to ensure that these queries are (i) valid and (ii) that they return records that correspond to the considered model. ## Filtering with raw SQL predicates Marten provides a feature to filter query sets using raw SQL predicates within the `#filter` method. This is useful when you need more complex filtering logic than simple field comparisons but still want to leverage Marten's query building capabilities. Using raw SQL predicates involves specifying a string containing the actual predicate and optional parameters to the `#filter` query set method. For example: ```crystal Author.filter("author_id IS NOT NULL") Author.filter("first_name = ?", "John") ``` ### Specifying parameters You can "inject" parameters into your SQL raw predicates when using the `#filter` method. To do so you have two options: either you specify these parameters as positional arguments, or you specify them as named arguments. Positional parameters must be specified using the `?` syntax while named parameters must be specified using the `:param` format. For example, the following query uses positional parameters: ```crystal Article.filter("title = ? and created_at > ?", "Hello World!", "2022-10-30") ``` And the following one uses named parameters: ```crystal Article.filter( "title = :title and created_at > :created_at", title: "Hello World!", created_at: "2022-10-30" ) ``` :::caution **Do not use string interpolations in your SQL predicates!** You should never use string interpolations in your raw SQL predicates as this would expose your code to SQL injection attacks (where attackers can inject and execute arbitrary SQL into your database). As such, never - ever - do something like that: ```crystal Article.filter("title = '#{title}'") ``` And instead, do something like that: ```crystal Article.filter("title = ?", title) ``` Also, note that the parameters are left **unquoted** in the raw SQL queries: this is very important as not doing it would expose your code to SQL injection vulnerabilities as well. Parameters are quoted automatically by the underlying database backend. ::: ### Using `q` expressions For even more flexibility, you can combine raw SQL predicates with the [`q` expression](https://martenframework.com/docs/next/models-and-databases/queries#complex-filters-with-q-expressions) syntax within a block: ```crystal Post.all.filter { q(category: "news") & q("created_at > ?", Time.local - 7.days) } ``` ## Fetching single records with raw SQL predicates Marten allows you to fetch single records directly using raw SQL conditions with the [`get`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#get) and [`get!`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#get-1) methods. These methods provide an intuitive interface for retrieving individual records while maintaining the safety and flexibility of parameterized queries. The [`get`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#get) method retrieves a single record matching the raw SQL condition. It returns `nil` if no record matches the condition. For example, use `get` with positional parameters: ```crystal article = Article.get("title = ? AND created_at > ?", "Hello World!", "2022-10-30") ``` The [`get!`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#get-1) method is similar but raises an exception if no record is found. For example, use `get!` with named parameters: ```crystal article = Article.get!( "title = :title AND created_at > :created_at", title: "Hello World!", created_at: "2022-10-30" ) ``` ## Updating with raw SQL expressions Marten provides a feature to update query set records using raw SQL expressions within the `#update` method. This is useful when you need to perform updates where the new value is computed at the SQL level (eg. copying one column into another) but still want Marten to handle the query building for the rest of the update statement. Using raw SQL update expressions involves specifying a string containing the actual `SET` clause and optional parameters to the `#update` query set method. For example: ```crystal Invoice.filter(number__isnull: true).update("number = id") Invoice.filter(status: "draft").update("label = ?", "default") ``` Column names should refer to database column names. ### Specifying parameters You can "inject" parameters into your SQL raw update expressions when using the `#update` method. To do so you have two options: either you specify these parameters as positional arguments, or you specify them as named arguments. Positional parameters must be specified using the `?` syntax while named parameters must be specified using the `:param` format. For example, the following query uses positional parameters: ```crystal Invoice.filter(status: "draft").update("label = ?", "default") ``` And the following one uses named parameters: ```crystal Invoice.filter( status: "draft" ).update( "label = :label", label: "default" ) ``` :::caution **Do not use string interpolations in your raw SQL update expressions!** You should never use string interpolations in your raw SQL update expressions as this would expose your code to SQL injection attacks (where attackers can inject and execute arbitrary SQL into your database). As such, never - ever - do something like that: ```crystal Invoice.update("label = '#{label}'") ``` And instead, do something like that: ```crystal Invoice.update("label = ?", label) ``` Also, note that the parameters are left **unquoted** in the raw SQL update expressions: this is very important as not doing it would expose your code to SQL injection vulnerabilities as well. Parameters are quoted automatically by the underlying database backend. ::: It should be noted that raw updates follow the same semantics as regular `#update` calls: no validation and no callbacks are executed. Developers are responsible for ensuring that the specified SQL is valid and safe. ## Executing other SQL statements If it is necessary to execute other SQL statements that don't fall into the scope of what's provided by the [`#raw`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#raw) query set method, then it's possible to rely on the low-level DB connection capabilities. Marten's DB connections are essentially wrappers around DB connections provided by the [crystal-db](https://github.com/crystal-lang/crystal-db) package. They can be opened, which allows you to essentially execute any query on the considered database. For example, the following snippet would open a connection to the default database and execute a simple query: ```crystal Marten::DB::Connection.default.open do |db| db.scalar("SELECT 1") end ``` :::tip If you are using multiple databases and need to execute SQL statements on a database that is not the default one, then you can retrieve the considered DB connection object by using the [`Marten::DB::Connection#get`](https://martenframework.com/docs/api/dev/Marten/DB/Connection.html#get(db_alias%3AString|Symbol)-class-method) method. This method simply requires an argument corresponding to the DB alias you want to retrieve (ie. the alias you assigned to the database in the [databases configuration](https://martenframework.com/docs/next/development/reference/settings#database-settings)) and returns the corresponding DB connection: ```crystal db = Marten::DB::Connection.get(:other_db) db.open do |db| db.scalar("SELECT 1") end ``` ::: The [`#open`](https://martenframework.com/docs/api/dev/Marten/DB/Connection/Base.html#open(%26)-instance-method) method allows opening a connection to the considered database, which you can then use to perform queries. This method leverages Crystal's [DB opening mechanism](https://crystal-lang.org/reference/database/index.html#open-database) and it returns the same DB connection objects that you would get if you were using `DB#open` directly: ```crystal Marten::DB::Connection.default.open do |db| db.exec "create table contacts (name varchar(30), age int)" end ``` Please refer to [Crystal's official documentation on interacting with databases](https://crystal-lang.org/reference/database/index.html) to learn more about this low-level API. # Multiple databases Source: https://martenframework.com/docs/next/models-and-databases/multiple-databases This section covers how to leverage multiple databases within a Marten project: how to configure these additional databases, how to query them, and how to route model operations automatically. ## Defining multiple databases Each Marten project leveraging a single database uses what is called a "default" database. This is the database whose configuration is defined when calling the [`#database`](https://martenframework.com/docs/api/dev/Marten/Conf/GlobalSettings.html#database(id%3DDB%3A%3AConnection%3A%3ADEFAULT_CONNECTION_NAME%2C%26)-instance-method) configuration method: ```crystal config.database do |db| db.backend = :sqlite db.name = "default_db.db" end ``` The "default" database is implied whenever you interact with the database (eg. by performing queries, creating records, etc), unless specified otherwise or unless a database router selects another connection. The [`#database`](https://martenframework.com/docs/api/dev/Marten/Conf/GlobalSettings.html#database(id%3DDB%3A%3AConnection%3A%3ADEFAULT_CONNECTION_NAME%2C%26)-instance-method) configuration method can take an additional argument in order to define additional databases. For example: ```crystal config.database :other_db do |db| db.backend = :sqlite db.name = "other_db.db" end ``` Think of this additional argument as a "database identifier" or alias that you can choose and that will allow you to interact with this specific database later on. ## Database routers Database routers let you define which database should be used for reads, writes, relations, and migrations. Routers are configured via the [`database_routers`](https://martenframework.com/docs/next/development/reference/settings#database_routers) setting: ```crystal config.database_routers = [ AnalyticsRouter, ] ``` Each router must inherit from [`Marten::DB::Router::Base`](https://martenframework.com/docs/api/dev/Marten/DB/Router/Base.html) and can override any of the following methods: | Method | Role | Return value | | --- | --- | --- | | `#db_for_read` | Suggest a database alias for read operations | alias `String`, or `nil` (no opinion) | | `#db_for_write` | Suggest a database alias for write operations | alias `String`, or `nil` | | `#allow_relation?` | Allow or forbid a relation between two records | `true`, `false`, or `nil` | | `#allow_migrate?` | Allow or forbid applying migrations to a database | `true`, `false`, or `nil` | Configured routers are consulted **in order**. The first non-`nil` opinion wins. If all routers abstain: * read/write operations fall back to the `"default"` database * relations and migrations are allowed ### Example: routing an app to a dedicated database ```crystal class AnalyticsRouter < Marten::DB::Router::Base def db_for_read(model, hints = Marten::DB::Router::Hints.new) : String? "analytics" if model.app_config.label == "analytics" end def db_for_write(model, hints = Marten::DB::Router::Hints.new) : String? db_for_read(model, hints) end def allow_migrate?(db, app_label, model_name = nil, hints = Marten::DB::Router::Hints.new) : Bool? return app_label == "analytics" if db == "analytics" return app_label != "analytics" if db == "default" nil end end ``` ### Example: primary / replica split ```crystal class PrimaryReplicaRouter < Marten::DB::Router::Base def db_for_read(model, hints = Marten::DB::Router::Hints.new) : String? "replica" end def db_for_write(model, hints = Marten::DB::Router::Hints.new) : String? "default" end end ``` ### Connection resolution order When Marten needs a database connection for a model operation, it resolves it in this order: 1. An explicit `#using` / `using:` argument, if provided 2. The sticky database alias stored on the model instance, if any 3. The first configured router that returns a non-`nil` alias 4. The `"default"` database The sticky alias is set when a record is loaded from or saved to a database via an explicit `#using` selection. Subsequent bare `#save`, `#delete`, `#update`, or `#update_columns` calls on that instance reuse the same database. ## Applying migrations to your databases The [`migrate`](https://martenframework.com/docs/next/development/reference/management-commands#migrate) management command operates on the "default" database by default, but it also accepts an optional `--db` option that lets you specify to which database the migrations should be applied. The value you specify for this option must correspond to the alias you configured when defining your databases in your project's configuration. For example: ```bash marten migrate --db=other_db ``` When database routers are configured, Marten consults `#allow_migrate?` for each migration and only applies migrations that are allowed for the target database. This makes it possible to keep app-specific schemas on dedicated databases. ## Manually selecting databases Marten lets you select which database you want to use when performing model-related operations. Unless specified, the connection suggested by routers (or the "default" database) is used, but it is possible to explicitly define to which database operations should be applied. Explicit selection always takes precedence over routers. ### Querying records When querying records, you can use the [`#using`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#using) query set method in order to specify the target database. For example: ```crystal Article.all # Targets the routed (or default) database Article.using(:other_db).all # Targets the "other_db" database ``` ### Persisting records When creating, updating, or deleting records, it is possible to specify to which database the operation should be applied to by using the `using` argument. For example: ```crystal tag = Tag.new(label: "crystal") tag.save(using: :other_db) tag.delete(using: :other_db) ``` After an explicit `using:` persistence, the record remembers that database alias. Later bare saves on the same instance continue targeting it unless another alias is specified. # Create custom model fields Source: https://martenframework.com/docs/next/models-and-databases/how-to/create-custom-model-fields Marten gives you the ability to create your own custom model field implementations, which can involve custom validation logics, errors, and custom behaviors. You can choose to leverage these custom fields as part of your project's model definitions, and you can even distribute them to let other projects use them. ## Model fields: scope and responsibilities Model fields have the following responsibilities: * they define the type and properties of the underlying column at the database level * they define the necessary Crystal bindings at the model class level: this means that they can contribute custom methods or instance variables to the models making use of them (eg. getters, setters, etc) * they define how field values are validated and/or sanitized Creating a custom model field does not necessarily mean that all of these responsibilities need to be taken care of as part of the custom field implementation. It really depends on whether you want to: * leverage an existing built-in model field (eg. integer, string, etc) * or create a new model field from scratch. ## Registering new model fields Regardless of the approach you take in order to define new model field classes ([subclassing built-in fields](#subclassing-existing-model-fields), or [creating new ones from scratch](#creating-new-model-fields-from-scratch)), these classes must be registered to the Marten's global fields registry in order to make them available for use when defining models. To do so, you will have to call the [`Marten::DB::Field#register`](https://martenframework.com/docs/api/dev/Marten/DB/Field.html#register(id%2Cfield_klass)-macro) method with the identifier of the field you wish to use, and the actual field class. For example: ```crystal Marten::DB::Field.register(:foo, FooField) ``` The identifier you pass to `#register` can be a symbol or a string. This is the identifier that is then made available to model classes in order to define their fields: ```crystal class MyModel < Marten::DB::Model field :id, :big_int, primary_key: true, auto: true // highlight-next-line field :test, :foo, blank: true, null: true end ``` The call to `#register` can be made from anywhere in your codebase, but obviously, you will want to ensure that it is done before requiring your model classes: indeed, Marten will make the compilation of your project fail if it can't find the field type you are trying to use as part of a model definition. ## Subclassing existing model fields The easiest way to introduce a model field is probably to subclass one of the [built-in model fields](https://martenframework.com/docs/next/models-and-databases/reference/fields) provided by Marten. This can make a lot of sense if the "type" of the field you are trying to implement is already supported by Marten. For example, implementing a custom "email" field could be done by subclassing the existing [`Marten::DB::Field::String`](https://martenframework.com/docs/api/dev/Marten/DB/Field/String.html) class. Indeed, an "email" field is essentially a string with a pre-defined maximum size and some additional validation logic: ```crystal class EmailField < Marten::DB::Field::String def initialize( @id : ::String, @max_size : ::Int32 = 254, @primary_key = false, @default : ::String? = nil, @blank = false, @null = false, @unique = false, @index = false, @db_column = nil ) end def validate(record, value) return if !value.is_a?(::String) # Leverage string's built-in validations (max size). super if !EmailValidator.valid?(value) record.errors.add(id, "Provide a valid email address") end end macro check_definition(field_id, kwargs) # No-op max_size automatic checks... end end ``` Everything that is described in the following section about [creating model fields from scratch](#creating-new-model-fields-from-scratch) also applies to the case of subclassing existing model fields: the same methods can be overridden if necessary, but leveraging an existing class can save you some work. ## Creating new model fields from scratch Creating new model fields from scratch involves subclassing the [`Marten::DB::Field::Base`](https://martenframework.com/docs/api/dev/Marten/DB/Field/Base.html) abstract class. Because of this, the new field class is required to implement a set of mandatory methods. These mandatory methods, and some other ones that are optional (but interesting in terms of capabilities), are described in the following sections. ### Mandatory methods #### `default` The `#default` method is responsible for returning the field's default value, if any. Not all fields support default values; if this does not apply to your field use case, you can simply "no-op" this method: ```crystal def default # no-op end ``` On the other hand, if your field can be initialized with a `default` argument (and if it defines a `@default` instance variable), another possibility is to define a `#default` getter: ```crystal getter default ``` #### `from_db` The `#from_db` method is responsible for converting the passed raw DB value to the right field value. Indeed, the value that is read from the database will usually need to be converted to another format. For example, a `uuid` field might need to convert a `String` value to a proper `UUID` object: ```crystal def from_db(value) : ::UUID? case value when Nil value.as?(Nil) when ::String ::UUID.new(value.as(::String)) when ::UUID value.as(::UUID) else raise_unexpected_field_value(value) end end ``` It should be noted that you will usually want to handle the case of `nil` values as part of this method since fields can be configured as nullable via the [`null: true`](https://martenframework.com/docs/next/models-and-databases/reference/fields#null) option. If the value can't be processed properly by your field class, then it may be necessary to raise an exception. To do that you can leverage the `#raise_unexpected_field_value` method, which will raise a `Marten::DB::Errors::UnexpectedFieldValue` exception. #### `from_db_result_set` The `#from_db_result_set` method is responsible for extracting the field value from a DB result set and returning the right object corresponding to this value. This method will usually be called when retrieving your field's value from the database (when using the Marten ORM). The method takes a standard `DB::ResultSet` object as argument and it is expected that you use `#read` to retrieve the intended column value. See the [Crystal reference documentation](https://crystal-lang.org/reference/1.5/database/index.html#reading-query-results) for more details around these objects and methods. For example: ```crystal def from_db_result_set(result_set : ::DB::ResultSet) : ::UUID? from_db(result_set.read(Nil | ::String | ::UUID)) end ``` The `#from_db_result_set` method is supposed to return the read value into the right "representation", that is the final object representing the field value that users will interact with when manipulating model records (for example a `UUID` object created from a string). As such, you will usually want to call [`#from_db`](#from_db) once you get the value from the database result set in order to return the final value. #### `to_column` Most model fields will contribute a corresponding column at the database level; these columns are read by Marten in order to generate migrations from model definitions. The column returned by the `#to_column` method should be an instance of a subclass of [`Marten::DB::Management::Column::Base`](https://martenframework.com/docs/api/dev/Marten/DB/Management/Column/Base.html). For example, an "email" field could return a string column as part of its `#to_column` method: ```crystal def to_column : Marten::DB::Management::Column::Base? Marten::DB::Management::Column::String.new( name: db_column!, max_size: max_size, primary_key: primary_key?, null: null?, unique: unique?, index: index?, default: to_db(default) ) end ``` If for some reason your custom field does not contribute any columns to the database model, it is possible to simply "no-op" the `#to_column` method by returning `nil` instead. #### `to_db` The `#to_db` method converts a field value from the "Crystal" representation to the database representation. As such, this method performs the reverse operation of the [`#from_db`](#from_db) method. For example, this method could return the string representation of a `UUID` object: ```crystal def to_db(value) : ::DB::Any case value when Nil nil when ::UUID value.hexstring else raise_unexpected_field_value(value) end end ``` Again, if the value can't be processed properly by the field class, it may be necessary to raise an exception. To do that you can leverage the `#raise_unexpected_field_value` method, which will raise a `Marten::DB::Errors::UnexpectedFieldValue` exception. ### Other useful methods #### `initialize` The default `#initialize` method that is provided by the [`Marten::DB::Field::Base`](https://martenframework.com/docs/api/dev/Marten/DB/Field/Base.html) is fairly simply and looks like this: ```crystal def initialize( @id : ::String, @primary_key = false, @blank = false, @null = false, @unique = false, @index = false, @db_column = nil ) end ``` Depending on your field requirements, you might want to override this method completely in order to support additional parameters (such as default values, max sizes, validation-related options, etc). #### `validate` The `#validate` method does nothing by default and can be overridden on a per-field class basis in order to implement custom validation logic. This method takes the model record being validated and the field value as arguments, which allows you to easily run validation checks and to add [validation errors](https://martenframework.com/docs/next/models-and-databases/validations) to the model record. For example: ```crystal def validate(record, value) return if !value.is_a?(::String) if !EmailValidator.valid?(value) record.errors.add(id, "Provide a valid email address") end end ``` ### An example Let's consider the use case of the "email" field highlighted in [Subclassing existing model fields](#subclassing-existing-model-fields). The exact same field could be implemented from scratch with the following snippet: ```crystal class EmailField < Marten::DB::Field::Base getter default getter max_size def initialize( @id : ::String, @max_size : ::Int32 = 254, @primary_key = false, @default : ::String? = nil, @blank = false, @null = false, @unique = false, @index = false, @db_column = nil ) end def from_db(value) : ::String? case value when Nil | ::String value.as?(Nil | ::String) else raise_unexpected_field_value(value) end end def from_db_result_set(result_set : ::DB::ResultSet) : ::String? result_set.read(::String?) end def to_column : Marten::DB::Management::Column::Base? Marten::DB::Management::Column::String.new( name: db_column!, max_size: max_size, primary_key: primary_key?, null: null?, unique: unique?, index: index?, default: to_db(default) ) end def to_db(value) : ::DB::Any case value when Nil nil when ::String value when Symbol value.to_s else raise_unexpected_field_value(value) end end def validate(record, value) return if !value.is_a?(::String) if value.size > @max_size record.errors.add(id, "The maximum allowed length is #{@max_size} characters") end if !EmailValidator.valid?(value) record.errors.add(id, "Provide a valid email address") end end end ``` # Create custom field predicates Source: https://martenframework.com/docs/next/models-and-databases/how-to/create-custom-field-predicates Marten has built-in support for common [field predicates](https://martenframework.com/docs/next/models-and-databases/reference/query-set#field-predicates), but the framework also allows you to write your own. Custom predicates are useful when you need a lookup that does not map to `exact`, `contains`, `gt`, and the other built-in types. This can include a not-equal comparison, a regular expression match, or a database-specific operator. ## Defining a field predicate Field predicates are subclasses of the [`Marten::DB::Query::SQL::Predicate::Base`](https://martenframework.com/docs/api/dev/Marten/DB/Query/SQL/Predicate/Base.html) abstract class. Each predicate class is responsible for: * declaring the lookup name used in query sets (for example `ne` in `title__ne`) * generating the SQL clause and bound parameters for that comparison The lookup name is defined with [`#predicate_name`](https://martenframework.com/docs/api/dev/Marten/DB/Query/SQL/Predicate/Base.html#predicate_name(name%3AString%3F)-class-method). The SQL is generated by implementing [`#to_sql`](https://martenframework.com/docs/api/dev/Marten/DB/Query/SQL/Predicate/Base.html#to_sql(connection%3AConnection%3A%3ABase)-instance-method), which receives the current database connection and must return a tuple of `{sql, params}`. The base class provides helpers that you should reuse from `#to_sql`: * `#sql_left_operand(connection)` — the quoted column (or [field transformation](https://martenframework.com/docs/next/models-and-databases/queries#field-transformations) / annotation expression) on the left-hand side * `#sql_params(connection)` — the bound parameters, with values converted through the field's `#to_db` method :::caution Built-in predicates get their SQL operators from each database connection. Custom predicate names are unknown to those mappings, so `#to_sql` must provide the operator itself. Relying on the default implementation will raise when the connection cannot find an operator for your lookup. ::: ### Example: a not-equal predicate The following predicate adds a `ne` lookup that translates to a SQL `<>` comparison. That operator is supported by all official Marten database backends: ```crystal class NotEqual < Marten::DB::Query::SQL::Predicate::Base predicate_name "ne" def to_sql(connection : Marten::DB::Connection::Base) {"#{sql_left_operand(connection)} <> %s", sql_params(connection)} end end ``` The `%s` placeholder in the SQL string is replaced with a backend-specific parameter marker when the query is executed. Do not interpolate the filter value into the SQL string; always pass it through the returned parameters. ## Registering field predicates In order to use a custom predicate in query sets, you must register it to Marten's global predicates registry. To do so, call [`Marten::DB::Query::SQL::Predicate#register`](https://martenframework.com/docs/api/dev/Marten/DB/Query/SQL/Predicate.html#register(predicate_klass%3ABase.class)-class-method) with the predicate class: ```crystal Marten::DB::Query::SQL::Predicate.register(NotEqual) ``` The lookup name comes from `#predicate_name` (here, `ne`). The call to `#register` can be made from anywhere in your codebase, but it must happen before the predicate is used in a query set. ## Using custom field predicates Once registered, the predicate is available as a double-underscore lookup on any field, the same way [built-in predicates](https://martenframework.com/docs/next/models-and-databases/queries#field-predicates) are: ```crystal Article.filter(title__ne: "Draft") ``` Because `#sql_left_operand` already applies [field transformations](https://martenframework.com/docs/next/models-and-databases/queries#field-transformations), the same predicate works on transformed values: ```crystal Article.filter(released_on__year__ne: 2022) ``` ## Handling backend-specific SQL Some lookups only exist on certain databases, or use a different operator per backend. In that case, branch on the connection class inside `#to_sql`. For example, a case-sensitive `regex` predicate could be implemented as follows: ```crystal class Regex < Marten::DB::Query::SQL::Predicate::Base predicate_name "regex" def to_sql(connection : Marten::DB::Connection::Base) sql = case connection when Marten::DB::Connection::PostgreSQL "#{sql_left_operand(connection)} ~ %s" when Marten::DB::Connection::MySQL "#{sql_left_operand(connection)} REGEXP BINARY %s" when Marten::DB::Connection::SQLite "#{sql_left_operand(connection)} REGEXP %s" else raise Marten::DB::Errors::UnmetQuerySetCondition.new( "The regex predicate is not supported for this database backend" ) end {sql, sql_params(connection)} end end ``` ```crystal Marten::DB::Query::SQL::Predicate.register(Regex) Article.filter(title__regex: "^Top") ``` :::note SQLite only provides a `REGEXP` operator if a corresponding function has been registered on the connection. If your project uses SQLite, make sure that function is available before using this predicate. ::: ## Customizing bound values `#sql_params` converts the filter value through the field. You can map over those parameters when the bound value should differ from the value passed to `#filter` — for example to wrap a string for a `LIKE` pattern, using [`#sanitize_like_pattern`](https://martenframework.com/docs/api/dev/Marten/DB/Connection/Base.html#sanitize_like_pattern(pattern%3AString)%3AString-instance-method) to escape `%` and `_`: ```crystal class ContainsWord < Marten::DB::Query::SQL::Predicate::Base predicate_name "contains_word" def to_sql(connection : Marten::DB::Connection::Base) params = sql_params(connection).map do |param| "% #{connection.sanitize_like_pattern(param.to_s)} %" end {"#{sql_left_operand(connection)} LIKE %s", params} end end ``` :::caution `LIKE` syntax varies across backends: SQLite expects `ESCAPE '\'`, and MySQL uses `LIKE BINARY` for case-sensitive matches. For `LIKE`-based predicates that must work on every backend, branch on the connection as shown in [Handling backend-specific SQL](#handling-backend-specific-sql), or reuse a built-in operator whose SQL is already backend-aware: ```crystal operator = connection.operator_for_predicate("contains") % "%s" {"#{sql_left_operand(connection)} #{operator}", params} ``` Passing `"contains"` (a built-in predicate name) is required here: `operator_for_predicate` does not know about custom lookup names. ::: # Model fields Source: https://martenframework.com/docs/next/models-and-databases/reference/fields This page provides a reference for all the available field options and field types that can be used when defining models. ## Common field options The following field options can be used for all the available field types when declaring model fields using the `field` macro. ### `blank` The `blank` argument allows to define whether a field is allowed to receive blank values from a validation perspective. The fields with `blank: false` that receive blank values will make their associated model record validation fail. The default value for this argument is `false`. ### `db_column` The `db_column` argument can be used to specify the name of the column corresponding to the field at the database level. Unless specified, the database column name will correspond to the field name. ### `default` The `default` argument allows to define a default value for a given field. The default value for this argument is `nil`. ### `index` The `index` argument can be used to specify that a database index must be created for the corresponding column. The default value for this argument is `false`. ### `primary_key` The `primary_key` argument can be used to specify that a field corresponds to the primary key of the considered model table. The default value for this argument is `false`. ### `null` The `null` argument allows to define whether a field is allowed to store `NULL` values in the database. The default value for this argument is `false`. ### `unique` The `unique` argument allows to define that values for a specific field must be unique throughout the associated table. The default value for this argument is `false`. ## Field types ### `big_int` A `big_int` field allows persisting 64-bit integers. In addition to the [common field options](#common-field-options), such fields support the following arguments: #### `auto` The `auto` argument auto-increment for the considered database column. Defaults to `false`. This argument will be used mainly when defining integer IDs that automatically increment: ```crystal class MyModel < Marten::Model field :id, :big_int, primary_key: true, auto: true # ... end ``` ### `bool` A `bool` field allows persisting booleans. ### `date` A `date` field allows persisting date values, which map to `Time` objects in Crystal. In addition to the [common field options](#common-field-options), such fields support the following arguments: #### `auto_now` The `auto_now` argument allows ensuring that the corresponding field value is automatically set to the current time every time a record is saved. This provides a convenient way to define `updated_at` fields. Defaults to `false`. #### `auto_now_add` The `auto_now_add` argument allows ensuring that the corresponding field value is automatically set to the current time every time a record is created. This provides a convenient way to define `created_at` fields. Defaults to `false`. ### `date_time` A `date_time` field allows persisting date-time values, which map to `Time` objects in Crystal. In addition to the [common field options](#common-field-options), such fields support the following arguments: #### `auto_now` The `auto_now` argument allows ensuring that the corresponding field value is automatically set to the current time every time a record is saved. This provides a convenient way to define `updated_at` fields. Defaults to `false`. #### `auto_now_add` The `auto_now_add` argument allows ensuring that the corresponding field value is automatically set to the current time every time a record is created. This provides a convenient way to define `created_at` fields. Defaults to `false`. ### `decimal` A `decimal` field allows persisting fixed-precision decimal numbers, which map to [`BigDecimal`](https://crystal-lang.org/api/BigDecimal.html) objects in Crystal. This is the right choice for monetary amounts and other values that must not lose precision (unlike [`float`](#float) fields). Both [`max_digits`](#max_digits) and [`decimal_places`](#decimal_places) are required: ```crystal class Product < Marten::Model field :id, :big_int, primary_key: true, auto: true field :price, :decimal, max_digits: 10, decimal_places: 2 end product = Product.create!(price: BigDecimal.new("19.99")) product.price # => 19.99 # Float, Int, and String values are also accepted and converted to BigDecimal product.price = 19.99 product.price = 20 product.price = "19.99" ``` :::info `decimal` fields are mapped to: * `numeric(max_digits, decimal_places)` columns in PostgreSQL databases * `numeric(max_digits, decimal_places)` columns in MySQL databases * `decimal(max_digits, decimal_places)` columns in SQLite databases ::: #### `max_digits` The `max_digits` argument **is required** and defines the maximum number of digits allowed in the number, including digits on both sides of the decimal point. #### `decimal_places` The `decimal_places` argument **is required** and defines the number of decimal places to store with the number. It must be less than or equal to [`max_digits`](#max_digits). ### `duration` A `duration` field allows persisting duration values, which map to [`Time::Span`](https://crystal-lang.org/api/Time/Span.html) objects in Crystal. `duration` fields are persisted as big integer values (number of nanoseconds) at the database level. ### `email` An `email` field allows to persist _valid_ email addresses. In addition to the [common field options](#common-field-options), such fields support the following arguments: #### `max_size` The `max_size` argument is optional and defaults to 254 characters (in accordance with RFCs 3696 and 5321). It allows to specify the maximum size of the persisted email addresses. This maximum size is used for the corresponding column definition and when it comes to validating field values. ### `enum` An `enum` field allows persisting the value of an [`Enum`](https://crystal-lang.org/api/Enum.html). When defining `enum` fields, it's necessary to specify a `values` argument that matches the actual enum: ```crystal enum Category NEWS BLOG end class Article < Marten::Model field :id, :big_int, primary_key: true, auto: true field :category, :enum, values: Category end article = Article.last! article.category # => Category::BLOG ``` :::info The way enums are handled at the database level depends on the database backend being used. Indeed, an ENUM type is used for MySQL databases while column checks are used for SQLite and PostgreSQL databases. ::: In addition to the [common field options](#common-field-options), such fields support the following arguments: #### `values` The `values` argument **is required** and allows to specify the actual enum class that should be used for the field. It is worth mentioning that the configured enum will impact the values allowed for the corresponding column at the database level. ### `file` A `file` field allows persisting the reference to an uploaded file. :::warning `file` fields can't be configured as primary keys. ::: #### `storage` This optional argument can be used to configure the storage that will be used to persist the actual files. It defaults to the media files storage (configured via the `media_files.storage` setting), but can be overridden on a per-field basis if needed: ```crystal my_storage = Marten::Core::Storage::FileSystem.new(root: "files", base_url: "/files/") class Attachment < Marten::Model field :id, :big_int, primary_key: true, auto: true field :uploaded_file, :file, storage: my_storage end ``` Please refer to [Managing files](https://martenframework.com/docs/next/files/managing-files) for more details on how to manage uploaded files and the associated storages. #### `upload_to` This optional argument can be used to configure where the uploaded files are persisted in the storage. It defaults to an empty string and can be set to either a string or a proc. If set to a string, it allows to define in which directory of the underlying storage files will be persisted: ```crystal class Attachment < Marten::Model field :id, :big_int, primary_key: true, auto: true field :uploaded_file, :file, upload_to: "foo/bar" end ``` If set to a proc, it allows to customize the logic allowing to generate the resulting path _and_ filename: ```crystal class Attachment < Marten::Model field :id, :big_int, primary_key: true, auto: true field :uploaded_file, :file, upload_to: ->(filename : String) { File.join("files/uploads", filename) } end ``` ### `float` A `float` field allows persisting floating point numbers (`Float64` objects). ### `image` An `image` field allows persisting the reference to an uploaded image file. :::info The [crystal-vips](https://github.com/naqvis/crystal-vips) shard is required for defining `image` model fields. If this shard is not installed and required by your project, it will not be possible to use `image` model fields and compilation errors will be raised. As such, make sure that: 1. Your project's `shard.yml` includes: ```yaml dependencies: vips: github: naqvis/crystal-vips ``` 2. Your project's `src/project.cr` includes: ```crystal require "vips" ``` ::: :::warning `image` fields can't be configured as primary keys. ::: #### `storage` This optional argument can be used to configure the storage that will be used to persist the actual image files. It defaults to the media files storage (configured via the `media_files.storage` setting), but can be overridden on a per-field basis if needed: ```crystal my_storage = Marten::Core::Storage::FileSystem.new(root: "files", base_url: "/files/") class Attachment < Marten::Model field :id, :big_int, primary_key: true, auto: true field :uploaded_image, :image, storage: my_storage end ``` Please refer to [Managing files](https://martenframework.com/docs/next/files/managing-files) for more details on how to manage uploaded files and the associated storages. #### `upload_to` This optional argument can be used to configure where the uploaded images files are persisted in the storage. It defaults to an empty string and can be set to either a string or a proc. If set to a string, it allows to define in which directory of the underlying storage files will be persisted: ```crystal class Attachment < Marten::Model field :id, :big_int, primary_key: true, auto: true field :uploaded_image, :image, upload_to: "foo/bar" end ``` If set to a proc, it allows to customize the logic allowing to generate the resulting path _and_ filename: ```crystal class Attachment < Marten::Model field :id, :big_int, primary_key: true, auto: true field :uploaded_image, :image, upload_to: ->(filename : String) { File.join("files/uploads", filename) } end ``` ### `int` An `int` field allows persisting 32-bit integers. In addition to the [common field options](#common-field-options), such fields support the following arguments: #### `auto` The `auto` argument auto-increment for the considered database column. Defaults to `false`. This argument will be used mainly when defining integer IDs that automatically increment: ```crystal class MyModel < Marten::Model field :id, :int, primary_key: true, auto: true # ... end ``` ### `json` A `json` field allows persisting JSON values to the database. JSON values are automatically parsed from the underlying database column and exposed as a [`JSON::Any`](https://crystal-lang.org/api/JSON/Any.html) object (or `nil` if no values are available) by default in Crystal: ```crystal class MyModel < Marten::Model # Other fields... field :metadata, :json end MyModel.last!.metadata # => JSON::Any object ``` Additionally, it is also possible to specify a [`serializable`](#serializable) option in order to specify a class that makes use of [`JSON::Serializable`](https://crystal-lang.org/api/JSON/Serializable.html). When doing so, the parsing of the JSON values will result in the initialization of the corresponding serializable objects: ```crystal class MySerializable include JSON::Serializable property a : Int32 | Nil property b : String | Nil end class MyModel < Marten::Model # Other fields... field :metadata, :json, serializable: MySerializable end MyModel.last!.metadata # => MySerializable object ``` :::info It should be noted that `json` fields are mapped to: * `jsonb` columns in PostgreSQL databases * `text` columns in MySQL databases * `text` columns in SQLite databases ::: #### `serializable` The `serializable` arguments allows to specify that a class making use of [`JSON::Serializable`](https://crystal-lang.org/api/JSON/Serializable.html) should be used in order to parse the JSON values for the model field at hand. When specifying a `serializable` class, the values returned for the considered model fields will be instances of that class instead of [`JSON::Any`](https://crystal-lang.org/api/JSON/Any.html) objects. ### `slug` A `slug` field allows to persist _valid_ slug values (ie. strings that can only include characters, numbers, dashes, and underscores). In addition to the [common field options](#common-field-options), such fields support the following arguments: :::info Since slug fields are usually used to query records, they are indexed by default. You can use the [`index`](#index) option (`index: false`) to disable auto-indexing. ::: #### `max_size` The `max_size` argument is optional and defaults to 50 characters. It allows to specify the maximum size of the persisted email addresses. This maximum size is used for the corresponding column definition and when it comes to validate field values. #### `slugify` The `slugify` argument allows specifying the field from which the slug should be generated. This is useful when you want the slug to be automatically derived from another field. ```crystal class Article < Marten::Model field :title, :string field :slug, :slug, slugify: :title end article = Article.create!(title: "My Article") article.slug # => "my-article" ``` When an `Article` object is saved, the slug field will automatically generate a slug based on the title field if no custom slug is provided. :::warning The slugification functionality also transforms Unicode characters and symbols. When filtering a model by the query parameter, it may be necessary to decode the slug parameter first, because although the browser may show you the unicode characters, it will send the encoded characters in the HTTP request: ```crystal class ArticleDetailsHandler < Marten::Handler def get article = Article.get(slug: URI.decode(params[:slug].to_s)) # … end end ``` ::: ### `string` A `string` field allows to persist small or medium string values. In addition to the [common field options](#common-field-options), such fields support the following arguments: #### `max_size` The `max_size` argument **is required** and allows to specify the maximum size of the persisted string. This maximum size is used for the corresponding column definition and when it comes to validate field values. #### `min_size` The `min_size` argument allows defining the minimum size allowed for the persisted string. The default value for this argument is `nil`, which means that the minimum size is not validated by default. #### `choices` The `choices` argument allows defining an array of allowed string values. The default value for this argument is `nil`, which means that values are not restricted to a specific set of choices by default. When set, field values must match one of the configured choices. ```crystal class Article < Marten::Model field :id, :big_int, primary_key: true, auto: true field :status, :string, max_size: 20, choices: ["draft", "published", "archived"] end ``` ### `text` A `text` field allows to persist large text values. In addition to the [common field options](#common-field-options), such fields support the following arguments: #### `max_size` The `max_size` argument allows to specify the maximum size of the persisted string. This maximum size is used when it comes to validate field values. Defaults to `nil`. ### `url` A `url` field allows persisting _valid_ URL addresses. In addition to the [common field options](#common-field-options), such fields support the following arguments: #### `max_size` The `max_size` argument is optional and defaults to 200 characters. It allows to specify the maximum size of the persisted URLs. This maximum size is used for the corresponding column definition and when it comes to validate field values. ### `uuid` A `uuid` field allows persisting Universally Unique IDentifiers (`UUID` objects). ## Relationship field types ### `many_to_many` A `many_to_many` field allows to define a many-to-many relationship. This special field type requires the use of a special `to` argument in order to specify the model class to which the current model is related. For example, an `Article` model could have a many-to-many field towards a `Tag` model. In such case, an `Article` record could have many associated `Tag` records, and every `Tag` records could be associated to many `Article` records as well: ```crystal class Tag < Marten::Model # ... end class Article < Marten::Model # ... field :tags, :many_to_many, to: Tag end ``` In addition to the [common field options](#common-field-options), such fields support the following arguments: #### `to` The `to` argument **is required** and allows to specify the model class that is related to the model where the `many_to_many` field is defined. #### `related` The `related` argument allows defining the name of the reverse (or backward) relation on the targeted model. If we consider the previous example, it could be possible to define an `articles` backward relation in order to let `Tag` records expose their related `Article` records: ```crystal class Tag < Marten::Model # ... end class Article < Marten::Model # ... field :tags, :many_to_many, to: Tag, related: :articles end ``` When the `related` argument is used, a method will be automatically created on the targeted model by using the chosen argument's value. For example, this means that all the `Article` records using a specific `Tag` record could be accessed through the use of the `Tag#articles` method in the previous snippet. The default value is `nil`, which means that no reverse relation is defined on the targeted model by default. ### `many_to_one` A `many_to_one` field allows defining a many-to-one relationship. This special field type requires the use of a special `to` argument in order to specify the model class to which the current model is related. For example, an `Article` model could have a many-to-one field towards an `Author` model. In such case, an `Article` record would only have one associated `Author` record, but every `Author` record could be associated to many `Article` records: ```crystal class Author < Marten::Model # ... end class Article < Marten::Model # ... field :author, :many_to_one, to: Author end ``` In addition to the [common field options](#common-field-options), such fields support the following arguments: #### `to` The `to` argument **is required** and allows to specify the model class that is related to the model where the `many_to_one` field is defined. #### `related` The `related` argument allows defining the name of the reverse (or backward) relation on the targeted model. If we consider the previous example, it could be possible to define an `articles` backward relation in order to let `Author` records expose their related `Article` records: ```crystal class Author < Marten::Model # ... end class Article < Marten::Model # ... field :author, :many_to_one, to: Author, related: :articles end ``` When the `related` argument is used, a method will be automatically created on the targeted model by using the chosen argument's value. For example, this means that all the `Article` records associated with a specific `Author` record could be accessed through the use of the `Author#articles` method in the previous snippet. The default value is `nil`, which means that no reverse relation is defined on the targeted model by default. #### `on_delete` The `on_delete` argument allows to specify the deletion strategy to adopt when a related record (one that is targeted by the `many_to_one` field) is deleted. The following strategies can be specified (as symbols): * `:do_nothing`: is the default strategy. With this strategy, Marten won't do anything to ensure that records referencing the record being deleted are deleted or updated. If the database enforces referential integrity (which will be the case for foreign key fields), this means that deleting a record could result in database errors. * `:cascade`: this strategy can be used to perform cascade deletions. When deleting a record, Marten will try to first destroy the other records that reference the object being deleted. * `:protect`: this strategy allows to explicitly prevent the deletion of records if they are referenced by other records. This means that attempting to delete a "protected" record will result in a `Marten::DB::Errors::ProtectedRecord` error. * `:set_null`: this strategy will set the reference column to `null` when the related record is deleted. ### `one_to_one` A `one_to_one` field allows defining a one-to-one relationship. This special field type requires the use of a special `to` argument in order to specify the model class to which the current model is related. For example, a `User` model could have a one-to-one field towards a `Profile` model. In such case, the `User` model could only have one associated `Profile` record, and the reverse would be true as well (a `Profile` record could only have one associated `User` record). In fact, a one-to-one field is really similar to a many-to-one field, but with an additional unicity constraint: ```crystal class Profile < Marten::Model # ... end class User < Marten::Model # ... field :profile, :one_to_one, to: Profile end ``` In addition to the [common field options](#common-field-options), such fields support the following arguments: #### `to` The `to` argument **is required** and allows to specify the model class that is related to the model where the `one_to_one` field is defined. #### `related` The `related` argument allows defining the name of the reverse (or backward) relation on the targeted model. If we consider the previous example, it could be possible to define a `user` backward relation in order to let `Profile` records expose their related `User` record: ```crystal class Profile < Marten::Model # ... end class User < Marten::Model # ... field :profile, :one_to_one, to: Profile, related: :user end ``` When the `related` argument is used, a method will be automatically created on the targeted model by using the chosen argument's value. For example, this means that the `User` record associated with a specific `Profile` record could be accessed through the use of the `Profile#user` method in the previous snippet. The default value is `nil`, which means that no reverse relation is defined on the targeted model by default. #### `on_delete` Same as [the similar option for the `#many_to_one` field](#on_delete). ### `polymorphic` A `polymorphic` field allows defining a polymorphic relationship. This special field type requires the use of a special `to` argument in order to specify the model classes to which the current model can be related. For example, a `Comment` model could have a polymorphic field towards an `Article` or a `Recipe` model. In such case, a `Comment` record could be associated with an `Article` or a `Recipe` record: ```crystal class Article < Marten::Model # ... end class Recipe < Marten::Model # ... end class Comment < Marten::Model # ... field :target, :polymorphic, to: [Article, Recipe] end ``` In addition to the [common field options](#common-field-options), such fields support the following arguments: #### `to` The `to` argument **is required** and allows to specify the model classes that can be related to the model where the `polymorphic` field is defined. #### `related` The `related` argument allows defining the name of the reverse (or backward) relation on the targeted model. If we consider the previous example, it could be possible to define a `comments` backward relation in order to let `Article` and `Recipe` records access their related `Comment` records: ```crystal class Article < Marten::Model # ... end class Recipe < Marten::Model # ... end class Comment < Marten::Model # ... field :target, :polymorphic, to: [Article, Recipe], related: :comments end ``` When the `related` argument is used, a method will be automatically created on the associated models by using the chosen argument's value. For example, this means that all the `Comment` records associated with a specific `Article` or `Recipe` record could be accessed through the use of the `Article#comments` or `Recipe#comments` methods in the previous snippet. The default value is `nil`, which means that no reverse relation is defined on the associated models by default. #### `on_delete` Same as [the similar option for the `#many_to_one` field](#on_delete). Because polymorphic fields are not backed by a database foreign key, the default `:do_nothing` strategy will leave related records in place (with a dangling type/ID pair) unless another strategy is specified. When `:set_null` is used, both the `_id` and `_type` columns of the polymorphic field are set to `null`. # Table options Source: https://martenframework.com/docs/next/models-and-databases/reference/table-options This page provides a reference for all the table options that can be leveraged when defining models. ## Table name Table names for models are automatically generated from the model name and the label of the associated application. That being said, it is possible to specifically override the name of a model table by leveraging the [`#db_table`](https://martenframework.com/docs/api/dev/Marten/DB/Model/Table/ClassMethods.html#db_table(db_table%3AString|Symbol)-instance-method) class method, which requires a table name string or symbol. For example: ```crystal class Article < Marten::Model field :id, :big_int, primary_key: true, auto: true field :title, :string, max_size: 255 field :content, :text // highlight-next-line db_table :articles end ``` ## Table indexes Multifields indexes can be configured in a model by leveraging the [`#db_index`](https://martenframework.com/docs/api/dev/Marten/DB/Model/Table/ClassMethods.html#db_index(name%3AString|Symbol%2Cfield_names%3AArray(String)|Array(Symbol))%3ANil-instance-method) class method. This method requires an index name argument as well as an array of targeted field names. For example: ```crystal class Person < Marten::Model field :id, :int, primary_key: true, auto: true field :first_name, :string, max_size: 50 field :last_name, :string, max_size: 50 // highlight-next-line db_index :person_full_name_index, field_names: [:first_name, :last_name] end ``` ## Table unique constraints Multifields unique constraints can be configured in a model by leveraging the [`#db_unique_constraint`](https://martenframework.com/docs/api/dev/Marten/DB/Model/Table/ClassMethods.html#db_unique_constraint(name%3AString|Symbol%2Cfield_names%3AArray(String)|Array(Symbol))%3ANil-instance-method) class method. This method requires an index name argument as well as an array of targeted field names. For example: ```crystal class Booking < Marten::Model field :id, :int, primary_key: true, auto: true field :room, :string, max_size: 50 field :date, :date, max_size: 50 // highlight-next-line db_unique_constraint :booking_room_date_constraint, field_names: [:room, :date] end ``` # Query set Source: https://martenframework.com/docs/next/models-and-databases/reference/query-set This page provides a reference for all the query set methods and available predicates that can be leveraged when filtering model records. ## Query set laziness Query sets are **lazily evaluated**: defining a query set will usually not involve any database operations. Additionally, most methods provided by query sets also return new query set objects. Query sets are only translated to SQL queries hitting the underlying database when records need to be extracted or manipulated by the considered codebase. For example: ```crystal qset = Article.filter(title__startswith: "Top") # the query set is not evaluated qset = qset.filter(author__first_name: "John") # the query set is not evaluated puts qset # the query set is evaluated ``` In the above example the two filters are simply chained without these resulting in database hits. The query set is only evaluated when the actual records need to be printed. Overall, query sets are evaluated in the following situations: * when iterating over the underlying records (eg. when using `#each`) ```crystal Article.filter(title__startswith: "Top").each do |article| puts article end ``` * when retrieving the records for a specific range ```crystal Article.filter(title__startswith: "Top")[4..10] ``` * when printing the query set object (eg. using `puts`) ## Methods that return new query sets Query sets provide a set of methods that allow to generate other (possibly filtered) query sets. Calling these methods won't result in the query set to be evaluated. ### `[](range)` Returns the records corresponding to the passed range. If no records match the passed range, an `IndexError` exception is raised. If the current query set was already evaluated (records were retrieved from the database), an array of records will be returned. Otherwise, another sliced query set will be returned: ```crystal qset_1 = Article.all qset_1.each { } qset_1[2..6] # returns an array of Article records qset_2 = Article.all qset_2[2..6] # returns a "sliced" query set ``` ### `[]?(range)` Returns the records corresponding to the passed range. `nil` is returned if no records match the passed range. If the current query set was already evaluated (records were retrieved from the database), an array of records will be returned. Otherwise, another sliced query set will be returned: ```crystal qset_1 = Article.all qset_1.each { } qset_1[2..6]? # returns an array of Article records qset_2 = Article.all qset_2[2..6]? # returns a "sliced" query set ``` ### `&` (AND) Combines the current query set with another one using the **AND** operator. This method returns a new query set that is the result of combining the current query set with another one using the AND SQL operator. For example: ```crystal query_set_1 = Post.all.filter(title: "Test") query_set_2 = Post.all.filter(is_published: true) combined_query_set = query_set_1 & query_set_2 ``` ### `|` (OR) Combines the current query set with another one using the **OR** operator. This method returns a new query set that is the result of combining the current query set with another one using the OR SQL operator. For example: ```crystal query_set_1 = Post.all.filter(title: "Test") query_set_2 = Post.all.filter(is_published: true) combined_query_set = query_set_1 | query_set_2 ``` ### `^` (XOR) Combines the current query set with another one using the **XOR** operator. This method returns a new query set that is the result of combining the current query set with another one using the XOR SQL operator. For example: ```crystal query_set_1 = Post.all.filter(title: "Test") query_set_2 = Post.all.filter(is_published: true) combined_query_set = query_set_1 ^ query_set_2 ``` :::info XOR is natively support on MariaDB and MySQL only. Other database backends (PostgreSQL and SQLite) will use `case ... when` statements in order to perform XOR operations at the SQL level. ::: ### `all` Allows retrieving all the records of a specific model. `#all` can be used as a class method from any model class, or it can be used as an instance method from any query set object. In this last case, calling `#all` returns a copy of the current query set. For example: ```crystal qset = Article.all # returns a query set matching "all" the records of the Article model qset2 = qset.all # returns a copy of the initial query set ``` ### `annotate` Returns a new query set that will include the specified annotations. This method returns a new query set with the specified annotations. The annotations are specified using a block where each annotation has to be wrapped using the `#annotate` method. For example: ```crystal query_set = Book.all.annotate { count(:authors) } other_query_set = Book.all.annotate do count(:authors, alias_name: :author_count) sum(:pages, alias_name: :total_pages) end ``` Each of the specified annotations is then available for further use in the query set (in order to filter or order the records). The annotations are also available in retrieved model records via the [`#annotations`](https://martenframework.com/docs/api/dev/Marten/DB/Model.html#annotations%3AHash(String%2CBool|File|Float32|Float64|Int32|Int64|JSON%3A%3AAny|JSON%3A%3ASerializable|Marten%3A%3ADB%3A%3AField%3A%3AFile%3A%3AFile|Marten%3A%3AHTTP%3A%3AUploadedFile|String|Symbol|Time|Time%3A%3ASpan|UUID|Nil)-instance-method) method, which returns a hash containing the annotations as keys and their values as values. Those are the supported annotation types: | Aggregation method | Description | |---------------------|-------------| | `count` | Counts the number of records | | `sum` | Returns the sum of the values of a given field | | `average` | Returns the average of the values of a given field | | `minimum` | Returns the minimum value of a given field | | `maximum` | Returns the maximum value of a given field | Please refer to the [Annotating query sets with aggregated data](https://martenframework.com/docs/next/models-and-databases/queries#annotating-query-sets-with-aggregated-data) section to learn more about using annotations. ### `distinct` Returns a new query set that will use `SELECT DISTINCT` or `SELECT DISTINCT ON` in its SQL query. If you use this method without arguments, a `SELECT DISTINCT` statement will be used at the database level. If you pass field names as arguments, a `SELECT DISTINCT ON` statement will be used to eliminate any duplicated rows based on the specified fields: ```crystal query_set_1 = Post.all.distinct query_set_2 = Post.all.distinct(:title) ``` It should be noted that it is also possible to follow associations of direct related models too by using the [double underscores notation](https://martenframework.com/docs/next/models-and-databases/queries#filtering-relations) (`__`). For example the following query will select distinct records based on a joined "author" attribute: ``` query_set = Post.all.distinct(:author__name) ``` Finally, it should be noted that `#distinct` cannot be used on [sliced query sets](#range). ### `exclude` Returns a query set whose records do not match the given set of filters. The filters passed to this method method can be specified using the [standard predicate format](https://martenframework.com/docs/next/models-and-databases/queries#basic-querying-capabilities). If multiple filters are specified, they will be joined using an **AND** operator at the SQL level: ```crystal query_set = Post.all query_set.exclude(title: "Test") query_set.exclude(title__startswith: "A") ``` Complex filters can also be used as part of this method by leveraging [`q` expressions](https://martenframework.com/docs/next/models-and-databases/queries#complex-filters-with-q-expressions): ```crystal query_set = Post.all query_set.exclude { (q(name: "Foo") | q(name: "Bar")) & q(is_published: True) } ``` ### `filter` Returns a query set matching a specific set of filters. The filters passed to this method method can be specified using the [standard predicate format](https://martenframework.com/docs/next/models-and-databases/queries#basic-querying-capabilities). If multiple filters are specified, they will be joined using an **AND** operator at the SQL level: ```crystal query_set = Post.all query_set.filter(title: "Test") query_set.filter(title__startswith: "A") ``` Complex filters can also be used as part of this method by leveraging [`q` expressions](https://martenframework.com/docs/next/models-and-databases/queries#complex-filters-with-q-expressions): ```crystal query_set = Post.all query_set.filter { (q(name: "Foo") | q(name: "Bar")) & q(is_published: True) } ``` ### `join` Returns a queryset whose specified `relations` are "followed" and joined to each result (see [Queries](https://martenframework.com/docs/next/models-and-databases/queries#filtering-relations) for an introduction about this capability). When using `#join`, the specified relationships will be followed and each record returned by the queryset will have the corresponding related objects already selected and populated. Using `#join` can result in performance improvements since it can help reduce the number of SQL queries, as illustrated by the following example: ```crystal query_set = Post.all p1 = query_set.get(id: 1) puts p1.author # hits the database to retrieve the related "author" p2 = query_set.join(:author).get(id: 1) puts p2.author # doesn't hit the database since the related "author" was already selected ``` It should be noted that it is also possible to follow foreign keys of direct related models too by using the double underscores notation (`__`). For example, the following query will select the joined "author" and its associated "profile": ```crystal query_set = Post.all query_set.join(:author__profile) ``` :::info The `#join` method also supports targeting the reverse relation of a [`one_to_one`](https://martenframework.com/docs/next/models-and-databases/reference/fields#one_to_one) field (such reverse relation can be defined through the use of the [`related`](https://martenframework.com/docs/next/models-and-databases/reference/fields#related-2) field option). That way, you can traverse a [`one_to_one`](https://martenframework.com/docs/next/models-and-databases/reference/fields#one_to_one) field back to the model record on which the field is specified. ::: ### `limit` Returns a query set that will limit the number of records returned. This method allows to specify the maximum number of records to return. For example: ```crystal query_set = Post.all.limit(10) ``` In the above example, only the first 10 records will be returned. ### `lock` Returns a query set that will lock selected rows using `SELECT ... FOR UPDATE`. This method allows obtaining a pessimistic lock on the records targeted by the query set. On database backends that support row locking, it must be used inside a [transaction](https://martenframework.com/docs/next/models-and-databases/transactions) (otherwise a `Marten::DB::Errors::UnmetQuerySetCondition` exception is raised). See [Pessimistic locking](https://martenframework.com/docs/next/models-and-databases/transactions#pessimistic-locking) for more details. ```crystal Post.transaction do post = Post.lock.get!(id: 1) post.title = "Updated" post.save! end ``` A custom locking clause can also be passed: ```crystal Post.transaction do post = Post.lock("FOR UPDATE NOWAIT").get!(id: 1) post = Post.lock("FOR SHARE").get!(id: 1) end ``` :::info SQLite does not support `SELECT ... FOR UPDATE`. On SQLite, `#lock` still returns a query set that can be evaluated inside a transaction, but no database-level row lock is acquired. ::: ### `none` Returns a query set that will always return an empty array of records, without querying the database. Once this method is used, any subsequent method calls (such as extra filters) will continue returning an empty array of records: ```crystal query_set = Post.all query_set.none.exists? # => false ``` ### `offset` Returns a query set that will offset the records returned. This method allows to specify the starting point for the records to return. For example: ```crystal query_set = Post.all.offset(10) ``` In the above example, the records will be returned starting from the 10th record. ### `order` Allows specifying the ordering in which records should be returned when evaluating the query set. Multiple fields can be specified in order to define the final ordering. For example: ```crystal query_set = Post.all query_set.order("-published_at", "title") ``` In the above example, records would be ordered by descending publication date (because of the `-` prefix), and then by title (ascending). ### `prefetch` Returns a query set that will automatically prefetch in a single batch the records for the specified relations (see [Queries](https://martenframework.com/docs/next/models-and-databases/queries#pre-fetching-relations) for an introduction about this capability). When using `#prefetch`, the records corresponding to the specified relationships will be prefetched in single batches and each record returned by the query set will have the corresponding related objects already selected and populated. Using `#prefetch` can result in performance improvements since it can help reduce the number of SQL queries, as illustrated by the following example: ```crystal posts_1 = Post.all.to_a # hits the database to retrieve the related "tags" (many-to-many relation) puts posts_1[0].tags.to_a posts_2 = Post.all.prefetch(:tags).to_a # doesn't hit the database since the related "tags" relation was already prefetched puts posts_2[0].tags ``` It should be noted that it is also possible to follow relations and reverse relations too by using the double underscores notation(`__`). For example, the following query will prefetch the "author" relation and then the "favorite tags" relation of the author records: ```crystal query_set = Post.all query_set.prefetch(:author__favorite_tags) ``` In some situations, it might be necessary to use a custom query set for the prefetched records. This is possible by using a variant of the `#prefetch` method in which a single relation name and the associated query set (`query_set` argument) are provided: ```crystal # Query all lists and order the list items by position query_set = List.prefetch(:items, query_set: Item.order(:position)) ``` Finally, it is worth mentioning that multiple relations can be specified to `#prefetch`. For example: ```crystal Author.all.prefetch(:books__genres, :publisher) ``` :::tip The `#prefetch` method can also be called directly on model classes: ```crystal Author.prefetch(:books__genres, :publisher) ``` ::: ### `raw` Returns a raw query set for the passed SQL query and optional parameters. This method returns a [`Marten::DB::Query::RawSet`](https://martenframework.com/docs/api/dev/Marten/DB/Query/RawSet.html) object, which allows to iterate over the model records matched by the passed SQL query. For example: ```crystal Article.all.raw("SELECT * FROM articles") ``` Additional parameters can also be specified if the query needs to be parameterized. Those can be specified as positional or named arguments. For example: ```crystal # Using splat positional parameters: Article.all.raw("SELECT * FROM articles WHERE title = ? and created_at > ?", "Hello World!", "2022-10-30") # Using an array of positional parameters: Article.all.raw("SELECT * FROM articles WHERE title = ? and created_at > ?", ["Hello World!", "2022-10-30"]) # Using double splat named parameters: Article.all.raw( "SELECT * FROM articles WHERE title = :title and created_at > :created_at", title: "Hello World!", created_at: "2022-10-30" ) # Using a hash of named parameters: Article.all.raw( "SELECT * FROM articles WHERE title = :title and created_at > :created_at", { title: "Hello World!", created_at: "2022-10-30", } ) ``` Please refer to [Raw SQL](https://martenframework.com/docs/next/models-and-databases/raw-sql) to learn more about performing raw SQL queries. ### `reverse` Allows reversing the order of the current query set. For example, this would return all the `Article` records ordered by descending title: ```crystal query_set = Article.all.order(:title) query_set.reverse ``` ### `using` Allows defining which database alias should be used when evaluating the query set. For example: ```crystal query_set_1 = Article.all.filter(published: true) # records are retrieved from the default database query_set_2 = Article.all.filter(published: true).using(:other) # records are retrieved from the "other" database ``` The value passed to `#using` must be a valid database alias that was used to configure an additional database as part of the [database settings](https://martenframework.com/docs/next/development/reference/settings#database-settings). ## Methods that do not return new query sets Query sets also provide a set of methods that will usually result in specific SQL queries to be executed in order to return values that don't correspond to new query sets. ### `average` Allows calculating the average of a numeric field within the records of a specific model. The `#average` method can be used as a class method from any model class, or it can be used as an instance method from any query set object. When used on a query set, it calculates the average of the specified field for the records in that query set. For example: ```crystal average_price = Product.average(:price) # Calculate the average price of all products # Calculate the average rating for a specific category of products electronic_products = Product.filter(category: "Electronics") average_rating = electronic_products.average(:rating) ``` ### `build` Initializes a new model instance. This method allows initializing a new model instance using the arguments defined in the passed double splat argument. ```crystal new_post = Post.all.build(title: "My blog post") ``` This method can also be called with a block that is executed for the new object: ```crystal new_post = Post.all.build(title: "My blog post") do |p| p.complex_attribute = compute_complex_attribute end ``` ### `bulk_create` Bulk inserts the passed model instances into the database. This method allows to insert multiple model instances into the database in a single query. This can be useful when dealing with large amounts of data that need to be inserted into the database. For example: ```crystal query_set = Post.all query_set.bulk_create( [ Post.new(title: "First post"), Post.new(title: "Second post"), Post.new(title: "Third post"), ] ) ``` An optional `batch_size` argument can be passed to this method in order to specify the number of records that should be inserted in a single query. By default, all records are inserted in a single query (except for SQLite databases where the limit of variables in a single query is 999). For example: ```crystal query_set = Post.all query_set.bulk_create( [ Post.new(title: "First post"), Post.new(title: "Second post"), Post.new(title: "Third post"), ], batch_size: 2 ) ``` :::tip The `#bulk_create` method can also be called directly on model classes: ```crystal Post.bulk_create( [ Post.new(title: "First post"), Post.new(title: "Second post"), Post.new(title: "Third post"), ] ) ``` ::: It is worth mentioning that this method has a few caveats: * The specified records are assumed to be valid and no [callbacks](https://martenframework.com/docs/next/models-and-databases/callbacks) will be called on them. * Bulk-creating records making use of multi-table inheritance is not supported. * If the model's primary key field is auto-incremented at the database level, the newly inserted primary keys will only be assigned to records on certain databases that support retrieving bulk-inserted rows (namely MariaDB, PostgreSQL, and SQLite). ### `count` Returns the number of records that are targeted by the current query set. For example: ```crystal Article.all.count # returns the number of article records Article.all.count(:subtitle) # returns the number of articles where the subtitle is not null Article.filter(title__startswith: "Top").count # returns the number of articles whose title start with "Top" ``` Note that this method will trigger a `SELECT COUNT` SQL query if the query set was not already evaluated: when this happens, no model records will be instantiated since the records count will be determined at the database level. If the query set was already evaluated, the underlying array of records will be used to return the records count instead of running a dedicated SQL query. ### `create` Creates a model instance and saves it to the database if it is valid. The new model instance is initialized by using the attributes defined in the passed double splat argument. Regardless of whether it is valid or not (and thus persisted to the database or not), the initialized model instance is returned by this method: ```crystal query_set = Post.all query_set.create(title: "My blog post") ``` This method can also be called with a block that is executed for the new object. This block can be used to directly initialize the object before it is persisted to the database: ```crystal query_set = Post.all query_set.create(title: "My blog post") do |post| post.complex_attribute = compute_complex_attribute end ``` ### `create!` Creates a model instance and saves it to the database if it is valid. The model instance is initialized using the attributes defined in the passed double splat argument. If the model instance is valid, it is persisted to the database ; otherwise a `Marten::DB::Errors::InvalidRecord` exception is raised. ```crystal query_set = Post.all query_set.create!(title: "My blog post") ``` This method can also be called with a block that is executed for the new object. This block can be used to directly initialize the object before it is persisted to the database: ```crystal query_set = Post.all query_set.create!(title: "My blog post") do |post| post.complex_attribute = compute_complex_attribute end ``` ### `delete` Deletes the records corresponding to the current query set and returns the number of deleted records. By default, related objects will be deleted by following the [deletion strategy](https://martenframework.com/docs/next/models-and-databases/reference/fields#on_delete) defined in each foreign key field if applicable, unless the `raw` argument is set to `true`. When the `raw` argument is set to `true`, a raw SQL delete statement will be used to delete all the records matching the currently applied filters. Note that using this option could cause errors if the underlying database enforces referential integrity. ```crystal Article.all.delete # deletes all the Article records Article.filter(title__startswith: "Top").delete # deletes all the articles whose title start with "Top" ``` ### `each` Allows iterating over the records that are targeted by the current query set. This method can be used to define a block that iterates over the records that are targeted by a query set: ```crystal Post.all.each do |post| # Do something with the post end ``` ### `each_batch` Iterates over the records targeted by the current query set in batches. This method allows processing large query sets without loading all the matching records into memory at once. Each batch is fetched from the database separately using a primary key cursor and passed to the provided block as an array of records. For example: ```crystal Post.all.each_batch(500) do |posts| posts.each do |post| # Do something with the post end end ``` An optional `batch_size` argument can be passed to specify the number of records that should be fetched per batch. It defaults to `1000`. Records are always processed in ascending primary key order, regardless of any existing query set ordering. Note that this method does not populate the query set's result cache. ### `exists?` Returns `true` if the current query set matches at least one record, or `false` otherwise. ```crystal Article.filter(title__startswith: "Top").exists? ``` Note that this method will trigger a very simple `SELECT EXISTS` SQL query if the query set was not already evaluated: when this happens, no model records will be instantiated since the records existence will be determined at the database level. If the query set was already evaluated, the underlying array of records will be used to determine if records exist or not. It should be noted that `#exists?` can also take additional filters or `q()` expressions as arguments. This allows to apply additional filters to the considered query set in order to perform the check. For example: ```crystal query_set = Tag.filter(name__startswith: "c") query_set.exists?(is_active: true) query_set.exists? { q(is_active: true) } ``` ### `first` Returns the first record that is matched by the query set, or `nil` if no records are found. ```crystal Article.first Article.filter(title__startswith: "Top").first ``` ### `first!` Returns the first record that is matched by the query set, or raises a `NilAssertionError` exception if no records are found. ```crystal Article.first! Article.filter(title__startswith: "Top").first! ``` ### `get` Returns the model instance matching the given set of filters. Model fields such as primary keys or fields with a unique constraint should be used here in order to retrieve a specific record: ```crystal query_set = Post.all post_1 = query_set.get(id: 123) post_2 = query_set.get(id: 456, is_published: false) ``` Complex filters can also be used as part of this method by leveraging [`q` expressions](https://martenframework.com/docs/next/models-and-databases/queries#complex-filters-with-q-expressions): ```crystal query_set = Post.all post_1 = query_set.get { q(id: 123) } post_2 = query_set.get { q(id: 456, is_published: false) } ``` If the specified set of filters doesn't match any records, the returned value will be `nil`. Moreover, in order to ensure data consistency this method will raise a `Marten::DB::Errors::MultipleRecordsFound` exception if multiple records match the specified set of filters. Note that `#get` can be used to retrieve a record with a raw SQL predicate. For example: ```crystal Author.get("id=?", 42) Author.get("id=:id", id: 42) ``` ### `get!` Returns the model instance matching the given set of filters. Model fields such as primary keys or fields with a unique constraint should be used here in order to retrieve a specific record: ```crystal query_set = Post.all post_1 = query_set.get!(id: 123) post_2 = query_set.get!(id: 456, is_published: false) ``` Complex filters can also be used as part of this method by leveraging [`q` expressions](https://martenframework.com/docs/next/models-and-databases/queries#complex-filters-with-q-expressions): ```crystal query_set = Post.all post_1 = query_set.get! { q(id: 123) } post_2 = query_set.get! { q(id: 456, is_published: false) } ``` If the specified set of filters doesn't match any records, a `Marten::DB::Errors::RecordNotFound` exception will be raised. Moreover, in order to ensure data consistency this method will raise a `Marten::DB::Errors::MultipleRecordsFound` exception if multiple records match the specified set of filters. Note that `#get` can be used to retrieve a record with a raw SQL predicate. For example: ```crystal Author.get!("id=?", 42) Author.get!("id=:id", id: 42) ``` ### `get_or_create` Returns the model record matching the given set of filters or create a new one if no one is found. Model fields that uniquely identify a record should be used here. For example: ```crystal tag = Tag.all.get_or_create(label: "crystal") ``` When no record is found, the new model instance is initialized by using the attributes defined in the double splat arguments. Regardless of whether it is valid or not (and thus persisted to the database or not), the initialized model instance is returned by this method. This method can also be called with a block that is executed for new objects. This block can be used to directly initialize new records before they are persisted to the database: ```crystal tag = Tag.all.get_or_create(label: "crystal") do |new_tag| new_tag.active = false end ``` In order to ensure data consistency, this method will raise a `Marten::DB::Errors::MultipleRecordsFound` exception if multiple records match the specified set of filters. ### `get_or_create!` Returns the model record matching the given set of filters or create a new one if no one is found. Model fields that uniquely identify a record should be used here. For example: ```crystall tag = Tag.all.get_or_create!(label: "crystal") ``` When no record is found, the new model instance is initialized by using the attributes defined in the double splat arguments. If the new model instance is valid, it is persisted to the database ; otherwise a `Marten::DB::Errors::InvalidRecord` exception is raised. This method can also be called with a block that is executed for new objects. This block can be used to directly initialize new records before they are persisted to the database: ```crystal tag = Tag.all.get_or_create!(label: "crystal") do |new_tag| new_tag.active = false end ``` In order to ensure data consistency, this method will raise a `Marten::DB::Errors::MultipleRecordsFound` exception if multiple records match the specified set of filters. ### `includes?` Returns `true` if a specific model record is included in the query set. This method can be used to verify the membership of a specific model record in a given query set. If the query set is not evaluated yet, a dedicated SQL query will be executed in order to perform this check (without loading the entire list of records that are targeted by the query set). This is especially interesting for large query sets where we don't want all the records to be loaded in memory in order to perform such check. ```crystal tag = Tag.get!(name: "crystal") query_set = Tag.filter(name__startswith: "c") query_set.includes?(tag) # => true ``` ### `last` Returns the last record that is matched by the query set, or `nil` if no records are found. ```crystal Article.last Article.filter(title__startswith: "Top").last ``` ### `last!` Returns the last record that is matched by the query set, or raises a `NilAssertionError` exception if no records are found. ```crystal Article.last! Article.filter(title__startswith: "Top").last! ``` ### `maximum` Retrieves the maximum value in a specific field across all records within a query set. ```crystal Product.all.maximum(:price) # Retrieves the highest price across all products # => 125.25 ``` ### `minimum` Retrieves the minimum value in a specific field across all records within a query set. ```crystal Product.all.minimum(:price) # Retrieves the lowest price across all products # => 15.99 ``` ### `paginator` Returns a paginator that can be used to paginate the current query set. This method returns a [`Marten::DB::Query::Paginator`](https://martenframework.com/docs/Marten/DB/Query/Paginator.html) object, which can then be used to retrieve specific pages. A page size must be specified when calling this method. For example: ```crystal query_set = Article.all paginator = query_set.paginator(10) paginator.page(1) # Returns the first page of records ``` ### `pick` Returns specific column values for a single record without actually loading it. This method allows to easily select specific column values for a single record from the current query set. This allows retrieving specific column values without actually loading the entire record, and as such this is most useful for query sets that have been narrowed down to match a single record. The method returns an array containing the requested column values, or `nil` if no record was matched by the current query set. For example: ```crystal Post.filter(pk: 1).pick("title", "published") # => ["First article", true] ``` ### `pick!` Returns specific column values for a single record without actually loading it. This method allows to easily select specific column values for a single record from the current query set. This allows retrieving specific column values without actually loading the entire record, and as such this is most useful for query sets that have been narrowed down to match a single record. The method returns an array containing the requested column values, or raises `NilAssertionError` if no record was matched by the current query set. For example: ```crystal Post.filter(pk: 1).pick!("title", "published") # => ["First article", true] ``` ### `pks` Returns the primary key values of the considered model records targeted by the current query set. This method returns an array containing the primary key values of the model records that are targeted by the current query set. For example: ```crystal Post.all.pks # => [1, 2, 3] ``` ### `pluck` Returns specific column values without loading entire record objects. This method allows to easily select specific column values from the current query set. This allows retrieving specific column values without actually loading entire records. The method returns an array containing one array with the actual column values for each record targeted by the query set. For example: ```crystal Post.all.pluck("title", "published") # => [["First article", true], ["Upcoming article", false]] ``` ### `size` Alias for [`#count`](#count): returns the number of records that are targeted by the query set. ### `sum` Calculates the total sum of values in a specific field across all records within a query set. Example: ```crystal Order.all.sum(:amount) # Calculates the total amount across all orders # => 7 ``` ### `to_s` Returns a string representation of the considered query set. ### `to_sql` Returns the SQL representation of the considered query set. For example: ```crystal Tag.filter(name__startswith: "r").to_sql # => "SELECT app_tag.id, app_tag.name, app_tag.is_active FROM \"app_tag\" WHERE app_tag.name LIKE $1" ``` :::note The outputted SQL will vary depending on the database backend in use. ::: ### `update_or_create` Updates the model record matching the given set of filters, or creates a new one if no one is found. Model fields that uniquely identify a record should be used here. This method first attempts to retrieve a record that matches the specified filters. If it exists, the record is updated using the attributes provided in the required `updates` argument: ```crystal user = User.all.update_or_create( updates: {first_name: "Jane"}, username: "abc" ) ``` If no matching record is found, a new one is created using the attributes defined in `updates`. If additional attributes should only be used when creating new records, a `defaults` argument can be provided (these attributes will then be used instead of `updates` when creating the record): ```crystal user = User.all.update_or_create( updates: {first_name: "Jane"}, defaults: {first_name: "Jane", is_admin: true}, username: "abc" ) ``` In order to ensure data consistency, this method will raise a `Marten::DB::Errors::MultipleRecordsFound` exception if multiple records match the specified set of filters. ### `update_or_create!` Updates the model record matching the given set of filters, or creates a new one if no one is found. Model fields that uniquely identify a record should be used here. This method first attempts to retrieve a record that matches the specified filters. If it exists, the record is updated using the attributes provided in the required `updates` argument: ```crystal user = User.all.update_or_create!( updates: {first_name: "Jane"}, username: "abc" ) ``` If no matching record is found, a new one is created using the attributes defined in `updates`. If additional attributes should only be used when creating new records, a `defaults` argument can be provided (these attributes will then be used instead of `updates` when creating the record): ```crystal user = User.all.update_or_create!( updates: {first_name: "Jane"}, defaults: {first_name: "Jane", is_admin: true}, username: "abc" ) ``` In order to ensure data consistency, this method will raise a `Marten::DB::Errors::MultipleRecordsFound` exception if multiple records match the specified set of filters. Raises a `Marten::DB::Errors::InvalidRecord` exception if the updated or created record is invalid. ``` ### `update` Updates all the records matched by the current query set with the passed values. This method allows to update all the records that are matched by the current query set with the values defined in the passed double splat argument. It returns the number of records that were updated: ```crystal query_set = Post.all query_set.update(title: "Updated") # => 42 ``` It should be noted that this method results in a regular `UPDATE` SQL statement. As such, the records that are updated through the use of this method won't be instantiated nor validated, and no callbacks will be executed for them either. This method can also be called with a raw SQL expression that will be used as the `SET` clause of the produced `UPDATE` statement. For example: ```crystal query_set = Invoice.filter(number__isnull: true) query_set.update("number = id") # => 42 query_set.update("label = ?", "default") query_set.update("label = :label", label: "default") ``` Please refer to [Updating with raw SQL expressions](https://martenframework.com/docs/next/models-and-databases/raw-sql#updating-with-raw-sql-expressions) to learn more about this capability. ## Field predicates Below are listed all the available [field predicates](https://martenframework.com/docs/next/models-and-databases/queries#field-predicates) that can be used when filtering query sets. Implementing custom field predicates is also a possibility that is documented in [Create custom field predicates](https://martenframework.com/docs/next/models-and-databases/how-to/create-custom-field-predicates). ### `contains` Allows filtering records based on field values that contain a specific substring. Note that this is a **case-sensitive** predicate. ```crystal Article.all.filter(title__contains: "tech") ``` ### `endswith` Allows filtering records based on field values that end with a specific substring. Note that this is a **case-sensitive** predicate. ```crystal Article.all.filter(title__endswith: "travel") ``` ### `exact` Allows filtering records based on a specific field value (exact match). Note that providing a `nil` value will result in a `IS NULL` check at the SQL level. This is the default predicate; as such it is not necessary to specify it when filtering records. The following two query sets are equivalent: ```crystal Article.all.filter(published: true) Article.all.filter(published__exact: true) ``` ### `gte` Allows filtering records based on field values that are greater than or equal to a specified value. ```crystal Article.all.filter(rating__gte: 10) ``` ### `gt` Allows filtering records based on field values that are greater than a specified value. ```crystal Article.all.filter(rating__gt: 10) ``` ### `icontains` Allows filtering records based on field values that contain a specific substring, in a case-insensitive way. ```crystal Article.all.filter(title__icontains: "tech") ``` ### `iendswith` Allows filtering records based on field values that end with a specific substring, in a case-insensitive way. ```crystal Article.all.filter(title__iendswith: "travel") ``` ### `iexact` Allows filtering records based on a specific field value (exact match), in a case-insensitive way. ```crystal Article.all.filter(title__iexact: "Top blog posts") ``` ### `istartswith` Allows filtering records based on field values that start with a specific substring, in a case-insensitive way. ```crystal Article.all.filter(title__istartswith: "top") ``` ### `in` Allows filtering records based on field values that are contained in a specific array of values. ```crystal Tag.all.filter(slug__in=["foo", "bar", "xyz"]) ``` Note that this predicate can also be used for filtering relation fields (such as [`many_to_one`](https://martenframework.com/docs/next/models-and-databases/reference/fields#many_to_one) or [`one_to_one`](https://martenframework.com/docs/next/models-and-databases/reference/fields#one_to_one) fields) using arrays of model records. For example: ```crystal authors = Author.filter(first_name: "John") articles = Article.filter(author__in: authors) ``` ### `isnull` Allows filtering records based on field values that should be null or not null. ```crystal Article.all.filter(subtitle__isnull: true) Article.all.filter(subtitle__isnull: false) ``` ### `lte` Allows filtering records based on field values that are less than or equal to a specified value. ```crystal Article.all.filter(rating__lte: 10) ``` ### `lt` Allows filtering records based on field values that are less than a specified value. ```crystal Article.all.filter(rating__lt: 10) ``` ### `startswith` Allows filtering records based on field values that start with a specific substring. Note that this is a **case-sensitive** predicate. ```crystal Article.all.filter(title__startswith: "Top") ``` ## Field transformations Below are listed all the available [field transformations](https://martenframework.com/docs/next/models-and-databases/queries#field-transformations) that can be used when filtering query sets. ### `day` Transforms a specific [`date_time`](https://martenframework.com/docs/next/models-and-databases/reference/fields#date_time) or [`date`](https://martenframework.com/docs/next/models-and-databases/reference/fields#date) field value to an integer representing the day. ```crystal Article.all.filter(released_on__day: 12) Article.all.filter(released_on__day__gt: 12) ``` ### `hour` Transforms a specific [`date_time`](https://martenframework.com/docs/next/models-and-databases/reference/fields#date_time) field value to an integer representing the hour. ```crystal Article.all.filter(released_on__hour: 12) Article.all.filter(released_on__hour__gt: 12) ``` ### `minute` Transforms a specific [`date_time`](https://martenframework.com/docs/next/models-and-databases/reference/fields#date_time) field value to an integer representing the minute. ```crystal Article.all.filter(released_on__minute: 12) Article.all.filter(released_on__minute__gt: 12) ``` ### `month` Transforms a specific [`date_time`](https://martenframework.com/docs/next/models-and-databases/reference/fields#date_time) or [`date`](https://martenframework.com/docs/next/models-and-databases/reference/fields#date) field value to an integer representing the month. ```crystal Article.all.filter(released_on__month: 12) Article.all.filter(released_on__month__gt: 12) ``` ### `second` Transforms a specific [`date_time`](https://martenframework.com/docs/next/models-and-databases/reference/fields#date_time) field value to an integer representing the second. ```crystal Article.all.filter(released_on__second: 12) Article.all.filter(released_on__second__gt: 12) ``` ### `year` Transforms a specific [`date_time`](https://martenframework.com/docs/next/models-and-databases/reference/fields#date_time) or [`date`](https://martenframework.com/docs/next/models-and-databases/reference/fields#date) field value to an integer representing the year. ```crystal Article.all.filter(released_on__year: 2022) Article.all.filter(released_on__year__gt: 2022) ``` # Migration operations Source: https://martenframework.com/docs/next/models-and-databases/reference/migration-operations This page provides a reference for all the available migration operations that can be leveraged when writing migrations. ## `add_column` The `add_column` operation allows adding a column to an existing table. It must be called with a table name as first argument, followed by a column definition (column name and attributes). For example: ```crystal add_column :test_table, :foo, :string, max_size: 255 add_column :test_table, :new_id, :reference, to_table: :target_table, to_column: :id ``` ## `add_index` The `add_index` operation allows adding an index to an existing table. It must be called with a table name as first argument, followed by an index definition (index name and indexed column names). For example: ```crystal add_index :test_table, :test_index, [:foo, :bar] ``` An optional `concurrently: true` argument can be used to create the index without locking the table for writes. On PostgreSQL this emits `CREATE INDEX CONCURRENTLY`; on MySQL / MariaDB it uses `ALGORITHM=INPLACE LOCK=NONE`. SQLite ignores the flag. Concurrent index operations cannot run inside a transaction. Migrations that use `concurrently: true` must set [`atomic false`](https://martenframework.com/docs/next/models-and-databases/migrations#transactions): ```crystal class Migration::Blog::V202608191200000 < Marten::Migration atomic false def plan add_index :blog_article, :index_blog_article_published_at, [:published_at], concurrently: true end end ``` ## `add_unique_constraint` The `add_unique_constraint` operation allows adding a unique constraint to an existing table. It must be called with a table name as first argument, followed by a unique constraint definition (constraint name and targeted column names). For example: ```crystal add_unique_constraint :test_table, :test_constraint, [:foo, :bar] ``` ## `change_column` The `change_column` operation allows altering an existing column definition. It must be called with a table name as first argument, followed by a column definition (column name and attributes). For example: ```crystal change_column :test_table, :test_column, :string, max_size: 155, null: true ``` ## `create_table` The `create_table` operation allows creating a new table, which includes the underlying column definitions, indexes, and unique constraints. It must be called with a table name as first argument and requires a block where columns, indexes, and unique constraints are defined. For example: ```crystal create_table :test_table do column :id, :big_int, primary_key: true, auto: true column :foo, :int, null: true column :bar, :int, null: true unique_constraint :cname, [:foo, :bar] index :index_name, [:foo, :bar] end ``` ## `delete_table` The `delete_table` operation allows deleting an existing table. It must be called with a table name as first argument. For example: ```crystal delete_table :test_table ``` ## `execute` The `execute` operation allows executing custom SQL statements as part of a migration. It must be called with a forward statement as first positional argument, and it can also take a second positional argument in order to specify the statement to execute when unapplying the migration. For example: ```crystal execute( ( <<-SQL SELECT 1 SQL ), ( <<-SQL SELECT 2 SQL ) ) ``` ## `remove_column` The `remove_column` operation allows removing an existing column from a table. It must be called with a table name as first argument, followed by a column name. For example: ```crystal remove_column :test_table, :test_column ``` ## `remove_index` The `remove_index` operation allows removing an existing index from a table. It must be called with a table name as first argument, followed by an index name. For example: ```crystal remove_index :test_table, :test_index ``` An optional `concurrently: true` argument can be used to drop the index without locking the table for writes. On PostgreSQL this emits `DROP INDEX CONCURRENTLY`; on MySQL / MariaDB it uses `ALGORITHM=INPLACE LOCK=NONE`. SQLite ignores the flag. As with [`add_index`](#add_index), concurrent index operations require [`atomic false`](https://martenframework.com/docs/next/models-and-databases/migrations#transactions) on the migration class: ```crystal class Migration::Blog::V202608191200000 < Marten::Migration atomic false def plan remove_index :blog_article, :index_blog_article_published_at, concurrently: true end end ``` ## `remove_unique_constraint` The `remove_unique_constraint` operation allows removing an existing unique constraint from a table. It must be called with a table name as first argument, followed by a unique constraint name. For example: ```crystal remove_unique_constraint :test_table, :test_constraint ``` ## `rename_column` The `rename_column` operation allows renaming an existing column in a table. It must be called with a table name as first argument, followed by the old column name, and the new one. For example: ```crystal rename_column :test_table, :old_column, :new_column ``` ## `rename_table` The `rename_table` operation allows renaming an existing table. It must be called with the existing table name as first argument, followed by the new table name. For example: ```crystal rename_table :old_table, :new_table ``` ## `run_code` The `run_code` operation allows to define that arbitrary methods will be called when applying and unapplying a migration. It must be called with a method name as first positional argument (the method that will be called when applying the migration), and it can also take an additional argument in order to specify the name of the method to execute when unapplying the migration. For example: ```crystal run_code :run_forward_code, :run_backward_code ``` # Handlers and HTTP Source: https://martenframework.com/docs/next/handlers-and-http Handlers are classes that process a web request and return a response. They implement the necessary logic allowing to return this response, which can involve processing form data for example. ## Guides - [Introduction](https://martenframework.com/docs/next/handlers-and-http/introduction) - [Routing](https://martenframework.com/docs/next/handlers-and-http/routing) - [Generic handlers](https://martenframework.com/docs/next/handlers-and-http/generic-handlers) - [Error handlers](https://martenframework.com/docs/next/handlers-and-http/error-handlers) - [Sessions](https://martenframework.com/docs/next/handlers-and-http/sessions) - [Cookies](https://martenframework.com/docs/next/handlers-and-http/cookies) - [Callbacks](https://martenframework.com/docs/next/handlers-and-http/callbacks) - [Middlewares](https://martenframework.com/docs/next/handlers-and-http/middlewares) ## How-to's - [Customize handler template contexts](https://martenframework.com/docs/next/handlers-and-http/how-to/customize-handler-template-contexts) - [Create custom route parameters](https://martenframework.com/docs/next/handlers-and-http/how-to/create-custom-route-parameters) - [Build a JSON API](https://martenframework.com/docs/next/handlers-and-http/how-to/build-a-json-api) ## Reference - [Generic handlers](https://martenframework.com/docs/next/handlers-and-http/reference/generic-handlers) - [Middlewares](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares) # Introduction to handlers Source: https://martenframework.com/docs/next/handlers-and-http/introduction Handlers are classes whose responsibility is to process web requests and to return responses. They implement the necessary logic allowing to return this response, which can involve processing form data through the use of [schemas](https://martenframework.com/docs/next/schemas) for example, retrieving [model records](https://martenframework.com/docs/next/models-and-databases) from the database, etc. They can return responses corresponding to HTML pages, JSON objects, redirects, ... ## Writing handlers At their core, handlers are subclasses of the [`Marten::Handler`](https://martenframework.com/docs/api/dev/Marten/Handlers/Base.html) class. These classes are usually defined under a `handlers` folder, at the root of a Marten project or application. Here is an example of a very simple handler: ```crystal class SimpleHandler < Marten::Handler def dispatch respond "Hello World!" end end ``` The above handler returns a `200 OK` response containing a short text, regardless of the incoming HTTP request method. Handlers are initialized from a [`Marten::HTTP::Request`](https://martenframework.com/docs/api/dev/Marten/HTTP/Request.html) object and an optional set of routing parameters. Their inner logic is executed when calling the `#dispatch` method, which _must_ return a [`Marten::HTTP::Response`](https://martenframework.com/docs/api/dev/Marten/HTTP/Response.html) object. When the `#dispatch` method is explicitly overridden, it is responsible for applying different logics in order to handle the various incoming HTTP request methods. For example, a handler might display an HTML page containing a form when handling a `GET` request, and it might process possible form data when handling a `POST` request: ```crystal class FormHandler < Marten::Handler def dispatch if request.method == 'POST' # process form data else # return HTML page end end end ``` It should be noted that this "dispatching" logic based on the incoming request method does not have to live inside an overridden `#dispatch` method. By default, each handler provides methods whose names match HTTP method verbs. This allows writing the logic allowing to process `GET` requests by overriding the `#get` method for example, or to process `POST` requests by overriding the `#post` method: ```crystal class FormHandler < Marten::Handler def get # return HTML page end def post # process form data end end ``` Note that that this technique can be used for all the HTTP methods, which includes `#get`, `#post`, `#put`, `#patch`, `#delete`, `#options`, `#trace`, and `#query`. :::info If a handler's logic is defined like in the above example, trying to access such handler via another HTTP verb (eg. `DELETE`) will automatically result in a "Not allowed" response (405). ::: ### The `request` and `response` objects As mentioned previously, a handler is always initialized from an incoming HTTP request object (instance of [`Marten::HTTP::Request`](https://martenframework.com/docs/api/dev/Marten/HTTP/Request.html)) and is required to return an HTTP response object (instance of [`Marten::HTTP::Response`](https://martenframework.com/docs/api/dev/Marten/HTTP/Response.html)) as part of its `#dispatch` method. The `request` object gives access to a set of useful information and attributes associated with the incoming request. Things like the HTTP request verb, headers, or query parameters can be accessed through this object. The most common methods that you can use are listed below: | Method | Description | | ----------- | ----------- | | `#body` | Returns the raw body of the request as a string. | | `#cookies` | Returns a hash-like object (instance of [`Marten::HTTP::Cookies`](https://martenframework.com/docs/api/dev/Marten/HTTP/Cookies.html)) containing the cookies associated with the request. | | `#data` | Returns a hash-like object (instance of [`Marten::HTTP::Params::Data`](https://martenframework.com/docs/api/dev/Marten/HTTP/Params/Data.html)) containing the request data. | | `#flash` | Returns a hash-like object (instance of [`Marten::HTTP::FlashStore`](https://martenframework.com/docs/api/dev/Marten/HTTP/FlashStore.html)) containing the flash messages available to the current request. | | `#headers` | Returns a hash-like object (instance of [`Marten::HTTP::Headers`](https://martenframework.com/docs/api/dev/Marten/HTTP/Headers.html)) containing the headers embedded in the request. | | `#host` | Returns the host associated with the considered request. | | `#method` | Returns the considered HTTP request method (`GET`, `POST`, `PUT`, etc). | | `#query_params` | Returns a hash-like object (instance of [`Marten::HTTP::Params::Query`](https://martenframework.com/docs/api/dev/Marten/HTTP/Params/Query.html)) containing the HTTP GET parameters embedded in the request. | | `#session` | Returns a hash-like object (instance of [`Marten::HTTP::Session::Store::Base`](https://martenframework.com/docs/api/dev/Marten/HTTP/Session/Store/Base.html)) corresponding to the session store for the current request. | The `response` object corresponds to the HTTP response that is returned to the client. Response objects can be created by initializing the [`Marten::HTTP::Response`](https://martenframework.com/docs/api/dev/Marten/HTTP/Response.html) class directly (or one of its subclasses) or by using [response helper methods](#response-helper-methods). Once initialized, these objects can be mutated to further configure what is sent back to the browser. The most common methods that you can use in this regard are listed below: | Method | Description | | ----------- | ----------- | | `#content` | Returns the content of the response as a string. | | `#content_type` | Returns the content type of the response as a string. | | `#cookies` | Returns a hash-like object (instance of [`Marten::HTTP::Cookies`](https://martenframework.com/docs/api/dev/Marten/HTTP/Cookies.html)) containing the cookies that will be sent with the response. | | `#headers` | Returns a hash-like object (instance of [`Marten::HTTP::Headers`](https://martenframework.com/docs/api/dev/Marten/HTTP/Headers.html)) containing the headers that will be used for the response. | | `#status` | Returns the status of the response (eg. 200 or 404). | ### Parameters Handlers are mapped to URLs through a [routing configuration](#mapping-handlers-to-urls). Some routes require parameters that are used by the handler to retrieve objects or perform any arbitrary logic. These parameters can be accessed by using the `#params` method, which returns a hash of all the parameters that were used to initialize the considered handler. For example such parameters can be used to retrieve a specific model instance: ```crystal class FormHandler < Marten::Handler def get if (record = MyModel.get(id: params["id"])) respond "Record found: #{record}" else respond "Record not found!", status: 404 end end end ``` :::tip Note that you can use either strings or symbols when interacting with the routing parameters returned by the `#params` method. ::: ### Response helper methods Technically, it is possible to forge HTTP responses by instantiating the [`Marten::HTTP::Response`](https://martenframework.com/docs/api/dev/Marten/HTTP/Response.html) class directly (or one of its subclasses such as [`Marten::HTTP::Response::Found`](https://martenframework.com/docs/api/dev/Marten/HTTP/Response/Found.html) for example). That being said, Marten provides a set of helper methods that can be used to conveniently forge responses for various use cases: #### `respond` You already saw `#respond` in action in the [first example](#writing-handlers). Basically, `#respond` allows forging an HTTP response by specifying a content, a content type, and a status code: ```crystal respond("Response content", content_type: "text/html", status: 200) ``` Unless specified, the `content_type` is set to `text/html` and the `status` is set to `200`. :::tip You can also express the `status` of the response as a symbol that must comply with the values of the [`HTTP::Status`](https://crystal-lang.org/api/HTTP/Status.html) enum. For example: ```crystal respond("Response content", content_type: "text/html", status: :ok) ``` ::: #### `render` `render` allows returning an HTTP response whose content is generated by rendering a specific [template](https://martenframework.com/docs/next/templates). The template can be rendered by specifying a context hash or named tuple. For example: ```crystal render("path/to/template.html", context: { foo: "bar" }, content_type: "text/html", status: 200) ``` Unless specified, the `content_type` is set to `text/html` and the `status` is set to `200`. :::tip You can also express the `status` of the response as a symbol that must comply with the values of the [`HTTP::Status`](https://crystal-lang.org/api/HTTP/Status.html) enum. For example: ```crystal render("path/to/template.html", context: { foo: "bar" }, content_type: "text/html", status: :ok) ``` ::: #### `redirect` `#redirect` allows forging a redirect HTTP response. It requires a `url` and accepts an optional `permanent` argument in order to define whether a permanent redirect is returned (301 Moved Permanently) or a temporary one (302 Found): ```crystal redirect("https://example.com", permanent: true) ``` Unless explicitly specified, `permanent` will automatically be set to `false`. #### `#head` `#head` allows constructing a response containing headers but without actual content. The method accepts a status code only: ```crystal head(404) ``` :::tip You can also express the `status` of the response as a symbol that must comply with the values of the [`HTTP::Status`](https://crystal-lang.org/api/HTTP/Status.html) enum. For example: ```crystal head :not_found ``` ::: #### `json` `json` allows forging an HTTP response with the `application/json` content type. It can be used with a raw JSON string, or any serializable object: ```crystal json({ foo: "bar" }, status: 200) ``` Unless specified, the `status` is set to `200`. :::tip You can also express the `status` of the response as a symbol that must comply with the values of the [`HTTP::Status`](https://crystal-lang.org/api/HTTP/Status.html) enum. For example: ```crystal json({ foo: "bar" }, status: :ok) ``` ::: :::tip Schema and model validation errors can be included in the payload. [`Marten::Core::Validation::ErrorSet`](https://martenframework.com/docs/api/dev/Marten/Core/Validation/ErrorSet.html) serializes as an array of objects with `field`, `type`, and `message`. See [Serializing errors as JSON](https://martenframework.com/docs/next/schemas/validations#serializing-errors-as-json) and [Build a JSON API](https://martenframework.com/docs/next/handlers-and-http/how-to/build-a-json-api). ```crystal json({errors: schema.errors}, status: 422) ``` ::: ### Callbacks It is possible to define callbacks in order to bind methods and logics to specific events in the lifecycle of your handlers. For example, it is possible to define callbacks that run before a handler's `#dispatch` method gets executed, or after it! Please head over to the [Handler callbacks](https://martenframework.com/docs/next/handlers-and-http/callbacks) guide in order to learn more about handler callbacks. ### Generic handlers Marten provides a set of generic handlers that can be used to perform common application tasks such as displaying lists of records, deleting entries, or rendering [templates](https://martenframework.com/docs/next/templates/introduction). This saves developers from reinventing common patterns. Please head over to the [Generic handlers](https://martenframework.com/docs/next/handlers-and-http/generic-handlers) guide in order to learn more about available generic handlers. ### Global template context All handlers have access to a [`#context`](https://martenframework.com/docs/api/dev/Marten/Handlers/Base.html#context-instance-method) method that returns a [template](https://martenframework.com/docs/next/templates/introduction) context object. This "global" context object is available for the lifetime of the considered handler and can be mutated in order to define which variables are made available to the template runtime when rendering templates through the use of the [`#render`](#render) helper method or when rendering templates as part of subclasses of the [`Marten::Handlers::Template`](https://martenframework.com/docs/next/handlers-and-http/generic-handlers#rendering-a-template) generic handler. To modify this context object effectively, it's recommended to utilize [`before_render`](https://martenframework.com/docs/next/handlers-and-http/callbacks#before_render) callbacks, which are invoked just before rendering a template within a handler. For example, this can be achieved as follows when using a [`Marten::Handlers::Template`](https://martenframework.com/docs/next/handlers-and-http/generic-handlers#rendering-a-template) subclass: ```crystal class MyHandler < Marten::Handlers::Template template_name "app/my_template.html" before_render :add_variable_to_context private def add_variable_to_context : Nil context["foo"] = "bar" end end ``` ### Returning errors It is easy to forge any error response by leveraging the `#respond` or `#head` helpers that were mentioned [previously](#response-helper-methods). Using these helpers, it is possible to forge HTTP responses that are associated with specific error status codes and specific contents. For example: ```crystal class MyHandler < Marten::Handler def get respond "Content not found", status: 404 end end ``` It should be noted that Marten also support a couple of exceptions that can be raised to automatically trigger default error handlers. For example [`Marten::HTTP::Errors::NotFound`](https://martenframework.com/docs/api/dev/Marten/HTTP/Errors/NotFound.html) can be raised from any handler to force a 404 Not Found response to be returned. Default error handlers can be returned automatically by the framework in many situations (eg. a record is not found, or an unhandled exception is raised); you can learn more about them in [Error handlers](https://martenframework.com/docs/next/handlers-and-http/error-handlers). ### Exceptions handling Marten lets you define callback methods that are invoked when certain exceptions are encountered during the execution of your handler's `#dispatch` method. These exception handling callbacks can be defined by using the [`#rescue_from`](https://martenframework.com/docs/api/dev/Marten/Handlers/ExceptionHandling.html#rescue_from(*exception_klasses%2C**kwargs%2C%26block)-macro) macro, which accepts one or more exception classes and an exception handler that can be specified by a trailing `:with` option containing the name of a method to invoke or a block containing the exception handling logic. For example, the following handler will react to possible `Auth::UnauthorizedUser` exceptions by calling the `#handle_unauthorized_user` private method: ```crystal class ProfileHandler < Marten::Handlers::Template include RequireSignedInUser template_name "auth/profile.html" rescue_from Auth::UnauthorizedUser, with: :handle_unauthorized_user private def handle_unauthorized_user head :forbidden end end ``` And the following handler will do exactly the same by invoking the specified block: ```crystal class ProfileHandler < Marten::Handlers::Template include RequireSignedInUser template_name "auth/profile.html" rescue_from Auth::UnauthorizedUser do head :forbidden end end ``` It is worth mentioning that exception handling callbacks are inherited and that they are searched bottom-up in the inheritance hierarchy. :::warning Your exception handling callbacks should return [`Marten::HTTP::Response`](https://martenframework.com/docs/api/dev/Marten/HTTP/Response.html) objects. If that's not the case, then your exception handling callback logic will be executed but the original exception will be allowed to "bubble up" (which will likely result in a server error). ::: ## Mapping handlers to URLs Handlers define the logic allowing to handle incoming HTTP requests and return corresponding HTTP responses. In order to define which handler gets called for a specific URL (and what are the expected URL parameters), handlers need to be associated with a specific route. This configuration usually takes place in the `config/routes.rb` configuration file, where you can define "paths" and associate them to your handler classes: ```crystal title="config/routes.cr" Marten.routes.draw do path "/", HomeHandler, name: "home" path "/articles", ArticlesHandler, name: "articles" path "/articles/", ArticleDetailHandler, name: "article_detail" end ``` Please refer to [Routing](https://martenframework.com/docs/next/handlers-and-http/routing) for more information regarding routes configuration. ## Using cookies Handlers are able to interact with a cookies store, that you can use to store small amounts of data on the client. This data will be persisted across requests, and will be made accessible with every incoming request. The cookies store is an instance of [`Marten::HTTP::Cookies`](https://martenframework.com/docs/api/dev/Marten/HTTP/Cookies.html) and provides a hash-like interface allowing to retrieve and store data. Handlers can access it through the use of the `#cookies` method. Here is a very simple example of how to interact with cookies: ```crystal class MyHandler < Marten::Handler def get cookies[:foo] = "bar" respond "Hello World!" end end ``` It should be noted that the cookies store gives access to two sub stores: an encrypted one and a signed one. `cookies.encrypted` allows defining cookies that will be signed and encrypted. Whenever a cookie is requested from this store, the raw value of the cookie will be decrypted. This is useful to create cookies whose values can't be read nor tampered by users: ```crystal cookies.encrypted[:secret_message] = "Hello!" ``` `cookies.signed` allows defining cookies that will be signed but not encrypted. This means that whenever a cookie is requested from this store, the signed representation of the corresponding value will be verified. This is useful to create cookies that can't be tampered by users, but it should be noted that the actual data can still be read by the client. ```crystal cookies.signed[:signed_message] = "Hello!" ``` Please refer to [Cookies](https://martenframework.com/docs/next/handlers-and-http/cookies) for more information around using cookies. ## Using sessions Handlers can interact with a session store, which you can use to store small amounts of data that will be persisted between requests. How much data you can persist in this store depends on the session backend being used. The default backend persists session data using an encrypted cookie. Cookies have a 4K size limit, which is usually sufficient in order to persist things like a user ID and flash messages. The session store is an instance of [`Marten::HTTP::Session::Store::Base`](https://martenframework.com/docs/api/dev/Marten/HTTP/Session/Store/Base.html) and provides a hash-like interface. Handlers can access it through the use of the `#session` method. For example: ```crystal class MyHandler < Marten::Handler def get session[:foo] = "bar" respond "Hello World!" end end ``` Please refer to [Sessions](https://martenframework.com/docs/next/handlers-and-http/sessions) for more information regarding configuring sessions and the available backends. ## Using the flash store The flash store provides a way to pass basic string messages from one handler to the next one. Any string value that is set in this store will be available to the next handler processing the next request, and then it will be cleared out. Such mechanism provides a convenient way of creating one-time notification messages (such as alerts or notices). The flash store is an instance [`Marten::HTTP::FlashStore`](https://martenframework.com/docs/api/dev/Marten/HTTP/FlashStore.html) and provides a hash-like interface. Handlers can access it through the use of the `#flash` method. For example: ```crystal class MyHandler < Marten::Handler def post flash[:notice] = "Article successfully created!" redirect("/success") end end ``` In the above example, the handler creates a flash message before returning a redirect response to another URL. It is up to the handler processing this URL to decide what to do with the flash message; this can involve rendering it as part of a base template for example. Note that it is possible to explicitly keep the current flash messages so that they remain all accessible to the next handler processing the next request. This can be done by using the `flash.keep` method, which can take an optional argument in order to keep the message associated with a specific key only. ```crystal flash.keep # keeps all the flash messages for the next request flash.keep(:foo) # keeps the message associated with the "foo" key only ``` The reverse operation is also possible: you can decide to discard all the current flash messages so that none of them will remain accessible to the next handler processing the next request. This can be done by using the `flash.discard` method, which can take an optional argument in order to discard the message associated with a specific key only. ```crystal flash.discard # discards all the flash messages flash.discard(:foo) # discards the message associated with the "foo" key only ``` ## Streaming responses The [`Marten::HTTP::Response::Streaming`](https://martenframework.com/docs/api/dev/Marten/HTTP/Response/Streaming.html) response class gives you the ability to stream a response from Marten to the browser. However, unlike a standard response, this specialized class requires initialization from an [iterator](https://crystal-lang.org/api/Iterator.html) of strings instead of a content string. This approach proves to be beneficial if you intend to generate lengthy responses or responses that consume excessive memory (a classic example of this is the generation of large CSV files). Compared to a regular [`Marten::HTTP::Response`](https://martenframework.com/docs/api/dev/Marten/HTTP/Response.html) object, the [`Marten::HTTP::Response::Streaming`](https://martenframework.com/docs/api/dev/Marten/HTTP/Response/Streaming.html) class operates differently in two ways: * Instead of initializing it with a content string, it requires initialization from an [iterator](https://crystal-lang.org/api/Iterator.html) of strings. * The response content is not directly accessible. The only way to obtain the actual response content is by iterating through the streamed content iterator, which can be accessed through the [`Marten::HTTP::Response::Streaming#streamed_content`](https://martenframework.com/docs/api/dev/Marten/HTTP/Response/Streaming.html#streamed_content%3AIterator(String)-instance-method) method. However, this is handled by Marten itself when sending the response to the browser, so you shouldn't need to worry about it. To generate streaming responses, you can either instantiate [`Marten::HTTP::Response::Streaming`](https://martenframework.com/docs/api/dev/Marten/HTTP/Response/Streaming.html) objects directly, or you can also leverage the [`#respond`](https://martenframework.com/docs/api/dev/Marten/Handlers/Base.html#respond(streamed_content%3AIterator(String)%2Ccontent_type%3DHTTP%3A%3AResponse%3A%3ADEFAULT_CONTENT_TYPE%2Cstatus%3D200)-instance-method) helper method, which works similarly to the [`#respond`](#respond) variant for response content strings. For example, the following handler generates a CSV and streams its content by leveraging the [`#respond`](https://martenframework.com/docs/api/dev/Marten/Handlers/Base.html#respond(streamed_content%3AIterator(String)%2Ccontent_type%3DHTTP%3A%3AResponse%3A%3ADEFAULT_CONTENT_TYPE%2Cstatus%3D200)-instance-method) helper method: ```crystal require "csv" class StreamingTestHandler < Marten::Handler def get respond(streaming_iterator, content_type: "text/csv") end private def streaming_iterator csv_io = IO::Memory.new csv_builder = CSV::Builder.new(io: csv_io) (1..1000000).each.map do |idx| csv_builder.row("Row #{idx}", "Val #{idx}") row_content = csv_io.to_s csv_io.rewind csv_io.flush row_content end end end ``` :::caution When considering streaming responses, it is crucial to understand that the process of streaming ties up a worker process for the entire response duration. This can significantly impact your worker's performance, so it's essential to use this approach only when necessary. Generally, it's better to carry out expensive content generation tasks outside the request-response cycle to avoid any negative impact on your worker's performance. ::: # Routing Source: https://martenframework.com/docs/next/handlers-and-http/routing Marten gives you the ability to design your URLs the way you want, by allowing you to easily map routes to specific [handlers](https://martenframework.com/docs/next/handlers-and-http/introduction), and by letting you generate paths and URLs from your application code. ## The basics In order to access a handler via a browser, it is necessary to map it to a URL route. To do so, route "maps" can be used to define mappings between route paths and existing handler classes. These route maps can be as long or as short as needed, but it is generally a good idea to create sub routes maps that are included in the main routes map. The main routes map usually lives in the `config/routes.cr` file. For example, the content of such a file could look like this: ```crystal Marten.routes.draw do path "/", HomeHandler, name: "home" path "/articles", ArticlesHandler, name: "articles" path "/articles/", ArticleDetailHandler, name: "article_detail" end ``` As you can see, routes are defined by calling a `#path` method that requires three arguments: * the first argument is the route pattern, which is a string like `/foo/bar` and which can contain additional [parameters](#specifying-route-parameters) * the second argument is the handler class associated with the specified route * the last argument is the route name, which is an identifier that can later be used in your codebase to generate the full URL for a specific route, and optionally inject parameters in it (see [Reverse URL resolutions](#reverse-url-resolutions)) :::tip It is possible to map multiple routes to the same handler class if necessary. This can be useful if you need to provide route aliases for some handlers for example. ::: These routes are evaluated and constructed at runtime, which means that you can define conditional routes if you need to. For example, a "debug" handler (only available in a development environment) could be added to the above routes map with the following addition: ```crystal Marten.routes.draw do path "/", HomeHandler, name: "home" path "/articles", ArticlesHandler, name: "articles" path "/articles/", ArticleDetailHandler, name: "article_detail" // highlight-next-line if Marten.env.development? // highlight-next-line path "/debug", DebugHandler, name: "debug" // highlight-next-line end end ``` When a URL is requested, Marten runs through all the defined routes to identify a matching one. The handler associated with this route will be initialized from the route parameters (if there are any) and the handler object will be used to respond to the considered request. It should be noted that if no route is matched for a specific URL, Marten will automatically return a 404 Not Found response, by leveraging a configurable [error handler](https://martenframework.com/docs/next/handlers-and-http/error-handlers). ## Specifying route parameters As highlighted in the previous examples, route parameters can be defined using angle brackets. Each route parameter must define a mandatory name and an optional type using the following syntaxes: * `` * `` When no type is specified for a parameter, any string excluding the forward slash character (**`/`**) will be matched. The following route parameter types are available: | Type | Description | | ----------- | ----------- | | `str` or `string` | Matches any non-empty string (excluding the forward slash character **`/`**). This is the default parameter type used for untyped parameters (eg. ``). | | `int` | Matches zero or any positive integer. These parameter values are always deserialized as `UInt64` objects. | | `path` | Matches any non-empty strings including forward slash characters (**`/`**). For example `foo/bar/xyz` could be matched by this parameter type. | | `slug` | Matches any string containing only ASCII letters, numbers, hyphen, and underscore characters. For example `my-first-project-01` could be matched by this parameter type. | | `uuid` | Matches a valid UUID string. These parameter values are always deserialized as `UUID` objects. | It should be noted that it is possible to register custom route parameter implementations if needed. See [Create custom route parameters](https://martenframework.com/docs/next/handlers-and-http/how-to/create-custom-route-parameters) to learn more about this capability. ## Defining included routes The main routes map (which usually lives in the `config/routes.cr` file) does not have to be a "flat" definition of all the available routes. Indeed, you can define "sub" routes maps if you need to and "include" these in your main routes map. This capability can be extremely useful to "include" a set of routes from an installed application (a third-party library or one of your in-project applications). This also allows better organizing route namespaces and bundling a set of related routes under a similar prefix. For example, a main routes map and an article routes map could be defined as follows: ```crystal ARTICLE_ROUTES = Marten::Routing::Map.draw do path "", ArticlesHandler, name: "list" path "/create", ArticleCreateHandler, name: "create" path "/", ArticleDetailHandler, name: "detail" path "//update", ArticleUpdateHandler, name: "update" path "//delete", ArticleDeleteHandler, name: "delete" end Marten.routes.draw do path "/", HomeHandler, name: "home" path "/articles", ARTICLE_ROUTES, name: "articles" end ``` In the above example, the following URLs would be generated by Marten in addition to the root URL: | URL | Handler | Name | | --- | ---- | ---- | | `/articles` | `ArticlesHandler` | `articles:list` | | `/articles/create` | `ArticleCreateHandler` | `articles:create` | | `/articles/` | `ArticleDetailHandler` | `articles:detail` | | `/articles//update` | `ArticleUpdateHandler` | `articles:update` | | `/articles//delete` | `ArticleDeleteHandler` | `articles:delete` | As you can see, both the URLs and the route names end up being prefixed respectively with the path and the name specified in the including route. :::info The `name` parameter for included routes is optional, i.e. `path "/articles", ARTICLE_ROUTES` is also valid. Please note that this will increase the possibility of a name collision and it is, therefore, advisable to prefix the individual paths of the included route, e.g. `article_list`, `article_create`, etc. ```crystal ARTICLE_ROUTES = Marten::Routing::Map.draw do path "/", ArticlesHandler, name: "article_list" path "/create", ArticlesCreateHandler, name: "article_create" end Marten.routes.draw do path "/articles", ARTICLE_ROUTES end ``` This example will generate the following URLs: | URL | Handler | Name | | --- | ------- | ---- | | `/articles` | `ArticlesHandler` | `articles_list` | | `/articles/create` | `ArticlesCreateHandler` | `articles_create` | It is also possible to add a namespace to the included route at the map level: ```crystal ARTICLE_ROUTES = Marten::Routing::Map.draw(:article) do path "/", ArticlesHandler, name: "list" end Marten.routes.draw do path "/articles", ARTICLE_ROUTES # Note: providing the name parameter overrides the namespace end ``` This example will generate the following URLs: | URL | Handler | Name | | --- | ------- | ---- | | `/articles` | `ArticlesHandler` | `articles:list` | ::: Note that the sub-routes map does not have to live in the `config/routes.cr` file: it can technically live anywhere in your codebase. The ideal way to define the routes map of a specific application would be to put it in a `routes.cr` file in the application's directory. When Marten encounters a path that leads to another sub-routes map, it chops off the part of the URL that was matched up to that point and then forwards the remaining to the sub-routes map in order to see if it is matched by one of the underlying routes. ## Reverse URL resolutions When working with web applications, a frequent need is to generate URLs in their final forms. To do so, you will want to avoid hard-coding URLs and instead leverage the ability to generate them from their associated names: this is what we call a reverse URL resolution. "Reversing" a URL is as simple as calling the [`Marten::Routing::Map#reverse`](https://martenframework.com/docs/api/dev/Marten/Routing/Map.html#reverse(name%3AString|Symbol%2Cparams%3AHash(String|Symbol%2CParameter%3A%3ATypes))-instance-method) method from the main routes map, which is accessible through the use of the [`Marten#routes`](https://martenframework.com/docs/api/dev/Marten.html#routes-class-method) method: ```crystal Marten.routes.reverse("home") # will return "/" ``` In order to reverse a URL from within a handler class, you can simply leverage the [`Marten::Handlers::Base#reverse`](https://martenframework.com/docs/api/dev/Marten/Handlers/Base.html#reverse(*args%2C**options)-instance-method) handler method: ```crystal class MyHandler < Marten::Handler def post redirect(reverse("home")) end end ``` As highlighted previously, some routes require one or more parameters and in order to reverse these URLs you can simply specify these parameters as arguments when calling `#reverse`: ```crystal Marten.routes.reverse("article_detail", pk: 42) # will return "/articles/42" ``` Finally, it should be noted that the namespaces that are created when defining [included routes](#defining-included-routes) also apply when reversing the corresponding URLs. For example, the name allowing to reverse the URL associated with the `ArticleUpdateHandler` in the previous snippet would be `articles:update`: ```crystal Marten.routes.reverse("articles:update", pk: 42) # will return "/articles/42/update" ``` ## Localization Routes can be localized to accommodate the requirements of multi-locales projects. Please refer to [Localized routes](https://martenframework.com/docs/next/i18n/localized-routes) to learn more about this capability. # Generic handlers Source: https://martenframework.com/docs/next/handlers-and-http/generic-handlers Marten includes a set of generic handlers that can be leveraged to perform common tasks. These tasks are frequently encountered when working on web applications. For example: displaying a list of records extracted from the database, or deleting a record. Generic handlers take care of these common patterns so that developers don't end up reimplementing the wheel. ## Scope Marten provides generic handlers allowing to perform the following actions: * redirect to a specific URL * render an existing [template](https://martenframework.com/docs/next/templates) * process a [schema](https://martenframework.com/docs/next/schemas) * list, display, create, update, or delete [model records](https://martenframework.com/docs/next/models-and-databases) A few of these generic handlers are described below (and all of them are listed in the [dedicated reference](https://martenframework.com/docs/next/handlers-and-http/reference/generic-handlers)). Each of these handler classes must be subclassed on a per-project basis to define the required "attributes", and optionally to override methods to customize things like objects exposed in template contexts. By doing so you are essentially defining handlers that inherit these common patterns, without having to reimplement them. Finally, it should be noted that using generic handlers is totally optional. They provide a good starting point to implement frequently encountered use cases, but you can decide to design your own set of generic handlers to accommodate for your project needs if the built-in ones don't match your requirements. ## A few examples ### Performing a redirect Having a handler that performs a redirect can be easily achieved by subclassing the [`Marten::Handlers::Redirect`](https://martenframework.com/docs/api/dev/Marten/Handlers/Redirect.html) generic handler. For example, you could easily define a handler that redirects to a `articles:list` route with the following snippet: ```crystal class ArticlesRedirectHandler < Marten::Handlers::Redirect route_name "articles:list" end ``` The above handler will perform a reverse resolution of `articles:list` in order to get the corresponding URL and will return a 302 HTTP response (temporary redirect). Subclasses of this generic handler can also redirect to a plain URL and decide to return a permanent redirect (301) instead of a temporary one, for example: ```crystal class TestRedirectHandler < Marten::Handlers::Redirect url "https://example.com" permanent true end ``` Finally, you can even implement your own logic in order to compute the redirection URL by overriding the `#redirect_url` method: ```crystal class ArticleRedirectHandler < Marten::Handlers::Redirect def redirect_url article = Article.get(id: params["pk"]) if article.published? reverse("articles:detail", pk: article.id) else reverse("articles:list") end end end ``` ### Rendering a template One of the most frequent things you will want to do when writing handlers is to return HTML responses containing rendered [templates](https://martenframework.com/docs/next/templates). To do so, you can obviously define a regular handler and make use of the [`#render`](https://martenframework.com/docs/next/handlers-and-http/introduction#render) helper. But, you may also want to leverage the [`Marten::Handlers::Template`](https://martenframework.com/docs/api/dev/Marten/Handlers/Template.html) generic handler. This generic handler will return a 200 OK HTTP response containing a rendered HTML template. To make use of it, you can simply define a subclass of it and ensure that you call the `#template_name` class method in order to define the template that will be rendered: ```crystal class HomeHandler < Marten::Handlers::Template template_name "app/home.html" end ``` If you need to, it is possible to customize the context that is used to render the configured template. To do so, you can define a [`before_render`](https://martenframework.com/docs/next/handlers-and-http/callbacks#before_render) callback and add new variables to the [global template context](https://martenframework.com/docs/next/handlers-and-http/introduction#global-template-context) (which functions similarly to a hash object): ```crystal class HomeHandler < Marten::Handlers::Template template_name "app/home.html" before_render add_recent_articles_to_context private def add_recent_articles_to_context : Nil context[:recent_articles] = Article.all.order("-published_at")[:5] end end ``` Variables that are added to the global template context will automatically be available to the configured template's runtime. ### Displaying a model record It is possible to render a template that showcases a specific model record by leveraging the [`Marten::Handlers::RecordDetail`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordDetail.html) generic handler. For example, it would be possible to render an `articles/detail.html` template showcasing a specific `Article` model record with the following handler: ```crystal class ArticleDetailHandler < Marten::Handlers::RecordDetail model Article template_name "articles/detail.html" end ``` By assuming that the route path associated with this handler is something like `/articles/`, this handler will automatically retrieve the right `Article` record by using the primary key provided in the `pk` route parameter. If the record does not exist, a `Marten::HTTP::Errors::NotFound` exception will be raised (which will lead to the default "not found" error page being displayed to the user), and otherwise the configured template will be rendered (with the `Article` record exposed in the context under the `record` key). For example, the template associated with this handler could be something like this: ```html
  • Title: {{ record.title }}
  • Created at: {{ record.created_at }}
``` ### Processing a form It is possible to use the [`Marten::Handlers::Schema`](https://martenframework.com/docs/api/dev/Marten/Handlers/Schema.html) generic handler in order to process form data with a [schema](https://martenframework.com/docs/next/schemas). To do so, it is necessary: * to specify the schema class to use to validate the incoming POST data through the use of the `#schema` macro * to specify the template to render by using the `#template_name` class method: this template will likely generate an HTML form * to specify the route to redirect to when the schema is valid via the `#success_route_name` class method For example: ```crystal class MyFormHandler < Marten::Handlers::Schema schema MySchema template_name "app/my_form.html" success_route_name "home" def process_valid_schema # This method is called when the schema is valid. # You can decide to do something with the validated data... super end def process_invalid_schema # This method is called when the schema is invalid. super end end ``` By default, such a handler will render the configured template when the incoming request is a GET or for POST requests if the data cannot be validated using the specified schema (in that case, the template is expected to use the invalid schema to display a form with the right errored inputs). The specified template can have access to the configured schema through the use of the `schema` object in the template context. If the schema is valid, a temporary redirect is issued by using the URL corresponding to the `#success_route_name` value (although it should be noted that the way to generate this success URL can be overridden by defining a `#success_url` method). By default, the handler does nothing when the processed schema is valid (except redirecting to the success URL). :::tip Handlers making use of the [`Marten::Handlers::Schema`](https://martenframework.com/docs/api/dev/Marten/Handlers/Schema.html) generic handler can leverage additional types of callbacks. Please head over to [Schema handler callbacks](https://martenframework.com/docs/next/handlers-and-http/callbacks#schema-handler-callbacks) to learn more about those. ::: # Error handlers Source: https://martenframework.com/docs/next/handlers-and-http/error-handlers Marten provides default error handlers that you can leverage to show specific error conditions to your users: when a page is not found, when an operation is forbidden, in case of a server error, etc. ## The default error handlers Marten provides default error handlers for the following situations: * when **a record or a route is not found**, it will return a default Page Not Found (404) response * when **an unexpected error occurs**, it will return a default Internal Server Error (500) response * when **a suspicious operation is detected**, it will return a default Bad Request (400) response * when **an action is forbidden**, it will return a default Forbidden (403) response Note that you don't need to manually interact with these default error handlers: they are automatically used by the Marten server when the above error conditions are met. ### Page Not Found (404) A Page Not Found (404) response is automatically returned by the [`Marten::Handlers::Defaults::PageNotFound`](https://martenframework.com/docs/api/dev/Marten/Handlers/Defaults/PageNotFound.html) handler when: * a route cannot be found for an incoming request * the [`Marten::HTTP::Errors::NotFound`](https://martenframework.com/docs/api/dev/Marten/HTTP/Errors/NotFound.html) exception is raised :::info If your project is running in debug mode, Marten will automatically show a different page containing specific information about the original request instead of using the default Page Not Found handler. ::: ### Internal Server Error (500) An Internal Server Error (500) response is automatically returned by the [`Marten::Handlers::Defaults::ServerError`](https://martenframework.com/docs/api/dev/Marten/Handlers/Defaults/ServerError.html) handler when an unhandled exception is intercepted by the Marten server. :::info If your project is running in debug mode, Marten will automatically show a different page containing specific information about the error that occurred (traceback, request details, etc) instead of using the default Internal Server Error handler. ::: ### Bad Request (400) A Bad Request (400) response is automatically returned by the [`Marten::Handlers::Defaults::BadRequest`](https://martenframework.com/docs/api/dev/Marten/Handlers/Defaults/BadRequest.html) handler when the [`Marten::HTTP::Errors::SuspiciousOperation`](https://martenframework.com/docs/api/dev/Marten/HTTP/Errors/SuspiciousOperation.html) exception is raised. ### Forbidden (403) A Forbidden (403) response is automatically returned by the [`Marten::Handlers::Defaults::PermissionDenied`](https://martenframework.com/docs/api/dev/Marten/Handlers/Defaults/PermissionDenied.html) handler when the [`Marten::HTTP::Errors::PermissionDenied`](https://martenframework.com/docs/api/dev/Marten/HTTP/Errors/PermissionDenied.html) exception is raised. ## Customizing error handlers Each of the error handlers mentioned above can be easily customized: by default they provide a "raw" server response with a standard message, and it might make sense on a project basis to customize how they show up to your users. As such, each handler is associated with a dedicated template name that will be rendered if your project defines it. Each of these handlers can also be replaced by a custom one by using the appropriate settings. These customization options are listed below: | Error | Template name | Handler setting | | ----- | ------------- | ------------ | | Page Not Found (404) | `404.html` | [`handler404`](https://martenframework.com/docs/next/development/reference/settings#handler404) | | Internal Server Error (500) | `500.html` | [`handler500`](https://martenframework.com/docs/next/development/reference/settings#handler500) | | Bad Request (400) | `400.html` | [`handler400`](https://martenframework.com/docs/next/development/reference/settings#handler400) | | Forbidden (403) | `403.html` | [`handler403`](https://martenframework.com/docs/next/development/reference/settings#handler403) | For example, you could define a default "Page Not Found" template by defining a `404.html` HTML template file in your project's `templates` folder. # Sessions Source: https://martenframework.com/docs/next/handlers-and-http/sessions Sessions can be used to store small amounts of data that will be persisted between requests, on a per-visitor basis. This data is usually stored on the backend side (depending on the chosen session storage), and it is associated with a session ID that is persisted on the client through the use of a dedicated cookie. ## Configuration In order to use sessions, you need to make sure that the [`Marten::Middleware::Session`](https://martenframework.com/docs/api/dev/Marten/Middleware/Session.html) middleware is part of your project's middleware chain, which can be configured in the [`middleware`](https://martenframework.com/docs/next/development/reference/settings#middleware) setting. Note that the session middleware class is automatically added to this setting when initializing new projects. If your project does not require the use of sessions, you can simply ensure that the [`middleware`](https://martenframework.com/docs/next/development/reference/settings#middleware) setting does not include the [`Marten::Middleware::Session`](https://martenframework.com/docs/api/dev/Marten/Middleware/Session.html) middleware class. How the session ID cookie is generated can also be tweaked by leveraging the following settings: * [`sessions.cookie_domain`](https://martenframework.com/docs/next/development/reference/settings#cookie_domain-1) * [`sessions.cookie_http_only`](https://martenframework.com/docs/next/development/reference/settings#cookie_http_only-1) * [`sessions.cookie_max_age`](https://martenframework.com/docs/next/development/reference/settings#cookie_max_age-1) * [`sessions.cookie_name`](https://martenframework.com/docs/next/development/reference/settings#cookie_name-1) * [`sessions.cookie_same_site`](https://martenframework.com/docs/next/development/reference/settings#cookie_same_site-1) * [`sessions.cookie_secure`](https://martenframework.com/docs/next/development/reference/settings#cookie_secure-1) ## Session stores How session data is actually persisted can be defined by configuring the right session store backend, which can be done through the use of the [`sessions.store`](https://martenframework.com/docs/next/development/reference/settings#store) setting. By default, sessions are encrypted and stored within a single cookie (`:cookie` session store). Cookies have a 4K size limit, which is usually sufficient in order to persist things like a user ID and flash messages. `:cookie` is the only store that is built in the Marten web framework presently. :::info The `cookie` store leverages a [`Marten::Core::Encryptor`](https://martenframework.com/docs/api/dev/Marten/Core/Encryptor.html) encryptor object in order to encrypt and sign session data. This means that session data is encrypted with an **aes-256-cbc** cipher and signed with HMAC signatures that use the **SHA256** hash algorithm. ::: Other session stores can be installed as separate shards. For example, the [`marten-db-session`](https://github.com/martenframework/marten-db-session) shard can be leveraged to persist session data in the database while the [`marten-redis-session`](https://github.com/martenframework/marten-redis-session) shard can be used for persisting session data using Redis. ## Using sessions ### Setting and retrieving session values When the [`Marten::Middleware::Session`](https://martenframework.com/docs/api/dev/Marten/Middleware/Session.html) middleware is used, each HTTP request object will have a [`#session`](https://martenframework.com/docs/api/dev//Marten/HTTP/Request.html#session-instance-method) method returning the session store for the current request. The session store is an instance of [`Marten::HTTP::Session::Store::Base`](https://martenframework.com/docs/api/dev/Marten/HTTP/Session/Store/Base.html) and provides a hash-like interface: ```crystal # Persisting values: request.session[:foo] = "bar" # Accessing values: request.session[:foo] request.session[:foo]? # Deleting values: request.session.delete(:foo) # Checking emptiness: request.session.empty? ``` Both symbol and string keys can be used when trying to interact with the session store, but only **string values** can be stored. :::tip If you are trying to access the session store from within a handler, it should be noted that you can leverage the `#session` method instead of using the request object: ```crystal class MyHandler < Marten::Handler def get session[:foo] = "bar" respond "Hello World!" end end ``` ::: ### Customizing session expiry times By default, most session stores will expire session entries based on the value of the [`sessions.cookie_max_age`](https://martenframework.com/docs/next/development/reference/settings#cookie_max_age-1) setting. That being said, it is possible to customize when a specific session is set to expire by using one of the following methods: * [`#expires_at=`](https://martenframework.com/docs/api/dev/Marten/HTTP/Session/Store/Base.html#expires_at%3D(value%3ATime)-instance-method) allows to set the time when the session should expire by specifying a [`Time`](https://crystal-lang.org/api/Time.html) object or an integer (number of seconds). * [`#expires_at_browser_close=`](https://martenframework.com/docs/api/dev/Marten/HTTP/Session/Store/Base.html#expires_at_browser_close%3D(value%3ABool)-instance-method) allows to set whether the session should expire when the browser is closed. * [`#expires_in=`](https://martenframework.com/docs/api/dev/Marten/HTTP/Session/Store/Base.html#expires_in%3D(value%3ATime%3A%3ASpan)-instance-method) allows to set the session's expiration duration with [`Time::Span`](https://crystal-lang.org/api/Time/Span.html) object. For example: ```crystal request.session[:foo] = "bar" # Set the session to expire on a specific date time: request.session.expires_at = 2.days.from_now # Set the session to expire in a specific duration: request.session.expires_in = 2.hours # Set the session to expire when the browser is closed: request.session.expires_at_browser_close = true ``` # Cookies Source: https://martenframework.com/docs/next/handlers-and-http/cookies Handlers are able to interact with a cookies store that you can use to store small amounts of data - called cookies - on the client. This data will be persisted across requests and will be made accessible with every incoming request. ## Basic usage ### Accessing the cookie store Cookies can be interacted with by leveraging a cookie store: an instance of [`Marten::HTTP::Cookies`](https://martenframework.com/docs/api/dev/Marten/HTTP/Cookies.html) that provides a hash-like interface allowing to retrieve and store cookie values. This cookie store can be accessed from three different places: * Handlers can access it through the use of the [`#cookies`](https://martenframework.com/docs/api/dev/Marten/Handlers/Cookies.html#cookies(*args%2C**options)-instance-method) method. * [`Marten::HTTP::Request`](https://martenframework.com/docs/api/dev/Marten/HTTP/Request.html) objects give access to the cookies associated with the request via the [`#cookies`](https://martenframework.com/docs/api/dev/Marten/HTTP/Request.html#cookies-instance-method) method. * [`Marten::HTTP::Response`](https://martenframework.com/docs/api/dev/Marten/HTTP/Response.html) objects give access to the cookies that will be returned with the HTTP response via the [`#cookies`](https://martenframework.com/docs/api/dev/Marten/HTTP/Response.html#cookies%3AMarten%3A%3AHTTP%3A%3ACookies-instance-method) method. Here is a very simple example of how to interact with the cookies store within a handler: ```crystal class MyHandler < Marten::Handler def get cookies[:foo] = "bar" respond "Hello World!" end end ``` ### Retrieving cookie values The most simple way to retrieve the value of a cookie is to leverage the [`#[]`](https://martenframework.com/docs/api/dev/Marten/HTTP/Cookies.html#[](name%3AString|Symbol)-instance-method)[](name%3AString|Symbol)-instance-method) method or one of its variants. For example, the following lines could be used to read the value of a cookie named `foo`: ```crystal request.cookies[:foo] # => returns the value of "foo" or raises a KeyError if not found request.cookies[:foo]? # => returns the value of "foo" or returns nil if not found ``` Alternatively, the [`#fetch`](https://martenframework.com/docs/api/dev/Marten/HTTP/Cookies.html#fetch(name%3AString|Symbol%2Cdefault%3Dnil)-instance-method) method can also be leveraged in order to execute a block or return a default value if the specified cookie is not found: ```crystal request.cookies.fetch(:foo, "defaultval") request.cookies.fetch(:foo) { "defaultval" } ``` ### Setting cookies The most simple way to set a new cookie is to call the [`#[]=`](https://martenframework.com/docs/api/dev/Marten/HTTP/Cookies.html#[]%3D(name%2Cvalue)-instance-method) method on a cookie store. For example: ```crystal request.cookies[:foo] = "bar" ``` Calling this method will create a new cookie with the specified name and value. It should be noted that cookies created with the [`#[]=`](https://martenframework.com/docs/api/dev/Marten/HTTP/Cookies.html#[]%3D(name%2Cvalue)-instance-method) method will _not_ expire, will be associated with the root path (`/`), and will not be secure. Alternatively, it is possible to leverage the [`#set`](https://martenframework.com/docs/api/dev/Marten/HTTP/Cookies.html#set(name%3AString|Symbol%2Cvalue%2Cexpires%3ATime|Nil%3Dnil%2Cpath%3AString%3D"/"%2Cdomain%3AString|Nil%3Dnil%2Csecure%3ABool%3Dfalse%2Chttp_only%3ABool%3Dfalse%2Csame_site%3ANil|String|Symbol%3Dnil)%3ANil-instance-method) in order to specify custom cookie properties while setting new cookie values. For example: ```crystal request.cookies.set( :foo, "bar", expires: 2.days.from_now, secure: true, same_site: "lax" ) ``` Apart from the cookie name and value, the [`#set`](https://martenframework.com/docs/api/dev/Marten/HTTP/Cookies.html#set(name%3AString|Symbol%2Cvalue%2Cexpires%3ATime|Nil%3Dnil%2Cpath%3AString%3D"/"%2Cdomain%3AString|Nil%3Dnil%2Csecure%3ABool%3Dfalse%2Chttp_only%3ABool%3Dfalse%2Csame_site%3ANil|String|Symbol%3Dnil)%3ANil-instance-method) method allows to define some additional cookie properties: * The cookie expiry datetime (`expires` argument). * The cookie `path`. * The associated `domain` (useful in order to define cross-domain cookies). * Whether or not the cookie should be sent for HTTPS requests only (`secure` argument). * Whether or not client-side scripts should have access to the cookie (`http_only` argument). * The `same_site` policy (accepted values are `"lax"` or `"strict"`). ### Deleting cookies Cookies can be deleted by leveraging the [`#delete`](https://martenframework.com/docs/api/dev/Marten/HTTP/Cookies.html#delete(name%3AString|Symbol%2Cpath%3AString%3D"/"%2Cdomain%3AString|Nil%3Dnil%2Csame_site%3ANil|String|Symbol%3Dnil)%3AString|Nil-instance-method) method. This method will delete a specific cookie and return its value, or `nil` if the cookie does not exist: ```crystal request.cookies.delete(:foo) ``` Apart from the name of the cookie, this method allows to define some additional properties of the cookie to delete: * The cookie `path`. * The associated `domain` (useful in order to define cross-domain cookies). * The `same_site` policy (accepted values are `"lax"` or `"strict"`). Note that the `path`, `domain`, and `same_site` values should always be the same as the ones that were used to create the cookie in the first place. Otherwise, the cookie might not be deleted properly. ## Signed cookies In addition to the [regular cookie store](#accessing-the-cookie-store), Marten provides a signed cookie store version (which is accessible through the use of the [`Marten::HTTP::Cookies#signed`](https://martenframework.com/docs/api/dev/Marten/HTTP/Cookies.html#signed-instance-method) method) where cookies are signed (but **not** encrypted). This means that whenever a cookie is requested from this store, the signed representation of the corresponding value will be verified. This is useful to create cookies that can't be tampered by users, but it should be noted that the actual data can still be read by the client technically. All the methods that can be used with the regular cookie store that were highlighted in [Basic usage](#basic-usage) can also be used with the signed cookie store: ```crystal # Retrieving cookies... request.signed.cookies[:foo] request.signed.cookies[:foo]? request.signed.cookies.fetch(:foo, "defaultval") request.signed.cookies.fetch(:foo) { "defaultval" } # Setting cookies... request.signed.cookies[:foo] = "bar" request.signed.cookies.set(:foo, "bar", expires: 2.days.from_now) # Deleting cookies... request.signed.cookies.delete(:foo) ``` The signed cookie store uses a [`Marten::Core::Signer`](https://martenframework.com/docs/api/dev/Marten/Core/Signer.html) signer object in order to sign cookie values and to verify the signature of retrieved cookies. This means that cookies are signed with HMAC signatures that use the **SHA256** hash algorithm. :::info Only cookie _values_ are signed. Cookie _names_ are not signed. ::: ## Encrypted cookies In addition to the [regular cookie store](#accessing-the-cookie-store), Marten provides an encrypted cookie store version (which is accessible through the use of the [`Marten::HTTP::Cookies#encrypted`](https://martenframework.com/docs/api/dev/Marten/HTTP/Cookies.html#encrypted-instance-method) method) where cookies are signed and encrypted. This means that whenever a cookie is requested from this store, the raw value of the cookie will be decrypted and its signature will be verified. This is useful to create cookies whose values can't be read nor tampered by users. All the methods that can be used with the regular cookie store that were highlighted in [Basic usage](#basic-usage) can also be used with the encrypted cookie store: ```crystal # Retrieving cookies... request.encrypted.cookies[:foo] request.encrypted.cookies[:foo]? request.encrypted.cookies.fetch(:foo, "defaultval") request.encrypted.cookies.fetch(:foo) { "defaultval" } # Setting cookies... request.encrypted.cookies[:foo] = "bar" request.encrypted.cookies.set(:foo, "bar", expires: 2.days.from_now) # Deleting cookies... request.encrypted.cookies.delete(:foo) ``` The signed cookie store uses a [`Marten::Core::Encryptor`](https://martenframework.com/docs/api/dev/Marten/Core/Encryptor.html) encryptor object in order to encrypt and sign cookie values. This means that cookies are: * encrypted with an **aes-256-cbc** cipher. * signed with HMAC signatures that use the **SHA256** hash algorithm. :::info Only cookie _values_ are encrypted and signed. Cookie _names_ are not encrypted. ::: # Handler callbacks Source: https://martenframework.com/docs/next/handlers-and-http/callbacks Callbacks enable you to define logic that is triggered at different stages of a handler's lifecycle. This feature allows you to intercept incoming requests and potentially bypass the standard `#dispatch` method. This document covers the available callbacks and introduces you to the associated API, which you can use to define hooks in your handlers. ## Overview As stated above, callbacks are methods that will be called when specific events occur for a specific handler instance. They need to be registered explicitly in your handler classes. There are many types of callbacks: some are [shared between all types of handlers](#shared-handler-callbacks) while some others are specific to some kinds of generic handlers. For most types of callbacks, it is generally possible to register "before" or "after" callbacks. Registering a callback is as simple as calling the right callback macro (eg. `#before_dispatch`) with a symbol of the name of the method to call when the callback is executed. For example, the following handler leverages the [`#before_dispatch`](#before_dispatch) callback in order to redirect the user to a login page if they are not already authenticated: ```crystal class MyHandler < Marten::Handler before_dispatch :require_authenticated_user def get respond "Hello, authenticated user!" end private def require_authenticated_user redirect(login_url) unless user_authenticated?(request) end end ``` ## Shared handler callbacks The following callbacks are shared between all types of handlers. ### `before_dispatch` `before_dispatch` callbacks are executed _before_ a request is processed as part of the handler's `#dispatch` method. For example, this capability can be leveraged to inspect the incoming request and verify that a user is logged in: ```crystal class MyHandler < Marten::Handler before_dispatch :require_authenticated_user def get respond "Hello, authenticated user!" end private def require_authenticated_user redirect(login_url) unless user_authenticated?(request) end end ``` When one of the defined `before_dispatch` callbacks returns a [`Marten::HTTP::Response`](https://martenframework.com/docs/api/dev/Marten/HTTP/Response.html) object (like this is the case in the above example), this response is always used instead of calling the handler's `#dispatch` method (the latest is thus completely bypassed). ### `after_dispatch` `after_dispatch` callbacks are executed _after_ a request is processed as part of the handler's `#dispatch` method. For example, such a callback can be leveraged to automatically add headers or cookies to the returned response. ```crystal class MyHandler < Marten::Handler after_dispatch :add_required_header def get respond "Hello, authenticated user!" end private def add_required_header : Nil response!.headers["X-Foo"] = "Bar" end end ``` Similarly to `#before_dispatch` callbacks, `#after_dispatch` callbacks can return a brand new [`Marten::HTTP::Response`](https://martenframework.com/docs/api/dev/Marten/HTTP/Response.html) object. When this is the case, this response is always used instead of the one that was returned by the handler's `#dispatch` method. ### `before_render` `before_render` callbacks are invoked prior to rendering a template when generating a response that incorporates its content. This means that these callbacks are executed as part of the [`#render`](https://martenframework.com/docs/next/handlers-and-http/introduction#render) helper method and when rendering templates as part of subclasses of the [`Marten::Handlers::Template`](https://martenframework.com/docs/next/handlers-and-http/generic-handlers#rendering-a-template) generic handler. Typically, these callbacks are used to add new variables to the [global template context](https://martenframework.com/docs/next/handlers-and-http/introduction#global-template-context), in order to make them accessible to the template runtime. For example: ```crystal class MyHandler < Marten::Handlers::Template template_name "app/my_template.html" before_render :add_variable_to_context private def add_variable_to_context : Nil context["foo"] = "bar" end end ``` Note that `before_render` callbacks can technically be used to return a [`Marten::HTTP::Response`](https://martenframework.com/docs/api/dev/Marten/HTTP/Response.html) object. When this situation arises, this response always takes precedence over the one that would've been returned following the rendering of the template. ## Schema handler callbacks The following callbacks are only available for handlers that inherit from the [schema handler](https://martenframework.com/docs/next/handlers-and-http/reference/generic-handlers#processing-a-schema). That is, handlers that inherit from [`Marten::Handlers::Schema`](https://martenframework.com/docs/api/dev/Marten/Handlers/Schema.html), but also handlers that inherit from [`Marten::Handlers::RecordCreate`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordCreate.html) and [`Marten::Handlers::RecordUpdate`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordUpdate.html). These callbacks let you define logics that are triggered before or after the validation of the schema. This allows you to easily intercept validation and handle the response independently of the schema validity. All these callbacks can optionally return a [`Marten::HTTP::Response`](https://martenframework.com/docs/api/dev/Marten/HTTP/Response.html) object. When an HTTP response is returned, all following callbacks are skipped and the obtained response is returned directly, thus bypassing responses that might have been returned after by the handler. ### `before_schema_validation` `before_schema_validation` callbacks are executed _before_ a schema is checked for validity. For example, this capability can be leveraged to set an attribute on the schema object before the schema validity is checked: ```crystal class ArticleCreateHandler < Marten::Handlers::Schema success_url "https://example.com/articles/list" template_name "articles/create.html" schema ArticleSchema before_schema_validation :prepare_schema private def prepare_schema schema.user = request.user end end ``` ### `after_schema_validation` `after_schema_validation` callbacks are executed right _after_ a schema is checked for validity. For example, this capability can be leveraged to call a custom method on the schema instance: ```crystal class ArticleCreateHandler < Marten::Handlers::Schema success_url "https://example.com/articles/list" template_name "articles/create.html" schema ArticleSchema after_schema_validation :run_schema_post_validation private def run_schema_post_validation : Nil schema.trigger_post_something end end ``` ### `after_successful_schema_validation` `after_successful_schema_validation` callbacks are executed right _after_ a schema is checked for validity (and after possible [`after_schema_validation`](#after_schema_validation) callbacks), and only if the schema validation was successful. For example, this capability can be leveraged to create a flash message: ```crystal class ArticleCreateHandler < Marten::Handlers::Schema success_url "https://example.com/articles/list" template_name "articles/create.html" schema ArticleSchema after_successful_schema_validation :generate_success_flash_message private def generate_success_flash_message : Nil flash[:notice] = "Article successfully created!" end end ``` ### `after_failed_schema_validation` `after_failed_schema_validation` callbacks are executed right _after_ a schema is checked for validity (and after possible [`after_schema_validation`](#after_schema_validation) callbacks), but only if the schema validation failed. For example, this capability can be leveraged to create a flash message: ```crystal class ArticleCreateHandler < Marten::Handlers::Schema success_url "https://example.com/articles/list" template_name "articles/create.html" schema ArticleSchema after_failed_schema_validation :generate_failure_flash_message private def generate_failure_flash_message : Nil flash[:notice] = "Article creation failed!" end end ``` # Middlewares Source: https://martenframework.com/docs/next/handlers-and-http/middlewares Middlewares are used to "hook" into Marten's request/response lifecycle. They can be used to alter or implement logic based on incoming HTTP requests and the resulting HTTP responses. These hooks take an HTTP request as their input and they output an HTTP response; in the process, they can implement whatever logic they deem necessary to perform actions based on the incoming request and/or the associated response. ## How middlewares work Middlewares are subclasses of the [`Marten::Middleware`](https://martenframework.com/docs/api/dev/Marten/Middleware.html) abstract class. They must implement a `#call` method that takes a request object (instance of [`Marten::HTTP::Request`](https://martenframework.com/docs/api/dev/Marten/HTTP/Request.html)) and a `get_response` proc (allowing to get the final response) as arguments, and that returns a [`Marten::HTTP::Response`](https://martenframework.com/docs/api/dev/Marten/HTTP/Response.html) object: ```crystal class TestMiddleware < Marten::Middleware def call(request : Marten::HTTP::Request, get_response : Proc(Marten::HTTP::Response)) : Marten::HTTP::Response # Do something with the request object. response = get_response.call # Do something with the response object. response end end ``` The `get_response` proc will either call the next middleware in the chain of middlewares, or the handler processing the request and returning the response. Which of these is actually called is a detail that is hidden by the `get_response` proc, and this does not matter at an individual middleware level. ## Activating middlewares In order to be used, middleware classes need to be specified in the [`middleware`](https://martenframework.com/docs/next/development/reference/settings#middleware) setting. This setting is an array of middleware classes that defines the "chain" of middlewares that will be "hooked" into Marten's request/response lifecycle. For example: ```crystal config.middleware = [ Marten::Middleware::Session, Marten::Middleware::I18n, Marten::Middleware::GZip, ] ``` It should be noted that the order of middlewares is important. For example, if one of your middleware depends on a session value, you will want to ensure that it appears _after_ the `Marten::Middleware::Session` class in the `middleware` setting. ## Available middlewares All the available middlewares are listed in the [dedicated reference section](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares). # Customize handler template contexts Source: https://martenframework.com/docs/next/handlers-and-http/how-to/customize-handler-template-contexts This guide covers how to easily customize the [template context](https://martenframework.com/docs/next/templates/introduction) of handlers involving template renderings and how to add variables to it. Doing so will allow you to leverage custom variables in your handler templates and easily manipulate the appearance and content of your web pages, tailoring them to suit your specific needs and preferences. ## Requirements It is possible to customize the template context used by most handlers involving template renderings. This is the case for: * Handlers that make use of the [`#render`](https://martenframework.com/docs/next/handlers-and-http/introduction#render) helper method. * Handlers that inherit from the [`Marten::Handlers::Template`](https://martenframework.com/docs/next/handlers-and-http/reference/generic-handlers#rendering-a-template), [`Marten::Handlers::Schema`](https://martenframework.com/docs/next/handlers-and-http/reference/generic-handlers#processing-a-schema), [`Marten::Handlers::RecordCreate`](https://martenframework.com/docs/next/handlers-and-http/reference/generic-handlers#creating-a-record), [`Marten::Handlers::RecordDetail`](https://martenframework.com/docs/next/handlers-and-http/reference/generic-handlers#displaying-a-record), [`Marten::Handlers::RecordUpdate`](https://martenframework.com/docs/next/handlers-and-http/reference/generic-handlers#updating-a-record), or [`Marten::Handlers::RecordDelete`](https://martenframework.com/docs/next/handlers-and-http/reference/generic-handlers#deleting-a-record) generic handlers. ## Customizing the template context of a handler If your handler adheres to the [requirements](#requirements) mentioned above, then the simplest way to customize what variables are made available to the considered template context is to leverage the [`#before_render`](https://martenframework.com/docs/next/handlers-and-http/callbacks#before_render) callback. This callback is invoked prior to rendering a template when generating a response that incorporates its content. This means that they can be used to add new variables to the [global handler template context](https://martenframework.com/docs/next/handlers-and-http/introduction#global-template-context) so that they become accessible to the template runtime. For example: ```crystal class MyHandler < Marten::Handlers::Template template_name "app/my_template.html" before_render :add_foo_to_context private def add_foo_to_context : Nil context["foo"] = "bar" end end ``` In the above snippet, a very simple handler (that inherits from the [`Marten::Handlers::Template`](https://martenframework.com/docs/next/handlers-and-http/reference/generic-handlers#rendering-a-template) generic handler) defines a [`#before_render`](https://martenframework.com/docs/next/handlers-and-http/callbacks#before_render) callback in which a `foo` variable is added to the template context. ## A concrete example: currently active link in navigation sections To exemplify this functionality, let's consider a straightforward scenario involving navigation sections. Typically, it's essential to determine the currently active item within the navigation. This can be effortlessly accomplished by utilizing a dedicated template variable. For example, let's assume that our navigation template looks something like this: ```html ``` This template utilizes a `nav_bar_item` variable to determine the currently active navigation bar item and applies a dedicated `active` CSS class to the corresponding link based on the value of this variable. In order for this navigation to work as intended, we need to ensure that the applicable handlers define the `nav_bar_item` template variables. We could utilize the method described previously and simply define a [`#before_render`](https://martenframework.com/docs/next/handlers-and-http/callbacks#before_render) callback in the handlers that need to define this template variable. A better solution though would be to define a concern module that eases the process of doing this. For example, we could define a `NavBarActiveable` module that automatically sets the `nav_bar_item` template variable based on the value of a class variable that is set by handler classes making use of it: ```crystal module NavBarActiveable macro included class_getter nav_bar_item : String? extend NavBarActiveable::ClassMethods before_render :add_nav_bar_item_to_context end module ClassMethods def nav_bar_item(item : String | Symbol) @@nav_bar_item = item.to_s end end private def add_nav_bar_item_to_context context[:nav_bar_item] = self.class.nav_bar_item end end ``` Using this approach, defining the `nav_bar_item` variable in a handler would be as simple as including the `NavBarActiveable` module in the handler class and calling the `#nav_bar_item` method: ```crystal class MyHandler < Marten::Handlers::Template include NavBarActiveable template_name "app/my_template.html" nav_bar_item :home end ``` # Create custom route parameters Source: https://martenframework.com/docs/next/handlers-and-http/how-to/create-custom-route-parameters Although Marten has built-in support for [common route parameters](https://martenframework.com/docs/next/handlers-and-http/routing#specifying-route-parameters), it is also possible to implement your very own parameter types. This may be necessary if your routes have more complex matching requirements. ## Defining a route parameter In order to implement custom parameters, you need to subclass the [`Marten::Routing::Parameter::Base`](https://martenframework.com/docs/api/dev/Marten/Routing/Parameter/Base.html) abstract class. Each parameter class is responsible for: * defining a Regex allowing to match the parameters in raw paths (which can be done by implementing a [`#regex`](https://martenframework.com/docs/api/dev/Marten/Routing/Parameter/Base.html#regex%3ARegex-instance-method) method) * defining _how_ the route parameter value should be deserialized (which can be done by implementing a [`#loads`](https://martenframework.com/docs/api/dev/Marten/Routing/Parameter/Base.html#loads(value%3A%3A%3AString)-instance-method) method) * defining _how_ the route parameter value should serialized (which can be done by implementing a [`#dumps`](https://martenframework.com/docs/api/dev/Marten/Routing/Parameter/Base.html#dumps(value)%3A%3A%3AString%3F-instance-method) method) The [`#regex`](https://martenframework.com/docs/api/dev/Marten/Routing/Parameter/Base.html#regex%3ARegex-instance-method) method takes no arguments and must return a valid [`Regex`](https://crystal-lang.org/api/Regex.html) object. The [`#loads`](https://martenframework.com/docs/api/dev/Marten/Routing/Parameter/Base.html#loads(value%3A%3A%3AString)-instance-method) method takes the raw parameter (string) as argument and is expected to return the final Crystal object corresponding to the route parameter (this is the object that will be forwarded to the handler in the route parameters hash). The [`#dumps`](https://martenframework.com/docs/api/dev/Marten/Routing/Parameter/Base.html#dumps(value)%3A%3A%3AString%3F-instance-method) method takes the final route parameter object as argument and must return the corresponding string representation. Note that this method can either return a string or `nil`: `nil` means that the passed value couldn't be serialized properly, which will make any URL reverse resolution fail with a `Marten::Routing::Errors::NoReverseMatch` error. For example, a "year" (1000-2999) route parameter could be implemented as follows: ```crystal class YearParameter < Marten::Routing::Parameter::Base def regex : Regex /[12][0-9]{3}/ end def loads(value : ::String) : UInt64 value.to_u64 end def dumps(value) : Nil | ::String if value.as?(UInt8 | UInt16 | UInt32 | UInt64) value.to_s elsif value.is_a?(Int8 | Int16 | Int32 | Int64) && [1000..2999].includes?(value) value.to_s else nil end end end ``` ## Registering route parameters In order to be able to use custom route parameters in your [route definitions](https://martenframework.com/docs/next/handlers-and-http/routing#specifying-route-parameters), you must register them to Marten's global routing parameters registry. To do so, you will have to call the [`Marten::Routing::Parameter#register`](https://martenframework.com/docs/api/dev/Marten/Routing/Parameter.html#register(id%3A%3A%3AString|Symbol%2Cparameter_klass%3ABase.class)-class-method) method with the identifier of the parameter you wish to use in route path definitions, and the actual parameter class. For example: ```crystal Marten::Routing::Parameter.register(:year, YearParameter) ``` With the above registration, you could technically create the following route definition: ```crystal Marten.routes.draw do path "/vintage/", VintageHandler, name: "vintage" end ``` # Build a JSON API Source: https://martenframework.com/docs/next/handlers-and-http/how-to/build-a-json-api This guide covers how to add JSON endpoints for the `Article` model introduced in the [tutorial](https://martenframework.com/docs/next/getting-started/tutorial). These endpoints make it possible to list, retrieve, create, update, and delete articles by leveraging regular [handlers](https://martenframework.com/docs/next/handlers-and-http/introduction), [schemas](https://martenframework.com/docs/next/schemas/introduction), and the [`#json`](https://martenframework.com/docs/next/handlers-and-http/introduction#json) helper. It should be noted that generic handlers such as [`Marten::Handlers::RecordCreate`](https://martenframework.com/docs/next/handlers-and-http/reference/generic-handlers#creating-a-record) render a template and redirect once a schema is valid. The endpoints below return JSON responses, which is why they inherit from [`Marten::Handler`](https://martenframework.com/docs/next/handlers-and-http/introduction#writing-handlers) directly. The schema validates the incoming payload, and the handler decides which fields are included in the response. ## Requirements The examples below assume that you already created the `Article` model and the `ArticleSchema` schema from the tutorial: ```crystal title="src/models/article.cr" class Article < Marten::Model field :id, :big_int, primary_key: true, auto: true field :title, :string, max_size: 255 field :content, :text end ``` ```crystal title="src/schemas/article_schema.cr" class ArticleSchema < Marten::Schema field :title, :string, max_size: 255 field :content, :string end ``` Handlers defined under `src/handlers/` are automatically required by projects that were generated through the [`new`](https://martenframework.com/docs/next/development/reference/management-commands#new) management command (`require "./handlers/**"` in `src/project.cr`). Finally, it should be noted that one route maps to one handler. As such, the HTTP methods that share a URL are implemented as methods of the same handler class. Listing and creating articles share `GET` and `POST` on `/api/articles`, while retrieving, updating, and deleting an article share `GET`, `PUT`, and `DELETE` on `/api/articles/`. ## Listing and creating articles In order to list existing articles and to create new ones, let's create a `src/handlers/api/articles_handler.cr` file with the following content: ```crystal title="src/handlers/api/articles_handler.cr" class API::ArticlesHandler < Marten::Handler def get articles = Article.all.map { |article| article_json(article) } json({articles: articles}) end def post schema = ArticleSchema.new(request.data) if schema.valid? article = Article.new(schema.validated_data) article.save! json(article_json(article), status: 201) else json({errors: schema.errors}, status: 422) end end private def article_json(article : Article) {id: article.id, title: article.title, content: article.content} end end ``` This handler is able to handle both GET and POST requests: * when the incoming request is a GET, it loads every `Article` record and returns a JSON object containing the `id`, `title`, and `content` of each article * when the incoming request is a POST, it initializes an `ArticleSchema` schema with the data currently present in the request object (which is returned by the [`#data`](https://martenframework.com/docs/api/dev/Marten/HTTP/Request.html#data%3AParams%3A%3AData-instance-method) method). This data is automatically initialized from a JSON object when the `Content-Type` of the request is `application/json`. If the schema is valid, a new `Article` record is created using the schema's validated data and returned with a `201` status code. Otherwise, the schema errors are returned with a `422` status code For example, submitting a payload without a title produces a response like the following one: ```json { "errors": [ {"field": "title", "type": "required", "message": "This field is required."} ] } ``` It should be noted that the `field` attribute is `null` when the error is global. Model validation errors use the same representation, which means that `article.errors` can be passed to `#json` in the same way. Please refer to [Serializing errors as JSON](https://martenframework.com/docs/next/schemas/validations#serializing-errors-as-json) to learn more about this. ## Retrieving, updating, and deleting an article Let's now add the ability to retrieve, update, and delete a specific article. In this light, let's create a `src/handlers/api/article_handler.cr` file with the following content: ```crystal title="src/handlers/api/article_handler.cr" class API::ArticleHandler < Marten::Handler @article : Article? def get json(article_json(article)) end def put schema = ArticleSchema.new(request.data) if schema.valid? article.update!(schema.validated_data) json(article_json(article)) else json({errors: schema.errors}, status: 422) end end def delete article.delete head :no_content end private def article @article ||= Article.get!(id: params["pk"]) rescue Marten::DB::Errors::RecordNotFound raise Marten::HTTP::Errors::NotFound.new("Article not found") end private def article_json(article : Article) {id: article.id, title: article.title, content: article.content} end end ``` This handler is able to handle GET, PUT, and DELETE requests: * when the incoming request is a GET, it retrieves the `Article` record identified by the `pk` route parameter and returns it as JSON * when the incoming request is a PUT, it validates the incoming JSON payload with the same `ArticleSchema` schema. If the schema is valid, the record is updated using the schema's validated data. Otherwise, the schema errors are returned with a `422` status code * when the incoming request is a DELETE, it deletes the record and returns an empty response with a `204` status code by leveraging the [`#head`](https://martenframework.com/docs/next/handlers-and-http/introduction#head) helper In the above snippet, the `#article` method fetches the `Article` record by using the `pk` parameter value. If no record matches this primary key, a `Marten::DB::Errors::RecordNotFound` exception is rescued and a 404 Not Found response is returned. This is the same approach as the one used in the tutorial. ## Mapping the handlers to routes We can now map these handlers to proper routes. We can do this by editing the `config/routes.cr` file as follows: ```crystal title="config/routes.cr" Marten.routes.draw do path "/", HomeHandler, name: "home" path "/article/create", ArticleCreateHandler, name: "article_create" path "/article/", ArticleDetailHandler, name: "article_detail" path "/article//update", ArticleUpdateHandler, name: "article_update" path "/article//delete", ArticleDeleteHandler, name: "article_delete" // highlight-next-line path "/api/articles", API::ArticlesHandler, name: "api_articles" // highlight-next-line path "/api/articles/", API::ArticleHandler, name: "api_article" if Marten.env.development? path "#{Marten.settings.assets.url}", Marten::Handlers::Defaults::Development::ServeAsset, name: "asset" path "#{Marten.settings.media_files.url}", Marten::Handlers::Defaults::Development::ServeMediaFile, name: "media_file" end end ``` ## Cross-Site Request Forgery protection The CSRF protection is enabled for these handlers, which is the default. A browser that submits an unsafe request (`POST`, `PUT`, or `DELETE`) and that sends the session cookie must include the CSRF token in the `X-CSRF-Token` header. Please refer to [Using the CSRF protection with AJAX](https://martenframework.com/docs/next/security/csrf#using-the-csrf-protection-with-ajax) to learn more about how to retrieve this token and how to forward it. A client that does not rely on the session cookie (for example another server) can disable the CSRF protection on a per-handler basis. This can be achieved through the use of the [`#protect_from_forgery`](https://martenframework.com/docs/api/dev/Marten/Handlers/RequestForgeryProtection/ClassMethods.html#protect_from_forgery(protect%3ABool)%3ANil-instance-method) class method: ```crystal class API::ArticlesHandler < Marten::Handler protect_from_forgery false # [...] end ``` The same setting must be applied to `API::ArticleHandler` as well. ## Trying the endpoints You can now interact with these endpoints. For example, in order to list the available articles, you can run the following command: ```shell curl http://localhost:8000/api/articles ``` In order to create a new article, you can run the following command: ```shell curl http://localhost:8000/api/articles \ --request POST \ --header 'Content-Type: application/json' \ --header 'X-CSRF-Token: ' \ --data '{"title":"Hello","content":"First article"}' ``` :::info The `Content-Type` header must be set to `application/json`. Otherwise the request body is not made available through the `#data` method. ::: The above request returns a `201` response like the following one: ```json {"id": 1, "title": "Hello", "content": "First article"} ``` Retrieving, updating, and deleting this article can be achieved by running the following commands: ```shell curl http://localhost:8000/api/articles/1 curl http://localhost:8000/api/articles/1 \ --request PUT \ --header 'Content-Type: application/json' \ --header 'X-CSRF-Token: ' \ --data '{"title":"Hello","content":"Updated article"}' curl http://localhost:8000/api/articles/1 \ --request DELETE \ --header 'X-CSRF-Token: ' ``` :::tip The `X-CSRF-Token` header can be omitted when the considered handlers explicitly disable the CSRF protection. ::: # Generic handlers Source: https://martenframework.com/docs/next/handlers-and-http/reference/generic-handlers This page provides a reference for all the available [generic handlers](https://martenframework.com/docs/next/handlers-and-http/generic-handlers). ## Creating a record **Class:** [`Marten::Handlers::RecordCreate`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordCreate.html) Handler allowing to create a new model record by processing a schema. This handler can be used to process a form, validate its data through the use of a [schema](https://martenframework.com/docs/next/schemas), and create a record by using the validated data. It is expected that the handler will be accessed through a GET request first: when this happens the configured template is rendered and displayed, and the configured schema which is initialized can be accessed from the template context in order to render a form for example. When the form is submitted via a POST request, the configured schema is validated using the form data. If the data is valid, the corresponding model record is created and the handler returns an HTTP redirect to a configured success URL. ```crystal class ArticleCreateHandler < Marten::Handlers::RecordCreate model Article schema ArticleCreateSchema template_name "articles/create.html" success_route_name "my_form_success" end ``` It should be noted that the redirect response issued will be a 302 (found). The model class used to create the new record can be configured through the use of the [`#model`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordCreate.html#model(model_klass)-macro) macro. The schema used to perform the validation can be defined through the use of the [`#schema`](https://martenframework.com/docs/api/dev/Marten/Handlers/Schema.html#schema(schema_klass)-macro) macro. Alternatively, the [`#schema_class`](https://martenframework.com/docs/api/dev/Marten/Handlers/Schema.html#schema_class-instance-method) method can also be overridden to dynamically define the schema class as part of the request handler handling. The [`#template_name`](https://martenframework.com/docs/api/dev/Marten/Handlers/Rendering/ClassMethods.html#template_name(template_name%3AString%3F)-instance-method) class method allows defining the name of the template to use to render the schema while the [`#success_route_name`](https://martenframework.com/docs/api/dev/Marten/Handlers/Schema.html#success_route_name(success_route_name%3AString%3F)-class-method) method can be used to specify the name of a route to redirect to once the schema has been validated. Alternatively, the [`#success_url`](https://martenframework.com/docs/api/dev/Marten/Handlers/Schema.html#success_url(success_url%3AString%3F)-class-method) class method can be used to provide a raw URL to redirect to. The [same method](https://martenframework.com/docs/api/dev/Marten/Handlers/Schema.html#success_url-instance-method) can also be overridden at the instance level to rely on a custom logic to generate the success URL to redirect to. For example, if your application logic requires a success route that includes an identifier (such as a record's primary key), you can customize the success URL by overriding the `#success_url` method like this: ```crystal def success_url reverse("articles:detail", pk: record.pk!) # record is an instance of the model you defined for your handler end ``` :::tip Handlers making use of the [`Marten::Handlers::RecordCreate`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordCreate.html) generic handler can leverage additional types of callbacks. Please head over to [Schema handler callbacks](https://martenframework.com/docs/next/handlers-and-http/callbacks#schema-handler-callbacks) to learn more about those. ::: ## Deleting a record **Class:** [`Marten::Handlers::RecordDelete`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordDelete.html) Handler allowing to delete a specific model record. This handler can be used to delete an existing model record by issuing a POST request. Optionally the handler can be accessed with a GET request and a template can be displayed in this case; this allows to display a confirmation page to users before deleting the record: ```crystal class ArticleDeleteHandler < Marten::Handlers::RecordDelete model Article template_name "articles/delete.html" success_route_name "article_delete_success" end ``` It should be noted that the redirect response issued will be a 302 (found). The [`#template_name`](https://martenframework.com/docs/api/dev/Marten/Handlers/Rendering/ClassMethods.html#template_name(template_name%3AString%3F)-instance-method) class method allows defining the name of the template to use to render a deletion confirmation page while the [`#success_route_name`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordDelete.html#success_route_name(success_route_name%3AString%3F)-class-method) method can be used to specify the name of a route to redirect to once the deletion is complete. Alternatively, the [`#success_url`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordDelete.html#success_url(success_url%3AString%3F)-class-method) class method can be used to provide a raw URL to redirect to. The [same method](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordDelete.html#success_url-instance-method) can also be overridden at the instance level to rely on a custom logic to generate the success URL to redirect to. It's also possible to pre-filter the queryset before deleting the record by using the [`#queryset`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordRetrieving.html#queryset(queryset)-macro) macro. :::tip How to customize the query set? By default, handlers that inherit from [`Marten::Handlers::RecordDelete`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordDelete.html) will use a query set targeting _all_ the records in order to retrieve the record that should be deleted. It should be noted that you can customize this behavior easily by leveraging the [`#queryset`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordRetrieving.html#queryset(queryset)-macro) macro instead of the [`#model`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordRetrieving.html#model(model_klass)-macro) macro. For example: ```crystal class ArticleDeleteHandler < Marten::Handlers::RecordDelete queryset Article.filter(user: request.user) template_name "articles/delete.html" success_route_name "article_delete_success" end ``` Alternatively, it is also possible to override the [`#queryset`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordRetrieving.html#queryset-instance-method) method and apply additional filters to the default query set: ```crystal class ArticleDeleteHandler < Marten::Handlers::RecordDelete model Article template_name "articles/delete.html" success_route_name "article_delete_success" def queryset super.filter(user: request.user) end end ``` ::: ## Displaying a record **Class:** [`Marten::Handlers::RecordDetail`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordDetail.html) Handler allowing to display a specific model record. This handler can be used to retrieve a [model](https://martenframework.com/docs/next/models-and-databases/introduction) record, and to display it as part of a [rendered template](https://martenframework.com/docs/next/templates). ```crystal class ArticleDetailHandler < Marten::Handlers::RecordDetail model Article template_name "articles/detail.html" end ``` The model class used to retrieve the record can be configured through the use of the [`#model`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordRetrieving.html#model(model_klass)-macro) macro. It's also possible to pre-filter the queryset before retrieving the record by using the [`#queryset`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordRetrieving.html#queryset(queryset)-macro) macro. By default, a [`Marten::Handlers::RecordDetail`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordDetail.html) subclass will always retrieve model records by looking for a `pk` route parameter: this parameter is assumed to contain the value of the primary key field associated with the record that should be rendered. If you need to use a different route parameter name, you can also specify a different one through the use of the [`#lookup_param`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordRetrieving/ClassMethods.html#lookup_param(lookup_param%3AString|Symbol)-instance-method) class method. Finally, the model field that is used to get the model record (defaulting to `pk`) can also be configured by leveraging the [`#lookup_param`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordRetrieving/ClassMethods.html#lookup_param(lookup_param%3AString|Symbol)-instance-method) class method. The [`#template_name`](https://martenframework.com/docs/api/dev/Marten/Handlers/Rendering/ClassMethods.html#template_name(template_name%3AString%3F)-instance-method) class method allows defining the name of the template to use to render the considered model record. By default, the model record is associated with a `record` key in the template context, but this can also be configured by using the [`record_context_name`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordDetail.html#record_context_name(name%3AString|Symbol)-class-method) class method. :::tip How to customize the query set? By default, handlers that inherit from [`Marten::Handlers::RecordDetail`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordDetail.html) will use a query set targeting _all_ the records in order to retrieve the record that should be displayed. It should be noted that you can customize this behavior easily by leveraging the [`#queryset`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordRetrieving.html#queryset(queryset)-macro) macro instead of the [`#model`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordRetrieving.html#model(model_klass)-macro) macro. For example: ```crystal class ArticleDetailHandler < Marten::Handlers::RecordDetail queryset Article.filter(user: request.user) template_name "articles/detail.html" end ``` Alternatively, it is also possible to override the [`#queryset`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordRetrieving.html#queryset-instance-method) method and apply additional filters to the default query set: ```crystal class ArticleDetailHandler < Marten::Handlers::RecordDetail model Article template_name "articles/detail.html" def queryset super.filter(user: request.user) end end ``` ::: ## Listing records **Class:** [`Marten::Handlers::RecordList`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordList.html) Handler allowing to list model records. This base handler can be used to easily expose a list of model records: ```crystal class ArticleListHandler < Marten::Handlers::RecordList model Article template_name "articles/index.html" end ``` The model class used to retrieve the records can be configured through the use of the [`#model`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordListing.html#model(model_klass)-macro) macro. The [order](https://martenframework.com/docs/next/models-and-databases/reference/query-set#order) of these model records can also be specified by leveraging the [`#ordering`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordListing/ClassMethods.html#page_number_param(param%3AString|Symbol)-instance-method) class method. The [`#template_name`](https://martenframework.com/docs/api/dev/Marten/Handlers/Rendering/ClassMethods.html#template_name(template_name%3AString%3F)-instance-method) class method allows defining the name of the template to use to render the list of model records. By default, the list of model records is associated with a `records` key in the template context, but this can also be configured by using the [`list_context_name`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordList.html#list_context_name(name%3AString|Symbol)-class-method) class method. Optionally, it is possible to configure that records should be [paginated](https://martenframework.com/docs/next/models-and-databases/reference/query-set#paginator) by specifying a page size through the use of the [`page_size`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordListing/ClassMethods.html#page_size(page_size%3AInt32%3F)-instance-method) class method: ```crystal class ArticleListHandler < Marten::Handlers::RecordList model Article template_name "articles/index.html" page_size 12 end ``` When records are paginated, a [`Marten::DB::Query::Page`](https://martenframework.com/docs/api/dev/Marten/DB/Query/Page.html) object will be exposed in the template context (instead of the raw query set). It should be noted that the page number that should be displayed is determined by looking for a `page` GET parameter by default; this parameter name can be configured as well by calling the [`page_number_param`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordListing/ClassMethods.html#page_number_param(param%3AString|Symbol)-instance-method) class method. :::tip How to customize the query set? By default, handlers that inherit from [`Marten::Handlers::RecordList`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordList.html) will use a query set targeting _all_ the records of the specified model. It should be noted that you can customize this behavior easily by leveraging the [`#queryset`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordListing.html#queryset(queryset)-macro) macro instead of the [`#model`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordListing.html#model(model_klass)-macro) macro. For example: ```crystal class ArticleListHandler < Marten::Handlers::RecordList queryset Article.filter(user: request.user) template_name "articles/index.html" end ``` Alternatively, it is also possible to override the [`#queryset`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordListing.html#queryset-instance-method) method and apply additional filters to the default query set: ```crystal class ArticleListHandler < Marten::Handlers::RecordList model Article template_name "articles/index.html" def queryset super.filter(user: request.user) end end ``` ::: ## Updating a record **Class:** [`Marten::Handlers::RecordUpdate`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordUpdate.html) Handler allowing to update a model record by processing a schema. This handler can be used to process a form, validate its data through the use of a [schema](https://martenframework.com/docs/next/schemas), and update an existing record by using the validated data. It is expected that the handler will be accessed through a GET request first: when this happens the configured template is rendered and displayed, and the configured schema which is initialized can be accessed from the template context to render a form for example. When the form is submitted via a POST request, the configured schema is validated using the form data. If the data is valid, the model record that was retrieved is updated and the handler returns an HTTP redirect to a configured success URL. ```crystal class ArticleUpdateHandler < Marten::Handlers::RecordUpdate model Article schema ArticleUpdateSchema template_name "articles/update.html" success_route_name "my_form_success" end ``` It should be noted that the redirect response issued will be a 302 (found). The model class used to update the new record can be configured through the use of the [`#model`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordRetrieving.html#model(model_klass)-macro) macro. It's also possible to pre-filter the queryset before updating the record by using the [`#queryset`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordRetrieving.html#queryset(queryset)-macro) macro. By default, the record to update is retrieved by expecting a `pk` route parameter: this parameter is assumed to contain the value of the primary key field associated with the record that should be updated. If you need to use a different route parameter name, you can also specify a different one through the use of the [`#lookup_param`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordRetrieving/ClassMethods.html#lookup_param(lookup_param%3AString|Symbol)-instance-method) class method. Finally, the model field that is used to get the model record (defaulting to `pk`) can also be configured by leveraging the [`#lookup_param`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordRetrieving/ClassMethods.html#lookup_param(lookup_param%3AString|Symbol)-instance-method) class method. The schema used to perform the validation can be defined through the use of the [`#schema`](https://martenframework.com/docs/api/dev/Marten/Handlers/Schema.html#schema(schema_klass)-macro) macro. Alternatively, the [`#schema_class`](https://martenframework.com/docs/api/dev/Marten/Handlers/Schema.html#schema_class-instance-method) method can also be overridden to dynamically define the schema class as part of the request handler handling. The [`#template_name`](https://martenframework.com/docs/api/dev/Marten/Handlers/Rendering/ClassMethods.html#template_name(template_name%3AString%3F)-instance-method) class method allows defining the name of the template to use to render the schema while the [`#success_route_name`](https://martenframework.com/docs/api/dev/Marten/Handlers/Schema.html#success_route_name(success_route_name%3AString%3F)-class-method) method can be used to specify the name of a route to redirect to once the schema has been validated. Alternatively, the [`#success_url`](https://martenframework.com/docs/api/dev/Marten/Handlers/Schema.html#success_url(success_url%3AString%3F)-class-method) class method can be used to provide a raw URL to redirect to. The [same method](https://martenframework.com/docs/api/dev/Marten/Handlers/Schema.html#success_url-instance-method) can also be overridden at the instance level to rely on a custom logic to generate the success URL to redirect to. :::tip Handlers making use of the [`Marten::Handlers::RecordUpdate`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordUpdate.html) generic handler can leverage additional types of callbacks. Please head over to [Schema handler callbacks](https://martenframework.com/docs/next/handlers-and-http/callbacks#schema-handler-callbacks) to learn more about those. ::: :::tip How to customize the query set? By default, handlers that inherit from [`Marten::Handlers::RecordUpdate`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordUpdate.html) will use a query set targeting _all_ the records in order to retrieve the record that should be updated. It should be noted that you can customize this behavior easily by leveraging the [`#queryset`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordRetrieving.html#queryset(queryset)-macro) macro instead of the [`#model`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordRetrieving.html#model(model_klass)-macro) macro. For example: ```crystal class ArticleUpdateHandler < Marten::Handlers::RecordUpdate queryset Article.filter(user: request.user) schema ArticleUpdateSchema template_name "articles/update.html" success_route_name "my_form_success" end ``` Alternatively, it is also possible to override the [`#queryset`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordRetrieving.html#queryset-instance-method) method and apply additional filters to the default query set: ```crystal class ArticleUpdateHandler < Marten::Handlers::RecordUpdate model Article schema ArticleUpdateSchema template_name "articles/update.html" success_route_name "my_form_success" def queryset super.filter(user: request.user) end end ``` ::: ## Performing a redirect **Class:** [`Marten::Handlers::Redirect`](https://martenframework.com/docs/api/dev/Marten/Handlers/Redirect.html) Handler allowing to conveniently return redirect responses. This handler can be used to generate a redirect response (temporary or permanent) to another location. To configure such a location, you can either leverage the [`#route_name`](https://martenframework.com/docs/api/dev/Marten/Handlers/Redirect.html#route_name(route_name%3AString%3F)-class-method) class method (which expects a valid [route name](https://martenframework.com/docs/next/handlers-and-http/routing#reverse-url-resolutions)) or the [`#url`](https://martenframework.com/docs/api/dev/Marten/Handlers/Redirect.html#url(url%3AString%3F)-class-method) class method. If you need to implement a custom redirection URL logic, you can also override the [`#redirect_url`](https://martenframework.com/docs/api/dev/Marten/Handlers/Redirect.html#redirect_url-instance-method) method. ```crystal class TestRedirectHandler < Marten::Handlers::Redirect route_name "articles:list" end ``` By default, the redirect returned by this handler is a temporary one. In order to generate a permanent redirect response instead, it is possible to leverage the [`#permanent`](https://martenframework.com/docs/api/dev/Marten/Handlers/Redirect.html#permanent(permanent%3ABool)-class-method) class method. It should also be noted that by default, incoming query string parameters **are not** forwarded to the redirection URL. If you wish to ensure that these parameters are forwarded, you can make use of the [`forward_query_string`](https://martenframework.com/docs/api/dev/Marten/Handlers/Redirect.html#forward_query_string(forward_query_string%3ABool)-class-method) class method. ## Processing a schema **Class:** [`Marten::Handlers::Schema`](https://martenframework.com/docs/api/dev/Marten/Handlers/Schema.html) Handler allowing to process a form through the use of a [schema](https://martenframework.com/docs/next/schemas). This handler can be used to process a form and validate its data through the use of a [schema](https://martenframework.com/docs/next/schemas). It is expected that the handler will be accessed through a GET request first: when this happens the configured template is rendered and displayed, and the configured schema which is initialized can be accessed from the template context to render a form for example. When the form is submitted via a POST request, the configured schema is validated using the form data. If the data is valid, the handler returns an HTTP redirect to a configured success URL. ```crystal class MyFormHandler < Marten::Handlers::Schema schema MyFormSchema template_name "my_form.html" success_route_name "my_form_success" end ``` It should be noted that the redirect response issued will be a 302 (found). The schema used to perform the validation can be defined through the use of the [`#schema`](https://martenframework.com/docs/api/dev/Marten/Handlers/Schema.html#schema(schema_klass)-macro) macro. Alternatively, the [`#schema_class`](https://martenframework.com/docs/api/dev/Marten/Handlers/Schema.html#schema_class-instance-method) method can also be overridden to dynamically define the schema class as part of the request handler handling. The [`#template_name`](https://martenframework.com/docs/api/dev/Marten/Handlers/Rendering/ClassMethods.html#template_name(template_name%3AString%3F)-instance-method) class method allows defining the name of the template to use to render the schema while the [`#success_route_name`](https://martenframework.com/docs/api/dev/Marten/Handlers/Schema.html#success_route_name(success_route_name%3AString%3F)-class-method) method can be used to specify the name of a route to redirect to once the schema has been validated. Alternatively, the [`#success_url`](https://martenframework.com/docs/api/dev/Marten/Handlers/Schema.html#success_url(success_url%3AString%3F)-class-method) class method can be used to provide a raw URL to redirect to. The [same method](https://martenframework.com/docs/api/dev/Marten/Handlers/Schema.html#success_url-instance-method) can also be overridden at the instance level to rely on a custom logic to generate the success URL to redirect to. :::tip Handlers making use of the [`Marten::Handlers::Schema`](https://martenframework.com/docs/api/dev/Marten/Handlers/Schema.html) generic handler can leverage additional types of callbacks. Please head over to [Schema handler callbacks](https://martenframework.com/docs/next/handlers-and-http/callbacks#schema-handler-callbacks) to learn more about those. ::: ## Rendering a template **Class:** [`Marten::Handlers::Template`](https://martenframework.com/docs/api/dev/Marten/Handlers/Template.html) Handler allowing to respond to `GET` request with the content of a rendered HTML [template](https://martenframework.com/docs/next/templates). This handler can be used to render a specific template and returns the resulting content in the response. The template being rendered can be specified by leveraging the [`#template_name`](https://martenframework.com/docs/api/dev/Marten/Handlers/Rendering/ClassMethods.html#template_name(template_name%3AString%3F)-instance-method) class method. ```crystal class HomeHandler < Marten::Handlers::Template template_name "app/home.html" end ``` If you need to, it is possible to customize the context that is used to render the configured template. To do so, you can define a [`before_render`](https://martenframework.com/docs/next/handlers-and-http/callbacks#before_render) callback and add new variables to the [global template context](https://martenframework.com/docs/next/handlers-and-http/introduction#global-template-context) (which functions similarly to a hash object): ```crystal class HomeHandler < Marten::Handlers::Template template_name "app/home.html" before_render :add_recent_articles_to_context private def add_recent_articles_to_context : Nil context[:recent_articles] = Article.all.order("-published_at")[:5] end end ``` Variables that are added to the global template context will automatically be available to the configured template's runtime. :::tip The default content type of the response generated when rendering templates is `text/html`, but this can be customized using the [`#content_type`](https://martenframework.com/docs/api/dev/Marten/Handlers/Rendering/ClassMethods.html#content_type(content_type%3AString|Nil)-instance-method) class method. For example: ```crystal class MyHandler < Marten::Handlers::Template template_name "app/test.xml" content_type "application/xml" end ``` ::: # Middlewares Source: https://martenframework.com/docs/next/handlers-and-http/reference/middlewares This page provides a reference for all the available [middlewares](https://martenframework.com/docs/next/handlers-and-http/middlewares). ## Asset serving middleware **Class:** [`Marten::Middleware::AssetServing`](https://martenframework.com/docs/api/dev/Marten/Middleware/AssetServing.html) The purpose of this middleware is to handle the distribution of collected assets, which are stored under the configured assets root ([`assets.root`](https://martenframework.com/docs/next/development/reference/settings#root) setting). The assumption is that these assets have been "collected" using the [`collectassets`](https://martenframework.com/docs/next/development/reference/management-commands#collectassets) management command and that the file system storage ([`Marten::Core::Storage::FileSystem`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/FileSystem.html)) is being used. Additionally, the [`assets.url`](https://martenframework.com/docs/next/development/reference/settings#url) setting must either align with the domain of your Marten application or correspond to a relative URL path, such as `/assets/`. This ensures proper mapping and accessibility of the assets within your application (so that they can be served by this middleware). It is important to mention that this middleware automatically applies compression to the served assets, utilizing GZip or deflate based on the Accept-Encoding header of the incoming request. Additionally, the middleware sets the Cache-Control header and defines a max-age of 3600 seconds, ensuring efficient caching of the assets. :::info This middleware should be placed at the first position in the [`middleware`](https://martenframework.com/docs/next/development/reference/settings#middleware) setting (ie. before all other configured middlewares). ::: :::tip This middleware is provided to make it easy to serve assets in situations where you can't easily configure a web server such as [Nginx](https://nginx.org) or a third-party service (like Amazon's S3 or GCS) to serve your assets directly. ::: ## Content-Security-Policy middleware **Class:** [`Marten::Middleware::ContentSecurityPolicy`](https://martenframework.com/docs/api/dev/Marten/Middleware/ContentSecurityPolicy.html) This middleware guarantees the presence of the Content-Security-Policy header in the response's headers. This header provides clients with the ability to limit the allowed sources of different types of content. By default, the middleware will include a Content-Security-Policy header that corresponds to the policy defined in the [`content_security_policy`](https://martenframework.com/docs/next/development/reference/settings#content-security-policy-settings) settings. However, if a [`Marten::HTTP::ContentSecurityPolicy`](https://martenframework.com/docs/api/dev/Marten/HTTP/ContentSecurityPolicy.html) object is explicitly assigned to the request object, it will take precedence over the default policy and be used instead. Please refer to [Content Security Policy](https://martenframework.com/docs/next/security/content-security-policy) to learn more about the Content-Security-Policy header and how to configure it. ## Cross-Origin-Opener-Policy middleware **Class:** [`Marten::Middleware::CrossOriginOpenerPolicy`](https://martenframework.com/docs/api/dev/Marten/Middleware/CrossOriginOpenerPolicy.html) Sets the [Cross-Origin-Opener-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy) header in the response if it wasn't already set. When this middleware is used, a Cross-Origin-Opener-Policy header will be inserted into the HTTP response. The value for this header is configurable via the [`cross_origin_opener_policy`](https://martenframework.com/docs/next/development/reference/settings#cross_origin_opener_policy) setting (whose default value is `same-origin`). This header allows browsers to isolate a top-level window from other documents by putting them in a different browsing context group, which mitigates cross-origin attacks that rely on `window.opener`. You can also define a custom header value on a per-handler basis by using the [`#cross_origin_opener_policy`](https://martenframework.com/docs/api/dev/Marten/Handlers/CrossOriginOpenerPolicy/ClassMethods.html#cross_origin_opener_policy(value%3AString%7CSymbol)%3ANil-instance-method) class method: ```crystal class PopupHandler < Marten::Handler cross_origin_opener_policy :same_origin_allow_popups # [...] end ``` It is also possible to disable the header entirely on a per-handler basis by using the [`#exempt_from_cross_origin_opener_policy`](https://martenframework.com/docs/api/dev/Marten/Handlers/CrossOriginOpenerPolicy/ClassMethods.html#exempt_from_cross_origin_opener_policy(exempt%3ABool)%3ANil-instance-method) class method: ```crystal class UnprotectedHandler < Marten::Handler exempt_from_cross_origin_opener_policy true # [...] end ``` :::note Cross-origin flows that rely on `window.opener` (for example some OAuth or payment popups) may need `same-origin-allow-popups` or a per-handler exemption. ::: ## Flash middleware **Class:** [`Marten::Middleware::Flash`](https://martenframework.com/docs/api/dev/Marten/Middleware/Flash.html) Enables the use of [flash messages](https://martenframework.com/docs/next/handlers-and-http/introduction#using-the-flash-store). When this middleware is used, each request will have a flash store initialized and populated from the request's session store. This flash store is a hash-like object that allows to fetch or set values that are associated with specific keys, and that will only be available to the next request (after that they are cleared out). The flash store depends on the presence of a working session store. As such, the [Session middleware](#session-middleware) MUST be used along with this middleware. Moreover, this middleware must be placed _after_ the [`Marten::Middleware::Session`](https://martenframework.com/docs/api/dev/Marten/Middleware/Session.html) in the [`middleware`](https://martenframework.com/docs/next/development/reference/settings#middleware) setting. ## GZip middleware **Class:** [`Marten::Middleware::GZip`](https://martenframework.com/docs/api/dev/Marten/Middleware/GZip.html) Compresses the content of the response if the browser supports GZip compression. This middleware will compress responses that are big enough (200 bytes or more) if they don't already contain an Accept-Encoding header. It will also set the Vary header correctly by including Accept-Encoding in it so that caches take into account the fact that the content can be compressed or not. The GZip middleware should be positioned before any other middleware that needs to interact with the response content in the [`middleware`](https://martenframework.com/docs/next/development/reference/settings#middleware) setting. This is to ensure that the compression happens only when the response content is no longer accessed. :::note The GZip middleware incorporates a mitigation strategy against the [BREACH attack](https://www.breachattack.com/). This strategy (described in the [Heal The Breach paper](https://ieeexplore.ieee.org/document/9754554)) involves introducing up to 100 random bytes into GZip responses to enhance the security against such attacks. ::: ## I18n middleware **Class:** [`Marten::Middleware::I18n`](https://martenframework.com/docs/api/dev/Marten/Middleware/I18n.html) Activates the right I18n locale based on incoming requests. This middleware will activate the right locale based on the Accept-Language header or the value provided by the [locale cookie](https://martenframework.com/docs/next/development/reference/settings#locale_cookie_name). Only explicitly-configured locales can be activated by this middleware (that is, locales that are specified in the [`i18n.available_locales`](https://martenframework.com/docs/next/development/reference/settings#available_locales) and [`i18n.default_locale`](https://martenframework.com/docs/next/development/reference/settings#default_locale) settings). If the incoming locale can't be found in the project configuration, the default locale will be used instead. Additionally, if (and only if) [localized routes](https://martenframework.com/docs/next/i18n/localized-routes) are being used, the middleware will use the locale prefix specified in the incoming paths with priority over the rules mentioned previously in order to identify the locale to activate. For example if the request's path is `/fr/bonjour`, then the activated locale will be the `fr` one. ## Method Override middleware **Class:** [`Marten::Middleware::MethodOverride`](https://martenframework.com/docs/api/dev/Marten/Middleware/MethodOverride.html) This middleware enables support for overriding HTTP methods in HTML forms that natively only support GET and POST. It does this by inspecting requests and looking for a `_method` parameter, allowing to simulate methods like PUT, DELETE, and others. It's also possible to change the parameter name and the allowed override methods in the [method override configuration](https://martenframework.com/docs/next/development/reference/settings#method-overriding-settings). For example: ```html
``` With the `MethodOverride` middleware, the form submission would effectively be treated as a `DELETE` request instead of `POST`. :::info The middleware should be placed as far as possible at the beginning of the array of the [`middlewares`](https://martenframework.com/docs/next/development/reference/settings#middleware) setting so that other middlewares already recognise the overridden method. ::: ## Referrer-Policy middleware **Class:** [`Marten::Middleware::ReferrerPolicy`](https://martenframework.com/docs/api/dev/Marten/Middleware/ReferrerPolicy.html) Sets the [Referrer-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy) header in the response if it wasn't already set. When this middleware is used, a Referrer-Policy header will be inserted into the HTTP response. The value for this header is configurable via the [`referrer_policy`](https://martenframework.com/docs/next/development/reference/settings#referrer_policy) setting. This header controls the amount of referrer information sent along with requests from your site to other origins, enhancing user privacy and security. ## Session middleware **Class:** [`Marten::Middleware::Session`](https://martenframework.com/docs/api/dev/Marten/Middleware/Session.html) Enables the use of [sessions](https://martenframework.com/docs/next/handlers-and-http/sessions). When this middleware is used, each request will have a session store initialized according to the [sessions configuration](https://martenframework.com/docs/next/development/reference/settings#sessions-settings). This session store is a hash-like object that allows to fetch or set values that are associated with specific keys. The session store is initialized from a session key that is stored as a regular cookie. If the session store ends up being empty after a request's handling, the associated cookie is deleted. Otherwise, the cookie is refreshed if the session store is modified as part of the considered request. Each session cookie is set to expire according to a configured cookie max age (the default cookie max age is 2 weeks). ## SSL redirect middleware **Class:** [`Marten::Middleware::SSLRedirect`](https://martenframework.com/docs/api/dev/Marten/Middleware/SSLRedirect.html) Redirects all non-HTTPS requests to HTTPS. This middleware will permanently redirect all non-HTTP requests to HTTPS. By default the middleware will redirect to the incoming request's host, but a different host to redirect to can be configured with the [`ssl_redirect.host`](https://martenframework.com/docs/next/development/reference/settings#host-2) setting. Additionally, specific request paths can also be exempted from this SSL redirect if the corresponding strings or regexes are specified in the [`ssl_redirect.exempted_paths`](https://martenframework.com/docs/next/development/reference/settings#exempted_paths) setting. ## Strict-Transport-Security middleware **Class:** [`Marten::Middleware::StrictTransportSecurity`](https://martenframework.com/docs/api/dev/Marten/Middleware/StrictTransportSecurity.html) Sets the Strict-Transport-Security header in the response if it wasn't already set. This middleware automatically sets the HTTP Strict-Transport-Security (HSTS) response header for all responses unless it was already specified in the response headers. This allows to let browsers know that the considered website should only be accessed using HTTPS, which results in future HTTP requests being automatically converted to HTTPS (up until the configured strict transport policy max age is reached). Browsers ensure that this policy is applied for a specific duration because a `max-age` directive is embedded into the header value. This max age duration is expressed in seconds and can be configured using the [`strict_security_policy.max_age`](https://martenframework.com/docs/next/development/reference/settings#max_age) setting. :::caution When enabling this middleware, you should probably start with small values for the [`strict_security_policy.max_age`](https://martenframework.com/docs/next/development/reference/settings#max_age) setting (for example `3600` - one hour). Indeed, when browsers are aware of the Strict-Transport-Security header they will refuse to connect to your website using HTTP until the expiry time corresponding to the configured max age is reached. This is why the value of the [`strict_security_policy.max_age`](https://martenframework.com/docs/next/development/reference/settings#max_age) setting is `nil` by default: this prevents the middleware from inserting the Strict-Transport-Security response header until you actually specify a max age. ::: ## X-Content-Type-Options middleware **Class:** [`Marten::Middleware::XContentTypeOptions`](https://martenframework.com/docs/api/dev/Marten/Middleware/XContentTypeOptions.html) Sets the [X-Content-Type-Options](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options) header in the response if it wasn't already set. When this middleware is used, an `X-Content-Type-Options: nosniff` header is inserted into the HTTP response. This instructs browsers to always use the declared `Content-Type` instead of MIME-sniffing the response body, which helps mitigate certain cross-site scripting attacks involving mislabeled or user-uploaded content. It should be noted that you can decide to disable or enable the use of this middleware on a per-handler basis. To do so, you can simply make use of the [`#exempt_from_x_content_type_options`](https://martenframework.com/docs/api/dev/Marten/Handlers/XContentTypeOptions/ClassMethods.html#exempt_from_x_content_type_options(exempt%3ABool)%3ANil-instance-method) class method, which takes a single boolean as argument: ```crystal class ProtectedHandler < Marten::Handler exempt_from_x_content_type_options false # [...] end class UnprotectedHandler < Marten::Handler exempt_from_x_content_type_options true # [...] end ``` :::note This header only applies to responses served by your Marten application. If user-uploaded files are served directly by a web server or a CDN, you should configure `X-Content-Type-Options: nosniff` there as well. ::: ## X-Frame-Options middleware **Class:** [`Marten::Middleware::XFrameOptions`](https://martenframework.com/docs/api/dev/Marten/Middleware/XFrameOptions.html) Sets the X-Frame-Options header in the response if it wasn't already set. When this middleware is used, a X-Frame-Options header will be inserted into the HTTP response. The default value for this header (which is configurable via the [`x_frame_options`](https://martenframework.com/docs/next/development/reference/settings#x_frame_options) setting) is "DENY", which means that the response cannot be displayed in a frame. This allows preventing click-jacking attacks, by ensuring that the web app cannot be embedded into other sites. On the other hand, if the `x_frame_options` is set to "SAMEORIGIN", the page can be displayed in a frame if the including site is the same as the one serving the page. # Templates Source: https://martenframework.com/docs/next/templates Templates provide a convenient way to write HTML content that is rendered dynamically. This rendering can involve model records or any other variables you define. ## Guides - [Introduction](https://martenframework.com/docs/next/templates/introduction) ## How-to's - [Create custom template filters](https://martenframework.com/docs/next/templates/how-to/create-custom-filters) - [Create custom template tags](https://martenframework.com/docs/next/templates/how-to/create-custom-tags) - [Create custom context producers](https://martenframework.com/docs/next/templates/how-to/create-custom-context-producers) - [Create custom loaders](https://martenframework.com/docs/next/templates/how-to/create-custom-loaders) ## Reference - [Template filters](https://martenframework.com/docs/next/templates/reference/filters) - [Template tags](https://martenframework.com/docs/next/templates/reference/tags) - [Operators](https://martenframework.com/docs/next/templates/reference/operators) - [Context producers](https://martenframework.com/docs/next/templates/reference/context-producers) - [Template loaders](https://martenframework.com/docs/next/templates/reference/loaders) # Introduction to templates Source: https://martenframework.com/docs/next/templates/introduction Templates provide a convenient way for defining the presentation logic of a web application. They allow to write textual content that is rendered dynamically by using a dedicated syntax. This syntax enables the use of dynamic variables as well as some programming constructs. ## Syntax A template is a textual document or a string that makes use of the Marten template language, and that can be used to generate _any_ text-based format (HTML, XML, etc). In order to insert dynamic content, templates usually make use of a few constructs such as **variables**, which are replaced by the corresponding values when the template is evaluated, and **tags**, which can be used to implement the logic of the template. For example, the following template displays the properties of an `article` variable and loops over the associated comments in order to display them as a list: ```html

{{ article.title }}

{{ article.content }}

    {% for comment in article.comments %}
  • {{ comment.message }}
  • {% else %}
  • No comments!
  • {% endfor %}
``` Templates need to be evaluated with a **context**. This context is usually a hash-like object containing all the variables or values that can be used by the template when it is rendered. In the previous example, the template context would at least contain one `article` key giving access to the considered article properties. ### Variables Variables can be used to inject a value from the context into the rendered template. They must be surrounded by **`{{`** and **`}}`**. For example: ```html Hello, {{ name }}! ``` If the context used to render the above template is `{"name" => "John Doe"}`, then the output would be "Hello, John Doe!". Each variable can involve additional lookups in order to access specific object attributes (if such objects have ones). These lookups are expressed by relying on a dot notation (`foo.bar`). For example, the following snippet would output the `title` attribute of the `article` variable: ```html

{{ article.title }}

``` This notation can be used to call object methods but also to perform key lookups for hashes or named tuples. It can also be used to perform index lookups for indexable objects (such as arrays or tuples): ``` {{ my_array.0 }} ``` ### Filters Filters can be applied to [variables](#variables) or [tag](#tags) arguments in order to transform their values. They are applied to these variables or arguments through the use of a pipe (**`|`**) followed by the name of the filter. For example, the following snippet will apply the [`capitalize`](https://martenframework.com/docs/next/templates/reference/filters#capitalize) filter to the output of the `name` variable, which will capitalize the value of this variable: ```html Hello, {{ name|capitalize }}! ``` It should be noted that some filters can take an argument. When this is the case, the argument is specified following a colon character (**`:`**). For example, the following snippet will apply the [`default`](https://martenframework.com/docs/next/templates/reference/filters#default) filter to the output of the `name` variable in order to fallback to a default name if the variable has a null value: ```html Hello, {{ name|default:"Stranger" }}! ``` It should be noted that the fact that an argument is supported or not, and mandatory or not, varies based on the considered filter. In all cases, filters can support up to **one** argument only. Moreover, a filter argument can either correspond to a regular [variable](#variables) or a [literal](#literal-values). Please head over to the [filters reference](https://martenframework.com/docs/next/templates/reference/filters) to see a list of all the available filters. Implementing custom filters is also a possibility that is documented in [Create custom filters](https://martenframework.com/docs/next/templates/how-to/create-custom-filters). ### Tags Tags allow to do method-calling and to run any kind of logic within a template. Some tags allow to perform control flows (like if conditions, or for loops) while others simply output values. They are delimited by **`{%`** and **`%}`**. For example, the following snippet makes use of the [`assign`](https://martenframework.com/docs/next/templates/reference/tags#assign) tag to create a new variable within a template: ```html {% assign my_var = "Hello World!" %} ``` As mentioned above, some tags allow to perform control flows and require a "closing" tag, like the [`for`](https://martenframework.com/docs/next/templates/reference/tags#for) or [`if`](https://martenframework.com/docs/next/templates/reference/tags#if) tags: ```html {% for article in articles %} {{ article.title }} is {% if !article.published? %}not {% endif %}published {% endfor %} ``` Some tags also require arguments. Similarly to filters, these arguments can either correspond to regular [variables](#variables) or [literals](#literal-values). For example, the [`url`](https://martenframework.com/docs/next/templates/reference/tags#url) template tag requires at least the name of the route for which the URL resolution should be performed: ```html {% url "my_route" %} ``` Please head over to the [tags reference](https://martenframework.com/docs/next/templates/reference/tags) to see a list of all the available template tags. Implementing custom tags is also a possibility that is documented in [Create custom tags](https://martenframework.com/docs/next/templates/how-to/create-custom-tags). ### Comments Comments can be inserted in any templates and must be surrounded by **`{#`** and **`#}`**: ```html {# This will not be evaluated #} ``` ### Whitespace control By default, tags, variables, and comments do not alter the whitespace around them in the rendered output. You can change this behavior by adding a hyphen (**`-`**) immediately after an opening delimiter or immediately before a closing delimiter. This allows to strip whitespace (spaces, tabs, and newlines) adjacent to the corresponding delimiter: | Syntax | Effect | | ------ | ------ | | `{%- ... %}` | Strips whitespace before the tag | | `{% ... -%}` | Strips whitespace after the tag | | `{{- ... }}` | Strips whitespace before the variable | | `{{ ... -}}` | Strips whitespace after the variable | | `{#- ... #}` | Strips whitespace before the comment | | `{# ... -#}` | Strips whitespace after the comment | For example, the following template: ```html {%- if username == "John Doe" -%} Wow, {{ username -}} , you have a long name! {%- else -%} Hello there! {%- endif %} ``` Would render `Wow, John Doe, you have a long name!` when `username` is set to `John Doe`, and `Hello there!` otherwise, without the indentation and extra newlines from the template source. ### Literal values The Marten templating language supports making use of literal values as part of [variables](#variables), [filter](#filters) arguments, or [tag](#tags) arguments. These literals are essentially a representation of the corresponding objects in Crystal. Each supported type of literal is listed below: | Type | Example | | ----------- | ----------- | | Nil | `{{ nil }}` | | True | `{{ true }}` | | False | `{{ false }}` | | Integer | `{{ 42 }}` | | Float | `{{ 42.45 }}` | | Single-quoted string | `{{ 'Hello World' }}` | | Double-quoted string | `{{ "Hello World" }}` | ## Template inheritance Templates can inherit from each other: this allows you to easily define a "base" template containing the layout of your application so that you can reuse it in order to build other templates, which helps in keeping your codebase DRY. This works as follows: * a "base" template defines the shared layout as well as "blocks" where child templates will actually inject their own contents * "child" templates "extend" from the base template and explicitly define the contents of the "blocks" that are expected by the base template For example, a "base" template could look like this: ```html {% block title %}My super website{% endblock %} {% block content %}{% endblock %} ``` Here the base template defines two blocks by using the [`block`](https://martenframework.com/docs/next/templates/reference/tags#block) template tag. Using this tag essentially makes it possible for any child templates to "override" the content of these blocks. :::tip Note that it is possible to specify the name of the block being closed in the `endblock` tag to improve readability. For example: ```html {% block title %} My super website {% endblock title %} ```` ::: Given the above base template (that we assume is named `base.html`), a "child" template making use of it could look like this: ```html {% extend "base.html" %} {% block title %}Custom page title{% endblock %} {% block content %}Custom page content{% endblock %} ``` Here we make use of the [`extend`](https://martenframework.com/docs/next/templates/reference/tags#extend) template tag in order to indicate that we want to inherit from the `base.html` template that we created previously. When Marten encounters this tag, it'll make sure that the targeted template is properly loaded before resuming the evaluation of the current template. :::warning The `{% extend %}` tag should always be called at the top of the file, before the actual content of the template. Inheritance won't work properly if that's not the case. ::: We also use [`block`](https://martenframework.com/docs/next/templates/reference/tags#block) tags to redefine the content of the blocks that were defined in the `base.html` template. It should be noted that if a child template does not define the content of one of its parent's blocks, the default content of this block will be used instead (if there is one!). :::info You can use many levels of template inheritance if needed. Indeed, a `child.html` template can very well extend a `base_dashboard.html` template, which itself extends a `base.html` template for example. ::: It should be noted that it is also possible to get the content of a block from a parent template by using the `super` template tag. This can be useful in situations where blocks in a child template need to extend (add content) to a parent's block content instead of overwriting it. For example, with the following snippet the output of the `title` block would be "My super website - Example page": ```html {% extend "base.html" %} {% block title %}{% super %} - Example page{% endblock %} {% block content %}Custom page content{% endblock %} ``` It's important to remember that the `super` template tag can only be used within `block` tags. ## Template inclusion Templates can "include" other templates easily through the use of the [`include`](https://martenframework.com/docs/next/templates/reference/tags#include) template tag. Such templates are usually referred to as "partials": these are template snippets that can be easily "included" into other templates to avoid duplications of code. Included templates are rendered using the context of the including template. This means that all the variables that are provided to the including template can also be used as part of the included template. In addition to that, other specific variables can also be defined when including a specific template. For example, let's assume that a project defines the following partial template: ```html name="src/templates/partials/button.html ``` This partial could be included as follows in the following template: ```html {% include "partials/button.html" with type="primary" %} {% include "partials/button.html" with type="primary", text="Custom text" %} ``` Note the use of the `with` keyword to specify comma-separated variables that should be used to populate the included template's context. Obviously, it is also possible to include partials that don't require any variables. In that case, the use of the `with` keyword is not necessary: ```html {% include "partials/other_snippet.html" %} ``` ## Template loading Templates can be loaded from specific locations within your codebase and from application folders. This is controlled by two main settings: * [`templates.app_dirs`](https://martenframework.com/docs/next/development/reference/settings#app_dirs-1) is a boolean that indicates whether or not it should be possible to load templates that are provided by [installed applications](https://martenframework.com/docs/next/development/reference/settings#installed_apps). Indeed, applications can define a `templates` folder at their root, and these templates will be discoverable by Marten if this setting is set to `true` * [`templates.dirs`](https://martenframework.com/docs/next/development/reference/settings#dirs-1) is an array of additional directories where templates should be looked for Application templates are always enabled by default (`templates.app_dirs = true`) for new Marten projects. It is possible to programmatically load a template by name. To do so, you can use the [`#get_template`](https://martenframework.com/docs/api/dev/Marten/Template/Engine.html#get_template(template_name%3AString)%3ATemplate-instance-method) method that is provided by the Marten templates engine: ```crystal Marten.templates.get_template("foo/bar.html") ``` This will return a compiled [`Template`](https://martenframework.com/docs/api/dev/Marten/Template/Template.html) object that you can then render by using a specific context. :::tip Customizing template loaders The [`templates.loaders`](https://martenframework.com/docs/next/development/reference/settings#loaders) setting provides fine-grained control over how Marten discovers and loads templates. This setting expects an array of template loader classes, which must inherit from `Marten::Template::Loader::Base`. This setting will overwrite the default template loaders configured by Marten. This gives you the option to configure [custom loaders](https://martenframework.com/docs/next/templates/how-to/create-custom-loaders) to load templates from different sources, such as databases or in-memory data structures. Example: Configuring a File System Loader ```crystal config.templates.loaders = [Marten::Template::Loader::FileSystem.new("/path/to/templates")] of Marten::Template::Loader::Base ``` ::: ## Rendering a template You won't usually need to interact with the "low-level" API of the Marten template engine in order to render templates: most of the time you will render templates as part of [handlers](https://martenframework.com/docs/next/handlers-and-http), which means that you will likely end up using the [`#render`](https://martenframework.com/docs/next/handlers-and-http/introduction#render) shortcut or [generic handlers](https://martenframework.com/docs/next/handlers-and-http/generic-handlers) that automatically render templates for you. That being said, it is also possible to render any [`Template`](https://martenframework.com/docs/api/dev/Marten/Template/Template.html) object that you loaded by leveraging the [`#render`](https://martenframework.com/docs/api/dev/Marten/Template/Template.html#render(context%3AHash|NamedTuple)%3AString-instance-method) method. This method can be used either with a Marten context object, a hash, or a named tuple: ```crystal template = Marten.templates.get_template("foo/bar.html") template.render(Marten::Template::Context{"foo" => "bar"}) template.render({"foo" => "bar"}) template.render({ foo: "bar" }) ``` ## Using enums in contexts [Enum](https://crystal-lang.org/api/Enum.html) classes cannot be part of union types in Crystal. Because of this limitation, enum values are replaced by special objects in Marten templates. These objects always resolve to the integer value of the corresponding enum value. For example, let's consider the following enum: ```crystal enum Color Red Green Blue end ``` If a `color` variable is set to `Color::Red`, then the following template will output `0`: ```html {{ color }} ``` It's important to note that enum values within Marten templates can be compared with each other, yielding the same results as comparing enum values in Crystal. Additionally, `?` helper properties can be invoked on enum values within templates, simplifying the process of determining the type of the enum value being considered. For instance: ```html {% if color.red? %} This is the red color. {% endif %} ``` ## Using custom objects in contexts Most objects that are provided by Marten (such as Model records, query sets, schemas, etc) can automatically be used as part of templates. If your project involves other custom classes, and if you would like to interact with such objects in your templates, then you will need to explicitly ensure that they include the [`Marten::Template::Object`](https://martenframework.com/docs/api/dev/Marten/Template/Object.html) module. :::note Why? Crystal being a statically typed language, the Marten engine needs to know which types of objects it is dealing with in advance in order to know (i) what can go into template contexts and (ii) how to "resolve" object attributes when templates are rendered. It is not possible to simply expect any `Object` object, hence why we need to make use of a shared [`Marten::Template::Object`](https://martenframework.com/docs/api/dev/Marten/Template/Object.html) module to account for all the classes whose objects should be usable as part of template contexts. ::: Let's take the example of a `Point` class that provides access to an x-coordinate and a y-coordinate: ```crystal class Point getter x getter y def initialize(@x : Int32, @y : Int32) end end ``` By default, `Point` objects cannot be used as part of templates. Let's say we want to render the following template involving a `point` variable: ```html My point is: {{ point.x }}, {{ point.y }} ``` If you try to render such a template while passing a `Point` object into the template context, you will encounter a `Marten::Template::Errors::UnsupportedValue` exception stating: ``` Unable to initialize template values from Point objects ``` To remediate this, you will have to include the [`Marten::Template::Object`](https://martenframework.com/docs/api/dev/Marten/Template/Object.html) module in the `Point` class and define a `#resolve_template_attribute` method as follows: ```crystal class Point include Marten::Template::Object getter x getter y def initialize(@x : Int32, @y : Int32) end def resolve_template_attribute(key : String) case key when "x" x when "y" y end end end ``` Each class including the [`Marten::Template::Object`](https://martenframework.com/docs/api/dev/Marten/Template/Object.html) module must also implement a `#resolve_template_attribute` method in order to allow resolutions of object attributes when templates are rendered (for example `{{ point.x }}`). That being said, there are a few shortcuts that can be used in order to avoid writing such methods. The first one is to use the [`#template_attributes`](https://martenframework.com/docs/api/dev/Marten/Template/Object.html#template_attributes(*names)-macro) macro in order to easily define the names of the methods that should be made available to the template runtime. For example, such macro could be used like this with our `Point` class: ```crystal class Point include Marten::Template::Object getter x getter y def initialize(@x : Int32, @y : Int32) end template_attributes :x, :y end ``` Another possibility is to include the [`Marten::Template::Object::Auto`](https://martenframework.com/docs/api/dev/Marten/Template/Object/Auto.html) module instead of the [`Marten::Template::Object`](https://martenframework.com/docs/api/dev/Marten/Template/Object.html) one in your class. This module will automatically ensure that every "attribute-like" public method that is defined in the including class can also be accessed in templates when performing variable lookups. ```crystal class Point include Marten::Template::Object::Auto getter x getter y def initialize(@x : Int32, @y : Int32) end end ``` Note that **all** "attribute-like" public methods will be made available to the template runtime when using the [`Marten::Template::Object::Auto`](https://martenframework.com/docs/api/dev/Marten/Template/Object/Auto.html) module. This may be a good enough behavior, but if you want to have more control over what can be accessed in templates or not, you will likely end up using [`Marten::Template::Object`](https://martenframework.com/docs/api/dev/Marten/Template/Object.html) and the [`#template_attributes`](https://martenframework.com/docs/api/dev/Marten/Template/Object.html#template_attributes(*names)-macro) macro instead. ## Using context producers Context producers are helpers that ensure that common variables are automatically inserted in the template context whenever a template is rendered. They are applied every time a new template context is generated. For example, they can be used to insert the current HTTP request object in every template context being rendered in the context of a handler and HTTP request. This makes sense considering that the HTTP request object is a common object that is likely to be used by multiple templates in your project: that way there is no need to explicitly "insert" it in the context every time you render a template. This specific capability is provided by the [`Marten::Template::ContextProducer::Request`](https://martenframework.com/docs/api/dev/Marten/Template/ContextProducer/Request.html) context producer, which inserts a `request` object into every template context. Template context producers can be configured through the use of the [`templates.context_producers`](https://martenframework.com/docs/next/development/reference/settings#context_producers) setting. When generating a new project by using the `marten new` command, the following context producers will be automatically configured: ```crystal config.templates.context_producers = [ Marten::Template::ContextProducer::Request, Marten::Template::ContextProducer::Flash, Marten::Template::ContextProducer::Debug, Marten::Template::ContextProducer::I18n, ] ``` Each context producer in this array will be applied in order when a new template context is created and will contribute "common" context values to it. This means that the order of these is important since context producers can technically overwrite the values that were added by previous context producers. Please head over to the [context producers reference](https://martenframework.com/docs/next/templates/reference/context-producers) to see a list of all the available context producers. Implementing custom context producers is also a possibility that is documented in [Create custom context producers](https://martenframework.com/docs/next/templates/how-to/create-custom-context-producers). ## Auto-escaping The output of template variables is automatically escaped by Marten in order to prevent Cross-Site Scripting (XSS) vulnerabilities. For example, let's consider the following snippet: ```html Hello, {{ name }}! ``` If this template is rendered with `` as the content of the `name` variable, then the output will be: ```html Hello, <script>alert('popup')</script>! ``` It should be noted that this behavior can be disabled _explicitly_. Indeed, sometimes it is expected that some template variables will contain trusted HTML content that you intend to embed into the template's HTML. To do this, it is possible to make use of the [`safe`](https://martenframework.com/docs/next/templates/reference/filters#safe) template filter. This filter "marks" the output of a variable as safe, which ensures that its content is not escaped before being inserted in the final output of a rendered template. For example: ```html Hello, {{ name }}! Hello, {{ name|safe }}! ``` When rendered with `John` as the content of the `name` variable, the above template will output: ```html Hello, <b>John</b>! Hello, John! ``` ## Strict variables By default, when a template variable is unknown or undefined, Marten treats it as a `nil` value. Consequently, nothing will be displayed for such variables, and they will be evaluated as falsey in if conditions. However, it is possible to modify this behavior by enabling the [`templates.strict_variables`](https://martenframework.com/docs/next/development/reference/settings#strict_variables) setting. When this setting is set to `true`, unknown variables encountered in templates will raise [`Marten::Template::Errors::UnknownVariable`](https://martenframework.com/docs/api/dev/Marten/Template/Errors/UnknownVariable.html) exceptions. # Create custom template filters Source: https://martenframework.com/docs/next/templates/how-to/create-custom-filters Marten has built-in support for common [template filters](https://martenframework.com/docs/next/templates/reference/filters), but the framework also allows you to write your own template filters that you can leverage as part of your project's templates. ## Defining a template filter Filters are subclasses of the [`Marten::Template::Filter::Base`](https://martenframework.com/docs/api/dev/Marten/Template/Filter/Base.html) abstract class. They must implement a single `#apply` method: this method takes the value the filter should be applied to (a [`Marten::Template::Value`](https://martenframework.com/docs/api/dev/Marten/Template/Value.html) object wrapping _any_ of the object types supported by templates) and an optional argument that was specified to the filter. For example, in the expression `{{ var|test:42 }}`, the `test` filter would be called with the value of the `var` variable and the filter argument `42`. Let's say we want to write an `underscore` template filter: this template won't need any arguments and will simply return the "underscore" version of the string representation of the incoming value. Such filter could be defined as follows: ```crystal class UnderscoreFilter < Marten::Template::Filter::Base def apply(value : Marten::Template::Value, arg : Marten::Template::Value? = nil) : Marten::Template::Value Marten::Template::Value.from(value.to_s.underscore) end end ``` As you can see, the `#apply` method must return a [`Marten::Template::Value`](https://martenframework.com/docs/api/dev/Marten/Template/Value.html) object. Now let's try to write a `chomp` template filter that actually makes use of the specified argument. In this case, the argument will be used to define the suffix that should be removed from the end of the string representation of the incoming value: ```crystal class ChompFilter < Marten::Template::Filter::Base def apply(value : Marten::Template::Value, arg : Marten::Template::Value? = nil) : Marten::Template::Value raise Marten::Template::Errors::InvalidSyntax.new("The 'chomp' filter requires one argument") if arg.nil? Marten::Template::Value.from(value.to_s.chomp(arg.not_nil!.to_s)) end end ``` :::info You should feel free to raise [`Marten::Template::Errors::InvalidSyntax`](https://martenframework.com/docs/api/dev/Marten/Template/Errors/InvalidSyntax.html) from a filter's `#apply` method: this is especially relevant if the input has an unexpected type or if an argument is missing. That being said, it should be noted that any exception raised from a template filter won't be handled by the template engine and will result in a server error (unless explicitly handled by the application itself). ::: ### `Marten::Template::Value` objects As highlighted previously, template filters mainly interact with [`Marten::Template::Value`](https://martenframework.com/docs/api/dev/Marten/Template/Value.html) objects: they take such objects as parameters (for the incoming value the filter should be applied to and for the optional filter parameter), and they must return such objects as well. [`Marten::Template::Value`](https://martenframework.com/docs/api/dev/Marten/Template/Value.html) objects can be created from any supported object by using the `#from` method as follows: ```crystal Marten::Template::Value.from("hello") Marten::Template::Value.from(42) Marten::Template::Value.from(true) ``` These objects are essentially "wrappers" around a real value that is manipulated as part of a template's runtime, and they provide a common interface allowing to interact with these during the template rendering. Your filter implementation can perform checks on the incoming [`Marten::Template::Value`](https://martenframework.com/docs/api/dev/Marten/Template/Value.html) objects if necessary: eg. in order to verify that the underlying value is of the expected type. In this light, it is possible to make use of the `#raw` method to retrieve the real value that is wrapped by the [`Marten::Template::Value`](https://martenframework.com/docs/api/dev/Marten/Template/Value.html) object: ```crystal value = Marten::Template::Value.from("hello") value.raw # => "hello" ``` ### Filters and HTML auto-escaping When writing filters that are intended to operate on strings, it is important to remember that [HTML is automatically escaped](https://martenframework.com/docs/next/templates/introduction#auto-escaping) in templates. As such, some string values might be flagged as "safe" and some others as "unsafe": * regular `String` values are always assumed to be "unsafe" and will be automatically escaped by Marten's template engine * safe strings are wrapped in `Marten::Template::SafeString` objects This means that if your filter needs to have a different behavior based on the fact that a string is safe or not, then you will have to verify what is the type of the underlying value (by relying on the `#raw` method as explained in the previous section). It is the filter's responsibility to ensure that an incoming "safe string" is returned as a "safe string" as well or simply converted to a regular string that will be auto-escaped. Creating safe strings is simply a matter of initializing `Marten::Template::SafeString` from a regular string: ```crystal class SafeFilter < Marten::Template::Filter::Base def apply(value : Marten::Template::Value, arg : Marten::Template::Value? = nil) : Marten::Template::Value Marten::Template::Value.from(Marten::Template::SafeString.new(value.to_s)) end end ``` ## Registering template filters To be able to use custom template filters, you must register them to Marten's global template filters registry. To do so, you will have to call the [`Marten::Template::Filter#register`](https://martenframework.com/docs/api/dev/Marten/Template/Filter.html#register(filter_name%3AString|Symbol%2Cfilter_klass%3ABase.class)-class-method) method with the name of the filter you wish to use in templates, and the filter class. For example: ```crystal Marten::Template::Filter.register("underscore", UnderscoreFilter) ``` With the above registration, you could technically use this filter as follows: ```html {{ my_var|underscore }} ``` # Create custom template tags Source: https://martenframework.com/docs/next/templates/how-to/create-custom-tags Marten has built-in support for common [template tags](https://martenframework.com/docs/next/templates/reference/tags), but the framework also allows you to write your own template tags that you can leverage as part of your project's templates. ## Defining a template tag Template tags are subclasses of the [`Marten::Template::Tag::Base`](https://martenframework.com/docs/api/dev/Marten/Template/Tag/Base.html) abstract class. When writing custom template tags, you will usually want to define two methods in your tag classes: the `#initialize` and the `#render` methods. These two methods are called at different moments in a template's lifecycle: * the `#initialize` method is used to initialize a template tag object and it is called at **parsing time**: this means that it is the responsibility of this method to ensure that the content of the template tag is valid from a parsing standpoint * the `#render` method is called at **rendering time** to apply the tag's logic: this means that the method is only called for valid template tag statements that were parsed without errors Since tags are created and processed when the template is parsed, they can theoretically be used to implement any kind of behavior. That being said, there are a few patterns that are frequently used when writing tags that you might want to consider to help you get started: * **simple tags:** tags outputting a value that can (optionally) be assigned to a new variable * **inclusion tags:** tags including and rendering other templates * **closable tags:** tags involving closing statements and doing something with the output of a block ### Simple tags Simple tags usually output a value while allowing this value to be assigned to a new variable (that will be added to the template context). They can eventually take arguments in order to return the right result at rendering time. Let's take the example of a `local_time` template tag that outputs the string representation of the local time and that takes one mandatory argument (the [format](https://crystal-lang.org/api/Time/Format.html) used to output the time). Such a template tag could be implemented as follows: ```crystal class LocalTimeTag < Marten::Template::Tag::Base include Marten::Template::Tag::CanSplitSmartly @assigned_to : String? = nil def initialize(parser : Marten::Template::Parser, source : String) parts = split_smartly(source) if parts.size < 2 raise Marten::Template::Errors::InvalidSyntax.new( "Malformed local_time tag: one argument must be provided" ) end @pattern_expression = Marten::Template::FilterExpression.new(parts[1]) # Identify possible assigned variable name. if parts.size > 2 && parts[-2] == "as" @assigned_to = parts[-1] elsif parts.size > 2 raise Marten::Template::Errors::InvalidSyntax.new( "Malformed local_time tag: only one argument must be provided" ) end end def render(context : Marten::Template::Context) : String time_pattern = @pattern_expression.resolve(context).to_s local_time = Time.local(Marten.settings.time_zone).to_s(time_pattern) if @assigned_to.nil? local_time else context[@assigned_to.not_nil!] = local_time "" end end end ``` As you can see template tags are initialized from a parser (instance of [Marten::Template::Parser](https://martenframework.com/docs/api/dev/Marten/Template/Parser.html)) and the raw "source" of the template tag (that is the content between the `{%` and `%}` tag delimiters). The `#initialize` method is responsible for extracting any information that might be necessary to implement the template tag's logic. In the case of the `local_time` template tag, we must take care of a few things: * ensure that we have a format specified as argument (and raise an invalid syntax error otherwise) * initialize a filter expression (instance of [Marten::Template::FilterExpression](https://martenframework.com/docs/api/dev/Marten/Template/FilterExpression.html)) from the format argument: this is necessary because the argument can be a string literal or variable with filters applied to it * verify if the output of the template tag is assigned to a variable by looking for an `as` statement: if that's the case the name of the variable is persisted in a dedicated instance variable The `#render` method is called at rendering time: it takes the current context object as argument and must return a string. In the above example, this method "resolves" the time format expression that was identified at initialization time from the context (which is necessary if it was a variable) and generates the right time representation. If the tag wasn't specified with an `as` variable, then this value is simply returned, otherwise, it is persisted in the context and an empty string is returned. ### Inclusion tags Inclusion tags are similar to simple tags: they can take arguments (mandatory or not), and assign their outputs to variables, but the difference is that they render a template in order to produce the final output. Let's take the example of a `list` template tag that outputs the elements of an array in a regular `ul` HTML tag. The template being rendered by such template tag could look like this: ```html title=path/to/list_tag.html
    {% for item in list %}
  • {{ item }}
  • {% endfor %}
``` And the template tag itself could be implemented as follows: ```crystal class ListTag < Marten::Template::Tag::Base include Marten::Template::Tag::CanSplitSmartly @assigned_to : String? = nil def initialize(parser : Marten::Template::Parser, source : String) parts = split_smartly(source) if parts.size < 2 raise Marten::Template::Errors::InvalidSyntax.new( "Malformed list tag: one argument must be provided" ) end @list_expression = Marten::Template::FilterExpression.new(parts[1]) # Identify possible assigned variable name. if parts.size > 2 && parts[-2] == "as" @assigned_to = parts[-1] elsif parts.size > 2 raise Marten::Template::Errors::InvalidSyntax.new( "Malformed list tag: only one argument must be provided" ) end end def render(context : Marten::Template::Context) : String template = Marten.templates.get_template("path/to/list_tag.html") rendered = "" context.stack do |include_context| include_context["list"] = @list_expression.resolve(context) rendered = template.render(include_context) end if @assigned_to.nil? Marten::Template::SafeString.new(rendered) else context[@assigned_to.not_nil!] = rendered "" end end end ``` As you can see, the implementation of this tag looks quite similar to the one highlighted in [Simple tags](#simple-tags). The only differences that are worth noting here are: 1. the argument of the template tag corresponds to the list of items that should be rendered 2. the `#render` method explicitly renders the template mentioned previously by using a context with the "list" object in it (the [`#stack`](https://martenframework.com/docs/api/dev/Marten/Template/Context.html#stack(%26)%3ANil-instance-method) method allows to create a new context where new values are stacked over the existing ones). The output of this rendering operation is either assigned to a variable or returned directly depending on whether the `as` statement was used ### Closable tags Closable tags involve a closing statement, like this is the case for the `{% block %}...{% endblock %}` template tag for example. Usually, such tags will "capture" all the nodes between the opening tag and the closing tag, render them at rendering time, and do something with the output of this rendering. To illustrate this, let's take the example of a `spaceless` tag that will remove whitespaces, tabs and new lines between HTML tags. Such a template tag could be implemented as follows: ```crystal class SpacelessTag < Marten::Template::Base @inner_nodes : Marten::Template::NodeSet def initialize(parser : Marten::Template::Parser, source : String) @inner_nodes = parser.parse(up_to: %w(endspaceless)) parser.shift_token end def render(context : Marten::Template::Context) : String @inner_nodes.render(context).strip.gsub(/>\s+<") end end ``` In this example, the `#initialize` method explicitly calls the parser's [`#parse`](https://martenframework.com/docs/api/dev/Marten/Template/Parser.html#parse(up_to%3AArray(String)%3F%3Dnil)%3ANodeSet-instance-method) in order to parse the following "nodes" up to the expected closing tag (`endspaceless` in this case). If the specified closing tag is not encountered, the parser will automatically raise a syntax error. The obtained nodes are returned as a "node set" (instance of [`Marten::Template::NodeSet`](https://martenframework.com/docs/api/dev/Marten/Template/NodeSet.html)): this is a special object returned by the template parser that maps to multiple parsed nodes (those can be tags, variables, or plain text values) that can be rendered through a [`#render`](https://martenframework.com/docs/api/dev/Marten/Template/NodeSet.html#render(context%3AContext)-instance-method) method at rendering time. The `#render` method of the above tag is relatively simple: it simply "renders" the node set corresponding to the template nodes that were extracted between the `{% spaceless %}...{% endspaceless %}` tags and then removes any whitespaces between the HTML tags in the output. ## Registering template tags In order to be able to use custom template tags, you must register them to Marten's global template tags registry. To do so, you will have to call the [`Marten::Template::Tag#register`](https://martenframework.com/docs/api/dev/Marten/Template/Tag.html#register(tag_name%3AString|Symbol%2Ctag_klass%3ABase.class)-class-method) method with the name of the tag you wish to use in templates, and the template tag class. For example: ```crystal Marten::Template::Tag.register("local_time", LocalTimeTag) ``` With the above registration, you could technically use this tag (the one from the above [Simple tags](#simple-tags) section) as follows: ```html {% local_time "%Y-%m-%d %H:%M:%S %:z" %} ``` # Create custom context producers Source: https://martenframework.com/docs/next/templates/how-to/create-custom-context-producers Marten has built-in support for common [context producers](https://martenframework.com/docs/next/templates/reference/context-producers), but the framework also allows you to write your own context producers that you can leverage as part of your project's templates. This allows you to easily reuse common context values over multiple templates. ## Defining a context producer Defining a context producer involves creating a subclass of the [`Marten::Template::ContextProducer`](https://martenframework.com/docs/api/dev/Marten/Template/ContextProducer.html) abstract class. This abstract class requires that subclasses implement a single [`#produce`](https://martenframework.com/docs/api/dev/Marten/Template/ContextProducer.html#produce(request%3AHTTP%3A%3ARequest%3F%3Dnil)-instance-method) method: this method takes an optional request object as argument and must return either: * a hash or a named tuple containing the values to contribute to the template context * or `nil` if no values can be generated for the passed request For example, the following context producer would expose the value of the [`debug`](https://martenframework.com/docs/next/development/reference/settings#debug) setting to all the template contexts being created: ```crystal class Debug < Marten::Template::ContextProducer def produce(request : Marten::HTTP::Request? = nil) {"debug" => Marten.settings.debug} end end ``` ## Activating context producers As mentioned in [Using context producers](https://martenframework.com/docs/next/templates/introduction#using-context-producers), context producers classes must be added to the [`templates.context_producers`](https://martenframework.com/docs/next/development/reference/settings#context_producers) setting in order to be used by the Marten templates engine when initializing new context objects. # Create custom template loaders Source: https://martenframework.com/docs/next/templates/how-to/create-custom-loaders Marten has built-in support for [common template loaders](https://martenframework.com/docs/next/templates/reference/loaders), but the framework also allows you to write your own template loader that you can leverage as part of your project's templates. ## Defining a template loaders Template loaders are subclasses of the [`Marten::Template::Loader::Base`](https://martenframework.com/docs/api/dev/Marten/Template/Loader/Base.html) abstract class. They must implement a single `#get_template_source` method: this method returns the raw content of a template from a provided template name. For example, rendering the template `content.html` with a file system loader initialised with `Marten::Template::Loader::FileSystem.new("/app/custom_dir/templates")` would return the content defined in `/app/custom_dir/templates/content.html`. Let's say we want to write a `DatabaseTemplate` template loader: we first have to define a new class which inherits from `Marten::Template::Loader::Base`. This new class needs to define a `#get_template_source` method which takes a `template_name` string argument and also returns a string. For simplicity we assume that there already exists an `HtmlTemplate` model, featuring a `name` field and `content` field: ```crystal class DatabaseTemplate < Marten::Template::Loader::Base def get_template_source(template_name) : String begin return HtmlTemplate.get!(name: template_name).content! rescue e : Marten::DB::Errors::RecordNotFound raise Marten::Template::Errors::TemplateNotFound.new("Template #{template_name} could not be found ; #{e.message}", e) end end end ``` # Template filters Source: https://martenframework.com/docs/next/templates/reference/filters This page provides a reference for all the available filters that can be used when defining [templates](https://martenframework.com/docs/next/templates/introduction). ## `capitalize` The `capitalize` filter allows to modify a string so that the first letter is converted to uppercase and all the subsequent letters are converted to lowercase. For example: ```html {{ value|capitalize }} ``` If `value` is "marten", the output will be "Marten". ## `default` The `default` filter allows to fallback to a specific value if the left side of the filter expression is empty or not truthy. A filter argument is mandatory. It should be noted that empty strings are considered truthy and will be returned by this filter. For example: ```html {{ value|default:"foobar" }} ``` If `value` is `nil` (or `0` or `false`), the output will be "foobar". ## `downcase` The `downcase` filter allows to convert a string so that each of its characters is lowercase. For example: ```html {{ value|downcase }} ``` If `value` is "Hello", then the output will be "hello". ## `escape` The `escape` filter replaces special characters (namely `&`, `<`, `>`, `"` and `'`) in the template variable with their corresponding HTML entities. For example: ```html {{ value|escape }} ``` If `value` is `Let's do it`, then the output will be `<b>Let's do it</b>`. ## `join` The `join` filter converts an array of elements into a string separated by `arg`. For example: ```html {{ value|join: arg }} ``` If `value` is `["Bananas","Apples","Oranges"]` and `arg` is `, `, then the output will be "Bananas, Apples, Oranges". ## `linebreaks` The `linebreaks` filter allows to convert a string replacing all newlines with HTML line breaks (`
`). For example: ```html {{ value|linebreaks }} ``` If `value` is `Hello\nWorld`, then the output will be `Hello
World`. ## `safe` The `safe` filter allows to mark that a string is safe and that it should not be escaped before being inserted in the final output of a rendered template. Indeed, string values are always automatically HTML-escaped by default in templates. For example: ```html {{ value|safe }} ``` If `value` is `

Hello

`, then the output will be `

Hello

` as well. ## `size` The `size` filter allows returning the size of a string or an enumerable object. For example: ```html {{ value|size }} ``` ## `split` The `split` filter converts a string into an array of elements separated by `arg`. For example: ```html {{ value|split: arg }} ``` If `value` is `Bananas,Apples,Oranges` and `arg` is `,`, then the output will be ["Bananas","Apples","Oranges"]. ## `time` The `time` filter allows outputting the string representation of a time variable. It requires the specification of a filter argument, which is the format string used to format the time (whose available directives are part of [`Time::Format`](https://crystal-lang.org/api/Time/Format.html)). ```html {{ value | time: "%Y-%m-%d" }} ``` In the above example, the output will be a date string such as `2023-09-25`. ## `truncate` The `truncate` filter truncates a string so that it fits within a maximum number of characters. A filter argument corresponding to that maximum size is mandatory. Truncated strings end with an ellipsis (`"..."`), and that ellipsis is included in the resulting size. For example: ```html {{ value|truncate:15 }} ``` If `value` is "This is a long test sentence", then the output will be "This is a lo...". ## `underscore` The `underscore` filter allows to convert a string to its underscored version. For example: ```html {{ value|underscore }} ``` If `value` is "FooBar", then the output will be "foo_bar". ## `upcase` The `upcase` filter allows to convert a string so that each of its characters is uppercase. For example: ```html {{ value|upcase }} ``` If `value` is "Hello", then the output will be "HELLO". # Template tags Source: https://martenframework.com/docs/next/templates/reference/tags This page provides a reference for all the available tags that can be used when defining [templates](https://martenframework.com/docs/next/templates/introduction). ## `asset` The `asset` template tag allows to generate the URL of a given [asset](https://martenframework.com/docs/next/assets/introduction). It must take at least one argument (the filepath of the asset). For example, the following line is a valid usage of the `asset` tag and will output the path or URL of the `app/app.css` asset: ```html {% asset "app/app.css" %} ``` Optionally, resolved asset URLs can be assigned to a specific variable using the `as` keyword: ```html {% asset "app/app.css" as my_var %} ``` ## `assign` The `assign` template tag allows to define a new variable that will be stored in the template's context. For example: ```html {% assign my_var = "Hello World!" %} ``` By default, variables assigned using this template tag will overwrite any existing variables with the same name in the template context. To prevent overwriting existing variables, you can append `unless assigned` after the assignment to ensure that new variables are only assigned if there isn't already one with the same name present. For example: ```html {% assign my_var = "Hello World!" unless defined %} ``` ## `block` The `block` template tag allows to define that some specific portions of a template can be overridden by child templates. This tag is only useful when used in conjunction with the [`extend`](#extend) tag. See [Template inheritance](https://martenframework.com/docs/next/templates/introduction#template-inheritance) to learn more about this capability. ## `cache` The `cache` template tag allows to cache the content of a template fragment (enclosed within the `{% cache %}...{% endcache %}` tags) for a specific duration. This caching operation is done by leveraging the configured [cache store](https://martenframework.com/docs/next/caching/introduction#configuration-and-cache-stores). At least a cache key and and a cache expiry (expressed in seconds) must be specified when using this tag: ```html {% cache "mykey" 3600 %} Cached content! {% endcache %} ``` It should be noted that the `cache` template tag also supports specifying additional "vary on" arguments that allow to invalidate the cache based on the value of other template variables: ```html {% cache "mykey" 3600 current_locale user.id %} Cached content! {% endcache %} ``` ## `capture` The `capture` template tag allows to define that the output of a block of code should be stored in a new variable. For example: ```html {% capture my_var %} Hello World, {{ name }}! {% endcapture %} ``` Assuming the variable `name` is assigned the value "John Doe" upon rendering this snippet, the variable `my_var` will hold the string "Hello World, John Doe!". By default, variables assigned using this template tag will overwrite any existing variables with the same name in the template context. To prevent overwriting existing variables, you can append `unless assigned` after the variable name to ensure that new variables are only assigned if there isn't already one with the same name present. For example: ```html {% capture my_var unless defined %} Hello World, {{ name }}! {% endcapture %} ``` ## `csrf_input` The `csrf_input` template tag allows generating a hidden HTML input containing the CSRF token (computed for the request at hand). This tag can only be used in templates that are rendered as part of a handler (for example by leveraging [`#render`](https://martenframework.com/docs/next/handlers-and-http/introduction#render) or one of the [generic handlers](https://martenframework.com/docs/next/handlers-and-http/generic-handlers) involving rendered templates). This can be used to ensure the CSRF token gets inserted into a form so that it gets sent to the handler processing the form data for example. Indeed, handlers will automatically perform a CSRF check in order to protect unsafe requests (ie. requests whose methods are not `GET`, `HEAD`, `OPTIONS`, `QUERY`, or `TRACE`): ```html
{% csrf_input %}
``` The above template will output the following HTML: ```html
// highlight-next-line
``` Where `` is the actual CSRF token. See [Cross-Site Request Forgery protection](https://martenframework.com/docs/next/security/csrf) to learn more about this. Optionally, the output of the `csrf_input` template tag can be assigned to a specific variable using the `as` keyword: ```html {% csrf_input as my_var %} ``` ## `csrf_token` The `csrf_token` template tag allows to compute and insert the value of the CSRF token into a template. This tag can only be used in templates that are rendered as part of a handler (for example by leveraging [`#render`](https://martenframework.com/docs/next/handlers-and-http/introduction#render) or one of the [generic handlers](https://martenframework.com/docs/next/handlers-and-http/generic-handlers) involving rendered templates). This can be used to insert the CSRF token into a hidden form input so that it gets sent to the handler processing the form data for example. Indeed, handlers will automatically perform a CSRF check in order to protect unsafe requests (ie. requests whose methods are not `GET`, `HEAD`, `OPTIONS`, `QUERY`, or `TRACE`): ```html
``` See [Cross-Site Request Forgery protection](https://martenframework.com/docs/next/security/csrf) to learn more about this. Optionally, the output of the `csrf_token` template tag can be assigned to a specific variable using the `as` keyword: ```html {% csrf_token as my_var %} ``` ## `escape` The `escape` tag is used to enable or disable [auto-escaping](https://martenframework.com/docs/next/templates/introduction#auto-escaping) for a block of code. It takes one argument, either `on` or `off`, to enable or disable auto-escaping, respectively. For example: ```html {% escape off %}
{{ article.html_body }}
{% endescape %} ``` ## `extend` The `extend` template tag allows to define that a template inherits from a specific base template. This tag must be used with one mandatory argument, which can be either a string literal or a variable that will be resolved at runtime. This mechanism is useful only if the base template defines [blocks](#block) that are overridden or extended by the child template. See [Template inheritance](https://martenframework.com/docs/next/templates/introduction#template-inheritance) to learn more about this capability. ## `filter` The `filter` template tag allows to apply one or more [filters](https://martenframework.com/docs/next/templates/reference/filters) to the content of a block. Multiple filters can be specified with pipes and filters can have arguments, just as in variable syntax. It should be noted that the `filter` template tag requires a closing `endfilter` tag. For example: ```html {% filter upcase %} Hello {{ name }}! {% endfilter %} ``` ```html {% filter upcase|truncate:10 %} Hello {{ name }}! {% endfilter %} ``` The [`escape`](https://martenframework.com/docs/next/templates/reference/filters#escape) and [`safe`](https://martenframework.com/docs/next/templates/reference/filters#safe) filters are not acceptable arguments. Instead, use the [`escape`](#escape) tag to manage auto-escaping for blocks of template code. ## `for` The `for` template tag allows to loop over the items of iterable objects and it also handles fallbacks through the use of the `else` inner block. It should be noted that the `for` template tag requires a closing `endfor` tag. For example: ```html {% for item in items %} Display {{ item }} {% else %} No items! {% endfor %} ``` It should be noted that `for` loops support unpacking multiple items when applicable (eg. when iterating over hashes or enumerables containing arrays or tuples): ```html {% for label, url in navigation_items %} {{ label }} {% endfor %} ``` Finally, loops give access to a special `loop` variable _inside_ the loop in order to expose information about the iteration process: | Variable | Description | | -------- | ----------- | | `loop.index` | The index of the current iteration (1-indexed) | | `loop.index0` | The index of the current iteration (0-indexed) | | `loop.revindex` | The index of the current iteration counting from the end of the loop (1-indexed) | | `loop.revindex0` | The index of the current iteration counting from the end of the loop (0-indexed) | | `loop.first?` | A boolean indicating if this is the first iteration of the loop | | `loop.last?` | A boolean indicating if this is the last iteration of the loop | | `loop.length` | The total number of iterations in the loop | | `loop.even?` | A boolean indicating if the index of the current iteration (0-indexed) is even | | `loop.odd?` | A boolean indicating if the index of the current iteration (0-indexed) is odd | | `loop.parent` | The parent's `loop` variable (only for nested for loops) | ## `if` The `if` template tag makes it possible to define conditions allowing to control which blocks should be executed. An `if` tag must always start with an `if` condition, followed by any number of intermediate `elsif` conditions and an optional (and final) `else` block. It also requires a closing `endif` tag. For example: ```html {% if my_var == 0 %} Zero! {% elsif my_var == 1 && other_var == "foobar" %} One! {% elsif !additional_var %} Something else! {% else %} Other! {% endif %} ``` The supported operators are listed in the [operators reference](https://martenframework.com/docs/next/templates/reference/operators). ## `include` The `include` template tag allows to include and render another template using the current context. This tag must be used with one mandatory argument: the name of the template to include, which can be either a string literal or a variable that will be resolved at runtime. For example: ```html {% include "path/to/my_snippet.html" %} ``` Included templates are rendered using the context of the including template. This means that all the variables that are expected or provided to the including template can also be used as part of the included template. For example: ```html title="hello.html" Hello, {{ name }}! {% include "question.html" %} ``` ```html title="question.html" How are you {{ name }}? ``` If `name` is "John", then the output will be "Hello, John! How are you John?". It should be noted that additional variables that are specific to the included template only can be specified using the `with` keyword: ```html {% include "path/to/my_snippet.html" with new_var="hello" %} ``` Multiple variables can also be specified if necessary. In that case, variable assignments must be separated by commas. For example: ```html {% include "path/to/my_snippet.html" with var1="foo", var2="bar" %} ``` Additionally, it is important to note that the accessibility of outer context variables for included templates depends on the value of the [`templates.isolated_inclusions`](https://martenframework.com/docs/next/development/reference/settings#isolated_inclusions) setting. By default, this setting is set to `false`, which means that included templates have access to the outer context variables. However, it is important to note that this behavior can be modified for each inclusion, regardless of the value of the [`templates.isolated_inclusions`](https://martenframework.com/docs/next/development/reference/settings#isolated_inclusions) setting. This can be achieved by appending the `isolated` modifier to specify that the included template must not access the outer context, or using the `contextual` modifier to indicate that it should have access. For example: ```html {% include "path/to/my_snippet.html" with new_var="hello" isolated %} {% include "path/to/my_snippet.html" with new_var="hello" contextual %} ``` :::caution Templates that are included using the `include` template are parsed and rendered _when_ the including template is rendered as well. Included templates are not parsed when the including template is parsed itself. This means that the including template and the included template are always rendered _separately_. ::: ## `localize` The `localize` template tag allows performing localization of values such as dates, numbers, and times by using the [I18n gem](https://crystal-i18n.github.io/localization.html), which is leveraged by Marten for its [internationalization features](https://martenframework.com/docs/next/i18n/introduction). It must take at least one argument (the value to localize) followed by an optional `format` keyword argument. For example, the following lines are valid usages of the `localize` tag: ```html {% localize created_at %} {% localize price format: "currency" %} ``` The provided values and the `format` argument can be resolved as template variables too, but they can also be defined as literal values if necessary. The `format` argument must match a key defined in the locale file. Optionally, the result of the localization can be assigned to a specific variable using the `as` keyword: ```html {% localize created_at format: "short" as localized_date %} ``` ## `l` Alias for [`localize`](#localize). ## `local_time` The `local_time` template tag allows to output the string representation of the local time. It must take one argument (the [format](https://crystal-lang.org/api/Time/Format.html) used to output the time). For example, the following lines are valid usages of the `local_time` tag: ```html {% local_time "%Y" %} {% local_time "%Y-%m-%d %H:%M:%S %:z" %} ``` Optionally, the output of this tag can be assigned to a specific variable using the `as` keyword: ```html {% local_time "%Y" as current_year %} ``` ## `method_input` The `method_input` template tag creates a hidden form input tag. This input tag has the name `_method` and gets the value assigned provided by the first tag argument For example: ```html
{% method_input "DELETE" %}
``` ## `reverse` Alias for [`url`](#url). ## `spaceless` The `spaceless` template tag allows to remove whitespaces, tabs, and new lines between HTML tags. Whitespaces inside tags are left untouched. It should be noted that the `spaceless` template tag requires a closing `endspaceless` tag. For example: ```html {% spaceless %}

Sign In

{% endspaceless %} ``` Would output the following: ```html

Sign In

``` ## `super` The `super` template tag allows to render the content of a block from a parent template (in a situation where both the `extend` and `block` tags are used). This can be useful in situations where blocks in a child template need to extend (add content) to a parent's block content instead of overwriting it. See [Template inheritance](https://martenframework.com/docs/next/templates/introduction#template-inheritance) to learn more about this capability. ## `translate` The `translate` template tag allows to perform translation lookups by using the [I18n configuration](https://martenframework.com/docs/next/development/reference/settings#i18n-settings) of the project. It must take at least one argument (the translation key) followed by keyword arguments. For example the following lines are valid usages of the `translate` tag: ```html {% translate "simple.translation" %} {% translate "simple.interpolation" value: 'test' %} ``` Translation keys and parameter values can be resolved as template variables too, but they can also be defined as literal values if necessary. Optionally, resolved translations can be assigned to a specific variable using the `as` keyword: ```html {% translate "simple.interpolation" value: 'test' as my_var %} ``` ## `trans` Alias for [`translate`](#translate). ## `t` Alias for [`translate`](#translate). ## `unless` The `unless` template tag makes it possible to define conditions allowing to control which blocks should be executed. An `unless` tag must always start with an `unless` condition, followed by an optional (and final) `else` block. It also requires a closing `endunless` tag. For example: ```html {% unless my_var == 0 %} Other value! {% else %} Zero! {% endunless %} ``` The `unless` template tag supports the same [operators](https://martenframework.com/docs/next/templates/reference/operators) as the ones supported by the [`if`](#if) template tag. ## `url` The `url` template tag allows to perform [URL lookups](https://martenframework.com/docs/next/handlers-and-http/routing#reverse-url-resolutions). It must take at least one argument (the name of the targeted handler) followed by optional keyword arguments (if the route requires parameters). For example, the following lines are valid usages of the `url` tag: ```html {% url "my_handler" %} {% url "my_other_handler" arg1: var1, arg2: var2 %} ``` URL names and parameter values can be resolved as template variables too, but they can also be defined as literal values if necessary. Optionally, resolved URLs can be assigned to a specific variable using the `as` keyword: ```html {% url "my_other_handler" arg1: var1, arg2: var2 as my_var %} ``` ## `verbatim` The `verbatim` template tag prevents the content of the tag to be processed by the template engine. It should be noted that the `verbatim` template tag requires a closing `endverbatim` tag. For example: ``` {% verbatim %} This should not be {{ processed }}. {% endverbatim %} ``` Would output `This should not be {{ processed }}.`. ## `with` The `with` template tag assigns one or more variables inside a block. After the end of the block has been reached the block variables are no longer available. For example: ``` {% with x = 'Hello World', y = 1 %} {{ x }} {{ y }}! {% endwith %} ``` Would output `Hello World 1!`. # Operators Source: https://martenframework.com/docs/next/templates/reference/operators This page provides a reference for all the available operators that can be used when defining conditions in templates with the [`if`](https://martenframework.com/docs/next/templates/reference/tags#if) and [`unless`](https://martenframework.com/docs/next/templates/reference/tags#unless) tags. ## Equality and comparison operators The following equality and comparison operators can be used: | Operator | Description | | -------- | ----------- | | `==` | Equals | | `!=` | Not equals | | `>` | Greater than | | `>=` | Greater than or equals | | `<` | Less than | | `<=` | Greater than or equals | For example: ```html {% if my_var == 0 %} Zero! {% elsif my_var >= 1 %} One or greater! {% else %} Other! {% endif %} ``` ## Logical operators The following logical operators can be used: | Operator | Description | | -------- | ----------- | | `&&` | Logical AND | | `\|\|` | Logical OR | | `!` or `not` | Logical negation | For example: ```html {% if my_var == 0 %} Zero! {% elsif my_var == 1 && other_var == "foobar" %} One! {% elsif !additional_var %} Something else! {% else %} Other! {% endif %} ``` ## Inclusion operator The `in` operator is the inclusion operator that can be used in [`if`](https://martenframework.com/docs/next/templates/reference/tags#if) or [`unless`](https://martenframework.com/docs/next/templates/reference/tags#unless) conditions. This operator allows to check for the presence of a substring in another string or for the presence of a value in an array or tuple. For example: ```html {% if "Top 10" in blog.title %} Top 10 blog article {% endif %} {% if "red" in colors %} Red color available {% endif %} ``` # Context producers Source: https://martenframework.com/docs/next/templates/reference/context-producers This page provides a reference for all the available context producers that can be used when rendering [templates](https://martenframework.com/docs/next/templates/introduction). ## Debug context producer **Class:** [`Marten::Template::ContextProducer::Debug`](https://martenframework.com/docs/api/dev/Marten/Template/ContextProducer/Debug.html) The Debug context producer contributes a `debug` variable to the context: the associated value is `true` or `false` depending on whether [debug mode](https://martenframework.com/docs/next/development/reference/settings#debug) is enabled for the project or not. ## Flash context producer **Class:** [`Marten::Template::ContextProducer::Flash`](https://martenframework.com/docs/api/dev/Marten/Template/ContextProducer/Flash.html) The Flash context producer contributes a `flash` variable to the context: this variable corresponds to the [flash store](https://martenframework.com/docs/next/handlers-and-http/introduction#using-the-flash-store) that is associated with the current HTTP request. If the template context is not initialized with an HTTP request object, then no variables are inserted. ## I18n context producer **Class:** [`Marten::Template::ContextProducer::I18n`](https://martenframework.com/docs/api/dev/Marten/Template/ContextProducer/I18n.html) The I18n context producer contributes I18n-related variables to the context: * `locale`: the current locale * `available_locales`: an array of all the available locales that can be activated for the project ## Request context producer **Class:** [`Marten::Template::ContextProducer::Request`](https://martenframework.com/docs/api/dev/Marten/Template/ContextProducer/Request.html) The Request context producer contributes a `request` variable to the context: this variable corresponds to the current HTTP request object. If the template context is not initialized with an HTTP request object, then no variables are inserted. # Template loaders Source: https://martenframework.com/docs/next/templates/reference/loaders This page provides a reference for all the available template loaders that can be used to customize template retrieval in Marten. ## FileSystem Loader **Class**: [`Marten::Template::Loader::FileSystem`](https://martenframework.com/docs/api/dev/Marten/Template/Loader/FileSystem.html) Loads templates directly from the file system. Initialization example: ```crystal loader = Marten::Template::Loader::FileSystem.new("/path/to/templates") ``` ## AppDirs Loader **Class**: [`Marten::Template::Loader::AppDirs`](https://martenframework.com/docs/api/dev/Marten/Template/Loader/AppDirs.html) Coordinates template loading from application directories. Relies on instances of FileSystem. Initialization example: ```crystal loader = Marten::Template::Loader::AppDirs.new ``` ## Cached Loader **Class**: [`Marten::Template::Loader::Cached`](https://martenframework.com/docs/api/dev/Marten/Template/Loader/Cached.html) Provides a caching layer for compiled templates. Can wrap other loaders to optimize retrieval. Initialization example: ```crystal file_loader = Marten::Template::Loader::FileSystem.new("/path/to/templates") loader = Marten::Template::Loader::Cached.new([file_loader] of Marten::Template::Loader::Base) ``` # Schemas Source: https://martenframework.com/docs/next/schemas Schemas are classes that define how input data should be serialized / deserialized, and validated. Schemas are usually used when processing web requests containing form data or pre-defined payloads. ## Guides - [Introduction](https://martenframework.com/docs/next/schemas/introduction) - [Validations](https://martenframework.com/docs/next/schemas/validations) ## How-to's - [Create custom schema fields](https://martenframework.com/docs/next/schemas/how-to/create-custom-schema-fields) ## Reference - [Schema fields](https://martenframework.com/docs/next/schemas/reference/fields) # Introduction to schemas Source: https://martenframework.com/docs/next/schemas/introduction Schemas are classes that define how input data should be serialized/deserialized, and validated. Schemas are usually used when processing web requests containing form data or pre-defined payloads. ## Basic schema definition and usage ### The schema class A schema class describes an _expected_ set of data. It describes the logical structure of this data, what are its expected characteristics, and what are the rules to use in order to identify whether it is valid or not. Schemas classes must inherit from the [`Marten::Schema`](https://martenframework.com/docs/api/dev/Marten/Schema.html) base class and they must define "fields" through the use of a `field` macro. These fields allow to define what data is expected by the schema, and how it is validated. For example, the following snippet defines a simple `ArticleSchema` schema: ```crystal class ArticleSchema < Marten::Schema field :title, :string, max_size: 128 field :content, :string field :published_at, :date_time, required: false end ``` In the above example, `title`, `content`, and `published_at` are fields of the `ArticleSchema` schema. This schema is very simple, but it already defines a set of validation rules that could be used to validate any data set the schema is applied to: * the `title` field is required, it must be a string that do not exceed 128 characters * the `content` field is required and must be a string as well * the `published_at` field is a date time that is _not_ required ### Using schemas Schemas can theoretically be used to process any kind of data, including a request's data. This makes them ideal when it comes to processing form inputs data or JSON payloads for example. When used as part of [handlers](https://martenframework.com/docs/next/handlers-and-http/introduction), and especially when processing HTML forms, schemas will usually be initialized and used to render a form when `GET` requests are submitted to the considered handler. Processing the actual form data will usually be done in the same handler when `POST` requests are submitted. For example, the handler in the following snippets displays a schema when a `GET` request is processed, and it validates the incoming data using the schema when the request is a `POST`: ```crystal class ArticleCreateHandler < Marten::Handler @schema : ArticleSchema? def get render("article_create.html", context: { schema: schema }) end def post if schema.valid? article = Article.new(schema.validated_data) article.save! redirect(reverse("home")) else render("article_create.html", context: { schema: schema }) end end private def schema @schema ||= ArticleSchema.new(request.data) end end ``` Let's break it down a bit more: * when the incoming request is a `GET`, the handler will simply render the `article_create.html` template, and initialize the schema (instance of `ArticleSchema`) with any data currently present in the request object (which is returned by the `#request` method). This schema object is made available to the template context * when the incoming request is a `POST`, it will initialize the schema and try to see if it is valid considering the incoming data (using the [`#valid?`](https://martenframework.com/docs/api/dev/Marten/Core/Validation.html#valid%3F(context%3ANil|String|Symbol%3Dnil)-instance-method) method). If it's valid, then a new `Article` record will be created using the schema's validated data ([`#validated_data`](https://martenframework.com/docs/api/dev/Marten/Schema.html#validated_data%3AHash(String%2CBool|Float64|Int64|JSON%3A%3AAny|JSON%3A%3ASerializable|Marten%3A%3AHTTP%3A%3AUploadedFile|String|Time|Time%3A%3ASpan|UUID|Nil)-instance-method)), and the user will be redirect to a home page. Otherwise, the `article_create.html` template will be rendered again with the invalid schema in the associated context :::tip Some [generic handlers](https://martenframework.com/docs/next/handlers-and-http/generic-handlers) allow to conveniently process schemas in handlers. This is the case for the [`Marten::Handlers::Schema`](https://martenframework.com/docs/next/handlers-and-http/reference/generic-handlers#processing-a-schema), the [`Marten::Handlers::RecordCreate`](https://martenframework.com/docs/next/handlers-and-http/reference/generic-handlers#creating-a-record), and the [`Marten::Handlers::RecordUpdate`](https://martenframework.com/docs/next/handlers-and-http/reference/generic-handlers#updating-a-record) generic handlers for example. ::: Note that schemas can be used for other things than processing form data. For example, they can also be used to process JSON payloads as part of API endpoints: ```crystal class API::ArticleCreateHandler < Marten::Handler def post schema = ArticleSchema.new(request.data) if schema.valid? article = Article.new(schema.validated_data) article.save! json({id: article.id}, status: 201) else json({errors: schema.errors}, status: 422) end end end ``` In the above example, an invalid payload produces a JSON response containing the schema errors. Please refer to [Serializing errors as JSON](https://martenframework.com/docs/next/schemas/validations#serializing-errors-as-json) to learn more about the shape of this payload, and to the [Build a JSON API](https://martenframework.com/docs/next/handlers-and-http/how-to/build-a-json-api) guide to learn how to list, retrieve, create, update, and delete records. :::info The `#data` method of an HTTP request object returns a hash-like object containing the request data: this object is automatically initialized from any form data or JSON data contained in the request body. ::: ### Rendering schemas as forms It should be noted that templates can easily interact with schema objects in order to introspect them and render a corresponding HTML form. In the previous example, the schema could be used as follows to render an equivalent form in the `article_create.html` template: ```html
{% if schema.errors.global %}
{% for error in schema.errors.global %}

{{ error.message }}

{% endfor %}
{% endif %}
{% for error in schema.title.errors %}

{{ error.message }}

{% endfor %}
{% for error in schema.content.errors %}

{{ error.message }}

{% endfor %}
{% for error in schema.published_at.errors %}

{{ error.message }}

{% endfor %}
``` The provided code also demonstrates how to efficiently handle errors within your templates. Here's a breakdown of the main guidelines to follow when dealing with schema errors in templates: * Begin by checking for any `schema.errors.global` errors. These are form-wide issues, and displaying them prominently alerts the user to broader problems with their input. * If `schema.field_name.errored?` returns true, it signals errors within that particular input field. * Display each individual `schema.field_name.errors` message directly below the associated input field. This provides the user with clear guidance on how to correct specific validation issues. ## Schema fields Schema classes must define _fields_. Fields allow to specify the expected attributes of a schema and they indicate how to validate incoming data sets. They are defined through the use of the `field` macro. For example: ```crystal class ArticleSchema < Marten::Schema field :title, :string, max_size: 128 field :content, :string field :published_at, :date_time, required: false end ``` ### Field ID and field type Pretty much like model fields, every field in a schema class must contain two mandatory positional arguments: a field identifier and a field type. The field identifier is used by Marten to determine the name of the corresponding key in any data set objects that should be validated by the schema. The field type determines a few other things: * the type of the expected value in the validated data set * how the field is serialized and deserialized * how field values are actually validated Marten provides numerous built-in schema field types that cover common web development needs. The complete list of supported fields is covered in the [schema fields reference](https://martenframework.com/docs/next/schemas/reference/fields). :::note It is possible to write custom schema fields and to use them in your schema definitions. See [How to create custom schema fields](https://martenframework.com/docs/next/schemas/how-to/create-custom-schema-fields) for more details regarding this capability. ::: ### Common field options In addition to their identifiers and types, fields can take keyword arguments that allow to further configure their behaviours and how they are validated. These keyword arguments are optional and they are shared across all the available fields. #### `required` The `required` argument allows to define whether a field is mandatory or not. The default value for this argument is `true`. The presence of mandatory fields is automatically enforced by schemas: if a mandatory field is missing in a data set, then a corresponding error will be generated by the schema. ## Validations One of the key characteristics of schemas is that they allow you to validate any incoming data and request parameters. As mentioned previously, the rules that are used to perform this validation can be inherited from the fields in your schema, depending on the options you used (for example fields using `required: true` will make the associated data validation fail if the field value is not present). They can also be explicitly specified in your schema class, which is useful if you need to implement custom validation logics. For example: ```crystal class SignUpSchema < Marten::Schema field :email, :string, max_size: 254 field :password1, :string, max_size: 128, strip: false field :password2, :string, max_size: 128, strip: false validate :validate_password def validate_password return unless validated_data["password1"]? && validated_data["password2"]? if validated_data["password1"] != validated_data["password2"] errors.add("The two password fields do not match") end end end ``` Schema validations are always triggered by the use of the [`#valid?`](https://martenframework.com/docs/api/dev/Marten/Core/Validation.html#valid%3F(context%3ANil|String|Symbol%3Dnil)-instance-method) or [`#invalid?`](https://martenframework.com/docs/api/dev/Marten/Core/Validation.html#invalid%3F(context%3ANil|String|Symbol%3Dnil)-instance-method) methods: these methods return `true` or `false` depending on whether the data is valid or invalid. Please head over to the [Schema validations](https://martenframework.com/docs/next/schemas/validations) guide in order to learn more about schema validations and how to customize it. ## Accessing validated data After performing [schema validations](#validations) (ie. after calling [`#valid?`](https://martenframework.com/docs/api/dev/Marten/Core/Validation.html#valid%3F(context%3ANil|String|Symbol%3Dnil)-instance-method) or [`#invalid?`](https://martenframework.com/docs/api/dev/Marten/Core/Validation.html#invalid%3F(context%3ANil|String|Symbol%3Dnil)-instance-method) on a schema object), accessing the validated data is often necessary. For instance, you may need to persist the validated data as part of a model record. To achieve this, you can make use of the [`#validated_data`](https://martenframework.com/docs/api/dev/Marten/Schema.html#validated_data%3AHash(String%2CBool|Float64|Int64|JSON%3A%3AAny|JSON%3A%3ASerializable|Marten%3A%3AHTTP%3A%3AUploadedFile|String|Time|Time%3A%3ASpan|UUID|Nil)-instance-method) method, which is accessible in all schema instances. This method provides access to a hash that contains the deserialized and validated field values of the schema. For instance, let's consider the example of the `ArticleSchema` schema [mentioned earlier](#the-schema-class): ```crystal schema = ArticleSchema.new(Marten::Schema::DataHash{"title" => "Test article", "content" => "Test content"}) schema.valid? # => true schema.validated_data["title"] # => "Test article" schema.validated_data["content"] # => "Test content" ``` It is important to note that accessing values using [`#validated_data`](https://martenframework.com/docs/api/dev/Marten/Schema.html#validated_data%3AHash(String%2CBool|Float64|Int64|JSON%3A%3AAny|JSON%3A%3ASerializable|Marten%3A%3AHTTP%3A%3AUploadedFile|String|Time|Time%3A%3ASpan|UUID|Nil)-instance-method) as shown in the above example is not type-safe. The [`#validated_data`](https://martenframework.com/docs/api/dev/Marten/Schema.html#validated_data%3AHash(String%2CBool|Float64|Int64|JSON%3A%3AAny|JSON%3A%3ASerializable|Marten%3A%3AHTTP%3A%3AUploadedFile|String|Time|Time%3A%3ASpan|UUID|Nil)-instance-method) hash can return any supported schema field values, and as a result, you may need to utilize the [`#as`](https://crystal-lang.org/reference/syntax_and_semantics/as.html) pseudo-method to handle the fetched validated data appropriately, depending on how and where you intend to use it. To palliate this, Marten automatically defines type-safe methods that you can utilize to access your validated schema field values: * `#` returns a nillable version of the `` field value * `#!` returns a non-nillable version of the `` field value * `#?` returns a boolean indicating if the `` field has a value For example: ```crystal schema = ArticleSchema.new(Marten::Schema::DataHash{"title" => "Test article"}) schema.valid? # => true schema.title # => "Test article" schema.title! # => "Test article" schema.title? # => true schema.content # => nil schema.content! # => raises NilAssertionError schema.content? # => false ``` ## Callbacks It is possible to define callbacks in your schema in order to bind methods and logics to specific events in the life cycle of your schema objects. Presently, schemas support callbacks related to validation only: `before_validation` and `after_validation` `before_validation` callbacks are called before running validation rules for a given schema while `after_validation` callbacks are executed after. They can be used to alter the validated data once the validation is done for example. ```crystal class ArticleSchema < Marten::Schema field :title, :string, max_size: 128 field :content, :string field :published_at, :date_time, required: false before_validation :run_pre_validation_logic after_validation :run_post_validation_logic private def run_pre_validation_logic # Do something before the validation end private def run_post_validation_logic # Do something after the validation end end ``` The use of methods like [`#valid?`](https://martenframework.com/docs/api/dev/Marten/Core/Validation.html#valid%3F(context%3ANil|String|Symbol%3Dnil)-instance-method) or [`#invalid?`](https://martenframework.com/docs/api/dev/Marten/Core/Validation.html#invalid%3F(context%3ANil|String|Symbol%3Dnil)-instance-method) will trigger validation callbacks. See [Schema validations](https://martenframework.com/docs/next/schemas/validations) for more details. # Schema validations Source: https://martenframework.com/docs/next/schemas/validations The main goal of schemas is to validate data and request parameters. As such, schemas provide a convenient mechanism allowing to define validation rules. These rules can be inherited from the fields in your schema depending on the options you used and the type of your fields. They can also be explicitly specified in your schema class, which is useful if you need to implement custom validation logics. ## Overview ### A short example Let's consider the following example: ```crystal class UserSchema < Marten::Schema field :name, :string, required: true, max_size: 128 end ``` In the above snippet, a `UserSchema` schema is defined and it is specified that the `name` field must be present (`required: true`) and that the associated value cannot exceed 128 characters. Given these characteristics, it is possible to initialize `UserSchema` instances and validate data through the use of the `#valid?` method: ```crystal schema_1 = UserSchema.new(Marten::Schema::DataHash.new) schema_1.valid? # => false schema_2 = UserSchema.new(Marten::Schema::DataHash{ "name" => "0" * 200) }) schema_2.valid? # => false schema_3 = UserSchema.new(Marten::Schema::DataHash{ "name" => "John Doe") }) schema_3.valid? # => true ``` As you can see in the above examples, the first two schemas are invalid because either the `name` field is not specified or because its value exceeds the maximum characters limit. The last schema is valid though because it has a `name` field that is less than 128 characters. ### Running schema validations As highlighted in the previous section, schema validation rules will be executed when calling the `#valid?` and `#invalid?` methods: these methods return `true` or `false` depending on whether the data is valid or invalid. ```crystal schema = UserSchema.new(Marten::Schema::DataHash.new) schema.valid? # => false schema.invalid? # => true ``` ## Field validation rules As mentioned previously, fields can contribute validation rules to your schemas. These validation rules can be inherited: * from the field type itself: some fields will validate that values are of a specific type (for example a `uuid` field will not validate values that don't correspond to valid UUIDs) * from the field options you define (for example fields using `required: true` will result in errors if the field is missing from the validated data) Please refer to the [fields reference](https://martenframework.com/docs/next/schemas/reference/fields) to learn more about the supported field types and their associated options. ## Custom validation rules Custom validation rules can be defined through the use of the `#validate` macro. This macro lets you configure the name of a validation method that should be called when a schema instance is validated. Inside this method, you can implement any validation logic that you might require and add errors to the schema instance if the data is invalid. For example: ```crystal class SignUpSchema < Marten::Schema field :email, :string, max_size: 254 field :password1, :string, max_size: 128, strip: false field :password2, :string, max_size: 128, strip: false validate :validate_password def validate_password return unless validated_data["password1"]? && validated_data["password2"]? if validated_data["password1"] != validated_data["password2"] errors.add("The two password fields do not match") end end end ``` In the above snippet, a custom validation method ensures that the `password1` and `password2` fields have the exact same value. If that's not the case, then a specific error (that is not associated with any fields) is added to the schema instance (which makes it invalid). It's interesting to note the use of the `#validated_data` method here: this method returns a hash of all the values that were previously sanitized and validated. You can make use of it when defining custom validation rules: indeed, these rules always run _after_ all the fields have been individually validated first. :::important You can define multiple validation rules in your schema classes. When doing so, don't forget that these custom validation rules are called in the order they are defined. ::: ## Validation errors Methods like `#valid?` or `#invalid?` only let you know whether a schema instance is valid or invalid for a specific data set. But you'll likely want to know exactly what are the actual errors or how to add new ones. As such, every schema instance has an associated error set, which is an instance of [`Marten::Core::Validation::ErrorSet`](https://martenframework.com/docs/api/dev/Marten/Core/Validation/ErrorSet.html). ### Inspecting errors A schema instance error set lets you access all the errors of a specific schema instance. For example: ```crystal schema = UserSchema.new(Marten::Schema::DataHash.new) schema.valid? # => false schema.errors.size # => 1 schema.errors # => #]> ``` As you can see, the error set gives you the ability to know how many errors are affecting your schema instance. Each error provides some additional information as well: * the associated field name (which can be `nil` if the error is global) * the error message * the error type, which is optional (`required` in the previous example) You can also access the errors that are associated with a specific field very easily by using the `#[]` method: ```crystal schema.errors[:name] # => [#] ``` Global errors (errors affecting the whole schema instances or multiple fields at once) can be listed through the use of the `#global` method. ### Adding errors Errors can be added to an error set through the use of the `#add` method. This method takes a field name, a message, and an optional error type: ```crystal schema.errors.add(:name, "Name is invalid") # error type is "invalid" schema.errors.add(:name, "Name is invalid", type: :invalid_name) # error type is "invalid_name" ``` Global errors can be specified through the use of an alternative `#add` method that doesn't take a field name: ```crystal schema.errors.add("User is invalid") # error type is "invalid" schema.errors.add("User is invalid", type: :invalid_user) # error type is "invalid_user" ``` ### Serializing errors as JSON An error set, and each error it contains, can be serialized to JSON. This lets a [handler](https://martenframework.com/docs/next/handlers-and-http/introduction) return validation errors from an API endpoint through the [`#json`](https://martenframework.com/docs/next/handlers-and-http/introduction#json) helper: ```crystal json({errors: schema.errors}, status: 422) ``` An error set is serialized as an array of objects. Each object contains the `field`, `type`, and `message` of one error. `field` is `null` when the error is global: ```json [ {"field": "name", "type": "required", "message": "This field is required."}, {"field": null, "type": "invalid", "message": "User is invalid"} ] ``` Model validation errors use the same representation, because models share this error set. The [Build a JSON API](https://martenframework.com/docs/next/handlers-and-http/how-to/build-a-json-api) how-to uses this payload for create and update endpoints. # Create custom schema fields Source: https://martenframework.com/docs/next/schemas/how-to/create-custom-schema-fields Marten gives you the ability to create your own custom schema field implementations. Those can involve custom validations, behaviors, and errors. You can leverage these custom fields as part of your project's schema definitions, and you can even distribute them to let other projects use them. ## Schema fields: scope and responsibilities Schema fields have the following responsibilities: * they define how field values are deserialized and serialized * they define how these values are validated When creating a custom schema field, there are usually two approaches that you can consider depending on the amount of customization that you want to implement. You can either: * leverage an existing built-in schema field (eg. integer, string, etc) and add custom behaviors and validations to it * or create a new schema field from scratch ## Registering new schema fields Regardless of the approach you take in order to define new schema field classes ([subclassing built-in fields](#subclassing-existing-schema-fields), or [creating new ones from scratch](#creating-new-schema-fields-from-scratch)), these classes must be registered to the Marten's global fields registry in order to make them available for use when defining schemas. To do so, you will have to call the [`Marten::Schema::Field#register`](https://martenframework.com/docs/api/dev/Marten/Schema/Field.html#register(id%2Cfield_klass)-macro) method with the identifier of the field you wish to use, and the actual field class. For example: ```crystal Marten::Schema::Field.register(:foo, FooField) ``` The identifier you pass to `#register` can be a symbol or a string. This is the identifier that is then made available to schema classes in order to define their fields: ```crystal class MySchema < Marten::Schema field :title, :string // highlight-next-line field :test, :foo end ``` The call to `#register` can be made from anywhere in your codebase, but obviously, you will want to ensure that it is done before requiring your schema classes: indeed, Marten will make the compilation of your project fail if it can't find the field type you are trying to use as part of a schema definition. ## Subclassing existing schema fields This is probably the easiest way to create a custom field: if the field you want to create can be derived from one of the [built-in schema fields](https://martenframework.com/docs/next/schemas/reference/fields) (usually those correspond to primitive types), then you can easily subclass the corresponding class and customize it so that it suits your needs. For example, implementing a custom "email" field could be done by subclassing the existing [`Marten::Schema::Field::String`](https://martenframework.com/docs/api/dev/Marten/Schema/Field/String.html) class. Indeed, an "email" field is essentially a string with a pre-defined maximum size and some additional validation logic: ```crystal class EmailField < Marten::Schema::Field::String def initialize( @id : ::String, @required : ::Bool = true, @max_size : ::Int32? = 254, @min_size : ::Int32? = nil ) @strip = true end def validate(schema, value) return if !value.is_a?(::String) # Leverage string's built-in validations (max size, min size). super if !EmailValidator.valid?(value) schema.errors.add(id, "Provide a valid email address") end end end ``` In the above snippet, the `EmailField` class simply overrides the `#validate` method so that it implements validation rules that are specific to the use case of email addresses (while also ensuring that regular string validations are executed as well). Everything that is described in the following section about [creating schema fields from scratch](#creating-new-schema-fields-from-scratch) also applies to the case of subclassing existing schema fields: the same methods can be overridden if necessary, but leveraging an existing class can save you some work. ## Creating new schema fields from scratch Creating new schema fields from scratch involves subclassing the [`Marten::Schema::Field::Base`](https://martenframework.com/docs/api/dev/Marten/Schema/Field/Base.html) abstract class. Because of this, the new field class is required to implement a set of mandatory methods. These mandatory methods, and some other ones that are optional (but interesting in terms of capabilities), are described in the following sections. ### Mandatory methods #### `deserialize` The `#deserialize` method is responsible for deserializing a schema field value. Indeed, the raw value of a schema field usually comes from a request's data and needs to be converted to another format. For example, a `uuid` field might need to convert a `String` value to a proper `UUID` object: ```crystal def deserialize(value) : ::UUID? return if empty_value?(value) case value when Nil value when ::String value.empty? ? nil : ::UUID.new(value) when JSON::Any deserialize(value.raw) else raise_unexpected_field_value(value) end rescue ArgumentError raise_unexpected_field_value(value) end ``` Fields can be configured as required or not ([`required`](https://martenframework.com/docs/next/schemas/reference/fields#required) option), this means that you will usually want to handle the case of `nil` values as part of this methods and return `nil` if the incoming value is `nil`. It should also be noted that incoming values can be any JSON data (`JSON::Any`), which means that you need to handle this case properly as well. If the value can't be processed properly by your field class, then it may be necessary to raise an exception. To do that you can leverage the `#raise_unexpected_field_value` method, which will raise a `Marten::Schema::Errors::UnexpectedFieldValue` exception. #### `serialize` The `#serialize` method is responsible for serializing a field value, which is essentially the reverse of the [`#deserialize`](#deserialize) method. As such, this method must convert a field value from the "Crystal" representation to the "raw" schema representation. For example, this method could return the string representation of a `UUID` object: ```crystal def serialize(value) : ::String? value.try(&.to_s) end ``` Again, if the value can't be processed properly by the field class, it may be necessary to raise an exception. To do that you can leverage the `#raise_unexpected_field_value` method, which will raise a `Marten::Schema::Errors::UnexpectedFieldValue` exception. ### Other useful methods #### `initialize` The default `#initialize` method that is provided by the [`Marten::Schema::Field::Base`](https://martenframework.com/docs/api/dev/Marten/Schema/Field/Base.html) is fairly simply and looks like this: ```crystal def initialize( @id : ::String, @required : ::Bool = true ) end ``` Depending on your field requirements, you might want to override this method completely in order to support additional parameters (such as default validation-related options for example). #### `validate` The `#validate` method does nothing by default and can be overridden on a per-field class basis in order to implement custom validation logic. This method takes the schema object being validated and the field value as arguments, which allows you to easily run validation checks and to add [validation errors](https://martenframework.com/docs/next/schemas/validations) to the schema object. For example: ```crystal def validate(schema, value) return if !value.is_a?(::String) if !EmailValidator.valid?(value) schema.errors.add(id, "Provide a valid email address") end end ``` ### An example Let's consider the use case of the "email" field highlighted in [Subclassing existing schema fields](#subclassing-existing-schema-fields). The exact same field could be implemented from scratch with the following snippet: ```crystal class EmailField < Marten::Schema::Field::Base getter max_size getter min_size def initialize( @id : ::String, @required : ::Bool = true, @max_size : ::Int32? = 254, @min_size : ::Int32? = nil, @strip : ::Bool = true ) end def deserialize(value) : ::String? strip? ? value.to_s.strip : value.to_s end def serialize(value) : ::String? value.try(&.to_s) end def strip? @strip end def validate(schema, value) return if !value.is_a?(::String) if !min_size.nil? && value.size < min_size.not_nil! schema.errors.add(id, "The minimum allowed length is #{min_size} characters") end if !max_size.nil? && value.size > max_size.not_nil! schema.errors.add(id, "The maximum allowed length is #{max_size} characters") end if !EmailValidator.valid?(value) record.errors.add(id, "Provide a valid email address") end end end ``` # Schema fields Source: https://martenframework.com/docs/next/schemas/reference/fields This page provides a reference for all the available field options and field types that can be used when defining schemas. ## Common field options The following field options can be used for all the available field types when declaring schema fields using the `field` macro. ### `required` The `required` argument can be used to specify whether a schema field is required or not required. The default value for this argument is `true`. ## Field types ### `array` An `array` field allows validating a list of values, with each value subject to the validation rules of an array member field. The type of the underlying array member field must be specified through the use of the [`of`](#of) option. This option must reference an [existing schema field type](#field-types) (such as `string`, `enum`, etc). For example, the following schema allows validating an array of strings: ```crystal class ColorsSchema < Marten::Schema field :colors, :array, of: :string end ``` It is possible to specify options that are specific to the chosen array member field. For example: ```crystal class ColorsSchema < Marten::Schema field :colors, :array, of: :string, max_size: 10 end ``` :::info The definition of nested array fields is not permitted. ::: #### `of` The `of` option is mandatory for `array` fields and allows specifying the type of the underlying array member field. This option must reference an [existing schema field type](#field-types) (such as `string`, `enum`, etc). ### `bool` A `bool` field allows validating boolean values. ### `date` A `date` field allows validating date values. Fields using this type are converted to `Time` objects in Crystal. :::info `date` fields automatically attempt to deserialize incoming values using a predefined set of input formats. These formats are localized and configurable through the `marten.schema.field.date.input_formats` translation key. If Marten does not supply translations for the locale you're using, you can define custom localized formats within your project. For detailed instructions, see [Defining Translations](https://martenframework.com/docs/next/i18n/introduction#defining-translations). For example: ```yaml en: marten: schema: field: date: input_formats: - "%Y-%m-%d" - "%m/%d/%Y" - "%b %d %Y" - "%b %d, %Y" - "%d %b %Y" - "%d %b, %Y" - "%B %d %Y" - "%B %d, %Y" - "%d %B %Y" - "%d %B, %Y" ``` If none of the localized input formats can successfully parse the incoming raw date value, `date` fields will fall back to the formats specified in the [`date_input_formats`](https://martenframework.com/docs/next/development/reference/settings#date_input_formats) setting. ::: ### `date_time` A `date_time` field allows validating date time values. Fields using this type are converted to `Time` objects in Crystal. :::info `date_time` fields automatically attempt to deserialize incoming values using a predefined set of input formats. These formats are localized and configurable through the `marten.schema.field.date_time.input_formats` translation key. If Marten does not supply translations for the locale you're using, you can define custom localized formats within your project. For detailed instructions, see [Defining Translations](https://martenframework.com/docs/next/i18n/introduction#defining-translations). For example: ```yaml en: marten: schema: field: date_time: input_formats: - "%Y-%m-%d %H:%M:%S" - "%Y-%m-%d %H:%M:%S.%f" - "%Y-%m-%d %H:%M" - "%m/%d/%Y %H:%M:%S" - "%m/%d/%Y %H:%M:%S.%f" - "%m/%d/%Y %H:%M" ``` If none of the localized input formats can successfully parse the incoming raw date time value, `date_time` fields will fall back to the formats specified in the [`date_time_input_formats`](https://martenframework.com/docs/next/development/reference/settings#date_time_input_formats) setting. ::: ### `decimal` A `decimal` field allows validating fixed-precision decimal values. Fields using this type are converted to [`BigDecimal`](https://crystal-lang.org/api/BigDecimal.html) objects in Crystal. This is the right choice for monetary amounts and other values that must not lose precision (unlike [`float`](#float) fields). Both [`max_digits`](#max_digits) and [`decimal_places`](#decimal_places) are required: ```crystal class ProductSchema < Marten::Schema field :price, :decimal, max_digits: 10, decimal_places: 2 end schema = ProductSchema.new(Marten::HTTP::Params::Data{"price" => ["19.99"]}) schema.valid? # => true schema.price # => 19.99 ``` In addition to the [common field options](#common-field-options), such fields support the following arguments: #### `max_digits` The `max_digits` argument **is required** and defines the maximum number of digits allowed in the number, including digits on both sides of the decimal point. #### `decimal_places` The `decimal_places` argument **is required** and defines the number of decimal places allowed in the number. It must be less than or equal to [`max_digits`](#max_digits). ### `duration` A `duration` field allows validating duration values, which map to [`Time::Span`](https://crystal-lang.org/api/Time/Span.html) objects in Crystal. `duration` fields expect serialized values to be in the `DD.HH:MM:SS.nnnnnnnnn` format (with `n` corresponding to nanoseconds) or in the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#Durations) format (eg. `P3DT2H15M20S`, which corresponds to a `3.2:15:20` time span). ### `email` An `email` field allows validating email address values. In addition to the [common field options](#common-field-options), such fields support the following arguments: #### `max_size` The `max_size` argument allows defining the maximum size allowed for the email address string. The default value for this argument is `254` (in accordance with RFCs 3696 and 5321). #### `min_size` The `min_size` argument allows defining the minimum size allowed for the email address string. The default value for this argument is `nil`, which means that the minimum size is not validated by default. #### `strip` The `strip` argument allows defining whether the string value should be stripped of leading and trailing whitespaces. The default is `true`. ### `enum` An `enum` field allows validating string values against the values of a specific [`Enum`](https://crystal-lang.org/api/Enum.html). When defining `enum` fields, it's necessary to specify a `values` argument that matches the actual enum: ```crystal enum Category NEWS BLOG end class ArticleSchema < Marten::Schema field :title, :string field :category, :enum, values: Category end schema = ArticleSchema.new( Marten::HTTP::Params::Data{"title" => ["Test"], "category" => ["blog"]} ) schema.valid? # => true schema.category # => Category::BLOG ``` In addition to the [common field options](#common-field-options), such fields support the following arguments: #### `values` The `values` argument **is required** and allows to specify the actual enum class that should be used for the field. Only string values matching the values of the enum will be validated by the field. ### `file` A `file` field allows validating uploaded files. In addition to the [common field options](#common-field-options), such fields support the following arguments: #### `allow_empty_files` The `allow_empty_files` argument allows defining whether empty files are allowed or not when files are validated. The default value is `false`. #### `max_name_size` The `max_name_size` argument allows defining the maximum file name size allowed. The default value is `nil`, which means that uploaded file name sizes are not validated. ### `float` A `float` field allows validating float values. Fields using this type are converted to `Float64` objects in Crystal. In addition to the [common field options](#common-field-options), such fields support the following arguments: #### `max_value` The `max_value` argument allows defining the maximum value allowed. The default value for this argument is `nil`, which means that the maximum value is not validated by default. #### `min_value` The `min_value` argument allows defining the minimum value allowed. The default value for this argument is `nil`, which means that the minimum value is not validated by default. ### `image` An `image` field allows validating uploaded files by ensuring that they are indeed images. In addition to the [common field options](#common-field-options), such fields support the following arguments: :::info The [crystal-vips](https://github.com/naqvis/crystal-vips) shard is required for defining `image` schema fields. If this shard is not installed and required by your project, it will not be possible to use `image` schema fields and compilation errors will be raised. As such, make sure that: 1. Your project's `shard.yml` includes: ```yaml dependencies: vips: github: naqvis/crystal-vips ``` 2. Your project's `src/project.cr` includes: ```crystal require "vips" ``` ::: #### `max_name_size` The `max_name_size` argument allows defining the maximum file name size allowed. The default value is `nil`, which means that uploaded file name sizes are not validated. ### `int` An `int` field allows validating integer values. Fields using this type are converted to `Int64` objects in Crystal. In addition to the [common field options](#common-field-options), such fields support the following arguments: #### `max_value` The `max_value` argument allows defining the maximum value allowed. The default value for this argument is `nil`, which means that the maximum value is not validated by default. #### `min_value` The `min_value` argument allows defining the minimum value allowed. The default value for this argument is `nil`, which means that the minimum value is not validated by default. ### `json` A `json` field allows validating JSON values, which are automatically parsed to [`JSON::Any`](https://crystal-lang.org/api/JSON/Any.html) objects. Additionally, it is also possible to leverage the [`serializable`](#serializable) option in order to specify a class that makes use of [`JSON::Serializable`](https://crystal-lang.org/api/JSON/Serializable.html). When doing so, the parsing of the JSON values will result in the initialization of the corresponding serializable objects: ```crystal class MySerializable include JSON::Serializable property a : Int32 | Nil property b : String | Nil end class MySchema < Marten::Schema # Other fields... field :metadata, :json, serializable: MySerializable end schema = MySchema.new(Marten::Schema::DataHash{"metadata" => %{{"a": 42, "b": "foo"}}}) schema.valid? # => true schema.metadata! # => MySerializable object ``` #### `serializable` The `serializable` arguments allows to specify that a class making use of [`JSON::Serializable`](https://crystal-lang.org/api/JSON/Serializable.html) should be used in order to parse the JSON values for the schema field at hand. When specifying a `serializable` class, the values returned for the considered schema fields will be instances of that class instead of [`JSON::Any`](https://crystal-lang.org/api/JSON/Any.html) objects. ### `slug` A `slug` field allows validating slug values (ie. strings that can only include characters, numbers, dashes, and underscores). In addition to the [common field options](#common-field-options), such fields support the following arguments: #### `max_size` The `max_size` argument allows defining the maximum size allowed for the slug string. The default value for this argument is `50`. #### `min_size` The `min_size` argument allows defining the minimum size allowed for the slug string. The default value for this argument is `nil`, which means that the minimum size is not validated by default. #### `strip` The `strip` argument allows defining whether the string value should be stripped of leading and trailing whitespaces. The default is `true`. ### `string` A `string` field allows validating string values. In addition to the [common field options](#common-field-options), such fields support the following arguments: #### `max_size` The `max_size` argument allows defining the maximum size allowed for the string. The default value for this argument is `nil`, which means that the maximum size is not validated by default. #### `min_size` The `min_size` argument allows defining the minimum size allowed for the string. The default value for this argument is `nil`, which means that the minimum size is not validated by default. #### `choices` The `choices` argument allows defining an array of allowed string values. The default value for this argument is `nil`, which means that values are not restricted to a specific set of choices by default. When set, field values must match one of the configured choices. ```crystal class ArticleSchema < Marten::Schema field :status, :string, choices: ["draft", "published", "archived"] end ``` #### `strip` The `strip` argument allows defining whether the string value should be stripped of leading and trailing whitespaces. The default is `true`. ### `uuid` A `uuid` field allows validating Universally Unique IDentifiers (UUID) values. Fields using this type are converted to `UUID` objects in Crystal. ### `url` A `url` field allows validating URL address values. In addition to the [common field options](#common-field-options), such fields support the following arguments: #### `max_size` The `max_size` argument allows defining the maximum size allowed for the URL string. The default value for this argument is `200`. #### `min_size` The `min_size` argument allows defining the minimum size allowed for the URL string. The default value for this argument is `nil`, which means that the minimum size is not validated by default. #### `strip` The `strip` argument allows defining whether the string value should be stripped of leading and trailing whitespaces. The default is `true`. # Assets Source: https://martenframework.com/docs/next/assets Marten provides a set of helpers in order to help you manage and resolve assets (also known as "static files") such as images, Javascript files, CSS files, etc. ## Guides - [Introduction](https://martenframework.com/docs/next/assets/introduction) - [Serving assets](https://martenframework.com/docs/next/assets/serving-assets) # Assets handling Source: https://martenframework.com/docs/next/assets/introduction Web applications generally need to serve "static files" or "assets": static images, Javascript files, CSS files, etc. Marten provides a set of helpers in order to help you manage assets, refer to them, and upload them to specific storages. ## Idea and scope Asset files can be defined in two places: * they can be provided by [apps](https://martenframework.com/docs/next/development/applications): for example, some apps need to rely on specific assets to provide full-featured UIs * they can be defined in [specifically configured folders](https://martenframework.com/docs/next/development/reference/settings#dirs) in projects This allows applications to be relatively independent and to rely on their own assets if they need to, while also allowing projects to define assets as part of their structure. When a project is deployed, it is expected that all these asset files will be "collected" to be placed to the final destination from which they will be served: this operation is made available through the use of the [`collectassets`](https://martenframework.com/docs/next/development/reference/management-commands#collectassets) management command. This "destination" depends on your deployment strategy: it can be as simple as moving all these assets to a dedicated folder in your server (so that they can be served by your web server), or it can involve uploading these assets to an S3 or GCS bucket for example. Please refer to [Serving assets](https://martenframework.com/docs/next/assets/serving-assets) for more details about this process. :::info The assets flow provided by Marten is **intentionally simple**. Indeed, Marten being a backend-oriented framework, can't account for all the ways assets can be packaged and/or bundled together. Some projects might require a webpack strategy to bundle assets, some might require a fingerprinting step on top of that, and others might need something entirely different. How these toolchains are configured or set up is left to the discretion of web application developers; it is just expected that these operations will be applied _before_ the [`collectassets`](https://martenframework.com/docs/next/development/reference/management-commands#collectassets) management command is executed. ::: Once assets have been "collected", it is possible to generate their URLs through the use of dedicated helpers: * by using the [assets engine](https://martenframework.com/docs/api/dev/Marten/Asset/Engine.html#url(filepath%3AString)%3AString-instance-method) in Crystal * by using the [`asset`](https://martenframework.com/docs/next/templates/reference/tags#asset) tag in templates The way these asset URLs are generated depends on the configured [asset storage](https://martenframework.com/docs/next/development/reference/settings#storage). ## Configuring assets Assets can be configured through the use of the [assets settings](https://martenframework.com/docs/next/development/reference/settings#assets-settings), which are available under the `assets` namespace. An example assets configuration might look like this: ```crystal config.assets.root = "assets" config.assets.url = "/assets/" ``` ### Assets storage One of the most important asset settings is the [`storage`](https://martenframework.com/docs/next/development/reference/settings#storage) one. Indeed, Marten uses a file storage mechanism to perform file operations related to assets (like uploading files, generating URLs, etc) by leveraging a standardized API. By default, assets use the [`Marten::Core::Store::FileSystem`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/FileSystem.html) storage backend, which ensures that assets files are collected and placed to a specific folder in the local file system: this allows these files to then be served by a web server such as Nginx for example. ### Assets root directory This directory - which can be configured through the use of the [`root`](https://martenframework.com/docs/next/development/reference/settings#root) setting - corresponds to the absolute path where collected assets will be persisted (when running the [`collectassets`](https://martenframework.com/docs/next/development/reference/management-commands#collectassets) command). By default, assets will be persisted in a folder that is relative to the Marten project's directory. Obviously, this folder should be empty before running the `collectassets` command in order to not overwrite existing files. The default value is `assets`. ### Assets URL The asset URL is used when generating URLs for assets. This base URL will be used by the default [`Marten::Core::Store::FileSystem`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/FileSystem.html) storage to construct asset URLs. For example, requesting a `css/App.css` asset might generate a `/assets/css/App.css` URL. The default value is `/assets/`. ### Asset directories By default, Marten will collect asset files that are defined under an `assets` folder in [application](https://martenframework.com/docs/next/development/applications) directories. That being said, your project will probably have asset files that are not associated with a particular app. That's why you can also define an array of additional directories where assets should be looked for. This array of directories can be defined through the use of the [`dirs`](https://martenframework.com/docs/next/development/reference/settings#dirs) assets setting: ```crystal config.assets.dirs = [ Path["src/path1/assets"], :"src/path2/assets", ] ``` ### Asset manifests and fingerprinting Fingerprinting involves adding a unique string of characters to the filename of each asset. This enables the browser to cache the file securely. When an asset is modified, its fingerprint changes, prompting the browser to retrieve and use the updated version. Modern asset bundling tools often provide the capability to generate manifest files. These manifest files typically contain mappings between the original asset filenames and their corresponding fingerprinted versions. Marten supports configuring paths to these manifest files so that [resolving assets](#resolving-asset-urls) produces URLs that automatically include the correct fingerprinted version of each asset. This can be achieved by adding manifest paths to the [`assets.manifests`](https://martenframework.com/docs/next/development/reference/settings#manifests) setting. For example: ```crystal config.assets.manifests = [ "src/assets/build/manifest.json", ] ``` It is assumed that the files whose paths are referenced in this setting are regular JSON manifests, containing mappings between original asset file names and their fingerprinted versions. For example: ```json { "app/home.css": "app/home.9495841be78cdf06c45d.css", "app/home.js": "app/home.9495841be78cdf06c45d.js" } ``` Considering the above manifest example, trying to resolve `app/home.css` would produce a URL ending with `app/home.9495841be78cdf06c45d.css`: ```crystal Marten.assets.url("app/home.css") # => "/assets/app/home.9495841be78cdf06c45d.css" ``` :::info The [`collectassets`](https://martenframework.com/docs/next/development/reference/management-commands#collectassets) command can also fingerprint assets at collect time. See [Fingerprinting collected assets](https://martenframework.com/docs/next/assets/serving-assets#fingerprinting-collected-assets) for more details. ::: ## Resolving asset URLs As mentioned previously, assets are collected and persisted in a specific storage. When building HTML [templates](https://martenframework.com/docs/next/templates/introduction), you will usually need to "resolve" the URL of assets to generate the absolute URLs that should be inserted into stylesheet or script tags (for example). One possible way to do so is to leverage the [`asset`](https://martenframework.com/docs/next/templates/reference/tags#asset) template tag. This template tag takes a single argument corresponding to the relative path of the asset you want to resolve, and it outputs the absolute URL of the asset (depending on your assets configuration). For example: ```html ``` In the above snippet, the `app/app.css` asset could be resolved to `/assets/app/app.css` (depending on the configuration of the project obviously). It is also possible to resolve asset URLs programmatically in Crystal. To do so, you can leverage the [`#url`](https://martenframework.com/docs/api/dev/Marten/Asset/Engine.html#url(filepath%3AString)%3AString-instance-method) method of the Marten assets engine: ```crystal Marten.assets.url("app/app.css") # => "/assets/app/app.css" ``` Please refer to [Serving assets](https://martenframework.com/docs/next/assets/serving-assets) to learn how to serve assets in development and in production. # Serving assets Source: https://martenframework.com/docs/next/assets/serving-assets How assets are served depends on the environment: in development, Marten can serve them directly from your applications and configured directories, while in production they must first be collected and then served from their final destination. This page covers serving assets in development, the [`collectassets`](https://martenframework.com/docs/next/development/reference/management-commands#collectassets) management command, fingerprinting, and the main strategies for serving collected assets in production. Asset configuration and URL resolution are covered in the [assets introduction](https://martenframework.com/docs/next/assets/introduction). ## Serving assets in development Marten provides a handler that you can use to serve assets in development environments only. This handler ([`Marten::Handlers::Defaults::Development::ServeAsset`](https://martenframework.com/docs/api/dev/Marten/Handlers/Defaults/Development/ServeAsset.html)) is automatically mapped to a route when creating new projects through the use of the [`new`](https://martenframework.com/docs/next/development/reference/management-commands#new) management command: ```crystal Marten.routes.draw do # Other routes... if Marten.env.development? path "#{Marten.settings.assets.url}", Marten::Handlers::Defaults::Development::ServeAsset, name: "asset" end end ``` As you can see, this route will automatically use the URL that is configured as part of the [`url`](https://martenframework.com/docs/next/development/reference/settings#url) asset setting. For example, this means that an `app/app.css` asset would be served by the `/assets/app/app.css` route in development if the [`url`](https://martenframework.com/docs/next/development/reference/settings#url) setting is set to `/assets/`. :::warning It is very important to understand that this handler should **only** be used in development environments. Indeed, the [`Marten::Handlers::Defaults::Development::ServeAsset`](https://martenframework.com/docs/api/dev/Marten/Handlers/Defaults/Development/ServeAsset.html) handler does not require assets to have been collected beforehand through the use of the [`collectassets`](https://martenframework.com/docs/next/development/reference/management-commands#collectassets) management command. This means that it will try to find assets in your applications' `assets` directories and in the directories configured in the [`dirs`](https://martenframework.com/docs/next/development/reference/settings#dirs) setting. This mechanism is helpful in development, but it is not suitable for production environments since it is inefficient and (probably) insecure. ::: ## Serving assets in production At deployment time, you will need to collect your project's assets and serve them from their final destination. There are many ways to do so, and every deployment situation will be different, but we can identify a few generic strategies. ### Collecting assets You will need to run the [`collectassets`](https://martenframework.com/docs/next/development/reference/management-commands#collectassets) management command to collect all the available assets from the applications' `assets` directories and from the directories configured in the [`dirs`](https://martenframework.com/docs/next/development/reference/settings#dirs) setting. This command will identify and "collect" those assets, and ensure they are "uploaded" into their final destination based on the storage that is currently used. :::tip The [`collectassets`](https://martenframework.com/docs/next/development/reference/management-commands#collectassets) management command should be executed _after_ your assets have been bundled and packaged. For example, your project could use a [gulp](https://gulpjs.com/) pipeline to compile your assets, minify them, and place them into a `src/app/assets/build` directory. Assuming that this directory is also specified in the [`dirs`](https://martenframework.com/docs/next/development/reference/settings#dirs) setting, these prepared assets would also be collected and uploaded into the configured storage. Which would allow you to then refer to them from your project's templates. Obviously, every project is different and might use different tools and a different deployment pipeline, but the overall strategy would remain the same. ::: ### Fingerprinting collected assets The [`collectassets`](https://martenframework.com/docs/next/development/reference/management-commands#collectassets) command provides a `--fingerprint` option. Using this option automatically fingerprints the collected assets and generates a `manifest.json` file, which maps the original file paths to their fingerprinted versions. When the `--fingerprint` option is used, it's important to include the path to the generated `manifest.json` in the appropriate [`assets.manifests`](https://martenframework.com/docs/next/development/reference/settings#manifests) environment config file, otherwise the collected assets can't be found when the URL is resolved. Please refer to [Asset manifests and fingerprinting](https://martenframework.com/docs/next/assets/introduction#asset-manifests-and-fingerprinting) to learn more about how Marten uses manifest files when resolving asset URLs. ### Serving assets from a web server As mentioned previously, Marten uses a file storage mechanism to perform file operations related to assets and to "collect" them. By default, assets use the [`Marten::Core::Store::FileSystem`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/FileSystem.html) storage backend, which ensures that assets files are collected and placed into a specific folder in the local file system. This allows these assets to easily be served by a local web server if you have one properly configured. For example, you could use a web server like [Apache](https://httpd.apache.org/) or [Nginx](https://nginx.org) to serve your collected assets. The way to configure these web servers will obviously vary from one solution to another, but you will likely need to define a location whose URL matches the [`url`](https://martenframework.com/docs/next/development/reference/settings#url) setting value and that serves files from the folder where assets were collected (the [`root`](https://martenframework.com/docs/next/development/reference/settings#root) folder). For example, a [Nginx](https://nginx.org) server configuration allowing to serve assets under a `/assets` location could look like this: ```conf server { listen 443 ssl; server_name myapp.example.com; gzip on; gzip_disable "msie6"; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_buffers 16 8k; gzip_http_version 1.1; gzip_min_length 256; gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype image/svg+xml image/x-icon; error_log /var/log/nginx/myapp_error.log; access_log /var/log/nginx/myapp_access.log; location /assets/ { expires 365d; alias /myapp/assets/; } } ``` ### Serving assets from a cloud service or CDN To serve assets from a cloud storage (like Amazon's S3 or GCS) and (optionally) a CDN (Content Delivery Network), you will likely need to write a custom file storage and set the [`storage`](https://martenframework.com/docs/next/development/reference/settings#storage) setting accordingly. The advantage of doing so is that you are basically delegating the responsibility of serving assets to a dedicated cloud storage, which can often translate into faster-loading pages for your end users. :::info Marten does not provide file storage implementations for the most frequently encountered cloud storage solutions presently. This is something that is planned for future releases though. ::: Writing a custom file storage implementation will involve subclassing the [`Marten::Core::Storage::Base`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/Base.html) abstract class and implementing a set of mandatory methods. The main difference compared to a "local file system" storage here is that you would need to make use of the API of the chosen cloud storage to perform low-level file operations (such as reading a file's content, verifying that a file exists, or generating a file URL). Please refer to [Create custom file storages](https://martenframework.com/docs/next/files/how-to/create-custom-file-storages) for more details on how to implement a custom storage. ### Serving assets using a middleware There are some situations where it is not possible to easily configure a web server such as [Nginx](https://nginx.org) or a third-party service (like Amazon's S3 or GCS) to serve your assets directly. To palliate this, Marten provides the [`Marten::Middleware::AssetServing`](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#asset-serving-middleware) middleware. The purpose of this middleware is to distribute collected assets stored under the configured assets root ([`assets.root`](https://martenframework.com/docs/next/development/reference/settings#root) setting). These assets are assumed to have been collected using the [`collectassets`](https://martenframework.com/docs/next/development/reference/management-commands#collectassets) management command, and it is also assumed that a "local file system" storage (such as [`Marten::Core::Store::FileSystem`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/FileSystem.html)) is used. In order to use this middleware, you can "insert" the corresponding class at the beginning of the [`middleware`](https://martenframework.com/docs/next/development/reference/settings#middleware) setting when defining production settings. For example: ```crystal Marten.configure :production do |config| config.middleware.unshift(Marten::Middleware::AssetServing) # Other settings... end ``` It is important to note that the [`assets.url`](https://martenframework.com/docs/next/development/reference/settings#url) setting must align with the Marten application domain or correspond to a relative URL path (e.g., /assets/) for this middleware to work correctly. This guarantees proper mapping and accessibility of the assets within the application, allowing them to be served by this middleware. # Files Source: https://martenframework.com/docs/next/files Dealing with files is a common requirement for web applications. This section covers how to upload and manage files. ## Guides - [Uploading files](https://martenframework.com/docs/next/files/uploading-files) - [Managing files](https://martenframework.com/docs/next/files/managing-files) ## How-to's - [Create custom file storages](https://martenframework.com/docs/next/files/how-to/create-custom-file-storages) ## Reference - [File storages](https://martenframework.com/docs/next/files/reference/stores) # Uploading files Source: https://martenframework.com/docs/next/files/uploading-files Marten gives you the ability to interact with uploaded files. These files are made available with each HTTP request object, and it is also possible to validate them using schemas. The following document explains how to expect and manipulate uploaded files, and what are their associated characteristics. ## Accessing uploaded files Uploaded files are made available in the [`#data`](https://martenframework.com/docs/api/dev/Marten/HTTP/Request.html#data%3AParams%3A%3AData-instance-method) hash-like object of any HTTP request object (instance of [`Marten::HTTP::Request`](https://martenframework.com/docs/api/dev/Marten/HTTP/Request.html)). These file objects are instances of the [`Marten::HTTP::UploadedFile`](https://martenframework.com/docs/api/dev/Marten/HTTP/UploadedFile.html) class. For example, you could access and process an `uploaded_file` file originating from an HTML form using a handler like this: ```crystal class ProcessUploadedFileHandler < Marten::Handler def post file = request.data["uploaded_file"].as(Marten::HTTP::UploadedFile) respond "Processed file: #{file.filename}" end end ``` [`Marten::HTTP::UploadedFile`](https://martenframework.com/docs/api/dev/Marten/HTTP/UploadedFile.html) objects give you access to the following key methods, which allow you to interact with the uploaded file and its content: * `#filename` returns the name of the uploaded file * `#size` returns the size of the uploaded file * `#io` returns a regular [`IO`](https://crystal-lang.org/api/IO.html) object allowing to read the content of the file and interact with it :::info Where are uploaded files stored? All uploaded files are automatically persisted to a temporary file in the system's temporary directory (usually this corresponds to the `/tmp` folder). ::: :::info Maximum request body size The total size of incoming request bodies (including uploaded files) is limited by the [`request_max_body_size`](https://martenframework.com/docs/next/development/reference/settings#request_max_body_size) setting, which defaults to 2.5MB. Requests exceeding this limit result in a 400 Bad Request. Increase this setting if your application needs to accept larger uploads. ::: ## Expecting uploaded files with schemas If you use [schemas](https://martenframework.com/docs/next/schemas/introduction) to validate input data (such as form data), then it's worth noting that you can explicitly define that you expect files in the validated data. The simplest way to do that is to make use of the [`file`](https://martenframework.com/docs/next/schemas/reference/fields#file) or [`image`](https://martenframework.com/docs/next/schemas/reference/fields#image) schema field. For example, you could define the following schema: ```crystal class UploadFileSchema < Marten::Schema field :uploaded_file, :file end ``` And use it in a regular [schema generic handler](https://martenframework.com/docs/next/handlers-and-http/reference/generic-handlers#processing-a-schema) like this: ```crystal class UploadFileHandler < Marten::Handlers::Schema schema UploadFileSchema template_name "upload_file.html" success_url "/" def process_valid_schema file = schema.validated_data["uploaded_file"] # Do something with the uploaded file... super end end ``` The presence/absence of the file (and - optionally - some of its attributes) will be validated according to the schema definition when `POST` requests are processed by the handler. ## Persisting uploaded files in model records Models can define [`file`](https://martenframework.com/docs/next/models-and-databases/reference/fields#file) or [`image`](https://martenframework.com/docs/next/models-and-databases/reference/fields#image) fields and persist "references" of uploaded files in their rows. This allows "retaining" specific uploaded files and associating their references with specific model records. For example, we could modify the handler in the previous section so that it persists and associate the uploaded file to a new `Attachment` record as follows: ```crystal class UploadFileHandler < Marten::Handlers::Schema schema UploadFileSchema template_name "upload_file.html" success_url "/" def process_valid_schema file = schema.validated_data["uploaded_file"] // highlight-next-line Attachment.create!(uploaded_file: file) super end end ``` Here, the `UploadFileHandler` inherits from the [`Marten::Handlers::Schema`](https://martenframework.com/docs/api/dev/Marten/Handlers/Schema.html) generic handler. It would also make sense to leverage the [`Marten::Handlers::RecordCreate`](https://martenframework.com/docs/api/dev/Marten/Handlers/RecordCreate.html) generic handler to process the schema and create the `Attachment` record at the same time. # Managing files Source: https://martenframework.com/docs/next/files/managing-files Marten gives you the ability to associate uploaded files with model records and to fully customize how and where those files are persisted. This section covers the basics of using files with models, how to interact with file objects, and introduces the concept of file storage. ## Using files with models You can make use of the [`file`](https://martenframework.com/docs/next/models-and-databases/reference/fields#file) or [`image`](https://martenframework.com/docs/next/models-and-databases/reference/fields#image) fields when defining models: this allows to associate an uploaded file with specific model records. For example, let's consider the following model: ```crystal class Attachment < Marten::Model field :id, :big_int, primary_key: true, auto: true field :uploaded_file, :file, blank: false, null: false end ``` Any `Attachment` model record will have an `uploaded_file` attribute allowing interacting with the attached file: ```crystal attachment = Attachment.first! attachment.uploaded_file # => # attachment.uploaded_file.attached? # => true attachment.uploaded_file.name # => "test.txt" attachment.uploaded_file.size # => 5796929 attachment.uploaded_file.url # => "/media/test.txt" ``` The object returned by the `Attachment#uploaded_file` method is a "file object": an instance of [`Marten::DB::Field::File::File`](https://martenframework.com/docs/api/dev/Marten/DB/Field/File/File.html). These objects and their associated capabilities are described below in [File objects](#file-objects). :::tip Under which path are files persisted? Files are stored at the root of the media [storage](#file-storages) by default. It should be noted that the path used to persist files in storages can be configured by setting the `upload_to` [`file`](https://martenframework.com/docs/next/models-and-databases/reference/fields#file) field option. For example, the previous `Attachment` model could be rewritten as follows to ensure that files are persisted in a `foo/bar` folder: ```crystal class Attachment < Marten::Model field :id, :big_int, primary_key: true, auto: true field :uploaded_file, :file, blank: false, null: false, upload_to: "foo/bar" end ``` It should also be noted that `upload_to` can correspond to a proc that takes the name of the file to save, which can be used to implement more complex file path generation logic if necessary: ```crystal class Attachment < Marten::Model field :id, :big_int, primary_key: true, auto: true field :uploaded_file, :file, blank: false, null: false, upload_to: ->(name : String) { File.join("files/uploads", name) } end ``` ::: It should be noted that saving a model record will automatically result in any associated files being saved and persisted in the right [storage](#file-storages) automatically. For example, the following snippet reads a locally available file and attaches it to a new model record: ```crystal attachment = Attachment.new File.open("test.txt") do |file| attachment.uploaded_file = file attachment.save! end ``` :::info You don't need to take care of possible collisions between attached file names: Marten automatically ensures that uploaded files have a unique file name in the destination storage in order to avoid possible conflicts. ::: ## File objects As mentioned previously, file objects are used internally by Marten to allow interacting with files that are associated with model records. These objects are instances of the [`Marten::DB::Field::File::File`](https://martenframework.com/docs/api/dev/Marten/DB/Field/File/File.html) class. They give access to basic file properties and they allow to interact with the associated IO. It should be noted that these "file objects" are **always** associated with a model record (persisted or not), and as such, they are only used in the context of the [`file`](https://martenframework.com/docs/next/models-and-databases/reference/fields#file) model field. Finally, it's worth mentioning that file objects can be **attached** and/or **committed**: * an **attached** file object has an associated file set: in that case, its [`#attached?`](https://martenframework.com/docs/api/dev/Marten/DB/Field/File/File.html#attached%3F-instance-method) method returns `true` * a **committed** file object has an associated file that is _persisted_ to the underlying [storage](#file-storages): in that case, its [`#committed?`](https://martenframework.com/docs/api/dev/Marten/DB/Field/File/File.html#committed%3F%3ABool-instance-method) method returns `true` For example: ```crystal attachment = Attachment.last! attachment.uploaded_file.attached? # => true attachment.uploaded_file.committed? # => true ``` ### Accessing file properties File objects give access to basic file properties through the use of the following methods: | Method | Description | | ----------- | ----------- | | `#file` | Returns the associated / "wrapped" file object. This can be a real [`File`](https://crystal-lang.org/api/File.html) object, an uploaded file (instance of [`Marten::HTTP::UploadedFile`](https://martenframework.com/docs/api/dev/Marten/HTTP/UploadedFile.html)), or `nil` if no file is associated yet. | | `#name` | Returns the name of the file. | | `#size` | Returns the size of the file, using the associated [storage](#file-storages). | | `#url` | Returns the URL of the file, using the associated [storage](#file-storages). | ### Accessing the underlying file content File objects allow you to access the underlying file content through the use of the [`#open`](https://martenframework.com/docs/api/dev/Marten/DB/Field/File/File.html#open%3AIO-instance-method) method. This method returns an [`IO`](https://crystal-lang.org/api/IO.html) object. For example: ```crystal attachment = Attachment.last! file_io = attachment.uploaded_file.open puts file_io.gets_to_end ``` ### Updating the attached file It is possible to update the actual file of a "file object" by using the [`#save`](https://martenframework.com/docs/api/dev/Marten/DB/Field/File/File.html#save(filepath%3A%3A%3AString%2Ccontent%3AIO%2Csave%3Dfalse)%3ANil-instance-method) method. This method allows saving the content of a specified [`IO`](https://crystal-lang.org/api/IO.html) object and associating it with a specific file path in the underlying [storage](#file-storages). For example: ```crystal attachment = Attachment.new File.open("test.txt") do |file| attachment.uploaded_file.save("path/to/test.txt", file) attachment.save! end attachment.uploaded_file.url # => "/media/path/to/test.txt" ``` ### Deleting the attached file It is also possible to manually "delete" the file associated with the "file object". To do so, the [`#delete`](https://martenframework.com/docs/api/dev/Marten/DB/Field/File/File.html#delete(save%3Dfalse)%3ANil-instance-method) method can be used. It should be noted that calling this method will remove the association between the model record and the file AND will also delete the file in the considered [storage](#file-storages). For example: ```crystal attachment = Attachment.last! attachment.uploaded_file.delete attachment.uploaded_file.attached? # => false attachment.uploaded_file.committed? # => false ``` ## File storages Marten uses a file storage mechanism to perform file operations like saving files, deleting files, generating URLs, ... This file storages mechanism allows to save files in different backends by leveraging a standardized API (eg. in the local file system, in a cloud bucket, etc). By default, [`file`](https://martenframework.com/docs/next/models-and-databases/reference/fields#file) model fields make use of the configured "media" storage. This storage uses the [`settings.media_files`](https://martenframework.com/docs/next/development/reference/settings#media-files-settings) settings to determine what storage backend to use, and where to persist files. By default, the media storage uses the [`Marten::Core::Store::FileSystem`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/FileSystem.html) storage backend, which ensures that files are persisted in the local file system, where the Marten application is running. All the available file storages are listed in the [file storage reference](https://martenframework.com/docs/next/files/reference/stores). ### Interacting with the media file storage You won't usually need to interact directly with the file storage, but it's worth mentioning that storage objects share the same API. Indeed, the class of these storage objects must inherit from the [`Marten::Core::Storage::Base`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/Base.html) abstract class and implement a set of mandatory methods which provide the following functionalities: * saving files ([`#save`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/Base.html#save(filepath%3AString%2Ccontent%3AIO)%3AString-instance-method)) * deleting files ([`#delete`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/Base.html#delete(filepath%3AString)%3ANil-instance-method)) * opening files ([`#open`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/Base.html#open(filepath%3AString)%3AIO-instance-method)) * verifying that files exist ([`#exist?`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/Base.html#exists%3F(filepath%3AString)%3ABool-instance-method)) * retrieving file sizes ([`#size`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/Base.html#size(filepath%3AString)%3AInt64-instance-method)) * retrieving file URLs ([`#url`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/Base.html#url(filepath%3AString)%3AString-instance-method)) These capabilities are highlighted with the following example, where the media storage is used to interact with files: ```crystal file = File.open("test.txt") storage = Marten.media_files_storage filepath = storage.save("test.txt", file) storage.exists?(filepath) # => true storage.exists?("unknown") # => false storage.size(filepath) # => 13 storage.url(filepath) # => "/media/test_c43ba020.txt" storage.delete(filepath) # => nil storage.exists?(filepath) # => false ``` It should be noted that everything in the previous example could be done with a custom storage initialized manually as well: ```crystal file = File.open("test.txt") storage = Marten::Core::Storage::FileSystem.new(root: "/tmp", base_url: "/tmp") filepath = storage.save("test.txt", file) storage.exists?(filepath) # => true storage.exists?("unknown") # => false storage.size(filepath) # => 13 storage.url(filepath) # => "/tmp/test.txt" storage.delete(filepath) # => nil storage.exists?(filepath) # => false ``` ### Using a different storage with models As mentioned previously, [`file`](https://martenframework.com/docs/next/models-and-databases/reference/fields#file) model fields make use of the configured "media" storage by default. That being said, it is possible to leverage the `storage` option in order to make use of another storage if necessary. For example: ```crystal custom_storage = Marten::Core::Storage::FileSystem.new(root: "/tmp", base_url: "/tmp") class Attachment < Marten::Model field :id, :big_int, primary_key: true, auto: true field :uploaded_file, :file, blank: false, null: false, storage: custom_storage end ``` When doing this, all the file operations will be done using the configured storage instead of the default media storage. ## Serving uploaded files during development Marten provides a handler that you can use to serve media files in development environments only. This handler ([`Marten::Handlers::Defaults::Development::ServeMediaFile`](https://martenframework.com/docs/api/dev/Marten/Handlers/Defaults/Development/ServeMediaFile.html)) is automatically mapped to a route when creating new projects through the use of the [`new`](https://martenframework.com/docs/next/development/reference/management-commands#new) management command: ```crystal Marten.routes.draw do # Other routes... if Marten.env.development? path "#{Marten.settings.media_files.url}", Marten::Handlers::Defaults::Development::ServeMediaFile, name: "media_file" end end ``` As you can see, this route will automatically use the URL that is configured as part of the [`url`](https://martenframework.com/docs/next/development/reference/settings#url-1) media files setting. For example, this means that a `foo/bar.txt` media file would be served by the `/media/foo/bar.txt` route in development if the [`url`](https://martenframework.com/docs/next/development/reference/settings#url-1) setting is set to `/media/`. :::warning It is very important to understand that this handler should **only** be used in development environments. Indeed, the [`Marten::Handlers::Defaults::Development::ServeMediaFile`](https://martenframework.com/docs/api/dev/Marten/Handlers/Defaults/Development/ServeMediaFile.html) handler is not suited for production environments as it is not really efficient or secure. A better way to serve uploaded files is to leverage a web server or a cloud bucket for example (depending on the configured media files storage). ::: # Create custom file storages Source: https://martenframework.com/docs/next/files/how-to/create-custom-file-storages Marten uses a file storage mechanism to perform file operations like saving files, deleting files, generating URLs, ... This file storages mechanism allows to save files in different backends by leveraging a standardized API. You can leverage this capability to implement custom file storages (which you can then use for [assets](https://martenframework.com/docs/next/assets/introduction) or as part of [file model fields](https://martenframework.com/docs/next/files/uploading-files#persisting-uploaded-files-in-model-records)). ## Basic file storage implementation File storages are implemented as subclasses of the [`Marten::Core::Storage::Base`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/Base.html) abstract class. As such, they must implement a set of mandatory methods which provide the following functionalities: * saving files ([`#save`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/Base.html#save(filepath%3AString%2Ccontent%3AIO)%3AString-instance-method)) * deleting files ([`#delete`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/Base.html#delete(filepath%3AString)%3ANil-instance-method)) * opening files ([`#open`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/Base.html#open(filepath%3AString)%3AIO-instance-method)) * verifying that files exist ([`#exist?`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/Base.html#exists%3F(filepath%3AString)%3ABool-instance-method)) * retrieving file sizes ([`#size`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/Base.html#size(filepath%3AString)%3AInt64-instance-method)) * retrieving file URLs ([`#url`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/Base.html#url(filepath%3AString)%3AString-instance-method)) Note that you can fully customize how file storage objects are initialized. For example, a custom-made "file system" storage (that reads and writes files in a specific folder of the local file system) could be implemented as follows: ```crystal require "file_utils" class FileSystem < Marten::Core::Storage::Base def initialize(@root : String, @base_url : String) end def delete(filepath : String) : Nil File.delete(path(filepath)) rescue File::NotFoundError raise Marten::Core::Storage::Errors::FileNotFound.new("File '#{filepath}' cannot be found") end def exists?(filepath : String) : Bool File.exists?(path(filepath)) end def open(filepath : String) : IO File.open(path(filepath), mode: "rb") rescue File::NotFoundError raise Marten::Core::Storage::Errors::FileNotFound.new("File '#{filepath}' cannot be found") end def size(filepath : String) : Int64 File.size(path(filepath)) end def url(filepath : String) : String File.join(base_url, URI.encode_path(filepath)) end def write(filepath : String, content : IO) : Nil new_path = path(filepath) FileUtils.mkdir_p(Path[new_path].dirname) File.open(new_path, "wb") do |new_file| IO.copy(content, new_file) end end private getter root private getter base_url private def path(filepath) File.join(root, filepath) end end ``` ## Using custom file storages You have many options when it comes to using your custom file storage classes, and those depend on what you are trying to do: * if you want to use a custom storage for [assets](https://martenframework.com/docs/next/assets/introduction), then you will likely want to assign an instance of your custom storage class to the [`assets.storage`](https://martenframework.com/docs/next/development/reference/settings#storage) setting (see [Assets storage](https://martenframework.com/docs/next/assets/introduction#assets-storage) to learn more about assets storages specifically) * if you want to use a custom storage for all your [file model fields](https://martenframework.com/docs/next/models-and-databases/reference/fields#file), then you will likely want to assign an instance of your custom storage class to the [`media_files.storage`](https://martenframework.com/docs/next/development/reference/settings#storage-1) setting (see [File storages](https://martenframework.com/docs/next/files/managing-files#file-storages) to learn more about file storages specifically) # File storages Source: https://martenframework.com/docs/next/files/reference/stores ## Built-in storages ### File system storage A basic file system storage that stores files locally. This file storage is implemented as part of the [`Marten::Core::Storage::FileSystem`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/FileSystem.html) class. It ensures that files are persisted in the local file system, where the Marten application is running. For example: ```crystal Marten.configure do |config| config.media_files.storage = Marten::Core::Storage::FileSystem.new(root: "media", base_url: "/media/") end ``` ## Other stores Additional file storages shards are also maintained under the umbrella of the Marten project or by the community itself and can be used as part of your application depending on your specific caching requirements: * [`marten-s3`](https://github.com/martenframework/marten-s3) provides an [S3](https://aws.amazon.com/s3/) file storage :::info Feel free to contribute to this page and add links to your shards if you've created file storages that are not listed here! ::: # Development Source: https://martenframework.com/docs/next/development Marten provides various tools and mechanisms that you can leverage in order to develop, structure, and test projects and applications. ## Guides - [Settings](https://martenframework.com/docs/next/development/settings) - [Applications](https://martenframework.com/docs/next/development/applications) - [Management commands](https://martenframework.com/docs/next/development/management-commands) - [Generators](https://martenframework.com/docs/next/development/generators) - [Testing](https://martenframework.com/docs/next/development/testing) ## How-to's - [Configure database backends](https://martenframework.com/docs/next/development/how-to/configure-database-backends) - [Create custom commands](https://martenframework.com/docs/next/development/how-to/create-custom-commands) ## Reference - [Settings](https://martenframework.com/docs/next/development/reference/settings) - [Management commands](https://martenframework.com/docs/next/development/reference/management-commands) - [Generators](https://martenframework.com/docs/next/development/reference/generators) # Settings Source: https://martenframework.com/docs/next/development/settings Marten projects can be configured through the use of settings files. This section explains how settings work, how they relate to environments, and how they can be altered. ## Overview Settings will be usually defined under a `config/settings` folder at the root of your project structure. There are no strict requirements regarding _where_ settings are defined nor how they are organized, but as a general rule of thumb, it is recommended to organize settings on a per-environment basis (shared settings, development settings, production settings, etc). In such configuration, you will usually define shared settings (settings that are shared across all your environments) in a dedicated settings file (eg. `config/settings/base.cr`) and other environment-specific settings in other files (eg. `config/settings/development.cr`). To define settings, it is necessary to access the global Marten configuration object through the use of the [`Marten#configure`](https://martenframework.com/docs/api/dev/Marten.html#configure(env%3ANil|String|Symbol%3Dnil%2C%26)-class-method) method. This method returns a [`Marten::Conf::GlobalSettings`](https://martenframework.com/docs/api/dev/Marten/Conf/GlobalSettings.html) object that you can use to define setting values. For example: ```crystal Marten.configure do |config| config.installed_apps = [ FooApp, BarApp, ] config.middleware = [ Marten::Middleware::Session, Marten::Middleware::Flash, Marten::Middleware::GZip, Marten::Middleware::XFrameOptions, Marten::Middleware::XContentTypeOptions, Marten::Middleware::CrossOriginOpenerPolicy, ] config.database do |db| db.backend = :postgresql db.name = "dummypress" db.host = "localhost" db.password = "" end end ``` It should be noted that the [`Marten#configure`](https://martenframework.com/docs/api/dev/Marten.html#configure(env%3ANil|String|Symbol%3Dnil%2C%26)-class-method) method can be called with an additional argument to ensure that the underlying settings are defined for a specific environment only: ```crystal Marten.configure :development do |config| config.secret_key = "INSECURE" end ``` :::caution You should avoid altering setting values outside of the configuration block provided by the [`Marten#configure`](https://martenframework.com/docs/api/dev/Marten.html#configure(env%3ANil|String|Symbol%3Dnil%2C%26)-class-method) method. Most settings are "read" and applied when the Marten project is set up, that is before the server actually starts. Changing these setting values afterward won't produce any meaningful result. ::: ## Environments When creating new projects by using the [`new`](https://martenframework.com/docs/next/development/reference/management-commands#new) management command, the following environments will be created automatically: * Development (settings defined in `config/settings/development.cr`) * Test (settings defined in `config/settings/test.cr`) * Production (settings defined in `config/settings/production.cr`) When your application is running, Marten will rely on the `MARTEN_ENV` environment variable to determine the current environment. If this environment variable is not found, the environment will automatically default to `development`. The value you specify in the `MARTEN_ENV` environment variable must correspond to the argument you pass to the [`Marten#configure`](https://martenframework.com/docs/api/dev/Marten.html#configure(env%3ANil|String|Symbol%3Dnil%2C%26)-class-method) method. It should be noted that the current environment can be retrieved through the use of the [`Marten#env`](https://martenframework.com/docs/api/dev/Marten.html#env-class-method) method, which returns a [`Marten::Conf::Env`](https://martenframework.com/docs/api/dev/Marten/Conf/Env.html) object. For example: ```crystal Marten.env # => Marten.env.id # => "development" Marten.env.development? # => true ``` ## Available settings All the available settings are listed in the [settings reference](https://martenframework.com/docs/next/development/reference/settings). # Applications Source: https://martenframework.com/docs/next/development/applications Marten projects can be organized into logical and reusable components called "applications". These applications can contribute specific behaviors and abstractions to a project, including [models](https://martenframework.com/docs/next/models-and-databases), [handlers](https://martenframework.com/docs/next/handlers-and-http), [schemas](https://martenframework.com/docs/next/schemas/introduction), [emails](https://martenframework.com/docs/next/emailing/introduction), and [templates](https://martenframework.com/docs/next/templates). They can be packaged and reused across various projects as well. ## Overview A Marten **application** is a set of abstractions (defined under a dedicated and unique folder) that provides some set of features. These abstractions can correspond to [models](https://martenframework.com/docs/next/models-and-databases), [handlers](https://martenframework.com/docs/next/handlers-and-http), [templates](https://martenframework.com/docs/next/templates), [schemas](https://martenframework.com/docs/next/schemas), [emails](https://martenframework.com/docs/next/emailing/introduction), etc. Marten projects always use one or many applications. Indeed, each Marten project comes with a default [main application](#the-main-application) that corresponds to the standard `src` folder: models, migrations, or other classes defined in this folder are associated with the main application by default (unless they are part of another _explicitly defined_ application). As projects grow in size and scope, it is generally encouraged to start thinking in terms of applications and how to split models, handlers, or features across multiple apps depending on their intended responsibilities. Another benefit of applications is that they can be packaged and reused across multiple projects. This allows third-party libraries and shards to easily contribute models, migrations, handlers, or templates to other projects. ## Using applications The use of applications must be manually enabled within projects: this is done through the use of the [`installed_apps`](https://martenframework.com/docs/next/development/reference/settings#installed_apps) setting. This setting corresponds to an array of installed app classes. Indeed, each Marten application must define a subclass of [`Marten::App`](https://martenframework.com/docs/api/dev/Marten/App.html) to specify a few things such as the application label (see [Creating applications](#creating-applications) for more information about this). When those subclasses are specified in the `installed_apps` setting, the applications' models, migrations, assets, and templates will be made available to the considered project. For example: ```crystal Marten.configure do |config| config.installed_apps = [ FooApp, BarApp, ] end ``` Adding an application class inside this array will have the following impact on the considered project: * the models of this application and the associated migrations will be used * the templates of the application will be made available to the templates engine * the assets of the application will be made available to the assets engine * the management commands defined by the application will be made available to the Marten CLI ### The main application The "main" application is a default application that is always implicitly used by Marten projects (which means that it does not appear in the [`installed_apps`](https://martenframework.com/docs/next/development/reference/settings#installed_apps) setting). This application is associated with the standard `src` folder: this means that models, migrations, assets, or templates defined in this folder will be associated with the main application by default. For example, models defined under a `src/models` folder would be associated with the main application. :::info The main application is associated with the `main` label by default (unless explicitly configured otherwise through the use of the [`main_app_label`](https://martenframework.com/docs/next/development/reference/settings#main_app_label) setting). This means that models of the main application that do not define an explicit table name will have table names starting with `main_`. ::: It should be noted that it is possible to create _explicitly defined_ applications whose structures live under the `src` folder as well: the abstractions (eg. models, migrations, etc) of these applications will be associated with them and _not_ with the main application. This is because abstractions are always associated with the closest application in the files/folders structure. In the end, the main application provides a convenient way for starting projects and prototyping without requiring to spec out how projects will be organized in terms of applications upfront. That being said, as projects grow in size and scope, it is really encouraged to start thinking in terms of applications and how to split abstractions and features across multiple apps depending on their intended responsibilities. ### Order of installed applications You should note that the order in which installed applications are defined in the [`installed_apps`](https://martenframework.com/docs/next/development/reference/settings#installed_apps) setting can actually matter. For example, a "foo" app might define a `test.html` template, and a similar template with the exact same name might be defined by a "bar" app. If the "foo" app appears before the "bar" app in the array of installed apps, then requesting and rendering the `test.html` template will actually involve the "foo" app's template only. This is because template loaders associated with app directories iterate over applications in the order in which they are defined in the installed apps array. This is why it is always important to _namespace_ abstractions, assets, templates, and locales when creating applications. Failing to do so exposes apps to conflicts with other applications' code. As such, in the previous example, the "foo" app should've defined a `foo/test.html` template while the "bar" app should've defined a `bar/test.html` template to avoid possible conflicts. ## Creating applications Creating applications can be done very easily through the use of the [`app`](https://martenframework.com/docs/next/development/reference/generators#app) generator. For example: ```bash marten gen app blog ``` Running such a command will add a new `blog` application to the current project with the following structure: ``` src/blog ├── emails ├── handlers ├── migrations ├── models ├── schemas ├── templates ├── app.cr └── cli.cr ``` These files and folders are described below: | Path | Description | | ----------- | ----------- | | `emails/` | Empty directory where the [emails](https://martenframework.com/docs/next/emailing/introduction) of the application will be defined. | | `handlers/` | Empty directory where the [request handlers](https://martenframework.com/docs/next/handlers-and-http/introduction) of the application will be defined. | | `migrations/` | Empty directory that will store the [migrations](https://martenframework.com/docs/next/models-and-databases/migrations) that will be generated for the models of the application. | | `models/` | Empty directory where the [models](https://martenframework.com/docs/next/models-and-databases/introduction) of the application will be defined. | | `schemas/` | Empty directory where the [schemas](https://martenframework.com/docs/next/schemas/introduction) of the application will be defined. | | `templates/` | Empty directory where the [templates](https://martenframework.com/docs/next/templates/introduction) of the application will be defined. | | `app.cr` | Definition of the application configuration abstraction; this is also where application-specific file requirements should be made. | | `cli.cr` | Requirements of CLI-related files, such as migrations for example. | | `routes.cr` | Module containing the [routes](https://martenframework.com/docs/next/handlers-and-http/routing) of the application. | :::tip The [`app`](https://martenframework.com/docs/next/development/reference/generators#app) generator automatically ensures that: * The newly created application is added to the [`installed_apps`](https://martenframework.com/docs/next/development/reference/settings#installed_apps) setting. * Requirements for the application itself are added to the `src/project.cr` and `src/cli.cr` files. * The application's routes are included in the main routes map (which lives in the `config/routes.cr` file). ::: The most important file of an application is the `app.cr` one. This file usually includes all the app requirements and defines the application configuration class itself, which must be a subclass of the [`Marten::App`](https://martenframework.com/docs/api/dev/Marten/App.html) abstract class. This class allows mainly to define the "label" identifier of the application (through the use of the [`#label`](https://martenframework.com/docs/api/dev/Marten/Apps/Config.html#label(label%3AString|Symbol)-class-method) class method): this identifier must be unique across all the installed applications of a project and is used to generate things like model table names or migration classes. Here is an example `app.cr` file content for a hypothetic "blog" app: ```crystal require "./emails/**" require "./handlers/**" require "./models/**" require "./routes" require "./schemas/**" module Blog class App < Marten::App label "blog" end end ``` :::info _Where_ the `app.cr` file is located is important: the directory where this file is defined is also the directory where key folders like `models`, `migrations`, `templates`, etc, must be present. This is necessary to ensure that these files and abstractions are associated with the considered app. ::: Another very important file is the `cli.cr` one: this file is there to define all the CLI-related requirements and will usually be required directly by your project's `manage.cr` file. _A minima_ the `cli.cr` file should require model migrations, but it could also require the management commands provided by the application. For example: ```crystal require "./cli/**" require "./migrations/**" ``` ### Defining settings for applications Applications that you create as part of your projects or third-party libraries can have their own associated settings, configurable through the use of regular [settings files](https://martenframework.com/docs/next/development/settings). In order to define settings for your applications, the simplest way is to create a `settings.cr` file containing a subclass of [`Marten::Conf::Settings`](https://martenframework.com/docs/api/dev/Marten/Conf/Settings.html) in your application's folder. This subclass must make use of the [`#namespace`](https://martenframework.com/docs/api/dev/Marten/Conf/Settings.html#namespace(ns)-macro) macro in order to define the setting "namespace" under which your application's settings will be accessible. For example: ```crystal module Blog class Settings < Marten::Conf::Settings namespace :blog @my_setting : String = "foo" getter my_setting setter my_setting end end ``` With the above example, it will be possible to configure the `blog.my_setting` setting as follows in a project's settings file: ```crystal Marten.configure do |config| config.blog.my_setting = "bar" end ``` As you can see, the application's settings are configurable like any other built-in settings, but they are namespaced to the namespace value that was defined in the `Blog::Settings` class through the use of the [`#namespace`](https://martenframework.com/docs/api/dev/Marten/Conf/Settings.html#namespace(ns)-macro) macro. It's important to note that [`Marten::Conf::Settings`](https://martenframework.com/docs/api/dev/Marten/Conf/Settings.html) subclasses have the flexibility to define any necessary methods to facilitate user configuration for the considered application. While basic settings typically necessitate only getters and setters for configuration, more intricate scenarios may demand additional methods, the utilization of blocks, or other complexities. # Management commands Source: https://martenframework.com/docs/next/development/management-commands Marten comes with a built-in command line interface (CLI) that developers can leverage to perform common actions and interact with the framework. This tool provides a set of built-in sub-commands that can be easily extended with new commands. ## Usage The `marten` command is available with each Marten installation, and it is also automatically compiled when the Marten shard is installed. This means that you can either use the `marten` command from anywhere in your system (if the Marten CLI was installed globally like described in [Installation](https://martenframework.com/docs/next/getting-started/installation)) or you can run the relative `bin/marten` command from inside your project structure. When the `marten` command is executed, it will look for a relative `manage.cr` file to identify your current project, its [settings](https://martenframework.com/docs/next/development/settings), and its installed [applications](https://martenframework.com/docs/next/development/applications), which in turn will define the available sub-commands that you can run. The `marten` command is intended to be used as follows: ```bash marten [command] [options] [arguments] ``` As you can see, the `marten` CLI must be used with a specific **command**, possibly followed by **options** and **arguments** (which may be required or not depending on the considered command). All the built-in commands are listed in the [management commands reference](https://martenframework.com/docs/next/development/reference/management-commands). ### Displaying help information You can display help information about a specific management command by using the `marten` CLI as follows: ```bash marten help [command] marten [command] --help ``` ### Listing commands It is possible to list all the available commands within a project by running the `marten` CLI as follows: ```bash marten help ``` This should output something like this: ```bash Usage: marten [command] [options] [arguments] Available commands: [marten] › clearsessions Clear all expired sessions. › collectartifacts Collect runtime artifacts required by compiled applications. › collectassets Collect all the assets and copy them in a unique storage. › gen / g Generate various structures, abstractions, and values within an existing project. › genmigrations Generate new database migrations. › listmigrations List all database migrations. › migrate Run database migrations. › new Initialize a new Marten project or application repository. › play Start a Crystal playground server initialized for the current project. › resetmigrations Reset an existing set of migrations into a single one. › routes Display all the routes of the application. › seed Populate the database by running the seed file. › serve / s Start a development server that is automatically recompiled when source files change. › version Show the Marten version. Run a command followed by --help to see command specific information, ex: marten [command] --help ``` All the available commands are listed per application: by default, only `marten` commands are listed obviously (if no other applications are installed), but it should be noted that [applications](https://martenframework.com/docs/next/development/applications) can contribute management commands as well. If that's the case, these additional commands will be automatically listed as well. ### Shared options Each command can accept its own set of arguments and options, but it should be noted that all the available commands always accept the following options: * `--error-trace` - Allows showing the full error trace (if a compilation is involved) * `--log-level=level` - Set the log level (default to "info") * `--no-color` - Disables colored outputs * `-h, --help` - Displays help information about the considered command ## Available commands Please head over to the [management commands reference](https://martenframework.com/docs/next/development/reference/management-commands) to see a list of all the available management commands. Implementing custom management commands is also a possibility that is documented in [Create custom commands](https://martenframework.com/docs/next/development/how-to/create-custom-commands). # Generators Source: https://martenframework.com/docs/next/development/generators Marten features a generator mechanism that simplifies the creation of various abstractions, files, and structures within an existing project. This feature facilitates the generation of key components such as [models](https://martenframework.com/docs/next/models-and-databases/introduction), [schemas](https://martenframework.com/docs/next/schemas/introduction), [emails](https://martenframework.com/docs/next/emailing/introduction), or [applications](https://martenframework.com/docs/next/development/applications). By leveraging generators, developers can improve their workflow and speed up the development of their Marten projects while following best practices. ## Usage Generators can be invoked by leveraging the [`marten gen`](https://martenframework.com/docs/next/development/reference/management-commands#gen) management command. This command is intended to be used as follows: ```bash marten gen [generator] [options] [arguments] ``` As you can see, the `marten gen` command must be used with a specific **generator** name, possibly followed by **options** and **arguments** (which may be required or not depending on the considered generator). All the built-in generators are listed in the [generators reference](https://martenframework.com/docs/next/development/reference/generators). ### Displaying help information You can display help information about a specific generator by using the `marten gen` command as follows: ```bash marten gen [generator] --help ``` ### Listing generators It is possible to list all the available generators within a project by running the `marten gen` command as follows: ```bash marten gen ``` This should output something like this: ``` Usage: marten gen [options] [generator] Generate various structures, abstractions, and values within an existing project. Arguments: generator Name of the generator to use Options: --error-trace Show full error trace (if a compilation is involved) --no-color Disable colored output -h, --help Show this help Available generators are listed below. [marten] › app › auth › email › handler › model › schema › secretkey Run a generator followed by --help to see generator specific information, ex: marten gen [generator] --help ``` ## Examples ### Generating a model Generating a model can be achieved with the [`model`](https://martenframework.com/docs/next/development/reference/generators#model) generator: ```bash # Generate a model in the main app: marten gen model User name:string email:string # Generate a model in the admin app: marten gen model User name:string email:string --app admin # Generate a model with a many-to-one reference: marten gen model Article label:string body:text author:many_to_one{User} # Generate a model with a parent class: marten gen model Admin::User name:string email:string --parent User # Generate a model without timestamps: marten gen model User name:string email:string --no-timestamps ``` ### Generating an email Generating an email can be achieved with the [`email`](https://martenframework.com/docs/next/development/reference/generators#email) generator: ```bash marten gen email TestEmail # Generate a new TestEmail email in the main application marten gen email TestEmail --app blog # Generate a new TestEmail email in the blog application ``` ### Generating an application Generating an application can be achieved with the [`app`](https://martenframework.com/docs/next/development/reference/generators#app) generator: ```bash marten gen app blogging # Generate a new 'blogging' application ``` ## Available generators Please head over to the [generators reference](https://martenframework.com/docs/next/development/reference/generators) to see a list of all the available generators. # Testing Source: https://martenframework.com/docs/next/development/testing This section covers the basics regarding how to test a Marten project and the various tools that you can leverage in this regard. ## The basics You should test your Marten project to ensure that it adheres to the specifications it was built for. Like any Crystal project, Marten lets you write "specs" (see the [official documentation related to testing in Crystal](https://crystal-lang.org/reference/guides/testing.html) to learn more about those). By default, when creating a project through the use of the [`new`](https://martenframework.com/docs/next/development/reference/management-commands#new) management command, Marten will automatically create a `spec/` folder at the root of your project structure. This folder contains a unique `spec_helper.cr` file allowing you to initialize the test environment for your Marten project. This file should look something like this: ```crystal title=spec/spec_helper.cr ENV["MARTEN_ENV"] = "test" require "spec" require "marten" require "marten/spec" require "../src/project" ``` As you can see, the `spec_helper.cr` file forces the Marten environment variable to be set to `test` and requires the spec library as well as Marten and your actual project. This file should be required by all your spec files. :::info It's very important to require `marten/spec` in your top-level spec helper as this will ensure that the mandatory spec callbacks are configured for your spec suite (eg. in order to ensure that your database is properly set up before each spec is executed). ::: When it comes to running your tests, you can simply make use of the standard [`crystal spec`](https://crystal-lang.org/reference/man/crystal/index.html#crystal-spec) command. ## Writing tests To write tests, you should write regular [specs](https://crystal-lang.org/reference/guides/testing.html) and ensure that your spec files always require the `spec/spec_helper.cr` file. For example: ```crystal require "./spec_helper" describe MySuperAbstraction do describe "#foo" do it "returns bar" do obj = MySuperAbstraction.new obj.foo.should eq "bar" end end end ``` You are encouraged to organize your spec files by following the structure of your projects. For example, you could create a `models` folder and define specs related to your models in it. :::tip When organizing spec files across multiple folders, one good practice is to define a `spec_helper.cr` file at each level of your folders structure. These additional `spec_helper.cr` files should require the same file from the parent folder. For example: ```crystal title=spec/models/spec_helper.cr require "../spec_helper" ``` ```crystal title=spec/models/article_spec.cr require "./spec_helper" describe Article do # ... end ``` ::: ## Running tests As mentioned before, running specs involves making use of the standard [`crystal spec`](https://crystal-lang.org/reference/man/crystal/index.html#crystal-spec) command. ### The test environment By default, the [`new`](https://martenframework.com/docs/next/development/reference/management-commands#new) management command always creates a `test` environment when generating new projects. As such, you should ensure that the `MARTEN_ENV` environment variable is set to `test` when running your Crystal specs. It should also be reminded that this `test` environment is associated with a dedicated settings file where test-related settings can be specified and/or overridden if necessary (see [Settings](https://martenframework.com/docs/next/development/settings#environments) for more details about this). ### The test database Marten **must** use a different database when running tests in order to not tamper with your regular database. Indeed, the database used in the context of specs will be flushed and generated automatically every time the specs suite is executed. You should not set these database names to the same names as the ones used for your development or production environments. If test database names are not explicitly set, your specs suite won't be allowed to run at all. One way to ensure you use a dedicated database specifically for tests is to override the [`database`](https://martenframework.com/docs/next/development/reference/settings#database-settings) settings as follows: ```crystal title=config/settings/test.cr Marten.configure :test do |config| config.database do |db| db.name = "my_project_test" end end ``` ## Testing tools Marten provides some tools that can become useful when writing specs. ### Using the test client The test client is an abstraction that is provided when requiring `marten/spec` and that acts as a very basic web client. This tool allows you to easily test your handlers and the various routes of your application by issuing requests and by introspecting the returned responses. By leveraging the test client, you can easily simulate various requests (eg. GET or POST requests) for specific URLs and observe the returned responses. While doing so, you can introspect the response properties (such as its status code, content, and headers) in order to verify that your handlers behave as expected. #### A simple example To use the test client, you can either initialize a [`Marten::Spec::Client`](https://martenframework.com/docs/api/dev/Marten/Spec/Client.html) object or make use of the per-spec test client that is provided by the [`Marten::Spec#client`](https://martenframework.com/docs/api/dev/Marten/Spec.html#client%3AClient-class-method) method. Initializing new [`Marten::Spec::Client`](https://martenframework.com/docs/api/dev/Marten/Spec.html#client%3AClient-class-method) objects allow you to set client-wide properties, like a default content type. :::info Note that the client returned by the [`Marten::Spec#client`](https://martenframework.com/docs/api/dev/Marten/Spec.html#client%3AClient-class-method) method is memoized and is reset after _each_ spec execution. ::: Let's have a look at a simple way to use the test client and verify the corresponding responses: ```crystal describe MyRedirectHandler do describe "#get" do it "returns the expected redirect response" do response = Marten::Spec.client.get("/my-redirect-handler", query_params: {"foo" => "bar"}) response.status.should eq 302 response.headers["Location"].should eq "/redirected" end end end ``` :::tip In the above example we are simply specifying a "raw" path by hardcoding its value. In a real scenario, you will likely want to [resolve your handler URLs](https://martenframework.com/docs/next/handlers-and-http/routing#reverse-url-resolutions) using the [`Marten::Routing::Map#reverse`](https://martenframework.com/docs/api/dev/Marten/Routing/Map.html#reverse(name%3AString|Symbol%2Cparams%3AHash(String|Symbol%2CParameter%3A%3ATypes))-instance-method) method of the main routes map (that way, you don't hardcode route paths in your specs). For example ```crystal url = Marten.routes.reverse("article_detail", pk: 42) response = Marten::Spec.client.get(url, query_params: {"foo" => "bar"}) ``` ::: Here we are simply issuing a GET request (by leveraging the [`#get`](https://martenframework.com/docs/api/dev/Marten/Spec/Client.html#get(path%3AString%2Cquery_params%3AHash|NamedTuple|Nil%3Dnil%2Ccontent_type%3AString|Nil%3Dnil%2Cheaders%3AHash|NamedTuple|Nil%3Dnil%2Csecure%3Dfalse)%3AMarten%3A%3AHTTP%3A%3AResponse-instance-method) test client method) and testing the obtained response. A few things can be noted: * The test client does not require your project's server to be running: internally it uses a lightweight server handlers chain that ensures that your project's middlewares are applied and that the URL you requested is resolved and mapped to the right handler * Only the path to the handler needs to be specified when issuing requests (eg. `/foo/bar`) Note that you can also issue other types of requests by leveraging methods like [`#post`](https://martenframework.com/docs/api/dev/Marten/Spec/Client.html#post(path%3AString%2Cdata%3AHash|NamedTuple|Nil|String%3Dnil%2Cquery_params%3AHash|NamedTuple|Nil%3Dnil%2Ccontent_type%3AString|Nil%3Dnil%2Cheaders%3AHash|NamedTuple|Nil%3Dnil%2Csecure%3Dfalse)%3AMarten%3A%3AHTTP%3A%3AResponse-instance-method), [`#put`](https://martenframework.com/docs/api/dev/Marten/Spec/Client.html#put(path%3AString%2Cdata%3AHash|NamedTuple|Nil|String%3Dnil%2Cquery_params%3AHash|NamedTuple|Nil%3Dnil%2Ccontent_type%3AString|Nil%3Dnil%2Cheaders%3AHash|NamedTuple|Nil%3Dnil%2Csecure%3Dfalse)%3AMarten%3A%3AHTTP%3A%3AResponse-instance-method), or [`#delete`](https://martenframework.com/docs/api/dev/Marten/Spec/Client.html#delete(path%3AString%2Cdata%3AHash|NamedTuple|Nil|String%3Dnil%2Cquery_params%3AHash|NamedTuple|Nil%3Dnil%2Ccontent_type%3AString|Nil%3Dnil%2Cheaders%3AHash|NamedTuple|Nil%3Dnil%2Csecure%3Dfalse)%3AMarten%3A%3AHTTP%3A%3AResponse-instance-method). For example: ```crystal describe MySchemaHandler do describe "#post" do it "validates the data and redirects" do response = Marten::Spec.client.post("/my-schema-handler", data: {"first_name" => "John", "last_name" => "Doe"}) response.status.should eq 302 response.headers["Location"].should eq "/redirected" end end end ``` :::info By default, CSRF checks are disabled for requests issued by the test client. If for some reasons you need to ensure that those are enabled, you can initialize a [`Marten::Spec::Client`](https://martenframework.com/docs/api/dev/Marten/Spec/Client.html) object with `disable_request_forgery_protection: false`. ::: #### Introspecting responses Responses returned by the test client are instances of the standard [`Marten::HTTP::Response`](https://martenframework.com/docs/api/dev/Marten/HTTP/Response.html) class. As such you can easily access response attributes such as the status code, the content and content type, cookies, and headers in your specs in order to verify that the expected response was returned by your handler. #### Exceptions It is important to note that exceptions raised in your handlers will be visible from your spec. This means that you should use the standard [`#expect_raises`](https://crystal-lang.org/api/Spec/Expectations.html#expect_raises%28klass%3AT.class%2Cmessage%3AString%7CRegex%7CNil%3Dnil%2Cfile%3D__FILE__%2Cline%3D__LINE__%2C%26%29forallT-instance-method) expectation helper to verify that these exceptions are indeed raised. #### Session and cookies Test clients are always stateful: if a handler sets a cookie in the returned response, then this cookie will be stored in the client's cookie store (available via the [`#cookies`](https://martenframework.com/docs/api/dev/Marten/Spec/Client.html#cookies-instance-method) method) and will be automatically sent for subsequent requests issued by the client. The same goes for session values: such values can be set using the session store returned by the [`#sessions`](https://martenframework.com/docs/api/dev/Marten/Spec/Client.html#session-instance-method) client method. If you set session values in this store prior to any request, the matched handler will have access to them and the new values that are set by the handler will be available for further inspection once the response is returned. These session values are also maintained between requests issued by a single client. For example: ```crystal describe MyHandler do describe "#get" do it "renders the expected content if the right value is in the session" do Marten::Spec.client.session["foo"] = "bar" url = Marten.routes.reverse("initiate_request") response = Marten::Spec.client.get(url) response.status.should eq 200 response.content.includes?("Initiate request").should be_true end end end ``` #### Flash messages Similarly to accessing session values, you can also access flash messages by leveraging the [`#flash`](https://martenframework.com/docs/api/dev/Marten/Spec/Client.html#flash-instance-method) method of the test client. This method returns a [`Marten::HTTP::FlashStore`](https://martenframework.com/docs/api/dev/Marten/HTTP/FlashStore.html) object, initialized from the currently configured session store. This can be helpful to access flash messages that might have been set by handlers and verify that they have the expected values. For example: ```crystal describe MyHandler do describe "#post" do it "sets the expected flash message and redirects to the expected URL" do url = Marten.routes.reverse("do_something") response = Marten::Spec.client.post(url, data: {"foo" => "bar"}) response.status.should eq 302 response.headers["Location"].should eq "/success" Marten::Spec.client.flash[:notice].should eq "Action successfully completed!" end end end ``` #### Testing client and authentication When using the [marten-auth](https://github.com/martenframework/marten-auth) shard and the built-in [authentication](https://martenframework.com/docs/next/authentication), a few additional helpers can be leveraged in order to easily sign in/sign out users while using the test client: * The `#sign_in` method can be used to simulate the effect of a signed-in user. This means that the user ID will be persisted into the test client session and that requests issued with it will be associated with the considered user * The `#sign_out` method can be used to ensure that any signed-in user is logged out and that the session is flushed For example: ```crystal describe MyHandler do describe "#get" do it "shows the profile page of the authenticated user" do user = Auth::User.create!(email: "test@example.com") do |user user.set_password("insecure") end url = Marten.routes.reverse("auth:profile") Marten::Spec.client.sign_in(user) response = Marten::Spec.client.get(url) response.status.should eq 200 response.content.includes?("Profile").should be_true end end end ``` ### Collecting emails If your code is sending [emails](https://martenframework.com/docs/next/emailing/introduction), you might want to test that these emails are sent as expected. To do that, you can leverage the [development emailing backend](https://martenframework.com/docs/next/emailing/reference/backends#development-backend) to ensure that sent emails are collected as part of each spec execution. To do that, the emailing backend needs to be initialized with `collect_emails: true` when configuring the [`emailing.backend`](https://martenframework.com/docs/next/development/reference/settings#backend-1) setting. For example: ```crystal title=config/settings/test.cr Marten.configure :test do |config| config.backend = Marten::Emailing::Backend::Development.new(collect_emails: true) end ``` Doing so will ensure that all sent emails are "collected" for further inspection. You can easily retrieve collected emails by calling the [`Marten::Spec#delivered_emails`](https://martenframework.com/docs/api/dev/Marten/Spec.html#delivered_emails%3AArray(Emailing%3A%3AEmail)-class-method) method, which returns an array of [`Marten::Email`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html) instances. For example: ```crystal describe MyObject do describe "#do_something" do it "sends an email as expected" do obj = MyObject.new obj.do_something Marten::Spec.delivered_emails.size.should eq 1 Marten::Spec.delivered_emails[0].subject.should eq "Test subject" end end end ``` :::info Note that Marten also automatically ensures that the collected emails are automatically reset after each spec execution so that you don't have to take care of that directly. ::: # Configure database backends Source: https://martenframework.com/docs/next/development/how-to/configure-database-backends This guide provides instructions on configuring new database backends or changing the existing database backend within your existing Marten projects. ## Context Marten officially supports **MariaDB**, **MySQL**, **PostgreSQL**, and **SQLite3** databases. New Marten projects default to utilizing a SQLite3 database, a lightweight serverless database application that is typically pre-installed on most existing operating systems. This makes it an excellent choice for a development or testing database, but you may want to use a more powerful database such as MariaDB, MySQL, or PostgreSQL. In this light, this guide explains what steps should be taken in order to use your database backend of choice in a Marten project. ## Prerequisites This guide presupposes that you already have a functional Marten project available. If you don't, you can easily create one using the following command: ```bash marten new project ``` Furthermore, it assumes that your preferred database is properly configured and ready for use. If this isn't the case, please consult the respective official documentation to install your chosen database: * [PostgreSQL Installation Guide](https://wiki.postgresql.org/wiki/Detailed_installation_guides) * [MariaDB Installation Guide](https://mariadb.com/kb/en/getting-installing-and-upgrading-mariadb) * [MySQL Installation Guide](https://dev.mysql.com/doc/refman/8.0/en/installing.html) * [SQLite Installation Guide](https://www.tutorialspoint.com/sqlite/sqlite_installation.htm) ## Installing the right database shard For each database, a dedicated Crystal shard is required. Depending on your chosen database, you must include one of the following entries in your project's `shard.yml` file: * [crystal-pg](https://github.com/will/crystal-pg) (required for PostgreSQL databases) * [crystal-mysql](https://github.com/crystal-lang/crystal-mysql) (required for MariaDB or MySQL databases) * [crystal-sqlite3](https://github.com/crystal-lang/crystal-sqlite3) (required for SQLite3 databases) This means that your `shard.yml` file should resemble one of the following examples: ### MariaDB or MySQL ```yaml title="shard.yml" name: myproject version: 0.1.0 dependencies: marten: github: martenframework/marten // highlight-next-line mysql: // highlight-next-line github: crystal-lang/crystal-mysql ``` ### PostgreSQL ```yaml title="shard.yml" name: myproject version: 0.1.0 dependencies: marten: github: martenframework/marten // highlight-next-line pg: // highlight-next-line github: will/crystal-pg ``` ### SQLite3 ```yaml title="shard.yml" name: myproject version: 0.1.0 dependencies: marten: github: martenframework/marten // highlight-next-line sqlite3: // highlight-next-line github: crystal-lang/crystal-sqlite3 ``` ## Adding the right DB Crystal requirement After you've included the correct Crystal shard in your project's `shard.yml` file, the subsequent task is to add the corresponding requirement in the `src/project.cr` file. This file contains all the requirements of your project (including Marten itself) and is automatically generated by the [`new`](https://martenframework.com/docs/next/development/reference/management-commands#new) management command. Please consult the examples below to determine which requirement you should include based on your selected database backend: ### MariaDB or MySQL ```crystal title="src/project.cr" # Third party requirements. require "marten" // highlight-next-line require "mysql" # Project requirements. # [...] # Configuration requirements. # [...] ``` ### PostgreSQL ```crystal title="src/project.cr" # Third party requirements. require "marten" // highlight-next-line require "pg" ``` ### SQLite3 ```crystal title="src/project.cr" # Third party requirements. require "marten" // highlight-next-line require "sqlite3" ``` ## Configuring your database The last step involves configuring database settings in one of your settings files (eg. `config/settings/base.cr`) so that they target the database you intend to use with your Marten project. While a comprehensive list of configuration options is available in the [Database settings reference](https://martenframework.com/docs/next/development/reference/settings#database-settings), the following sections offer example configurations tailored to each supported database backend. ### MariaDB or MySQL ```crystal title="config/settings/base.cr" # Using a block: config.database do |db| db.backend = :mysql db.host = "localhost" db.port = 1234 db.name = "my_db" db.user = "my_user" db.password = "insecure" end # Using a connection URL: config.database url: "mysql://my_user:insecure@localhost:1234/my_db" ``` ### PostgreSQL ```crystal title="config/settings/base.cr" # Using a block: config.database do |db| db.backend = :postgresql db.host = "localhost" db.port = 1234 db.name = "my_db" db.user = "my_user" db.password = "insecure" end # Using a connection URL: config.database url: "postgres://my_user:insecure@localhost:1234/my_db" ``` ### SQLite3 ```crystal title="config/settings/base.cr" # Using a block: config.database do |db| db.backend = :sqlite db.name = "my_db.db" end # Using a connection URL: config.database url: "sqlite3://my_db.db" ``` # Create custom commands Source: https://martenframework.com/docs/next/development/how-to/create-custom-commands Marten lets you create custom management commands as part of your [applications](https://martenframework.com/docs/next/development/applications). This allows you to contribute new features and behaviors to the Marten CLI. ## Basic management command definition Custom management commands are defined as subclasses of the [`Marten::CLI::Command`](https://martenframework.com/docs/api/dev/Marten/CLI/Manage/Command/Base.html) abstract class. Such subclasses should be defined in a `cli/` folder at the root of the application, and it should be ensured that they are required by your `cli.cr` file (see [Creating applications](https://martenframework.com/docs/next/development/applications#creating-applications) for more details regarding the structure of an application). Management command classes must at least define a [`#run`](https://martenframework.com/docs/api/dev/Marten/CLI/Manage/Command/Base.html#run-instance-method) method, which will be called when the subcommand is executed: ```crystal class MyCommand < Marten::CLI::Command help "Command that does something" def run # Do something end end ``` As you can see in the previous example, the [`#help`](https://martenframework.com/docs/api/dev/Marten/CLI/Manage/Command/Base.html#help(help%3AString)-class-method) class method allows setting a "help text" that will be displayed when the help information of the command is requested. If the above command was part of an installed application, it could be executed by using the Marten CLI as follows: ```bash marten my_command ``` ## Accepting options and arguments Marten management commands can accept options and arguments. These differ and may be used for different use cases: * options usually use the `-h` / `--help` style and can receive arguments if needed. They can be specified in any order * arguments are _positional_ and only their values must be specified By default options and arguments are always optional. That being said, they can be made mandatory in the command execution logic if needed. Both options and arguments must be specified in the optional [`#setup`](https://martenframework.com/docs/api/dev/Marten/CLI/Manage/Command/Base.html#setup-instance-method) method: this method will be called to prepare the definition of the command, including its arguments and options. For example: ```crystal class MyCommand < Marten::CLI::Command help "Command that does something" @arg1 : String? @example : Bool = false def setup on_argument(:arg1, "The first argument") { |v| @arg1 = v } on_option("example", "An example option") { @example = true } end def run # Do something end end ``` In the above example, the [`#on_argument`](https://martenframework.com/docs/api/dev/Marten/CLI/Manage/Command/Base.html#on_argument(name%3AString|Symbol%2Cdescription%3AString%2C%26block%3AString->)-instance-method) instance method is used to define an `arg1` argument. This method requires an argument name, an associated help text, and a proc where the value of the argument will be forwarded at execution time (which allows you to assign it to an instance variable or process it if you wish to). Similarly, the [`#on_option`](https://martenframework.com/docs/api/dev/Marten/CLI/Manage/Command/Base.html#on_option(flag%3AString|Symbol%2Cdescription%3AString%2C%26block%3AString->)-instance-method) instance method is used to define an `example` option. In this case, the name of the option and its associated help text must be specified, and a proc can be defined to identify that the option was specified at execution time (which can be used to set a related boolean instance variable for example). The above command would produce the following help information: ``` Usage: marten my_command [options] [arg1] Command that does something Arguments: arg1 The first argument Options: --example An example option --error-trace Show full error trace (if a compilation is involved) --no-color Disable colored output -h, --help Show this help ``` ### Configuring options As mentioned previously, it is possible to make use of the [`#on_option`](https://martenframework.com/docs/api/dev/Marten/CLI/Manage/Command/Base.html#on_option(flag%3AString|Symbol%2Cdescription%3AString%2C%26block%3AString->)-instance-method) instance method to configure a specific command option (eg. `--option`). It expects a flag name and a description, and it yields a block to let the command properly assign the option value to the command object at execution time: ```crystal on_option("example", "An example option") { @example = true } ``` Note that the `--` must not be included in the option name. Alternatively, it is possible to specify options that accept both a short flag (eg. `-h`) and a long flag (eg. `--help`): ```crystal on_option("e", "example", "An example option") { @example = true } ``` ### Configuring options that accept arguments It is possible to make use of the [`#on_option_with_arg`](https://martenframework.com/docs/api/dev/Marten/CLI/Manage/Command/Base.html#on_option_with_arg(flag%3AString|Symbol%2Carg%3AString|Symbol%2Cdescription%3AString%2C%26block%3AString->)-instance-method) instance method to configure a specific command option with an associated argument. This method will configure a command option (eg. `--option`) and an associated argument. It expects a flag name, an argument name, and a description. It yields a block to let the command properly assign the option to the command object at execution time: ```crystal on_option_with_arg(:option, :arg, "The name of the option") { @arg = arg } ``` Alternatively, it is possible to specify options that accept both a short flag (eg. `-h`) and a long flag (eg. `--help`): ```crystal on_option_with_arg("o", "option", "arg", "The name of the option") { |arg| @arg = arg } ``` ### Configuring arguments As mentioned previously, it is possible to make use of the [`#on_argument`](https://martenframework.com/docs/api/dev/Marten/CLI/Manage/Command/Base.html#on_argument(name%3AString|Symbol%2Cdescription%3AString%2C%26block%3AString->)-instance-method) instance method in order to configure a specific command argument. This method expects an argument name and a description, and it yields a block to let the command properly assign the argument value to the command object at execution time: ```crystal on_argument(:arg, "The name of the argument") { |value| @arg_var = value } ``` :::caution It should be noted that the order in which arguments are defined is important: this order corresponds to the order in which arguments will need to be specified when invoking the subcommand. ::: ## Outputting text contents When writing management commands, you will likely need to write text contents to the output file descriptor. To do so, you can make use of the [`#print`](https://martenframework.com/docs/api/dev/Marten/CLI/Manage/Command/Base.html#print(msg%2Cending%3D"\n")-instance-method) instance method: ```crystal class HelloWorldCommand < Marten::CLI::Command help "Command that prints Hello World!" def run print("Hello World!") end end ``` It should be noted that you can also choose to "style" the content you specify to [`#print`](https://martenframework.com/docs/api/dev/Marten/CLI/Manage/Command/Base.html#print(msg%2Cending%3D"\n")-instance-method) by wrapping your string with a call to the [`#style`](https://martenframework.com/docs/api/dev/Marten/CLI/Manage/Command/Base.html#style(msg%2Cfore%3Dnil%2Cmode%3Dnil)-instance-method) method. For example: ```crystal class HelloWorldCommand < Marten::CLI::Command help "Command that prints Hello World!" def run print(style("Hello World!", fore: :light_blue, mode: :bold)) end end ``` As you can see, the [`#style`](https://martenframework.com/docs/api/dev/Marten/CLI/Manage/Command/Base.html#style(msg%2Cfore%3Dnil%2Cmode%3Dnil)-instance-method) method can be used to apply `fore` and `mode` styles to a specific text value. The values you can use for the `fore` and `mode` arguments are the same as the ones that you can use with the [`Colorize`](https://crystal-lang.org/api/Colorize.html) module (which comes with the standard library). ## Handling error cases You will likely want to handle error situations when writing management commands. For example, to return error messages if a specified argument is not provided or if it is invalid. To do so you can make use of the [`#print_error`](https://martenframework.com/docs/api/dev/Marten/CLI/Manage/Command/Base.html#print_error(msg)-instance-method) helper method, which will print the passed string to the error file descriptor: ```crystal class HelloWorldCommand < Marten::CLI::Command help "Command that prints Hello World!" @name : String? def setup on_argument(:name, "A name") { |v| @name = v } end def run if @name.nil? print_error("A name must be provided!") else print("Hello World, #{@name}!") end end end ``` Alternatively, you can make use of the [`#print_error_and_exit`](https://martenframework.com/docs/api/dev/Marten/CLI/Manage/Command/Base.html#print_error_and_exit(msg%2Cexit_code%3D1)-instance-method) method to print a message to the error file descriptor and to exit the execution of the command. ## Customizing the subcommand name By default, management command names are inferred by using their associated class names (eg. a `MyCommand` command class would translate to a `my_command` subcommand). That being said, it should be noted that you can define a custom subcommand name by leveraging the [`#command_name`](https://martenframework.com/docs/api/dev/Marten/CLI/Manage/Command/Base.html#command_name(name%3AString|Symbol)-class-method) class method: ```crystal class MyCommand < Marten::CLI::Command command_name :dummycommand help "Command that does something" def run # Do something end end ``` It is also worth mentioning that command aliases can be configured easily by using the [`#command_aliases`](https://martenframework.com/docs/api/dev/Marten/CLI/Manage/Command/Base.html#command_aliases(*aliases%3AString|Symbol)-class-method) helper method. For example: ```crystal class MyCommand < Marten::CLI::Command command_name :test command_aliases :t help "Command that does something" def run # Do something end end ``` # Settings Source: https://martenframework.com/docs/next/development/reference/settings This page provides a reference for all the available settings that can be used to configure Marten projects. ## Common settings ### `allowed_hosts` Default: `[] of String` An explicit array of allowed hosts for the application. The application has to be explicitly configured to serve a list of allowed hosts. This is to mitigate HTTP Host header attacks. The strings in this array can correspond to regular domain names or subdomains (eg. `example.com` or `www.example.com`); when this is the case the Host header of the incoming request will be checked to ensure that it exactly matches one of the configured allowed hosts. It is also possible to match all the subdomains of a specific domain by prepending a `.` at the beginning of the host string. For example `.example.com` will matches `example.com`, `www.example.com`, `sub.example.com`, or any other subdomains. Finally, the special `*` string can be used to match any Host value, but this wildcard value should be used with caution as you wouldn't be protected against Host header attacks. It should be noted that this setting is automatically set to the following array when a project is running in [debug mode](#debug) (unless it is explicitly set): ```crystal [".localhost", "127.0.0.1", "[::1]"] ``` ### `cache_store` Default: `Marten::Cache::Store::Memory.new` The global cache store instance. This setting allows to configure the cache store returned by the [`Marten#cache`](https://martenframework.com/docs/api/dev/Marten.html#cache%3ACache%3A%3AStore%3A%3ABase-class-method) method (which can be used to perform low-level caching operations), and which is also leveraged for other caching features such as template fragment caching. Please refer to [Caching](https://martenframework.com/docs/next/caching) to learn more about the caching features provided by Marten. By default, the global cache store is set to be an in-memory cache (instance of [`Marten::Cache::Store::Memory`](https://martenframework.com/docs/api/dev/Marten/Cache/Store/Memory.html)). In test environments you might want to use the "null store" by assigning an instance of the [`Marten::Cache::Store::Null](https://martenframework.com/docs/api/dev/Marten/Cache/Store/Null.html) to this setting. Additional caching store shards are also maintained under the umbrella of the Marten project or by the community itself and can be used as part of your application depending on your caching requirements. These backends are listed in the [caching stores backend reference](https://martenframework.com/docs/next/caching/reference/stores). ### `cross_origin_opener_policy` Default: `"same-origin"` The value to use for the [Cross-Origin-Opener-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy) header when the associated middleware is used. This header allows browsers to isolate a top-level window from other documents by putting them in a different browsing context group, which mitigates cross-origin attacks that rely on `window.opener`. Possible values for the Cross-Origin-Opener-Policy header include: - `unsafe-none`: Allows the document to be added to its opener's browsing context group unless the opener itself has a COOP of `same-origin` or `same-origin-allow-popups`. - `same-origin-allow-popups`: Isolates the browsing context to same-origin documents or those which either don't set COOP or which opt out of isolation by setting a COOP of `unsafe-none`. - `same-origin`: Isolates the browsing context exclusively to same-origin documents. This is the default and most secure option. - `noopener-allow-popups`: Isolates the browsing context and always sets `window.opener` to `null` for opened documents. This setting will be used by the [`Marten::Middleware::CrossOriginOpenerPolicy`](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#cross-origin-opener-policy-middleware) middleware when inserting the Cross-Origin-Opener-Policy header in HTTP responses. ### `date_input_formats` Default: ```crystal [ "%Y-%m-%d", # '2024-10-25' "%m/%d/%Y", # '10/25/2024' "%m/%d/%y", # '10/25/06' "%b %d %Y", # 'Oct 25 2024' "%b %d, %Y", # 'Oct 25, 2024' "%d %b %Y", # '25 Oct 2024' "%d %b, %Y", # '25 Oct, 2024' "%B %d %Y", # 'October 25 2024' "%B %d, %Y", # 'October 25, 2024' "%d %B %Y", # '25 October 2024' "%d %B, %Y", # '25 October, 2024' ] ``` An array of default date input formats. This array of default date input formats is used by the [`date` schema field](https://martenframework.com/docs/next/schemas/reference/fields#date) to parse date values from strings. Note that the date input formats coming from locales will be used with priority over the formats defined in this array. ### `date_time_input_formats` Default: ```crystal [ "%Y-%m-%d %H:%M:%S", # '2024-10-25 14:30:00' "%Y-%m-%d %H:%M:%S.%f", # '2024-10-25 14:30:00.000000' "%Y-%m-%d %H:%M", # '2024-10-25 14:30' "%m/%d/%Y %H:%M:%S", # '10/25/2024 14:30:00' "%m/%d/%Y %H:%M:%S.%f", # '10/25/2024 14:30:00.000000' "%m/%d/%Y %H:%M", # '10/25/2024 14:30' ] ``` An array of default date input formats. This array of default date input formats is used by the [`date_time` schema field](https://martenframework.com/docs/next/schemas/reference/fields#date_time) to parse date time values from strings. Note that the date time input formats coming from locales will be used with priority over the formats defined in this array. ### `debug` Default: `false` A boolean allowing to enable or disable debug mode. When running in debug mode, Marten will automatically provide detailed information about raised exceptions (including tracebacks) and incoming HTTP requests. As such this mode is mostly useful for development environments. ### `handler400` Default: `Marten::Handlers::Defaults::BadRequest` The handler class that should generate responses for Bad Request responses (HTTP 400). Please refer to [Error handlers](https://martenframework.com/docs/next/handlers-and-http/error-handlers) to learn more about error handlers. ### `handler403` Default: `Marten::Handlers::Defaults::PermissionDenied` The handler class that should generate responses for Permission Denied responses (HTTP 403). Please refer to [Error handlers](https://martenframework.com/docs/next/handlers-and-http/error-handlers) to learn more about error handlers. ### `handler404` Default: `Marten::Handlers::Defaults::PageNotFound` The handler class that should generate responses for Not Found responses (HTTP 404). Please refer to [Error handlers](https://martenframework.com/docs/next/handlers-and-http/error-handlers) to learn more about error handlers. ### `handler500` Default: `Marten::Handlers::Defaults::ServerError` The handler class that should generate responses for Internal Error responses (HTTP 500). Please refer to [Error handlers](https://martenframework.com/docs/next/handlers-and-http/error-handlers) to learn more about error handlers. ### `host` Default: `"127.0.0.1"` The host the HTTP server running the application will be listening on. ### `installed_apps` Default: `[] of Marten::Apps::Config.class` An array of the installed app classes. Each Marten application must define a subclass of [`Marten::Apps::Config`](https://martenframework.com/docs/api/dev/Marten/Apps/Config.html). When those subclasses are specified in the `installed_apps` setting, the applications' models, migrations, assets, and templates will be made available to the considered project. Please refer to [Applications](https://martenframework.com/docs/next/development/applications) to learn more about applications. ### `log_backend` Default: `Log::IOBackend.new(...)` The log backend used by the application. Any `Log::Backend` object can be used, which can allow to easily configure how logs are formatted for example. ### `log_level` Default: `Log::Severity::Info` The default log level used by the application. Any severity defined in the [`Log::Severity`](https://crystal-lang.org/api/Log/Severity.html) enum can be used. :::info This setting exclusively controls the log level for the Marten server. To set the log level for [management commands](https://martenframework.com/docs/next/development/management-commands), use the `--log-level` command option (see [Shared options](https://martenframework.com/docs/next/development/management-commands#shared-options)). ::: ### `main_app_label` Default: `"main"` The label of the main application. The [main application](https://martenframework.com/docs/next/development/applications#the-main-application) is the application that corresponds to the `src` folder of the project. This setting allows to configure the label of the main application, which also impacts the names of the underlying model tables. :::warning Changing the main application label after the project has been initialized will impact the names of the underlying model tables. This can be an option if you don't have any models defined in the `src` folder yet or for new projects, but it is not recommended to change it when the project already has models defined in the main application as Marten **will not** automatically rename model tables to match the new label. ::: ### `middleware` Default: `[] of Marten::Middleware.class` An array of middlewares used by the application. For example: ```crystal config.middleware = [ Marten::Middleware::Session, Marten::Middleware::I18n, Marten::Middleware::GZip, ] ``` Middlewares are used to "hook" into Marten's request / response lifecycle. They can be used to alter or implement logics based on incoming HTTP requests and the resulting HTTP responses. Please refer to [Middlewares](https://martenframework.com/docs/next/handlers-and-http/middlewares) to learn more about middlewares. ### `database_routers` Default: `[] of Marten::DB::Router::Base.class` An array of database router classes used to resolve which database should be used for model operations. For example: ```crystal config.database_routers = [ AnalyticsRouter, PrimaryReplicaRouter, ] ``` Routers are consulted in order when resolving read/write connections, validating relations, and deciding which migrations may run on a given database. Each router must inherit from [`Marten::DB::Router::Base`](https://martenframework.com/docs/api/dev/Marten/DB/Router/Base.html). Please refer to [Multiple databases](https://martenframework.com/docs/next/models-and-databases/multiple-databases#database-routers) to learn more about database routing. ### `parallelism` Default: `1` (or the value of the `MARTEN_PARALLELISM` environment variable when set) The maximum parallelism of Crystal's default execution context. This setting is applied when starting the HTTP server via [`Marten.start`](https://martenframework.com/docs/api/dev/Marten.html#start(host%3AString%7CNil%3Dnil%2Cport%3AInt32%7CNil%3Dnil%2Cargs%3AArray(String)%3DARGV)-class-method). A value of `1` keeps Crystal's default concurrent-only behavior (fibers share a single thread). Setting a value greater than `1` opts into multi-threaded execution by resizing the default execution context, and requires **Crystal 1.21 or later**. When the `MARTEN_PARALLELISM` environment variable is set to an integer, it is used as the initial value for this setting. An explicit `config.parallelism = ...` assignment always takes precedence. :::info `parallelism` is **not** the maximum number of concurrent HTTP requests, and it is **not** a process count. With `parallelism = 1`, Marten can still handle many requests at once: each connection runs in a fiber, and fibers overlap while waiting on I/O (such as database queries). Raising `parallelism` only allows more fibers to execute Crystal code on multiple CPU cores at the same time. Prefer multiple server processes (or platform instances) for capacity and isolation; use `parallelism` when a single process should utilize multiple cores. ::: For example: ```bash MARTEN_PARALLELISM=4 ./myapp ``` :::warning Increasing `parallelism` enables true parallelism. Ensure your application and dependencies are ready for concurrent access to shared mutable state. Prefer a remote cache store over the default in-memory cache when running with `parallelism` greater than `1`. ::: ### `port` Default: `8000` The port the HTTP server running the application will be listening on. ### `port_reuse` Default: `true` A boolean indicating whether multiple processes can bind to the same HTTP server port. ### `referrer_policy` Default: `"same-origin"` The value to use for the [Referrer-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy) header when the associated middleware is used. This header controls the amount of referrer information sent along with requests from your site to other origins, enhancing user privacy and security. Possible values for the Referrer-Policy header include: - `no-referrer`: The Referer header will be omitted entirely. No referrer information is sent with requests. - `no-referrer-when-downgrade`: The Referer header will not be sent to less secure destinations (e.g., from HTTPS to HTTP), but will be sent to same or more secure destinations. - `origin`: Only the origin of the document is sent as the referrer. - `origin-when-cross-origin`: The full URL is sent as the referrer when performing a same-origin request, but only the origin is sent for cross-origin requests. - `same-origin`: The Referer header is sent with same-origin requests, but not with cross-origin requests. - `strict-origin`: Only the origin is sent as the referrer, and only for same-origin requests. - `strict-origin-when-cross-origin`: The full URL is sent as the referrer when performing a same-origin request, but only the origin is sent for cross-origin requests. No referrer information is sent to less secure destinations. - `unsafe-url`: The full URL is always sent as the referrer, regardless of the request's security. This setting will be used by the [`Marten::Middleware::ReferrerPolicy`](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#referrer-policy-middleware) middleware when inserting the Referrer-Policy header in HTTP responses. By configuring this setting, you can control how much referrer information is included with requests from your site to other origins. ### `request_max_body_size` Default: `2_621_440` (2.5MB) The maximum allowed size of a request body in bytes. This setting is used to prevent large requests that could be used in the context of denial-of-service attacks. Incoming request bodies (including uploaded files) that exceed this limit result in a [`Marten::HTTP::Errors::RequestBodyTooBig`](https://martenframework.com/docs/api/dev/Marten/HTTP/Errors/RequestBodyTooBig.html) exception, which produces a 400 Bad Request response. This protection can also be disabled by setting `request_max_body_size` to `nil`. Applications that need to accept larger uploads (such as images or documents) should increase this value accordingly. ### `request_max_parameters` Default: `1000` The maximum number of allowed parameters per request (such as GET or POST parameters). A large number of parameters will require more time to process and might be the sign of a denial-of-service attack, which is why this setting can be used. This protection can also be disabled by setting `request_max_parameters` to `nil`. ### `root_path` Default: `nil` The root path of the application. The root path of the application specifies the actual location of the project sources in your system. This can prove helpful in scenarios where the project was compiled in a specific location different from the final destination where the project sources (and the `lib` folder) are copied. For instance, platforms like Heroku often fall under this category. By configuring the root path, you can ensure that your application correctly locates the required project sources and avoids any discrepancies arising from inconsistent source paths. This can prevent issues related to missing dependencies or missing app-related files (eg. locales, assets, or templates) and make your application more robust and reliable. For example, deploying a Marten app on Heroku will usually involves setting the root path as follows: ```crystal config.root_path = "/app" ``` ### `secret_key` Default: `""` A secret key used for cryptographic signing for the considered Marten project. The secret key should be set to a unique and unpredictable string value. The secret key can be used by Marten to encrypt or sign messages (eg. for cookie-based sessions), or by other authentication applications. :::warning The `secret_key` setting value **must** be kept secret. You should never commit this setting value to source control (instead, consider loading it from environment variables for example). ::: ### `socket` Default: `nil` The Unix socket path the HTTP server running the application will be listening on. When this setting is configured, the server will bind to the specified Unix socket instead of binding to a TCP port. In this case, the `host` and `port` settings are ignored. This is particularly useful when deploying a Marten application behind a reverse proxy like Nginx or Caddy on the same machine, as it provides better performance and security compared to TCP loopback. ### `time_zone` Default: `Time::Location.load("UTC")` The default time zone used by the application when it comes to storing date times in the database and displaying them. Any [`Time::Location`](https://crystal-lang.org/api/Time/Location.html) object can be used. ### `trailing_slash` Default: `:remove` The trailing slash behavior applied in case an incoming request URL does not match any of the configured routes. This setting allows you to configure whether an HTTP permanent redirect (301) should be issued when an incoming URL that does not match any of the configured routes either ends with a slash or does not. Three values are supported: * `:do_nothing` - No redirect is issued. * `:add` - If the incoming URL does not end with a slash and does not match any routes, a redirect is issued to the same URL with a trailing slash appended. * `:remove` - If the incoming URL ends with a slash and does not match any routes, a redirect is issued to the same URL with the trailing slash removed. This is the default behavior. ### `unsupported_http_method_strategy` Default: `:deny` The strategy to use when an unsupported HTTP method is encountered. This setting allows you to configure the strategy to use when a handler processes an unsupported HTTP method. The default strategy is `:deny`, which means that the application will return a 405 Method Not Allowed response when an unsupported HTTP method is encountered. The other available strategy is `:hide`, which will results in 404 Not Found responses to be returned instead. ### `use_x_forwarded_host` Default: `false` A boolean indicating whether the `X-Forwarded-Host` header is used to look for the host. This setting can be enabled if the Marten application is served behind a proxy that sets this header. ### `use_x_forwarded_port` Default: `false` A boolean indicating if the `X-Forwarded-Port` header is used to determine the port of a request. This setting can be enabled if the Marten application is served behind a proxy that sets this header. ### `use_x_forwarded_proto` Default: `false` A boolean indicating if the `X-Forwarded-Proto` header is used to determine whether a request is secure. This setting can be enabled if the Marten application is served behind a proxy that sets this header. For example, if such proxy sets this header to `https`, Marten will assume that the request is secure at the application level **only** if `use_x_forwarded_proto` is set to `true`. ### `x_frame_options` Default: `"DENY"` The value to use for the X-Frame-Options header when the associated middleware is used. The value of this setting will be used by the [`Marten::Middleware::XFrameOptions`](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#x-frame-options-middleware) middleware when inserting the X-Frame-Options header in HTTP responses. ## Assets settings Assets settings allow configuring how Marten should interact with [assets](https://martenframework.com/docs/next/assets/introduction). These settings are all available under the `assets` namespace: ```crystal config.assets.root = "assets" config.assets.url = "/assets/" ``` ### `app_dirs` Default: `true` A boolean indicating whether assets should be looked for inside installed application folders. When this setting is set to `true`, this means that assets provided by installed applications will be collected by the `collectassets` command (please refer to [Asset handling](https://martenframework.com/docs/next/assets/introduction) for more details regarding how to manage assets in your project). ### `dirs` Default: `[] of String` An array of directories where assets should be looked for. The order of these directories is important as it defines the order in which assets are searched for. It should be noted that path objects or symbols can also be used to configure this setting: ```crystal config.assets.dirs = [ Path["src/path1/assets"], :"src/path2/assets", ] ``` ### `manifests` Default: `[] of String` An array of paths to manifest JSON files to use to resolve assets URLs. Manifest files will be used to return the right fingerprinted asset path for a generic path, which can be useful if your asset bundling strategy support this. You can read more about this capability in [Asset manifests and fingerprinting](https://martenframework.com/docs/next/assets/introduction#asset-manifests-and-fingerprinting). ### `max_age` Defaults: `3600` Allows to set the max-age directive value used as part of the Cache-Control header that is set by the [`Marten::Middleware::AssetServing`](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#asset-serving-middleware) middleware. ### `root` Default: `"assets"` A string containing the absolute path where collected assets will be persisted (when running the `collectassets` command). By default, assets will be persisted in a folder that is relative to the Marten project's directory. Obviously, this folder should be empty before running the `collectassets` command in order to not overwrite existing files: assets should be defined as part of your applications' `assets` folders instead. :::info This setting is only used if `assets.storage` is `nil`. ::: ### `storage` Default: `nil` An optional storage object, which must be an instance of a subclass of [`Marten::Core::Store::Base`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/Base.html). This storage object will be used when collecting asset files to persist them in a given location. By default this setting value is set to `nil`, which means that a [`Marten::Core::Store::FileSystem`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/FileSystem.html) storage is automatically constructed by using the `assets.root` and `assets.url` setting values: in this situation, asset files are collected and persisted in a local directory, and it is expected that they will be served from this directory by the web server running the application. A specific storage can be set instead to ensure that collected assets are persisted somewhere else in the cloud and served from there (for example in an Amazon's S3 bucket). When this is the case, the `assets.root` and `assets.url` setting values are basically ignored and are overridden by the use of the specified storage. ### `url` Default: `"/assets/"` The base URL to use when exposing asset URLs. This base URL will be used by the default [`Marten::Core::Store::FileSystem`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/FileSystem.html) storage to construct asset URLs. For example, requesting a `css/App.css` asset might generate a `/assets/css/App.css` URL by default. :::info This setting is only used if `assets.storage` is `nil`. ::: ## CSRF settings CSRF settings allow configuring how Cross-Site Request Forgeries (CSRF) attack protection measures are implemented within the considered Marten project. Please refer to [Cross-Site Request Forgery protection](https://martenframework.com/docs/next/security/csrf) for more details about this topic. The following settings are all available under the `csrf` namespace: ```crystal config.csrf.protection_enabled = true config.csrf.cookie_name = "csrf-token" ``` ### `cookie_domain` Default: `nil` An optional domain to use when setting the CSRF cookie. This can be used to share the CSRF cookie across multiple subdomains for example. For example, setting this option to `.example.com` will make it possible to send a POST request from a form on one subdomain (eg. `foo.example.com`) to another subdomain (eg. `bar.example.com `). ### `cookie_http_only` Default: `false` A boolean indicating whether client-side scripts should be prevented from accessing the CSRF token cookie. If this option is set to `true`, Javascript scripts won't be able to access the CSRF cookie. ### `cookie_max_age` Default: `31_556_952` (approximately one year) The max age (in seconds) of the CSRF cookie. ### `cookie_name` Default: `"csrftoken"` The name of the cookie to use for the CSRF token. This cookie name should be different than any other cookies created by your application. ### `cookie_same_site` Default: `"Lax"` The value of the [SameSite flag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite) to use for the CSRF cookie. Accepted values are `"Lax"`, `"Strict"`, or `"None"`. ### `cookie_secure` Default: `false` A boolean indicating whether to use a secure cookie for the CSRF cookie. Setting this to `true` will force browsers to send the cookie with an encrypted request over the HTTPS protocol only. ### `protection_enabled` Default: `true` A boolean indicating if the CSRF protection is enabled globally. When set to `true`, handlers will automatically perform a CSRF check to protect unsafe requests (ie. requests whose methods are not `GET`, `HEAD`, `OPTIONS`, `QUERY`, or `TRACE`). Regardless of the value of this setting, it is always possible to explicitly enable or disable CSRF protection on a per-handler basis. See [Cross-Site Request Forgery protection](https://martenframework.com/docs/next/security/csrf) for more details. ### `session_key` Default: `"csrftoken"` The name of the session key to use for the CSRF token. This session key should be different than any other session key created by your application. :::info This value is only relevant if [`use_session`](#use_session) is set to `true`. ::: ### `trusted_origins` Default: `[] of String` An array of trusted origins. These origins will be trusted for CSRF-protected requests (such as POST requests) and they will be used to check either the `Origin` or the `Referer` header depending on the request scheme. This is done to ensure that a specific subdomain such as `sub1.example.com` cannot issue a POST request to `sub2.example.com`. To enable CSRF-protected requests over different origins, it's possible to add trusted origins to this array. For example `https://sub1.example.com` can be configured as a trusted domain that way, but it's possible to allow CSRF-protected requests for all the subdomains of a specific domain by using `https://*.example.com`. For example: ```crystal config.csrf.trusted_origins = [ "https://*.example.com", "https://other.example.org", ] ``` ### `use_session` Default: `false` A boolean indicating whether the CSRF token should be stored inside a session. If set to `true`, the CSRF token will be stored [in a session](https://martenframework.com/docs/next/handlers-and-http/sessions) rather than in a cookie. ## Content-Security-Policy settings These settings allow configuring how the [`Marten::Middleware::ContentSecurityPolicy`](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#content-security-policy-middleware) middleware behaves and the actual directives of the Content-Security-Policy header that are set by this middleware. ```crystal config.content_security_policy.report_only = true config.content_security_policy.default_policy.default_src = [:self, "other"] ``` Please refer to [Content Security Policy](https://martenframework.com/docs/next/security/content-security-policy) to learn more about the Content-Security-Policy header protection. :::tip [Content-Security-Policy](https://www.w3.org/TR/CSP/) is a complicated header and there are possibly many values you may need to tweak. Make sure you understand it before configuring the below settings. ::: ### `default_policy` Default: `Marten::HTTP::ContentSecurityPolicy.new` The default Content-Security-Policy object. This [`Marten::HTTP::ContentSecurityPolicy`](https://martenframework.com/docs/api/dev/Marten/HTTP/ContentSecurityPolicy.html) object will be used to set the Content-Security-Policy header when the [`Marten::Middleware::ContentSecurityPolicy`](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#content-security-policy-middleware) middleware is used. All the attributes that can be set on this [`Marten::HTTP::ContentSecurityPolicy`](https://martenframework.com/docs/api/dev/Marten/HTTP/ContentSecurityPolicy.html) object through the use of methods such as [`#default_src=`](https://martenframework.com/docs/api/dev/Marten/HTTP/ContentSecurityPolicy.html#default_src%3D(value%3AArray|Nil|String|Symbol|Tuple)-instance-method) or [`#frame_src=`](https://martenframework.com/docs/api/dev/Marten/HTTP/ContentSecurityPolicy.html#frame_src%3D(value%3AArray|Nil|String|Symbol|Tuple)-instance-method) can also be used directly on the `content_security_policy` setting object. For example: ```crystal config.content_security_policy.default_src = [:self, "other"] config.content_security_policy.block_all_mixed_content = true ``` ### `nonce_directives` Default: `["script-src", "style-src"]` An array of directives where a dynamically-generated nonce will be included. For example, if this setting is set to `["script-src"]`, a `nonce-` value will be added to the `script-src` directive in the Content-Security-Policy header value. ### `report_only` Default: `false` A boolean indicating whether policy violations are reported without enforcing them. If this setting is set to `true`, the [`Marten::Middleware::ContentSecurityPolicy`](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#content-security-policy-middleware) middleware will set a [Content-Security-Policy-Report-Only](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only) header instead of the regular Content-Security-Policy header. Doing so can be useful to experiment with policies without enforcing them. ## Database settings These settings allow configuring the databases used by the considered Marten project. At least one default database must be configured if your project makes use of [models](https://martenframework.com/docs/next/models-and-databases/introduction), and additional databases can optionally be configured as well. ```crystal # Default database config.database do |db| db.backend = :sqlite db.name = "default_db.db" end # Additional database config.database :other do |db| db.backend = :sqlite db.name = "other_db.db" end ``` Configuring other database backends such as MariaDB, MySQL or PostgreSQL usually involves specifying more connection parameters (eg. user, password, etc). As such, you must define a block to configure the appropriate database options when calling the [`#database`](https://martenframework.com/docs/api/dev/Marten/Conf/GlobalSettings.html#database(id%3DDB%3A%3AConnection%3A%3ADEFAULT_CONNECTION_NAME%2Curl%3AString|Nil%3Dnil%2C%26)-instance-method) method. For example: ```crystal config.database do |db| db.backend = :postgresql db.host = "localhost" db.name = "my_db" db.user = "my_user" db.password = "my_password" end ``` It is worth mentioning that some cloud providers only provide a connection string in order to connect to a specific database (usually in a `DATABASE_URL` environment variable). In this situation, it is possible to automatically configure the database backend by providing the connection URL to the [`#database`](https://martenframework.com/docs/api/dev/Marten/Conf/GlobalSettings.html#database%28id%3DDB%3A%3AConnection%3A%3ADEFAULT_CONNECTION_NAME%2Curl%3AString%7CNil%3Dnil%29-instance-method) method as well. This technique can be used for configuring both the default database and additional databases too. For example: ```crystal # Default database config.database url: "postgres://my_user:my_db@localhost:1234/db" # Additional database config.database :my_other_db, url: "sqlite://other_db.db?journal_mode=wal&synchronous=normal" ``` :::tip You can combine both database configuration techniques mentioned above if needed. Indeed you can configure a database through the use of a connection string and also further customize the database by opening a block and setting additional options: ```crystal # Configure db with a URL and a block config.database url: "postgres://my_user:my_db@localhost:1234/db" do |db| db.retry_delay = 1.0 end ``` ::: The following sections provide details on all the available database configuration options. ### `backend` Default: `nil` The database backend to use for connecting to the considered database. Marten supports three backends presently: * `:mysql` * `:postgresql` * `:sqlite` ### `checkout_timeout` Default: `5.0` The number of seconds to wait for a connection to become available when the max pool size is reached. ### `host` Default: `nil` A string containing the host used to connect to the database. No value means that the host will be localhost. ### `initial_pool_size` Default: `1` The initial number of connections created for the database connections pool. ### `max_idle_pool_size` Default: `1` The maximum number of idle connections for the database connections pool. Concretely, this means that when released, a connection will be closed only if there are already `max_idle_pool_size` idle connections. ### `max_pool_size` Default: `0` The maximum number of connections that will be held by the database connections pool. When set to `0`, this means that there is no limit to the number of connections. ### `name` Default: `nil` The name of the database to connect to. If you use the `sqlite` backend, this can be a string or a `Path` object containing the path (absolute or relative) to the considered database path. ### `options` Default: `{} of String => String` A set of additional database options. This setting can be used to set additional database options that may be required in order to connect to the database at hand. For example: ```crystal config.database do |db| db.backend = :postgresql db.host = "localhost" db.name = "my_db" db.user = "my_user" db.password = "my_password" // highlight-next-line db.options = {"sslmode" => "disable"} end ``` The options that you can set here will vary based on your chosen database backend. For example, you could set the `sslmode` option for PostgreSQL databases or some [pragma options](https://github.com/crystal-lang/crystal-sqlite3?tab=readme-ov-file#setting-pragmas) for SQLite3 databases. Please refer to the applicable DB binding shard documentation for more details about the available options: * [crystal-pg](https://github.com/will/crystal-pg) (PostgreSQL) * [crystal-mysql](https://github.com/crystal-lang/crystal-mysql) (MariaDB, MySQL) * [crystal-sqlite3](https://github.com/crystal-lang/crystal-sqlite3) (SQLite3) ### `password` Default: `nil` A string containing the password to use to connect to the configured database. ### `port` Default: `nil` The port to use to connect to the configured database. No value means that the default port will be used. ### `retry_attempts` Default: `1` The maximum number of attempts to retry re-establishing a lost connection. ### `retry_delay` Default: `1.0` The delay to wait between each retry at re-establishing a lost connection. ### `user` Default: `nil` A string containing the name of the user that should be used to connect to the configured database. ## Emailing settings Emailing settings allow configuring emailing-related settings. Please refer to [Emailing](https://martenframework.com/docs/next/emailing) for more details about how to define and send emails in your projects. The following settings are all available under the `emailing` namespace: ```crystal config.emailing.from_address = "no-reply@example.com" config.emailing.backend = Marten::Emailing::Backend::Development.new(print_emails: true) ``` ### `backend` Default: `Marten::Emailing::Backend::Development.new` The backend to use when it comes to send emails. Emailing backends define _how_ emails are actually sent. By default, a development backend (instance of [`Marten::Emailing::Backend::Dev`](https://martenframework.com/docs/api/dev/Marten/Emailing/Backend/Development.html)) is used: this backend "collects" all the emails that are "delivered" by default (which can be used in specs in order to test sent emails), but it can also be configured to print email details to the standard output if necessary (see the [emailing backend reference](https://martenframework.com/docs/next/emailing/reference/backends) for more details about this capability). Additional emailing backend shards are also maintained under the umbrella of the Marten project or by the community itself and can be used as part of your application depending on your specific email sending requirements. These backends are listed in the [emailing backend reference](https://martenframework.com/docs/next/emailing/reference/backends#other-backends). ### `from_address` Default: `"webmaster@localhost"` The default from address used in emails. Email definitions that don't specify a "from" address explicitly will use this email address automatically for the sender email. It should be noted that this from email address can be defined as a string or as a [`Marten::Emailing::Address`](https://martenframework.com/docs/api/dev/Marten/Emailing/Address.html) object (which allows to specify the name AND the address of the sender email). ## I18n settings I18n settings allow configuring internationalization-related settings. Please refer to [Internationalization](https://martenframework.com/docs/next/i18n) for more details about how to leverage translations and localized content in your projects. :::info Marten makes use of [crystal-i18n](https://crystal-i18n.github.io/) to handle translations and locales. Further [configuration options](https://crystal-i18n.github.io/configuration.html) are also provided by this shard and can be leveraged by any Marten projects if necessary. ::: The following settings are all available under the `i18n` namespace: ```crystal config.i18n.default_locale = :fr ``` ### `available_locales` Default: `nil` Allows defining the locales that can be activated to perform translation lookups and localizations. For example: ```crystal config.i18n.available_locales = [:en, :fr] ``` ### `default_locale` Default: `"en"` The default locale used by the Marten project. ### `fallbacks` Default: `["en"]` The locale fallbacks of the project. By configuring locale fallbacks, you can force your project to try to lookup translations in other (configured) locales if the current locale the translation is requested into is missing. The specified fallbacks can be: * a hash or a named tuple defining the chains of fallbacks to use for specific locales. * a simple array of fallbacks. In that case, this chain of fallbacked locales will be used as a default for all the available locales when translations are missing. * an `I18n::Locale::Fallbacks` object, allowing you to specify a general default fallback array and fallback mappings at the same time (see the [crystal-i18n documentation](https://crystal-i18n.github.io/configuration.html#fallbacks)). For example: ```crystal # Simple fallback chain used by all configured locales: config.i18n.fallbacks = ["en-US", "en"] # Locale-specific fallback chains: config.i18n.fallbacks = {"en-CA" => ["en-US", "en"], "fr-CA" => "fr"} # Default fallback chain and locale-specific fallback chains: config.i18n.fallbacks = ::I18n::Locale::Fallbacks.new( {"fr-CA-special": ["fr-CA", "fr", "en"]}, default: ["en"] ) ``` ### `locale_cookie_name` Default: `"marten_locale"` The name of the cookie to use for saving the locale of the current user and activating the right locale (when the [`Marten::Middleware::I18n`](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#i18n-middleware) middleware is used). See [Internationalization](https://martenframework.com/docs/next/i18n/introduction) to learn more about this capability. ## Media files settings Media files settings allow configuring how Marten should interact with [media files](https://martenframework.com/docs/next/files/managing-files). These settings are all available under the `media_files` namespace: ```crystal config.media_files.root = "files" config.media_files.url = "/files/" ``` ### `root` Default: `"media"` A string containing the absolute path where uploaded files will be persisted. By default uploaded files will be persisted in a folder that is relative to the Marten project's directory. :::info This setting is only used if `media_files.storage` is `nil`. ::: ### `storage` Default: `nil` An optional storage object, which must be an instance of a subclass of [`Marten::Core::Store::Base`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/Base.html). This storage object will be used when uploading files to persist them in a given location. By default, this setting value is set to `nil`, which means that a [`Marten::Core::Store::FileSystem`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/FileSystem.html) storage is automatically constructed by using the `media_files.root` and `media_files.url` setting values: in this situation, media files are persisted in a local directory, and it is expected that they will be served from this directory by the web server running the application. A specific storage can be set instead to ensure that uploaded files are persisted somewhere else in the cloud and served from there (for example in an Amazon's S3 bucket). When this is the case, the `media_files.root` and `media_files.url` setting values are basically ignored and are overridden by the use of the specified storage. ### `url` Default: `"/media/"` The base URL to use when exposing media files URLs. This base URL will be used by the default [`Marten::Core::Store::FileSystem`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/FileSystem.html) storage to construct media files URLs. For example, requesting a `foo/bar.txt` file might generate a `/media/foo/bar.txt` URL by default. :::info This setting is only used if `media_files.storage` is `nil`. ::: ## Method overriding settings Method overriding settings allow configuring how the [`MethodOverride`](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#method-override-middleware) middleware should handle HTTP method overrides in forms. These settings are all available under the `method_override` namespace: ```crystal config.method_override.allowed_methods = ["DELETE", "PATCH", "PUT"] config.method_override.http_header_name = "X-Http-Method-Override" config.method_override.input_name = "_method" ``` ### `allowed_methods` Default: `["DELETE", "PATCH", "PUT"]` An array of HTTP methods that are allowed to be overridden using the `input_name` mechanism. This provides a layer of control, preventing the usage of arbitrary HTTP methods in overrides. ### `http_header_name` Default: `X-Http-Method-Override` The name of the HTTP header used to signal a method override. ### `input_name` Default: `_method` The name of the form input field (or query parameter) used to signal a method override. ## Sessions settings Sessions settings allow configuring how Marten should handle [sessions](https://martenframework.com/docs/next/handlers-and-http/introduction#using-sessions). These settings are all available under the `sessions` namespace: ```crystal config.sessions.cookie_name = "_sessions" config.sessions.store = :cookie ``` ### `cookie_domain` Default: `nil` An optional domain to use when setting the session cookie. This can be used to share the session cookie across multiple subdomains. ### `cookie_http_only` Default: `false` A boolean indicating whether client-side scripts should be prevented from accessing the session cookie. If this option is set to `true`, Javascript scripts won't be able to access the session cookie. ### `cookie_max_age` Default: `1_209_600` (two weeks) The max age (in seconds) of the session cookie. ### `cookie_name` Default: `"sessionid"` The name of the cookie to use for the session token. This cookie name should be different than any other cookies created by your application. ### `cookie_same_site` Default: `"Lax"` The value of the [SameSite flag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite) to use for the session cookie. Accepted values are `"Lax"`, `"Strict"`, or `"None"`. ### `cookie_secure` Default: `false` A boolean indicating whether to use a secure cookie for the session cookie. Setting this to `true` will force browsers to send the cookie with an encrypted request over the HTTPS protocol only. ### `store` Default: `"cookie"` A string containing the identifier of the store used to handle sessions. By default, sessions are stored within a single cookie. Cookies have a 4K size limit, which is usually sufficient to persist things like a user ID and flash messages. Other stores can be implemented and leveraged to store sessions data; see [Sessions](https://martenframework.com/docs/next/handlers-and-http/sessions) for more details about this capability. ## SSL redirect settings SSL redirect settings allow to configure how Marten should redirect non-HTTPS requests to HTTPS when the [`Marten::Middleware::SSLRedirect`](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#ssl-redirect-middleware) middleware is used: ```crystal config.ssl_redirect.host = "example-redirect.com" config.exempted_paths = [/^\/no-ssl\/$/] ``` ### `exempted_paths` Default: `[] of Regex | String` Allows to set the array of paths that should be exempted from HTTPS redirects. Both strings and regexes are accepted. ### `host` Default: `nil` Allows to set the host that should be used when redirecting non-HTTPS requests. If set to `nil`, the HTTPS redirect will be performed using the request's host. ## Strict transport security policy settings Strict transport security policy settings allow to configure how Marten should set the HTTP Strict-Transport-Security response header when the [`Marten::Middleware::StrictTransportSecurity`](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#strict-transport-security-middleware) middleware is used: ```crystal config.strict_transport_security.max_age = 3_600 config.strict_transport_security.include_sub_domains = true ``` ### `include_sub_domains` Default: `false` Defines whether the `includeSubDomains` directive should be inserted into the HTTP Strict-Transport-Security response header. When this directive is set, this means that the policy will also apply to all the site's subdomains. :::caution You should be careful when enabling this option as this will prevent browsers from connecting to your site's subdomains using HTTP for the duration defined by the [`max_age`](#max_age) setting. ::: ### `max_age` Default: `nil` Defines the duration in seconds that browsers should remember that the web app must be accessed using HTTPS only. A `nil` value means that the HTTP Strict-Transport-Security response header is not inserted in responses (which is equivalent to not using the [`Marten::Middleware::StrictTransportSecurity`](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#strict-transport-security-middleware) middleware). :::caution You should be careful when defining a value for this setting because this will prevent browsers from connecting to your site using HTTP for the duration you specified. ::: ### `preload` Default: `false` Defines whether the `preload` directive should be inserted into the HTTP Strict-Transport-Security response header. Setting this to `true` means that you allow your site to be submitted to the [HSTS browser preload list](https://hstspreload.org/) by browsers. ## Templates settings Templates settings allow configuring how Marten discovers and renders [templates](https://martenframework.com/docs/next/templates). These settings are all available under the `templates` namespace: ```crystal config.templates.app_dirs = false config.templates.cached = false ``` ### `app_dirs` Default: `true` A boolean indicating whether templates should be looked for inside installed application folders (local `templates` directories). When this setting is set to `true`, this means that templates provided by installed applications can be loaded and rendered by the templates engine. Otherwise, it would not be possible to load and render these application templates. ### `cached` Default: `false` A boolean indicating whether templates should be kept in a memory cache upon being loaded and parsed. This setting should likely be set to `false` in development environments (where changes to templates are frequent) and set to `true` in production environments (to avoid loading and parsing the same templates multiple times). ### `context_producers` Default: `[] of Marten::Template::ContextProducer.class` An array of context producer classes. Context producers are helpers that ensure that common variables are automatically inserted in the template context whenever a template is rendered. See [Using context producers](https://martenframework.com/docs/next/templates/introduction#using-context-producers) to learn more about this capability. ### `dirs` Default: `[] of String` An array of directories where templates should be looked for. The order of these directories is important as it defines the order in which templates are searched for when requesting a template for a given path (eg. `foo/bar/template.html`). It should be noted that path objects or symbols can also be used to configure this setting: ```crystal config.templates.dirs = [ Path["src/path1/templates"], :"src/path2/templates", ] ``` ### `isolated_inclusions` Default: `false` A boolean option enabling or disabling isolated inclusions of templates when using the [`include`](https://martenframework.com/docs/next/templates/reference/tags#include) template tag. When set to `true`, included templates won't have access to variables from the outer context by default, unless the `contextual` modifier is used with the `include` template tag. Conversely, when set to `false`, included templates will have access to the outer context's variables by default, unless explicitly disabled with the `isolated` modifier of the `include` template tag. ### `loaders` Default: `nil` Overwrites the loading mechanism of templates. Takes an array of classes inheriting from `Marten::Template::Loader::Base`. Customize this to load templates from various sources like databases or in-memory structures. For example, to load templates from a file system: ```crystal config.templates.loaders = [Marten::Template::Loader::FileSystem.new("/path/to/templates")] of Marten::Template::Loader::Base ``` ### `strict_variables` Default: `false` A boolean allowing to enable or disable the [strict variables](https://martenframework.com/docs/next/templates/introduction#strict-variables) for templates. When this setting is set to `true`, unknown variables encountered in templates will result in [`Marten::Template::Errors::UnknownVariable`](https://martenframework.com/docs/api/dev/Marten/Template/Errors/UnknownVariable.html) exceptions to be raised. When set to `false`, unknown variables will simply be treated as `nil` values in templates. # Management commands Source: https://martenframework.com/docs/next/development/reference/management-commands This page provides a reference for all the available management commands and their options. ## `clearsessions` **Usage:** `marten clearsessions [options]` Clears all expired sessions for the configured session store. Please refer to [Sessions](https://martenframework.com/docs/next/handlers-and-http/sessions) to learn more about sessions. ### Options * `--no-input` - Does not show prompts to the user ### Examples ```bash marten clearsessions # Clears all expired sessions marten clearsessions --no-input # Clears all expired sessions without any prompts ``` ## `collectartifacts` **Usage:** `marten collectartifacts [options]` Collects runtime artifacts that are required by compiled applications and copies them into a single destination directory. This command collects Marten's built-in locale files, project locale files from `config/locales`, and application locale and template files from `locales` and `templates` directories. Files are copied while preserving their paths relative to the project compilation root, so the destination directory can be used as the [`root_path`](https://martenframework.com/docs/next/development/reference/settings#root_path) setting in production. Symbolic links encountered in these directories are followed, and the linked files are collected as regular files. Custom template loaders and directories configured through `templates.dirs` are not collected by this command. ### Options * `--dest-path=PATH` - Configures where artifacts should be collected (defaults to `artifacts`) * `--no-input` - Does not show prompts to the user * `--app=APP_LABEL` - Collects artifacts for the specified application only ### Examples ```bash marten collectartifacts # Collects all runtime artifacts into artifacts/ marten collectartifacts --no-input --dest-path runtime_root # Collects all runtime artifacts without any prompts marten collectartifacts --app=auth # Collects artifacts for the "auth" app only ``` ## `collectassets` **Usage:** `marten collectassets [options]` Collects all the assets and copies them into a unique storage. Please refer to [Serving assets](https://martenframework.com/docs/next/assets/serving-assets#collecting-assets) to learn more about when and how assets are "collected". ### Options * `--no-input` - Does not show prompts to the user * `--fingerprint` - Attaches a fingerprint to the collected assets * `--manifest-path` - Configures where the manifest.json is stored. Only relevant if `--fingerprint` is activated. (default to `src/manifest.json`) ### Examples ```bash marten collectassets # Collects all the assets marten collectassets --no-input # Collects all the assets without any prompts ``` ## `gen` **Usage:** `marten gen [options] [generator] [arguments]` Generate various structures, abstractions, and values within an existing project. ### Options Generators support their own specific options. For an exact list of generator options, please refer to the [Generators reference](https://martenframework.com/docs/next/development/reference/generators). ### Arguments * `generator` - Name of the generator to use * `arguments` - Generator-specific arguments Generators support their own specific arguments. For an exact list of generator arguments, please refer to the [Generators reference](https://martenframework.com/docs/next/development/reference/generators). ### Examples ```bash marten gen secretkey # Generate a secret key value marten gen email WelcomeEmail # Generate a WelcomeEmail email in the main application marten gen handler MyHandler --app=blog # Generate a MyHandler handler in the blog application ``` :::tip You can also use the alias `g` to execute specific generators: ```bash marten g model Test label:string:uniq ``` ::: ## `genmigrations` **Usage:** `marten genmigrations [options] [app_label]` Generates new database migrations. This command will scan the table definition corresponding to your current models and will compare it to the equivalent tables that are defined by your migration files. Based on the result of this analysis, a new set of migrations will be created and persisted in your applications' `migrations` folders. Please refer to [Migrations](https://martenframework.com/docs/next/models-and-databases/migrations) to learn more about this mechanism. ### Options * `--dry-run` - Shows migrations that would be generated without writing them * `--check` - Exits with a non-zero status if model changes require migrations without generating them * `--empty` - Creates an empty migration * `--no-header` - Do not add header comments at the top of newly generated migration files ### Arguments * `app_label` - The name of an application to generate migrations for (optional) ### Examples ```bash marten genmigrations # Generates new migrations for all the installed apps marten genmigrations foo # Generates new migrations for the "foo" app marten genmigrations foo --empty # Generates an empty migration for the "foo" app marten genmigrations --dry-run # Shows migrations that would be generated without writing them ``` ## `listmigrations` **Usage:** `marten listmigrations [options] [app_label]` Lists all the available database migrations. This command will introspect your project and your installed applications to list the available migrations, and indicate whether they have already been applied or not. Please refer to [Migrations](https://martenframework.com/docs/next/models-and-databases/migrations) to learn more about this mechanism. ### Options * `--db=ALIAS` - Allows specifying the alias of the database on which migrations will be applied or unapplied (default to `default`) ### Arguments * `app_label` - The name of an application to list migrations for (optional) ### Examples ```bash marten listmigrations # Lists all the migrations for all the installed apps marten listmigrations foo # Lists all the migrations of the "foo" app ``` ## `migrate` **Usage:** `marten migrate [options] [app_label] [migration]` Runs database migrations. The `migrate` command allows you to apply (or unapply) migrations to your databases. By default, when executed without arguments, it will execute all the non-applied migrations for your installed applications. That being said, it is possible to ensure that only the migrations of a specific application are applied by specifying an additional `app_label` argument. To unapply certain migrations (or to apply some of them up to a certain version only), it is possible to specify another `migration` argument corresponding to the version of a targeted migration. Please refer to [Migrations](https://martenframework.com/docs/next/models-and-databases/migrations) to learn more about this mechanism. ### Options * `--fake` - Allows marking migrations as applied or unapplied without actually running them * `--check` - Exits with a non-zero status if unapplied migrations exist without applying them * `--plan` - Provides a comprehensive overview of the operations that will be performed by the applied or unapplied migrations * `--prune` - Deletes nonexistent migrations from the `marten_migrations` table * `--db=ALIAS` - Allows specifying the alias of the database on which migrations will be applied or unapplied (default to `default`) ### Arguments * `app_label` - The name of an application to run migrations for * `migration` - A migration target (name or version) up to which the DB should be migrated. Use `zero` to unapply all the migrations of a specific application ### Examples ```bash marten migrate # Applies all the non-applied migrations for all the installed apps marten migrate foo # Applies migrations for the "foo" app marten migrate foo 202203111821451 # Applies (or unapply) migrations for the "foo" app up until the "202203111821451" migration marten migrate --prune # Removes nonexistent migrations from the marten_migrations table ``` ## `new` **Usage:** `marten new [options] [type] [name]` Initializes a new Marten project or application repository structure. The `new` management command can be used to create either a new project repository or a new [application](https://martenframework.com/docs/next/development/applications) repository. This can be handy when creating new projects, or when creating new applications that are intended to be distributed as dedicated shards, as it ensures you are following Marten's best practices and conventions. New projects include an `AGENTS.md` file for coding agents. It records the Marten version, links to the matching guides and API, and states how requires, installed apps, migrations, CSRF, and specs work. Projects created with `--edge` link to the in-development guides. The command allows you to fully define the name of your project or application, and in which folder it should be created. ### Options * `-d DIR, --dir=DIR` - An optional destination directory * `--with-auth` - Adds an authentication application to newly created projects. See [Authentication](https://martenframework.com/docs/next/authentication) to learn more about this capability * `--with-image-support` - Adds support for [image fields](https://martenframework.com/docs/next/models-and-databases/reference/fields#image) by ensuring that the required shard is added to the project and required in the `src/project.cr` file. * `--database` - Preconfigures the application database. Currently `mysql`, `postgresql` and `sqlite3` are supported while `none` can be used to generate a project without configured databases. See [Database settings](https://martenframework.com/docs/next/development/reference/settings#database-settings) for more information * `-e, --edge` - Use the development version of Marten ### Arguments * `type` - The type of structure to create (must be either `project` or `app`) * `name` - The name of the project or app to create :::tip The `type` and `name` arguments are optional when the command runs in a terminal. Interactive mode then prompts for the structure type, the name, the database, and whether an auth app should be generated. When stdin is not a terminal, both arguments are required: otherwise the command prints its usage and exits with status 1. ::: ### Examples ```bash marten new project myblog # Creates a "myblog" project repository structure marten new project myblog --dir=./projects/myblog # Creates a "myblog" project in the "./projects/myblog" folder marten new project myblog --database=postgresql # Creates a "myblog" project with a PostgreSQL database marten new project myblog --database=none # Creates a "myblog" project without configured database marten new app auth # Creates an "auth" application repository structure ``` ## `play` **Usage:** `marten play [options]` Start a Crystal playground server initialized for the current project. ### Options * `-b HOST, --bind=HOST` - Binds the playground to the specified IP * `-p PORT, --port=PORT` - Runs the playground on the specified port * `--open` - Open the playground in the default browser automatically ### Examples ```bash marten play # Starts the Crystal playground using the default host/port marten play --open # Starts the Crystal playground using the default host/port and opens it in the default browser ``` ## `resetmigrations` **Usage:** `marten resetmigrations [options] [app_label]` Resets an existing set of migrations into a single one. Please refer to [Resetting migrations](https://martenframework.com/docs/next/models-and-databases/migrations#resetting-migrations) to learn more about this capability. ### Options * `--no-header` - Do not add header comments at the top of newly generated migration files ### Arguments * `app_label` - The name of an application to reset migrations for ### Examples ```bash marten resetmigrations foo # Resets the migrations of the "foo" application ``` ## `routes` **Usage:** `marten routes [options]` Displays all the routes of the application. ### Options * `-g PATTERN, --grep=PATTERN` - Only display routes whose path or name contains the given substring (case-insensitive) ## `seed` **Usage:** `marten seed [options]` Populate the database by running the seed file. ### Options * `-f PATH, --file=PATH` - Specify a custom path to the seed file ## `serve` **Usage:** `marten serve [options]` Starts a development server that is automatically recompiled when source files change. ### Options * `-b HOST, --bind=HOST` - Allows specifying a custom host to bind * `-p PORT, --port=PORT` - Allows specifying a custom port to listen for connections * `--open` - Open the server in the default browser automatically ### Examples ```bash marten serve # Starts a development server using the configured host and port marten serve -p 3000 # Starts a development server by overriding the port marten serve --open # Starts a development server and opens it in the default browser ``` :::tip You can also use the alias `s` to start the development server: ```bash marten s ``` ::: ## `version` **Usage:** `marten version [options]` Shows the Marten version. # Generators Source: https://martenframework.com/docs/next/development/reference/generators This page provides a reference for all the available generators and their options. ## `app` **Usage:** `marten gen app [options] [label]` Add and configure a new [application](https://martenframework.com/docs/next/development/applications) to the current project. :::info This generator will attempt to add the generated application to the [`installed_apps`](https://martenframework.com/docs/next/development/reference/settings#installed_apps) setting and will also configure Crystal requirements for it (in the `src/project.cr` and `src/cli.cr` files). ::: ### Arguments * `label` - Label of the application to generate ### Examples ```bash marten gen app blogging # Generate a new 'blogging' application ``` ## `auth` **Usage:** `marten gen auth [options] [label]` Generate and configure a fully functional authentication application for your project. Please refer to [Authentication](https://martenframework.com/docs/next/authentication) to learn more about authentication in Marten, and to [Generated files](https://martenframework.com/docs/next/authentication/reference/generated-files) to see a list of the files generated for the authentication app specifically. :::info This generator will attempt to add the generated application to the [`installed_apps`](https://martenframework.com/docs/next/development/reference/settings#installed_apps) setting and will also configure Crystal requirements for it (in the `src/project.cr` and `src/cli.cr` files). It will also add authentication-related settings to your base settings file and will add the [`marten-auth`](https://github.com/martenframework/marten-auth) shard to your project's `shard.yml`. ::: ### Arguments * `label` - Label of the authentication application to generate (default to "auth") ### Examples ```bash marten gen auth # Generate a new authentication app with the 'auth' label marten gen auth my_auth # Generate a new authentication app with the 'my_auth' label ``` ## `email` **Usage:** `marten gen email [options] [name]` Generate an email. Please refer to [Emailing](https://martenframework.com/docs/next/emailing) to learn more about emailing in Marten. ### Options * `--app=APP` - Target app where the email should be created (default to the [main app](https://martenframework.com/docs/next/development/applications#the-main-application)) * `--parent=PARENT` - Parent class name for the generated email ### Arguments * `name` - Name of the email to generate (must be CamelCase) ### Examples ```bash marten gen email TestEmail # Generate a new TestEmail email in the main application marten gen email TestEmail --app blog # Generate a new TestEmail email in the blog application ``` ## `handler` Generate a handler. Please refer to [Handlers](https://martenframework.com/docs/next/handlers-and-http/introduction) to learn more about handlers. ### Options * `--app=APP` - Target app where the handler should be created (default to the [main app](https://martenframework.com/docs/next/development/applications#the-main-application)) * `--parent=PARENT` - Parent class name for the generated handler ### Arguments * `name` - Name of the handler to generate (must be CamelCase) ### Examples ```bash marten gen handler TestHandler # Generate a new TestHandler handler in the main application marten gen handler TestHandler --app blog # Generate a new TestHandler handler in the blog application ``` ## `model` Generate a model. Please refer to [Models](https://martenframework.com/docs/next/models-and-databases/introduction) to learn more about models. ### Options * `--app=APP` - Target app where model handler should be created (default to the [main app](https://martenframework.com/docs/next/development/applications#the-main-application)) * `--parent=PARENT` - Parent class name for the generated model * `--no-timestamps` - Do not include timestamp fields in the generated model ### Arguments * `name` - Name of the model to generate (must be CamelCase) * `field_definitions` - Field definitions of the model to generate ### Details This generator can generate a model with the specified name and field definitions. The model is generated in the app specified by the `--app` option or in the [main app](https://martenframework.com/docs/next/development/applications#the-main-application) if no app is specified. Field definitions can be specified using the following formats: ``` name:type name:type{qualifier} name:type:modifier:modifier ``` Where `name` is the name of the field and `type` is the type of the field. `qualifier` can be required depending on the considered field type; when this is the case, it corresponds to a mandatory field option. For example, `label:string{128}` will produce a [string field](https://martenframework.com/docs/next/models-and-databases/reference/fields#string) whose `max_size` option is set to `128`. Another example: `author:many_to_one{User}` will produce a [many-to-one field](https://martenframework.com/docs/next/models-and-databases/reference/fields#many_to_one) whose `to` option is set to target the `User` model. `modifier` is an optional field modifier. Field modifiers are used to specify additional (but non-mandatory) field options. For example: `name:string:uniq` will produce a [string field](https://martenframework.com/docs/next/models-and-databases/reference/fields#string) whose `unique` option is set to `true`. Another example: `name:string:uniq:index` will produce a [string field](https://martenframework.com/docs/next/models-and-databases/reference/fields#string) whose `unique` and `index` options are set to `true`. ### Examples ```bash # Generate a model in the main app: marten gen model User name:string email:string # Generate a model in the admin app: marten gen model User name:string email:string --app admin # Generate a model with a many-to-one reference: marten gen model Article label:string body:text author:many_to_one{User} # Generate a model with a parent class: marten gen model Admin::User name:string email:string --parent User # Generate a model without timestamps: marten gen model User name:string email:string --no-timestamps ``` ## `schema` Generate a schema. Please refer to [Schemas](https://martenframework.com/docs/next/schemas/introduction) to learn more about schemas. ### Options * `--app=APP` - Target app where schema should be created (default to the [main app](https://martenframework.com/docs/next/development/applications#the-main-application)) * `--parent=PARENT` - Parent class name for the generated schema ### Arguments * `name` - Name of the schema to generate (must be CamelCase) * `field_definitions` - Field definitions of the schema to generate ### Details This generator can generate a schema with the specified name and field definitions. The schema is generated in the app specified by the `--app` option or in the [main app](https://martenframework.com/docs/next/development/applications#the-main-application) if no app is specified. Field definitions can be specified using the following formats: ``` name:type name:type:modifier:modifier ``` Where `name` is the name of the field and `type` is the type of the field. `modifier` is an optional field modifier. Field modifiers are used to specify additional (but non-mandatory) field options. For example: `name:string:optional` will produce a [string field](https://martenframework.com/docs/next/schemas/reference/fields#string) whose `required` option is set to `false`. ### Examples ```bash # Generate a schema in the main app: marten gen schema ArticleSchema title:string body:string # Generate a schema in the blog app: marten gen schema ArticleSchema title:string body:string --app admin # Generate a schema with a parent class: marten gen schema ArticleSchema title:string body:string --parent BaseSchema ``` ## `secretkey` Generate a new secret key value that can be used in the [`secret_key`](https://martenframework.com/docs/next/development/reference/settings#secret_key) setting. ### Examples ```bash marten gen secretkey ``` # Security Source: https://martenframework.com/docs/next/security Security is one of the most important topics to consider when developing web applications. This section covers the security measures that are provided by Marten and how to leverage them in your applications. ## Guides - [Introduction](https://martenframework.com/docs/next/security/introduction) - [CSRF protection](https://martenframework.com/docs/next/security/csrf) - [Clickjacking protection](https://martenframework.com/docs/next/security/clickjacking) - [Content Security Policy](https://martenframework.com/docs/next/security/content-security-policy) # Security in Marten Source: https://martenframework.com/docs/next/security/introduction This document describees the main security features that are provided by the Marten web framework. ## Cross-Site Request Forgery protection Cross-Site Request Forgery (CSRF) attacks generally involve a malicious website trying to perform actions on a web application on behalf of an already authenticated user. Marten comes with a built-in [CSRF protection mechanism](https://martenframework.com/docs/next/security/csrf) that is automatically enabled for your [handlers](https://martenframework.com/docs/next/handlers-and-http). The use of this CSRF protection mechanism is controlled by a set of [dedicated settings](https://martenframework.com/docs/next/development/reference/settings#csrf-settings). :::caution You should be careful when tweaking those settings and avoid disabling this protection unless this is absolutely necessary. ::: The CSRF protection provided by Marten is based on the verification of a token that must be provided for each unsafe HTTP request (ie. requests whose methods are not `GET`, `HEAD`, `OPTIONS`, `QUERY`, or `TRACE`). This token is stored in the client cookies and it must be specified when submitting unsafe requests (either in the data itself or using a specific header): if the tokens are not valid, or if the cookie-based token does not match the one provided in the data, then this means that the request is malicious and that it must be rejected. You can learn about the CSRF protection provided by Marten and the associated tools in the [dedicated documentation](https://martenframework.com/docs/next/security/csrf). ## Clickjacking protection Clickjacking attacks involve a malicious website embedding another unprotected website in a frame. This can lead to users performing unintended actions on the targeted website. Marten comes with a built-in [clickjacking protection mechanism](https://martenframework.com/docs/next/security/clickjacking), that involves using a dedicated middleware (the [X-Frame-Options middleware](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#x-frame-options-middleware)). This middleware is always automatically enabled for projects that are generated via the [`new`](https://martenframework.com/docs/next/development/reference/management-commands#new) management command and, as its name implies, it involves setting the X-Frame-Options header in order to prevent the considered Marten website from being inserted into a frame. You can learn about the clickjacking protection provided by Marten and the associated tools in the [dedicated documentation](https://martenframework.com/docs/next/security/clickjacking). ## Cross-Origin-Opener-Policy The [Cross-Origin-Opener-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy) (COOP) header allows browsers to isolate a top-level window from other documents by putting them in a different browsing context group. If a document protected by COOP opens a cross-origin popup, the popup's `window.opener` property will be `null`. This is a defense-in-depth protection against cross-origin attacks. Marten comes with a dedicated middleware (the [Cross-Origin-Opener-Policy middleware](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#cross-origin-opener-policy-middleware)) that sets this header. The value that is used depends on the [`cross_origin_opener_policy`](https://martenframework.com/docs/next/development/reference/settings#cross_origin_opener_policy) setting (whose default value is `same-origin`). This middleware is automatically enabled for projects that are generated via the [`new`](https://martenframework.com/docs/next/development/reference/management-commands#new) management command. You can define a custom header value on a per-handler basis by using the [`#cross_origin_opener_policy`](https://martenframework.com/docs/api/dev/Marten/Handlers/CrossOriginOpenerPolicy/ClassMethods.html#cross_origin_opener_policy(value%3AString%7CSymbol)%3ANil-instance-method) class method, or disable the header entirely with [`#exempt_from_cross_origin_opener_policy`](https://martenframework.com/docs/api/dev/Marten/Handlers/CrossOriginOpenerPolicy/ClassMethods.html#exempt_from_cross_origin_opener_policy(exempt%3ABool)%3ANil-instance-method). ## Cross Site Scripting protection Cross Site Scripting (XSS) attacks involve a malicious user injecting client-side scripts into the browser of another user. This usually happens when rendering database-stored HTML data or when generating HTML contents and displaying it in a browser: if these HTML contents are not properly sanitized, then this can allow an attacker's JavaScript to be executed in the browser. To prevent this, Marten [templates](https://martenframework.com/docs/next/templates) automatically escape HTML contents in variable outputs, unless those are marked as "safe". You can learn more about this capability in [Auto-Escaping](https://martenframework.com/docs/next/templates/introduction#auto-escaping). It should be noted that this auto-escaping mechanism can be disabled using a specific [filter](https://martenframework.com/docs/next/templates/reference/filters#safe) if needed, but you should be aware of the risks while doing so and ensure that your HTML contents are properly sanitized in order to avoid XSS vulnerabilities. Marten also comes with a dedicated middleware (the [X-Content-Type-Options middleware](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#x-content-type-options-middleware)) that sets the `X-Content-Type-Options: nosniff` header. This prevents browsers from MIME-sniffing responses away from the declared `Content-Type`, which can otherwise lead to XSS when serving mislabeled or user-uploaded content. This middleware is automatically enabled for projects that are generated via the [`new`](https://martenframework.com/docs/next/development/reference/management-commands#new) management command. You can disable this header on a per-handler basis by using the [`#exempt_from_x_content_type_options`](https://martenframework.com/docs/api/dev/Marten/Handlers/XContentTypeOptions/ClassMethods.html#exempt_from_x_content_type_options(exempt%3ABool)%3ANil-instance-method) class method. ## HTTP Host Header attacks protection HTTP Host Header attacks happen when websites that handle the value of the Host header (eg. in order to generate fully qualified URLs) trust this header value implicitly and don't verify it. Marten implements a protection mechanism against this type of attack by validating the Host header against a set of explicitly allowed hosts that must be specified in the [`allowed_hosts`](https://martenframework.com/docs/next/development/reference/settings#allowed_hosts) setting. The X-Forwarded-Host header can also be used to determine the host if the use of this header is enabled ([`use_x_forwarded_host`](https://martenframework.com/docs/next/development/reference/settings#use_x_forwarded_host) setting). ## SQL injection protection SQL injection attacks happen when a malicious user is able to execute arbitrary SQL queries on a database, which usually occurs when submitting input data to a web application. This can lead to database records being leaked and/or altered. The [query sets](https://martenframework.com/docs/next/models-and-databases/queries) API provided by Marten generates SQL code by using query parameterization. This means that the actual code of a query is defined separately from its parameters, which ensures that any user-provided parameter is escaped by the considered database driver before the query is executed. ## Content Security Policy The [Content-Security-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) (CSP) header is a collection of guidelines that the browser follows to allow specific sources for scripts, styles, embedded content, and more. It ensures that only these approved sources are allowed while blocking all other sources. Marten comes with a built-in [Content Security Policy mechanism](https://martenframework.com/docs/next/security/content-security-policy), that involves using a dedicated middleware (the [Content-Security-Policy middleware](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#content-security-policy-middleware)). This middleware guarantees the presence of the Content-Security-Policy header in the response's headers. You can learn about the Content-Security-Policy header and how to configure it in the [dedicated documentation](https://martenframework.com/docs/next/security/content-security-policy). # Cross-Site Request Forgery protection Source: https://martenframework.com/docs/next/security/csrf This document describes Marten's Cross-Site Request Forgery (CSRF) protection mechanism as well as the various tools that you can use in order to configure and make use of it. ## Overview Cross-Site Request Forgery (CSRF) attacks generally involve a malicious website trying to perform actions on a web application on behalf of an already authenticated user. Marten provides a built-in mechanism in order to protect your applications from this kind of attack. This mechanism is useful for protecting endpoints that handle "unsafe" HTTP requests (ie. requests whose methods are not `GET`, `HEAD`, `OPTIONS`, `QUERY`, or `TRACE`). :::caution The CSRF protection ignores safe HTTP requests. As such, you should ensure that those are side effect free. ::: The CSRF protection provided by Marten is based on the verification of a token that must be provided for each unsafe HTTP request. This token is stored in the client: Marten sends a token cookie with every HTTP response when the token value is requested in handlers ([`#get_csrf_token`](https://martenframework.com/docs/api/dev/Marten/Handlers/RequestForgeryProtection.html#get_csrf_token-instance-method) method) or templates (eg. through the use of the [`csrf_input`](https://martenframework.com/docs/next/templates/reference/tags#csrf_input) or [`csrf_token`](https://martenframework.com/docs/next/templates/reference/tags#csrf_token) template tags). It should be noted that the actual value of the token cookie changes every time an HTTP response is returned to the client: this is because the actual secret token is scrambled using a mask that changes for every request where the CSRF token is requested and used. The token value must be specified when submitting unsafe HTTP requests: this can be done either in the data itself (by specifying a `csrftoken` input) or by using a specific header (X-CSRF-Token). When receiving this value, Marten compares it to the token cookie value: if the tokens are not valid, or if there is a mismatch, then this means that the request is malicious and that it must be rejected (which will result in a 403 error). Finally, it should be noted that a few additional checks can be performed in addition to the token verification: * in order to protect against cross-subdomain attacks, the HTTP request host will be verified in order to ensure that it is either part of the allowed hosts ([`allowed_hosts`](https://martenframework.com/docs/next/development/reference/settings#allowed_hosts) setting) or that the value of the Origin header matches the configured trusted origins ([`csrf.trusted_origins`](https://martenframework.com/docs/next/development/reference/settings#trusted_origins) setting) * the Referer header will also be checked for HTTPS requests (if the Origin header is not set) in order to prevent subdomains to perform unsafe HTTP requests on the protected web applications (unless those subdomains are explicitly allowed as part of the [`csrf.trusted_origins`](https://martenframework.com/docs/next/development/reference/settings#trusted_origins) setting) The Cross-Site Request Forgery protection provided by Marten happens at the handler level automatically. This protection is implemented in the [`Marten::Handlers::RequestForgeryProtection`](https://martenframework.com/docs/api/dev/Marten/Handlers/RequestForgeryProtection.html) module. ## Basic usage You should first ensure that the CSRF protection is enabled, which is the case by default when projects are generated through the use of the [`new`](https://martenframework.com/docs/next/development/reference/management-commands#new) management command. That being said, if the CSRF protection is globally disabled (when the [`csrf.protection_enabled`](https://martenframework.com/docs/next/development/reference/settings#protection_enabled) setting is set to `false`) you need to ensure that your handler enables it _locally_. For example: ```crystal class MyHandler < Marten::Handler protect_from_forgery true # [...] end ``` Then all you need to do is to ensure that you include the CSRF token when submitting unsafe HTTP requests to your web application. How to do that depends on _how_ you intend to submit these requests. ### Using CSRF protection with forms If you need to embed the CSRF token into a form that is generated by a [template](https://martenframework.com/docs/next/templates), then you can make use of the [`csrf_input`](https://martenframework.com/docs/next/templates/reference/tags#csrf_input) template tag in order to ensure that a hidden `csrftoken` input containing the CSRF token is present in the form. For example: ```html
{% csrf_input %}
``` Alternatively, you can use the [`csrf_token`](https://martenframework.com/docs/next/templates/reference/tags#csrf_token) template tag to insert the raw value of the CSRF token directly into your templates. This approach is particularly useful if you need to manually create a hidden CSRF form input. For example: ```html
``` :::caution You should never define a hidden `csrftoken` input in a form that does not target your application directly. This is to prevent your CSRF token from being leaked. ::: ### Using the CSRF protection with AJAX If you need to submit unsafe HTTP requests on the client side using AJAX, then you also need to ensure that the CSRF token is specified in the request. In this light, you can generate requests that include a X-CSRF-Token header with the token value. But you first need to retrieve the CSRF token. To get it you can either: * retrieve the CSRF token from the cookies (which can be done only if the [`csrf.cookie_http_only`](https://martenframework.com/docs/next/development/reference/settings#cookie_http_only) setting is set to `false`) * or insert the CSRF token somewhere in your HTML markup (which is the way to go if the [`csrf.cookie_http_only`](https://martenframework.com/docs/next/development/reference/settings#cookie_http_only) setting is set to `true`) Retrieving the CSRF token from the cookies on the client side can be easily done by using a dedicated library such as the [JavaScript Cookie](https://www.npmjs.com/package/cookie) one: ```javascript const csrfToken = Cookies.get("csrftoken"); ``` If you can't leverage this technique because the [`csrf.cookie_http_only`](https://martenframework.com/docs/next/development/reference/settings#cookie_http_only) setting is set to `true`, then you can also define the CSRF token as a JavaScript variable on the template side (by using the [`csrf_token`](https://martenframework.com/docs/next/templates/reference/tags#csrf_token) template tag): ```html ``` An alternative approach could also involve defining an invisible tag with a data attribute, and retrieving this value in order to define a JavaScript variable containing the token value: ```html
``` Once you have the CSRF token value, all you need to do is to ensure that a X-CSRF-Token header is set with this value in all the unsafe HTTP requests you are issuing. ## Configuring the CSRF protection The CSRF protection is enabled by default and can be configured through the use of a [dedicated set of settings](https://martenframework.com/docs/next/development/reference/settings#csrf-settings). These settings can be used to enable or disable the protection globally, tweak some of the parameters of the CSRF token cookie, change the trusted origins, etc. ## Enabling or disabling the protection on a per-handler basis Regardless of the value of the [`csrf.protection_enabled`](https://martenframework.com/docs/next/development/reference/settings#protection_enabled) setting, it is possible to enable or disable the CSRF protection on a per-handler basis. This can be achieved through the use of the [`#protect_from_forgery`](https://martenframework.com/docs/api/dev/Marten/Handlers/RequestForgeryProtection/ClassMethods.html#protect_from_forgery(protect%3ABool)%3ANil-instance-method) class method, which takes a single boolean as arguments: ```crystal class ProtectedHandler < Marten::Handler protect_from_forgery true # [...] end class UnprotectedHandler < Marten::Handler protect_from_forgery false # [...] end ``` # Clickjacking protection Source: https://martenframework.com/docs/next/security/clickjacking This document describes Marten's clickjacking protection mechanism as well as the various tools that you can use in order to configure and make use of it. ## Overview Clickjacking attacks involve a malicious website embedding another unprotected website in a frame. This can lead to users performing unintended actions on the targeted website. The best way to mitigate this risk is to rely on the X-Frame-Options header: this header indicates whether or not the protected resource is allowed to be embedded into a frame, and if so under which conditions. The X-Frame-Options header can be set to `DENY` or `SAMEORIGIN`: * `DENY` means that the response cannot be displayed inside a frame at all * `SAMEORIGINS` means that the browser will allow the response to be displayed inside a frame if the site defining the frame is the same as the one serving the actual resource ## Basic usage Marten's clickjacking protection involves using a dedicated middleware: the [X-Frame-Options middleware](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#x-frame-options-middleware). This middleware is automatically added to the [`middleware`](https://martenframework.com/docs/next/development/reference/settings#middleware) setting when generating projects via the [`new`](https://martenframework.com/docs/next/development/reference/management-commands#new) management command. The [X-Frame-Options middleware](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#x-frame-options-middleware) simply sets the X-Frame-Options header in order to prevent the considered Marten website from being inserted into a frame. The value that is used for the X-Frame-Options header depends on the value of the [`x_frame_options`](https://martenframework.com/docs/next/development/reference/settings#x_frame_options) setting (whose default value is `DENY`). It should be noted that you can decide to disable or enable the use of the [X-Frame-Options middleware](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#x-frame-options-middleware) on a per-handler basis. To do so, you can simply make use of the [`#exempt_from_x_frame_options`](https://martenframework.com/docs/api/dev/Marten/Handlers/XFrameOptions/ClassMethods.html#exempt_from_x_frame_options(exempt%3ABool)%3ANil-instance-method) class method, which takes a single boolean as arguments: ```crystal class ProtectedHandler < Marten::Handler exempt_from_x_frame_options false # [...] end class UnprotectedHandler < Marten::Handler exempt_from_x_frame_options true # [...] end ``` # Content Security Policy Source: https://martenframework.com/docs/next/security/content-security-policy Marten offers a convenient mechanism to define the Content-Security-Policy header, which serves as a safeguard against vulnerabilities such as cross-site scripting (XSS) and injection attacks. This mechanism enables the specification of a trusted resource allowlist, enhancing security measures. ## Overview The [Content-Security-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) (CSP) header is a collection of guidelines that the browser follows to allow specific sources for scripts, styles, embedded content, and more. It ensures that only these approved sources are allowed while blocking all other sources. Utilizing the Content-Security-Policy header in a web application is a great way to mitigate or eliminate cross-site scripting (XSS) vulnerabilities. By implementing an effective Content-Security-Policy, the inclusion of inline scripts is prevented, and only scripts from trusted sources in separate files are allowed. ## Basic usage Marten's Content-Security-Policy mechanism involves using a dedicated middleware: the [Content-Security-Policy middleware](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#content-security-policy-middleware). To ensure that your project is using this middleware, you can add the [`Marten::Middleware::ContentSecurityPolicy`](https://martenframework.com/docs/api/dev/Marten/Middleware/ContentSecurityPolicy.html) class to the [`middleware`](https://martenframework.com/docs/next/development/reference/settings#middleware) setting as follows: ```crystal title="config/settings/base.cr" Marten.configure do |config| config.middleware = [ // highlight-next-line Marten::Middleware::ContentSecurityPolicy, # Other middlewares... Marten::Middleware::Session, Marten::Middleware::Flash, Marten::Middleware::I18n, ] end ``` The [Content-Security-Policy middleware](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#content-security-policy-middleware) guarantees the presence of the Content-Security-Policy header in the response's headers. By default, the middleware will include a Content-Security-Policy header that corresponds to the policy defined in the [`content_security_policy`](https://martenframework.com/docs/next/development/reference/settings#content-security-policy-settings) settings. However, if a [`Marten::HTTP::ContentSecurityPolicy`](https://martenframework.com/docs/api/dev/Marten/HTTP/ContentSecurityPolicy.html) object is explicitly assigned to the request object, it will take precedence over the default policy and be used instead. When enabling the [Content-Security-Policy middleware](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#content-security-policy-middleware), it is recommended to define a default Content-Security-Policy by leveraging the [`content_security_policy`](https://martenframework.com/docs/next/development/reference/settings#content-security-policy-settings) settings. For example: ```crystal title="config/settings/base.cr" Marten.configure do |config| config.content_security_policy.default_policy.default_src = [:self, "example.com"] config.content_security_policy.default_policy.script_src = [:self, :https] end ``` ## Disabling the CSP header in specific handlers You can decide to disable or enable the use of the Content-Security-Policy header on a per-[handler](https://martenframework.com/docs/next/handlers-and-http) basis. To do so, you can simply make use of the [`#exempt_from_content_security_policy`](https://martenframework.com/docs/api/dev/Marten/Handlers/ContentSecurityPolicy/ClassMethods.html#exempt_from_content_security_policy(exempt:Bool):Nil-instance-method) class method, which takes a single boolean as argument: ```crystal class ProtectedHandler < Marten::Handler exempt_from_content_security_policy false # [...] end class UnprotectedHandler < Marten::Handler exempt_from_content_security_policy true # [...] end ``` ## Overriding the CSP header in specific handlers Sometimes you may also need to override the content of the Content-Security-Policy header on a per-[handler](https://martenframework.com/docs/next/handlers-and-http) basis. To do so, you can make use of the [`#content_security_policy`](https://martenframework.com/docs/api/dev/Marten/Handlers/ContentSecurityPolicy/ClassMethods.html#content_security_policy(%26content_security_policy_block%3AHTTP%3A%3AContentSecurityPolicy->)-instance-method) class method, which yields a [`Marten::HTTP::ContentSecurityPolicy`](https://martenframework.com/docs/api/dev/Marten/HTTP/ContentSecurityPolicy.html) object that you can configure (by adding/modifying/removing CSP directives) for the handler at hand. For example: ```crystal class ProtectedHandler < Marten::Handler content_security_policy do |csp| csp.default_src = {:self, "example.com"} end # [...] end ``` ## Using a CSP nonce CSP nonces serve as a valuable tool to enable the execution or rendering of specific elements, such as inline script or style tags, by the browser. When a tag contains the correct nonce value in a `nonce` attribute, the browser grants permission for its execution or rendering, while blocking others that lack the expected nonce value. You can configure Marten so that it automatically adds a nonce to an explicit set of Content-Security-Policy directives. This can be achieved by specifying the list of intended CSP directives in the [`content_security_policy.nonce_directives`](https://martenframework.com/docs/next/development/reference/settings#nonce_directives) setting. For example: ```crystal title="config/settings/base.cr" Marten.configure do |config| config.content_security_policy.nonce_directives = ["script-src", "style-src"] end ``` For example, if this setting is set to `["script-src", "style-src"]`, a `nonce-` value will be added to the `script-src` and `style-src` directives in the Content-Security-Policy header value. The nonce is a randomly generated Base64 value (generated through the use of [`Random::Secure#urlsafe_base64`](https://crystal-lang.org/api/Random.html#urlsafe_base64(n:Int=16,padding=false):String-instance-method)). To make the browser do anything with the nonce value, you will need to include it in the attributes of the tags that you wish to mark as safe. In this light, you can use the [`Marten::HTTP::Request#content_security_policy_nonce`](https://martenframework.com/docs/api/dev/Marten/HTTP/Request.html#content_security_policy_nonce-instance-method) method, which returns the CSP nonce value for the current request. This method can also be called from within [templates](https://martenframework.com/docs/next/templates), making it easy to generate `script` or `style` tags containing the right `nonce` attribute: ```html ``` # Internationalization Source: https://martenframework.com/docs/next/i18n Marten provides various tools and mechanisms that you can leverage to benefit from translations and localized contents in your projects. ## Guides - [Introduction](https://martenframework.com/docs/next/i18n/introduction) - [Localized routes](https://martenframework.com/docs/next/i18n/localized-routes) # Introduction to internationalization Source: https://martenframework.com/docs/next/i18n/introduction Marten provides integration with [crystal-i18n](https://crystal-i18n.github.io/) to make it possible to leverage translations and localized content in your Marten projects. ## Overview Internationalization and localization are techniques allowing a website to provide content using languages and formats that are adapted to specific audiences. Marten's internationalization and localization integration rely on the use of the [crystal-i18n](https://crystal-i18n.github.io/) shard, which provides a unified interface allowing to leverage translations and localized contents in a Crystal project. You don't have to manually install this shard in your projects: it is a dependency of the framework itself, and as such, it is automatically installed with Marten. Crystal-I18n makes it easy to configure translations and formats for a specific set of locales. These can be used to perform translation lookups and localization. With this library, translations can be defined through the use of dedicated "loaders" (abstractions that load the translations from a specific source and make them available to the I18n API). For example, translations can be loaded from a YAML file, a JSON file, or something entirely different if needed. Marten itself defines a set of translated contents for things that should be internationalized (eg. model field errors or schema field errors) that are loaded through the use of the regular YAML loader. Other [app-specific translations](#locales-and-apps) must also be defined as YAML files since they are loaded using a YAML loader as well. ## Configuration Marten provides an integration allowing to configure internationalization-related settings. These settings are available under the [`i18n`](https://martenframework.com/docs/next/development/reference/settings#i18n-settings) namespace and allow to define things like the default locale and the available locales: ```crystal config.i18n.default_locale = :fr config.i18n.available_locales = [:en, :fr] ``` You can also leverage the [various configuration options](https://crystal-i18n.github.io/configuration.html) that are provided by this shard to further configure how translations should be performed. By doing so you can add more custom I18n backend loaders for example. :::tip If you need to further [configure Crystal I18n](https://crystal-i18n.github.io/configuration.html), you should probably define a dedicated initializer file under the `config/initializers` folder. ::: ## Basic usage As stated before, Marten relies on the [crystal-i18n](https://crystal-i18n.github.io/) shard, which means that you can also look at the dedicated documentation to learn more about this shard and its configuration options. The following section mainly highlights some of the main features of this library. ### Defining translations Translations are defined as YML files that must be placed in `locales` folders, which can be located in different parts of a project: * Within the `config` directory (`config/locales` folder). * At the root of the [main application](https://martenframework.com/docs/next/development/applications#the-main-application)'s directory (`src/locales` folder). * At the root of an [application](https://martenframework.com/docs/next/development/applications#creating-applications)'s directory. For example, if you are using the standard `config` directory and the [main application](https://martenframework.com/docs/next/development/applications#the-main-application) (which corresponds to the standard `src` folder) you could define `config/locales` and `src/locales` folders containing `en.yml` files as follows: ``` myproject/ ├── config │   ├── locales │   │   ├── en.yml ├── src │   ├── locales │   │   ├── en.yml ``` Translations inside a YAML file must be namespaced to the locale they are associated with (`en` in this case). Example content for our `en.yml` file could look like this: ```yaml title=src/en.yml en: message: "This is a message" simple: translation: "This is a simple translation" interpolation: "Hello, %{name}!" ``` The "path" leading to a translation in such files is important because it corresponds to the key that should be used when performing [translation lookups](#translations-lookups). For example, `simple.translation` would be the key to use in order to translate the corresponding message. It should be noted that the `%{var}` syntax in the above example is used to define _interpolations_: these variables must be specified when performing translation lookups so that their values are inserted in the translated strings. ### Translations lookups Translation lookups can be performed by leveraging the `I18n#translate` or `I18n#translate!` methods. Those methods try to find a matching translation for a specific key, which can be comprised of multiple namespaces or scopes separated by a dot (.): this key corresponds to the "path" leading to the actual translation (as mentioned before). The `I18n#translate` and `I18n#translate!` methods differ in regards to how they handle missing translations: * `I18n#translate` returns a message indicating that the translation is missing * `I18n#translate!` raises a specific exception For example, given the translations defined in [Defining translations](#defining-translations), we could perform the following translation lookups: ```crystal I18n.translate(:message) # => "This is a message" I18n.translate("simple.translation") # => "This is a simple translation" I18n.translate("simple.interpolation", name: "John Doe") # => "Hello, John Doe!" ``` This only scratches the surface of what's possible in terms of translation lookups. You can refer to the [dedicated documentation](https://crystal-i18n.github.io/translation_lookups.html), and more specifically the [interpolations](https://crystal-i18n.github.io/translation_lookups.html#interpolations) and [pluralizations](https://crystal-i18n.github.io/translation_lookups.html#pluralization) sections, to learn about these capabilities. ### Localization Localization of datetimes and numbers can be achieved through the use of the `I18n#localize` method. In both cases, localization _formats_ need to be defined in your locale files. There are a lot of available formats at your disposal (and all of them are documented in the [related documentation](https://crystal-i18n.github.io/localization.html)). For example, the following translations could be used to format dates in English: ```yaml en: i18n: date: month_names: [January, February, March, April, May, June, July, August, September, October, November, December] formats: default: "%Y-%m-%d" long: "%B %d, %Y" ``` The above structure is expected by Crystal I18n and defines basic translations for the relevant directives that can be outputted when localizing dates. It also defines a few formats under the `i18n.date.formats` scope: among these formats, only the default one is really mandatory since this is the one that is used by default if no other format is explicitly provided to the `I18n#localize` method. All these formats make use of the directives defined by the [`Time::Format`](https://crystal-lang.org/api/Time/Format.html) struct. Given the above translations, you could localize date objects as follows: ```crystal I18n.localize(Time.local.date) # outputs "2020-12-13" I18n.localize(Time.local.date, :long) # outputs "December 13, 2020" ``` ### Switching locales Once you have defined translations, it is generally needed to explicitly "activate" the use of a specific locale in order to ensure that the right translations are generated for your users. In this light, the current locale can be specified using the `I18n#activate` method: ```crystal I18n.activate(:fr) ``` When activating a locale with `I18n#activate`, all further translations or localizations will be done using the specified locale. Note that it is also possible to execute a block with a specific locale activated. This can be done by using the `I18n#with_locale` method: ```crystal I18n.with_locale(:fr) do I18n.t("simple.translation") # Will output a text in french end ``` Finally, it should be noted that Marten provides an [I18n middleware](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#i18n-middleware) that activates the right locale based on the Accept-Language header. Only explicitly-configured locales can be activated by this middleware (that is, locales that are specified in the [`i18n.available_locales`](https://martenframework.com/docs/next/development/reference/settings#available_locales) and [`i18n.default_locale`](https://martenframework.com/docs/next/development/reference/settings#default_locale) settings). If the incoming locale can't be found in the project configuration, the default locale will be used instead. By leveraging this middleware, you can be sure that the right locale is automatically enabled for your users, so you don't need to take care of it. ## Locales and apps As mentioned previously, each [application](https://martenframework.com/docs/next/development/applications) can define translations inside a `locales` folder that must be located at the root of the application's directory. This `locales` folder should contain YAML files defining the translations that are required by the application. The way to organize translations inside this folder is left to application developers. That being said, it is necessary to ensure that all the YAML files containing translations are namespaced with the targeted locale (eg. `en`, `fr`, etc). Moreover, it is also recommended to explicitly namespace an application's translations by using an identifier that is unique for the considered application. For example, a `foo` application could define a `message` translation and another `bar` application could define a `message` translation as well. If these translation keys are not properly namespaced, one of the translations will be overridden by the one of the other application. The best way to avoid this is to namespace all the translations of an application with the identifier of the application itself. For example: ```yaml en: foo: message: This is a message ``` In this case, the `foo` application's codebase would request translations using the `foo.message` key, which makes it impossible to encounter conflict issues with other application translations. ## How Marten resolves the current locale Marten will attempt to determine the "current" locale for activation only when the [I18n middleware](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#i18n-middleware) is used. This middleware can activate the appropriate locale by considering the following: * The value of the Accept-Language header. * The value of a cookie, with its name defined by the [`i18n.locale_cookie_name`](https://martenframework.com/docs/next/development/reference/settings#locale_cookie_name) setting. The [I18n middleware](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#i18n-middleware) only allows activation of explicitly configured locales, which are specified in the [`i18n.available_locales`](https://martenframework.com/docs/next/development/reference/settings#available_locales) and [`i18n.default_locale`](https://martenframework.com/docs/next/development/reference/settings#default_locale) settings. If the incoming locale is not found in the project configuration, the default locale will be used instead. By utilizing this middleware, you can be sure that the right locale is automatically enabled for your users, so that you don't need to take care of it. ## Limitations It's important to be aware of a few limitations when working with translations powered by [Crystal I18n](https://crystal-i18n.github.io/) within a Marten project: 1. Marten automatically configures YAML translation loaders for applications, and it is not currently possible to use other loader types (such as JSON) presently 2. Marten does not allow the use of "embedded" translations for applications since those are discovered and configured at runtime: as such application translations are treated as "assets" that must be deployed along with the compiled binary Note that these restrictions do not prevent the use of custom translation backends if necessary. Please refer to the [related documentation](https://crystal-i18n.github.io/configuration.html#loaders) if you need to use custom translation loaders in your projects. # Localized routes Source: https://martenframework.com/docs/next/i18n/localized-routes Marten enables route internationalization through two mechanisms: automatically adding locale prefixes to your routes and activating the appropriate locale based on the prefix, and translating the routes themselves to provide a seamless multilingual experience. These mechanisms can be used independently or in combination. ## Requirements The features described below require the correct locale to be automatically activated for each user when processing incoming requests. To achieve this, you must either use the [I18n middleware](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#i18n-middleware) or implement your [own middleware](https://martenframework.com/docs/next/handlers-and-http/middlewares#how-middlewares-work) that activates the appropriate locale based on a custom logic (eg. based on specific domains). ## Prefixing routes with locales Prefixing routes with locales allows to activate specific locales based on the accessed route paths when the [I18n middleware](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#i18n-middleware) is used. Defining localized routes involves wrapping route path definitions by a call to the [`#localized`](https://martenframework.com/docs/api/dev/Marten/Routing/Map.html#localized(prefix_default_locale%3Dtrue%2C%26)%3ANil-instance-method) method. When such routes are defined, the current locale will be automatically prepended to the path of the localized routes and the routes map will be able to resolve paths in a locale-aware manner. For example: ```crystal ARTICLE_ROUTES = Marten::Routing::Map.draw do path "", ArticlesHandler, name: "list" path "/create", ArticleCreateHandler, name: "create" path "/", ArticleDetailHandler, name: "detail" path "//update", ArticleUpdateHandler, name: "update" path "//delete", ArticleDeleteHandler, name: "delete" end Marten.routes.draw do localized do path "/landing", LandingPageHandler, name: "landing" path "/articles", ARTICLE_ROUTES, name: "articles" end end ``` After defining these routes, Marten automatically prepends the locale prefix to the paths of all routes included within the [`#localized`](https://martenframework.com/docs/api/dev/Marten/Routing/Map.html#localized(prefix_default_locale%3Dtrue%2C%26)%3ANil-instance-method) method block. ```crystal I18n.activate("en") Marten.routes.reverse("landing") # => "/en/landing" Marten.routes.reverse("articles:create") # => "/en/articles/create" ``` :::tip You can choose not to prefix routes for the [default locale](https://martenframework.com/docs/next/development/reference/settings#default_locale). To achieve this, set the `prefix_default_locale` argument to `false` when defining the `#localized` block: ```crystal Marten.routes.draw do localized(prefix_default_locale: false) do path "/landing", LandingPageHandler, name: "landing" path "/articles", ARTICLE_ROUTES, name: "articles" end end ``` ::: :::warning The `#localized` method can only be used within your root routes map, defined in your project's `config/routes.cr` file. Additionally, only one `#localized` block is allowed per project. Violating these requirements will result in a `Marten::Routing::Errors::InvalidRouteMap` exception being raised. ::: ## Translating route paths You can translate route paths whether or not they use [locale prefixes](#prefixing-routes-with-locales). Indeed, it is possible to define routes whose paths reference specific translation keys that map to predefined translations (translations which store the actual route paths for each locale). To do so, instead of specifying the paths of your routes as regular strings, you need to use the [`#t`](https://martenframework.com/docs/api/dev/Marten/Routing/Map.html#t(path%3AString)%3ATranslatedPath-instance-method) method to specify a translation key that will dynamically be used to generate a route's path for a given locale. This method takes a single argument: the translation key that should be used to dynamically determine the path of the considered route. For example, let's consider the following [translation file](https://martenframework.com/docs/next/i18n/introduction#defining-translations): ```yaml en: routes: landing: "/landing" articles: list: "" create: "/create" detail: "/" update: "//update" delete: "//delete" fr: routes: landing: "/accueil" articles: prefix: "/articles" list: "" create: "/creer" detail: "/" update: "//mettre-a-jour" delete: "//supprimer" ``` As you can see, route path translations can contain [route parameters](https://martenframework.com/docs/next/handlers-and-http/routing#specifying-route-parameters). Considering these translations, we could define the following routes map: ```crystal ARTICLE_ROUTES = Marten::Routing::Map.draw do path t("routes.articles.list"), ArticlesHandler, name: "list" path t("routes.articles.create"), ArticleCreateHandler, name: "create" path t("routes.articles.detail"), ArticleDetailHandler, name: "detail" path t("routes.articles.update"), ArticleUpdateHandler, name: "update" path t("routes.articles.delete"), ArticleDeleteHandler, name: "delete" end Marten.routes.draw do path t("routes.landing"), LandingPageHandler, name: "landing" path t("routes.articles.prefix"), ARTICLE_ROUTES, name: "articles" end ``` :::warning When using translated paths, the entirety of the path **must** be defined in locale files (including [route parameters](https://martenframework.com/docs/next/handlers-and-http/routing#specifying-route-parameters)). As such, interpolating the return values of the [`#t`](https://martenframework.com/docs/api/dev/Marten/Routing/Map.html#t(path%3AString)%3ATranslatedPath-instance-method) method is not allowed and will result in `Marten::Routing::Errors::InvalidRouteMap` exceptions to be raised. For example, the following route is not permitted: ```crystal path "#{t("routes.articles.detail")}/", ArticleDetailHandler, name: "detail" ``` ::: As highlighted above, all the paths of these routes will be dynamically determined by resolving the corresponding translation key for the current locale. For example: ```crystal I18n.activate("en") Marten.routes.reverse("landing") # => "/landing" Marten.routes.reverse("articles:create") # => "/articles/create" I18n.activate("fr") Marten.routes.reverse("landing") # => "/accueil" Marten.routes.reverse("articles:create") # => "/articles/creer" ``` :::tip It is possible to combine translated route paths and [locale prefixes](#prefixing-routes-with-locales). This allows to benefit from fully translated routes that are prefixed by a locale that is automatically activated by the [I18n middleware](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#i18n-middleware) if it is used. For example: ```crystal ARTICLE_ROUTES = Marten::Routing::Map.draw do path t("routes.articles.list"), ArticlesHandler, name: "list" path t("routes.articles.create"), ArticleCreateHandler, name: "create" path t("routes.articles.detail"), ArticleDetailHandler, name: "detail" path t("routes.articles.update"), ArticleUpdateHandler, name: "update" path t("routes.articles.delete"), ArticleDeleteHandler, name: "delete" end Marten.routes.draw do localized do path t("routes.landing"), LandingPageHandler, name: "landing" path t("routes.articles.prefix"), ARTICLE_ROUTES, name: "articles" end end I18n.activate("en") Marten.routes.reverse("landing") # => "/en/landing" Marten.routes.reverse("articles:create") # => "/en/articles/create" I18n.activate("fr") Marten.routes.reverse("landing") # => "/fr/accueil" Marten.routes.reverse("articles:create") # => "/fr/articles/creer" ``` ::: :::warning To avoid potential collisions between translated and non-translated route paths, it is generally best to translate route paths while also [incorporating locale prefixes](#prefixing-routes-with-locales). This ensures a clear distinction between different locales and minimizes the risk of conflicts. ::: # Emailing Source: https://martenframework.com/docs/next/emailing Marten provides a convenient email definition mechanism that leverages templates. These emails are sent through the use of a generic emailing backend system that can be used to fully customize how emails are delivered. ## Guides - [Introduction](https://martenframework.com/docs/next/emailing/introduction) - [Callbacks](https://martenframework.com/docs/next/emailing/callbacks) ## How-to's - [Create custom emailing backends](https://martenframework.com/docs/next/emailing/how-to/create-custom-emailing-backends) ## Reference - [Backends](https://martenframework.com/docs/next/emailing/reference/backends) # Introduction to emails Source: https://martenframework.com/docs/next/emailing/introduction Marten lets you define emails in a very declarative way and gives you the ability to fully customize the content of these emails, their properties and associated header values, and obviously how they should be delivered. ## Email definition Emails must be defined as subclasses of the [`Emailing::Email`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html) abstract class and they usually live in an `emails` folder at the root of an application. These classes can define to which email addresses the email is sent (including CC or BCC addresses) and with which [templates](https://martenframework.com/docs/next/templates) the body of the email (HTML or plain text) is rendered. For example, the following snippet defines a simple email that is sent to a specific user's email address: ```crystal class WelcomeEmail < Marten::Email from "no-reply@martenframework.com" to @user.email subject "Hello!" template_name "emails/welcome_email.html" def initialize(@user : User) end end ``` :::info It is not necessary to systematically specify the `from` email address with the [`#from`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#from(value)-macro) macro. Indeed, unless specified, the default "from" email address that is defined in the [`emailing.from_address`](https://martenframework.com/docs/next/development/reference/settings#from_address) setting is automatically used. ::: In the above snippet, a `WelcomeEmail` email class is defined by inheriting from the [`Emailing::Email`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html) abstract class. This email is initialized with a hypothetical `User` record, and this user's email address is used as the recipient email (through the use of the [`#to`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#to(value)-macro) macro). Other email properties are also defined in the above snippet, such as the "from" email address ([`#from`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#from(value)-macro) macro) and the subject of the email ([`#subject`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#subject(value)-macro) macro). ### Specifying email properties Most email properties (eg. from address, recipient addresses, etc) can be specified in two ways: * through the use of a dedicated macro * by overriding a corresponding method in the email class Indeed, it is convenient to define email properties through the use of the dedicated macros: [`#from`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#from(value)-macro) for the sender email, [`#to`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#to(value)-macro) for the recipient addresses, [`#cc`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#cc(value)-macro) for the CC addresses, [`#bcc`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#bcc(value)-macro) for the BCC addresses, [`#reply_to`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#reply_to(value)-macro) for the Reply-To address, and [`#subject`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#subject(value)-macro) for the email subject. That being said, if more complicated logics need to be implemented to generate these email properties, it is perfectly possible to simply override the corresponding method in the considered email class. For example: ```crystal class WelcomeEmail < Marten::Email from "no-reply@martenframework.com" to @user.email template_name "emails/welcome_email.html" def initialize(@user : User) end def subject if @user.referred? "Glad to see you here!" else "Welcome to the app!" end end end ``` ### Defining HTML and text bodies The HTML body (and optionally text body) of the email is rendered using a [template](https://martenframework.com/docs/next/templates) whose name can be specified by using the [`#template_name`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#template_name(template_name%3AString%3F%2Ccontent_type%3AContentType|String|Symbol%3DContentType%3A%3AHTML)%3ANil-class-method) class method. By default, unless explicitly specified, it is assumed that the template specified to this method is used for rendering the HTML body of the email. That being said, it is possible to explicitly specify for which content type the template should be used by specifying an optional `content_type` argument as follows: ```crystal class WelcomeEmail < Marten::Email to @user.email subject "Hello!" template_name "emails/welcome_email.html", content_type: :html template_name "emails/welcome_email.txt", content_type: :text def initialize(@user : User) end end ``` Note that it is perfectly valid to specify one template for rendering the HTML body AND another one for rendering the text body (like in the above example). :::info Note that you can define [`#html_body`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#html_body%3AString%3F-instance-method) and [`#text_body`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#html_body%3AString%3F-instance-method) methods if you need to override the logic that allows generating the HTML or text body of your email. ::: ### Modifying the template context All emails have access to a [`#context`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#context-instance-method) method that returns a [template](https://martenframework.com/docs/next/templates/introduction) context object. This "global" context object is available for the lifetime of the considered email and can be mutated in order to define which variables are made available to the template runtime when rendering templates in order to generate the HTML/text bodies of your email (which happens when [sending the email](#sending-emails)). To modify this context object effectively, it's recommended to utilize [`before_render`](https://martenframework.com/docs/next/emailing/callbacks#before_render) callbacks, which are invoked just before rendering a template within your email. For example, this can be achieved as follows: ```crystal class WelcomeEmail < Marten::Email from "no-reply@martenframework.com" to @user.email subject "Hello!" template_name "emails/welcome_email.html" before_render :prepare_context def initialize(@user : User) end private def prepare_context context[:user] = @user end end ``` In the above example, the [`before_render`](https://martenframework.com/docs/next/emailing/callbacks#before_render) callback simply assigns a new `user` variable to the email template context. Consequently, a corresponding `{{ user }}` variable will be available in the template configured for this email (`emails/welcome_email.html` in this case). ### Defining custom headers If you need to insert custom headers into your emails, then you can easily do so by defining a `#headers` method in your email class. This method must return a hash of string keys and values. For example: ```crystal class WelcomeEmail < Marten::Email to @user.email template_name "emails/welcome_email.html" def initialize(@user : User) end def headers {"X-Foo" => "bar"} end end ``` ### Defining attachments Attachments can be associated with an email by calling [`#attach`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#attach(path%3AString,filename%3AString%7CNil%3Dnil,mime_type%3AString%7CNil%3Dnil)%3ANil-instance-method). In most cases, this is done in a [`before_deliver`](https://martenframework.com/docs/next/emailing/callbacks#before_deliver) callback so that attachments are set right before the email is delivered. The following `#attach` method signatures are available: * `attach(path : String, filename : String? = nil, mime_type : String? = nil)` * `attach(file : File, filename : String? = nil, mime_type : String? = nil)` * `attach(io : IO, *, filename : String, mime_type : String? = nil)` :::note[IO Attachments] When using `attach(io, ...)`, the `filename` is required and the IO is read from its current position to EOF. If you need to attach the full IO content, call `io.rewind` before attaching it. ::: For example: ```crystal class WelcomeEmail < Marten::Email from "no-reply@martenframework.com" to @user.email subject "Hello!" template_name "emails/welcome_email.html" before_deliver :add_attachments def initialize(@user : User) end private def add_attachments # Attach a file from a path. attach "public/docs/terms.pdf" # Attach generated content from an IO. attach generate_pdf_io(@user), filename: "welcome.pdf", mime_type: "application/pdf" end end ``` When a `mime_type` is not specified, Marten infers it from the attachment file name. If no MIME type can be inferred, it defaults to `application/octet-stream`. ## Sending emails Emails are sent _synchronously_ through the use of the [`#deliver`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#deliver-instance-method). For example, the `WelcomeEmail` email defined in the previous sections could be initialized and delivered by doing: ```crystal email = WelcomeEmail.new(user) email.deliver ``` When calling [`#deliver`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#deliver-instance-method), the considered email will be delivered by using the currently configured [emailing backend](#emailing-backends). ## Emailing backends Emailing backends define _how_ emails are actually sent when [`#deliver`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#deliver-instance-method) gets called. For example, a [development backend](https://martenframework.com/docs/next/emailing/reference/backends#development-backend) might simply "collect" the sent emails and print their information to the standard output. Other backends might also integrate with existing email services or interact with an SMTP server to ensure email delivery. Which backend is used when sending emails is something that is controlled by the [`emailing.backend`](https://martenframework.com/docs/next/development/reference/settings#backend-1) setting. All the available emailing backends are listed in the [emailing backend reference](https://martenframework.com/docs/next/emailing/reference/backends). :::tip If necessary, it is also possible to override which emailing backend is used on a per-email basis by leveraging the [`#backend`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#backend(backend%3ABackend%3A%3ABase)%3ANil-class-method) class method. For example: ```crystal class WelcomeEmail < Marten::Email from "no-reply@martenframework.com" to @user.email subject "Hello!" template_name "emails/welcome_email.html" backend Marten::Emailing::Backend::Development.new(print_emails: true) def initialize(@user : User) end end ``` ::: ## Callbacks It is possible to define callbacks in order to bind methods and logics to specific events in the lifecycle of your emails. For example, it is possible to define callbacks that run before or after an email gets delivered. Please head over to the [Email callbacks](https://martenframework.com/docs/next/emailing/callbacks) guide in order to learn more about email callbacks. # Email callbacks Source: https://martenframework.com/docs/next/emailing/callbacks Callbacks enable you to define logic that is triggered at different stages of an email's lifecycle. This document covers the available callbacks and introduces you to the associated API, which you can use to define hooks in your emails. ## Overview As stated above, callbacks are methods that will be called when specific events occur for a specific email instance. They need to be registered explicitly in your email classes. Registering a callback is as simple as calling the right callback macro (eg. `#before_deliver`) with a symbol of the name of the method to call when the callback is executed. For example, the following email leverages the [`#after_deliver`](#after_deliver) callback in order to emit a specific StatsD metric: ```crystal require "statsd" statsd = Statsd::Client.new class WelcomeEmail < Marten::Email from "no-reply@martenframework.com" to @user.email subject "Hello!" template_name "emails/welcome_email.html" after_deliver :emit_delivered_welcome_email_metric def initialize(@user : User) end private def emit_delivered_welcome_email_metric statsd.increment "email.welcome.delivered", tags: ["app:myapp"] end end ``` ## Available callbacks ### `before_deliver` `before_deliver` callbacks are executed _before_ an email is delivered (as part of the email's [`#deliver`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#deliver-instance-method) method). For example, this capability can be leveraged to mutate the considered email instance before the actual email gets delivered: ```crystal class WelcomeEmail < Marten::Email from "no-reply@martenframework.com" to @user.email subject "Hello!" template_name "emails/welcome_email.html" before_deliver :set_header def initialize(@user : User) end private def set_header headers["X-Debug"] = "True" if Marten.env.staging? end end ``` This callback is also a common place to call [`#attach`](https://martenframework.com/docs/next/emailing/introduction#defining-attachments) in order to add email attachments right before delivery. ### `after_deliver` `after_deliver` callbacks are executed _after_ an email is delivered (as part of the email's [`#deliver`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#deliver-instance-method) method). For example, such callbacks can be leveraged to increment email-specific metrics: ```crystal require "statsd" statsd = Statsd::Client.new class WelcomeEmail < Marten::Email from "no-reply@martenframework.com" to @user.email subject "Hello!" template_name "emails/welcome_email.html" after_deliver :emit_delivered_welcome_email_metric def initialize(@user : User) end private def emit_delivered_welcome_email_metric statsd.increment "email.welcome.delivered", tags: ["app:myapp"] end end ``` ### `before_render` `before_render` callbacks are invoked prior to rendering a template when generating the HTML or text body of the email. This means that these callbacks are executed when calling either the [`#deliver`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#deliver-instance-method), [`#html_body`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#html_body%3AString|Nil-instance-method), or [`#text_body`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html#text_body%3AString|Nil-instance-method) methods. Typically, these callbacks can be used to add new variables to the global email template context, in order to make them available to the template runtime. This can be useful if your email has some instance variables that you want to expose to your email template. For example: ```crystal class WelcomeEmail < Marten::Email from "no-reply@martenframework.com" to @user.email subject "Hello!" template_name "emails/welcome_email.html" before_render :prepare_context def initialize(@user : User) end private def prepare_context context[:user] = @user end end ``` # Create emailing backends Source: https://martenframework.com/docs/next/emailing/how-to/create-custom-emailing-backends Marten lets you easily create custom [emailing backends](https://martenframework.com/docs/next/emailing/introduction#emailing-backends) that you can then use as part of your application when it comes to sending emails. ## Basic backend definition Defining an emailing backend is as simple as creating a class that inherits from the [`Marten::Emailing::Backend::Base`](https://martenframework.com/docs/api/dev/Marten/Emailing/Backend/Base.html) abstract class and that implements a unique `#deliver` method. This method takes a single `email` argument (instance of [`Marten::Emailing::Email`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html)), corresponding to the email to deliver. For example: ```crystal class CustomEmailingBackend < Marten::Emailing::Backend::Base def deliver(email : Email) # Deliver the email! end end ``` ## Handling attachments If your backend supports attachments, you can iterate over [`#attachments`](https://martenframework.com/docs/api/dev/Marten/Emailing/Email.html) in the `#deliver` implementation: ```crystal class CustomEmailingBackend < Marten::Emailing::Backend::Base def deliver(email : Email) email.attachments.each do |attachment| # attachment.filename # attachment.mime_type # attachment.content end end end ``` Each attachment exposes: * a `filename` * a `mime_type` * a `content` byte slice * a `size` in bytes ## Enabling the use of custom emailing backends Custom emailing backends can be used by assigning an instance of the corresponding class to the [`emailing.backend`](https://martenframework.com/docs/next/development/reference/settings#backend-1) setting. For example: ```crystal config.emailing.backend = CustomEmailingBackend.new ``` # Emailing backends Source: https://martenframework.com/docs/next/emailing/reference/backends ## Built-in backends ### Development backend This is the default backend used as part of the [`emailing.backend`](https://martenframework.com/docs/next/development/reference/settings#backend-1) setting. This backend "collects" all the emails that are "delivered", which can be used in specs in order to test sent emails. This "collect" behavior can be disabled if necessary, and the backend can also be configured to print email details to the standard output. For example: ```crystal config.emailing.backend = Marten::Emailing::Backend::Development.new(print_emails: true, collect_emails: false) ``` ## Other backends Additional emailing backend shards are also maintained under the umbrella of the Marten project or by the community itself and can be used as part of your application depending on your specific email sending requirements: * [`marten-smtp-emailing`](https://github.com/martenframework/marten-smtp-emailing) provides an SMTP emailing backend * [`marten-sendgrid-emailing`](https://github.com/martenframework/marten-sendgrid-emailing) provides a [Sendgrid](https://sendgrid.com/) emailing backend * [`marten-mailgun-emailing`](https://github.com/martenframework/marten-mailgun-emailing) provides a [Mailgun](https://www.mailgun.com/) emailing backend * [`marten-preview-emailing`](https://github.com/ellmetha/marten-preview-emailing) lets you preview emails in the browser (useful for testing emails in development) :::info Feel free to contribute to this page and add links to your shards if you've created emailing backends that are not listed here! ::: # Authentication Source: https://martenframework.com/docs/next/authentication Marten provides the ability to generate projects with a built-in authentication system that handles basic user management needs. This section gives detail on how this authentication system works out of the box, and how you can extend it to suit your project's needs. ## Guides - [Introduction](https://martenframework.com/docs/next/authentication/introduction) ## Reference - [Generated files](https://martenframework.com/docs/next/authentication/reference/generated-files) # Introduction to authentication Source: https://martenframework.com/docs/next/authentication/introduction Marten allows the generation of new projects with a built-in authentication application that handles basic user management needs. You can then extend and adapt this application so that it accommodates your project's needs. ## Overview Marten's [`new`](https://martenframework.com/docs/next/development/reference/management-commands#new) management command allows the generation of projects with a built-in `auth` application. The same application can also be added to existing projects by leveraging the [`auth`](https://martenframework.com/docs/next/development/reference/generators#auth) generator. The generated authentication application is part of your project: it provides the necessary [models](https://martenframework.com/docs/next/models-and-databases), [handlers](https://martenframework.com/docs/next/handlers-and-http), [schemas](https://martenframework.com/docs/next/schemas), [emails](https://martenframework.com/docs/next/emailing), and [templates](https://martenframework.com/docs/next/templates) allowing to authenticate users with email addresses and passwords, while also supporting standard password reset flows. On top of that, an `Auth::User` model is automatically generated for your newly created projects. Since this model is also part of your project, this means that it's possible to easily add new fields to it and generate migrations for it as well. Here is the list of responsibilities of the generated authentication application: * Signing up users * Signing in users * Signing out users * Allowing users to reset their passwords * Allowing users to access a basic profile page Internally, this authentication application relies on the official [`marten-auth`](https://github.com/martenframework/marten-auth) shard. This shard implements low-level authentication operations (such as authenticating user credentials, generating securely encrypted passwords, generating password reset tokens, etc). ## Generating projects with authentication Generating new projects with authentication can be easily achieved by leveraging the `--with-auth` option of the [`new`](https://martenframework.com/docs/next/development/reference/management-commands#new) management command. For example: ```bash marten new project myblog --with-auth ``` When using this option, Marten will generate an `auth` [application](https://martenframework.com/docs/next/development/applications) under the `src/apps/auth` folder of your project. As mentioned previously, this application provides a set of [models](https://martenframework.com/docs/next/models-and-databases), [handlers](https://martenframework.com/docs/next/handlers-and-http), [schemas](https://martenframework.com/docs/next/schemas), [emails](https://martenframework.com/docs/next/emailing), and [templates](https://martenframework.com/docs/next/templates) that implement basic authentication operations. You can test the generated authentication application by going to your application at [http://localhost:8000/auth/signup](http://localhost:8000/auth/signup) after having started the Marten development server (using `marten serve`). :::info You can see the full list of files generated for the `auth` application in [Generated files](https://martenframework.com/docs/next/authentication/reference/generated-files). ::: ## Adding authentication to existing projects The [`auth`](https://martenframework.com/docs/next/development/reference/generators#auth) generator can be leveraged in order to add an authentication application to an existing project. For example, the following command will add a new authentication app with the `auth` label to the current project: ```bash marten gen auth ``` :::tip Note that you can also customize the label given to the generated authentication app by providing an additional argument containing the intended app label: ```bash marten gen auth my_auth ``` ::: This generator will add an authentication application under your project's `src` folder (or `src/apps` folder if it is defined). As mentioned previously, this application provides a set of [models](https://martenframework.com/docs/next/models-and-databases), [handlers](https://martenframework.com/docs/next/handlers-and-http), [schemas](https://martenframework.com/docs/next/schemas), [emails](https://martenframework.com/docs/next/emailing), and [templates](https://martenframework.com/docs/next/templates) that implement basic authentication operations. Note that the generator will also add the generated application to the [`installed_apps`](https://martenframework.com/docs/next/development/reference/settings#installed_apps) setting and will also configure Crystal requirements for it (in the `src/project.cr` and `src/cli.cr` files). It will also add authentication-related settings to your base settings file and will add the [`marten-auth`](https://github.com/martenframework/marten-auth) shard to your project's `shard.yml` automatically. :::info You can see the full list of files generated for the generated authentication application in [Generated files](https://martenframework.com/docs/next/authentication/reference/generated-files). ::: :::tip Don't forget to run [`marten migrate`](https://martenframework.com/docs/next/development/reference/management-commands#migrate) after the authentication app has been generated so that your user model gets created at the database level. You should also check the `config/routes.cr` file or run the [`marten routes`](https://martenframework.com/docs/next/development/reference/management-commands#routes) management command to see the routes associated with your generated authentication app. ::: ## Usage This section covers the basics of how to use the `auth` application - powered by [`marten-auth`](https://github.com/martenframework/marten-auth) - that is generated when creating projects with the `--with-auth` option. ### The `User` model The `auth` application defines a single `Auth::User` model that inherits its fields from the abstract `MartenAuth::User` model. As such, this model automatically provides the following fields: * `id` - a [`big_int`](https://martenframework.com/docs/next/models-and-databases/reference/fields#big_int) field containing the primary key of the user * `email` - an [`email`](https://martenframework.com/docs/next/models-and-databases/reference/fields#email) field containing the user's email address * `password` - a [`string`](https://martenframework.com/docs/next/models-and-databases/reference/fields#string) field containing the user's encrypted password * `created_at` - a [`date_time`](https://martenframework.com/docs/next/models-and-databases/reference/fields#date_time) field containing the user creation date * `updated_at` - a [`date_time`](https://martenframework.com/docs/next/models-and-databases/reference/fields#date_time) field containing the last user modification date ### Retrieving the current user Projects that are generated with the `auth` application automatically make use of a middleware (`MartenAuth::Middleware`) that ensures that the currently authenticated user ID is associated with the current request. This means that given a specific HTTP request (instance of [`Marten::HTTP::Request`](https://martenframework.com/docs/api/dev/Marten/HTTP/Request.html)), it is possible to identify which user is signed-in or not. Concretely, the following methods are made available on the standard [`Marten::HTTP::Request`](https://martenframework.com/docs/api/dev/Marten/HTTP/Request.html) object in order to interact with the currently signed-in user: | Method | Description | | --- | --- | | `#user_id` | Returns the current user ID associated with the considered request, or `nil` if there is no authenticated user. | | `#user` | Returns the user associated with the request, or `nil` if there is no authenticated user. | | `#user!` | Returns the user associated with the request, or raise `NilAssertionError` if there is no authenticated user. | | `#user?` | Returns `true` if a user is authenticated for the request. | This makes it possible to easily check whether a user is authenticated in handlers in order to implement different logic. For example: ```crystal class MyHandler < Marten::Handler def get if request.user? respond "User ##{request.user!.id} is signed-in" else respond "No signed-in user" end end end ``` ### Creating users Creating a user is as simple as initializing an instance of the `Auth::User` model and defining its properties. That being said it is important to note that the user's password (`password` field) must be set using the `#set_password` method: this will ensure that the _raw_ password you provide to this method is properly encrypted and that the resulting hash is assigned to the `password` field. Because of this, you should not attempt to manipulate the `password` field attribute of user records directly. For example: ```crystal user = Auth::User.new(email: "test@example.com") do |user| user.set_password("insecure") end user.save! ``` :::tip In certain scenarios where passwords aren't required, such as with email magic link authentication or multi-provider OAuth authentication, it may be desirable to create user accounts without passwords. To achieve this, you can utilize the `#set_unusable_password` method on your user model instances. This method ensures that no password can be used for these accounts. For example: ```crystal user = Auth::User.new(email: "test@example.com") do |user| user.set_unusable_password end user.save! ``` ::: ### Authenticating users Authentication is the act of verifying a user's credentials. This capability is provided by the [`marten-auth`](https://github.com/martenframework/marten-auth) shard through the use of the `MartenAuth#authenticate` method: this method tries to authenticate the user associated identified by a natural key (typically, an email address) and check that the given raw password is valid. The method returns the corresponding user record if the authentication is successful. Otherwise, it returns `nil` if the credentials can't be verified because the user does not exist or because the password is invalid. For example: ```crystal user = MartenAuth.authenticate("test@example.com", "insecure") if user puts "User credentials are valid!" else puts "User credentials are not valid!" end ``` :::caution It is important to realize that this method _only_ verifies user credentials. **It does not sign in users** for a specific request. Signing in users (and attaching them to the current session) is handled by the `#sign_in` method, which is discussed in [Signing in users](#signing-in-users). ::: :::info The `MartenAuth#authenticate` method is automatically used by the handlers that are generated for your `auth` application before signing in users. ::: ### Signing in users Signing in a user is the act of attaching it to the current session - after having verified that the associated credentials are valid (see [Authenticating users](#authenticating-users)). This capability is provided by the [`marten-auth`](https://github.com/martenframework/marten-auth) shard through the use of the `MartenAuth#sign_in` method: This method takes a request object (instance of [`Marten::HTTP::Request`](https://martenframework.com/docs/api/dev/Marten/HTTP/Request.html)) and a user record as arguments and ensures that the user ID is attached to the current session so that they do not have to reauthenticate for every request. For example: ```crystal class MyHandler < Marten::Handler def post user = MartenAuth.authenticate(request.data["email"].to_s, request.data["password"].to_s) if user MartenAuth.sign_in(request, user) redirect reverse("auth:profile") else redirect reverse("auth:sign_in") end end end ``` :::caution It is important to understand that this method is intended to be used for a user record whose credentials were validated using the `#authenticate` method beforehand. See [Authenticating users](#authenticating-users) for more details. ::: ### Signing out users The ability to sign out users is provided by the [`marten-auth`](https://github.com/martenframework/marten-auth) shard through the use of the `MartenAuth#sign_out` method: this method takes a request object (instance of [`Marten::HTTP::Request`](https://martenframework.com/docs/api/dev/Marten/HTTP/Request.html)) as argument, removes the authenticated user ID from the current request, and flushes the associated session data. For example: ```crystal class MyHandler < Marten::Handler def get MartenAuth.sign_out(request) redirect reverse("auth:sign_in") end end ``` ### Changing a user's password The ability to change a user password is provided by the `#set_password` method of the `Auth::User` model (which is inherited from the `MartenAuth::User` abstract class that is provided by the [`marten-auth`](https://github.com/martenframework/marten-auth) shard). For example: ```crystal use = User.get!(email: "test@example.com") user.set_password("insecure") user.save! ``` :::info Passwords are encrypted using [`Crypto::Bcrypt`](https://crystal-lang.org/api/Crypto/Bcrypt.html). ::: As mentioned previously, you should not attempt to manipulate the `password` field directly: this field contains the hash value that results from the encryption of the raw password. ### Limiting access to signed-in users Limiting access to signed-in users can easily be achieved by leveraging the `#user?` method that is available from [`Marten::HTTP::Request`](https://martenframework.com/docs/api/dev/Marten/HTTP/Request.html) objects. Using this method, you can easily implement [`#before_dispatch`](https://martenframework.com/docs/next/handlers-and-http/callbacks#before_dispatch) handler callbacks in order to redirect anonymous users to a sign-in page or to an error page. For example: ```crystal class UserProfileHandler < Marten::Handler before_dispatch :require_signed_in_user def get render "auth/profile.html" { user: request.user } end private def require_signed_in_user redirect reverse("auth:sign_in") unless request.user? end end ``` It should be noted that the `auth` application generated for your project already contains an `Auth::RequireSignedInUser` concern module that you can include in your handlers in order to ensure that they can only be accessed by signed-in users (and that anonymous users are redirected to the sign-in page). For example: ```crystal class UserProfileHandler < Marten::Handler include Auth::RequireSignedInUser def get render "auth/profile.html" { user: request.user } end end ``` # Generated files Source: https://martenframework.com/docs/next/authentication/reference/generated-files This page provides a reference of the files that are generated for the `auth` application when running the [`new`](https://martenframework.com/docs/next/development/reference/management-commands#new) management command with the `--with-auth` option or when using the [`auth`](https://martenframework.com/docs/next/development/reference/generators#auth) generator. ## Application The `auth` application is generated under the `src` or `src/apps` folder. In addition to the abstractions mentioned below, this folder defines the following top-level files: * `app.cr` - The entrypoint of the `auth` application, where all the other abstractions are required * `cli.cr` - The CLI entrypoint of the `auth` application, where CLI-related abstractions (like migrations) are required * `routes.cr` - The `auth` application routes map ### Emails * `password_reset_email.cr` - Defines the [email](https://martenframework.com/docs/next/emailing) that is sent as part of the user password reset flow ### Handlers * `handlers/concerns/require_anonymous_user.cr` - A concern that ensures that a handler can only be accessed by anonymous users * `handlers/concerns/require_signed_in_user.cr` - A concern that ensures that a handler can only be accessed by signed-in users * `handlers/password_reset_confirm_handler.cr` - A handler that handles resetting a user's password as part of the password reset flow * `handlers/password_reset_initiate_handler.cr` - A handler that initiates the password reset flow for a given user * `handlers/password_update_handler.cr` - A handler that allows to update the user's password * `handlers/profile_handler.cr` - A handler that displays the currently signed-in user profile * `handlers/sign_in_handler.cr` - A handler that allows users to sign in * `handlers/sign_out_handler.cr` - A handler that allows users to sign out * `handlers/sign_up_handler.cr` - A handler that allows users to sign up ### Migrations * `migrations/0001_create_auth_user_table.cr` - Allows to create the table of the `Auth::User` model ### Models * `models/user.cr` - Defines the main `Auth::User` model ### Schemas * `schemas/password_reset_confirm_schema.cr` - A schema that allows a user to reset their password * `schemas/password_reset_initiate_schema.cr` - A schema that allows a user to initiate the password reset flow * `schemas/password_update_schema.cr` - A schema that allows a user to update their password * `schemas/sign_in_schema.cr` - A schema used to sign in users * `schemas/sign_up_schema.cr` - A schema used to sign up users ### Templates * `templates/auth/emails/password_reset.html` - The template of the password reset email * `templates/auth/password_reset_confirm.html` - The template used to let users reset their passwords * `templates/auth/password_reset_initiate.html` - The template used to let users initiate the password reset flow * `templates/auth/password_update.html` - The template used to let users update their password * `templates/auth/profile.html` - The template of the user profile * `templates/auth/sign_in.html` - The sign in page template * `templates/auth/sign_up.html` - The sign up page template ## Specs All the previously mentioned abstractions have associated specs that are defined under the `spec/apps/auth` folder. # Caching Source: https://martenframework.com/docs/next/caching Marten provides native support for caching, enabling you to store the outcome of resource-intensive operations and bypass performing them for each request. This encompasses basic caching abilities and advanced features like template fragment caching. ## Guides - [Introduction](https://martenframework.com/docs/next/caching/introduction) ## How-to's - [Create custom cache stores](https://martenframework.com/docs/next/caching/how-to/create-custom-cache-stores) ## Reference - [Stores](https://martenframework.com/docs/next/caching/reference/stores) # Introduction to caching Source: https://martenframework.com/docs/next/caching/introduction Marten provides a set of features allowing you to leverage caching as part of your application. By using caching, you can save the result of expensive operations so that you don't have to perform them for every request. ## Configuration and cache stores In order to be able to leverage caching in your application, you need to configure a "cache store". A cache store allows interacting with the underlying cache system and performing basic operations such as fetching cached entries, writing new entries, etc. Depending on the chosen cache store, these operations could be performed in-memory or by leveraging external caching systems such as [Redis](https://redis.io) or [Memcached](https://memcached.org). The global cache store used by Marten can be configured by leveraging the [`cache_store`](https://martenframework.com/docs/next/development/reference/settings#cache_store) setting. All the available cache stores are listed in the [cache store reference](https://martenframework.com/docs/next/caching/reference/stores). For example, the following configuration configures an in-memory cache as the global cache: ```crystal Marten.configure do |config| config.cache_store = Marten::Cache::Store::Memory.new(expires_in: 24.hours) end ``` :::info By default, Marten uses an in-memory cache (instance of [`Marten::Cache::Store::Memory`](https://martenframework.com/docs/api/dev/Marten/Cache/Store/Memory.html)). Note that this simple in-memory cache does not allow to perform cross-process caching since each process running your app will have its own private cache instance. In situations where you have multiple separate processes running your application, it's preferable to use a proper caching system such as [Redis](https://redis.io) or [Memcached](https://memcached.org), which can be done by leveraging respectively the [`marten-redis-cache`](https://github.com/martenframework/marten-redis-cache) or [`marten-memcached-cache`](https://github.com/martenframework/marten-memcached-cache) shards. In testing environments, you could configure your project so that it uses an instance of [`Marten::Cache::Store::Null`](https://martenframework.com/docs/api/dev/Marten/Cache/Store/Null.html) as the global cache. This approach can be helpful when caching is not necessary, but you still want to ensure that your code is passing through the caching interface. ::: ## Low-level caching ### Basic usage Low-level caching allows you to interact directly with the global cache store and perform caching operations. To do that, you can access the global cache store by calling the [`Marten#cache`](https://martenframework.com/docs/api/dev/Marten.html#cache%3ACache%3A%3AStore%3A%3ABase-class-method) method. The main way to put new values in cache is to leverage the [`#fetch`](https://martenframework.com/docs/api/dev/Marten/Cache/Store/Base.html#fetch(key%3AString|Symbol%2Cexpires_at%3ATime|Nil%3Dnil%2Cexpires_in%3ATime%3A%3ASpan|Nil%3Dnil%2Cversion%3AInt32|Nil%3Dnil%2Cforce%3Dfalse%2Crace_condition_ttl%3ATime%3A%3ASpan|Nil%3Dnil%2Ccompress%3ABool|Nil%3Dnil%2Ccompress_threshold%3AInt32|Nil%3Dnil%2C%26)%3AString|Nil-instance-method) method, which is provided on all cache stores. This method allows fetching data from the cache by using a specific key: if an entry exists for this key in cache, then the data is returned. Otherwise the return value of the block (that _must_ be specified when calling [`#fetch`](https://martenframework.com/docs/api/dev/Marten/Cache/Store/Base.html#fetch(key%3AString|Symbol%2Cexpires_at%3ATime|Nil%3Dnil%2Cexpires_in%3ATime%3A%3ASpan|Nil%3Dnil%2Cversion%3AInt32|Nil%3Dnil%2Cforce%3Dfalse%2Crace_condition_ttl%3ATime%3A%3ASpan|Nil%3Dnil%2Ccompress%3ABool|Nil%3Dnil%2Ccompress_threshold%3AInt32|Nil%3Dnil%2C%26)%3AString|Nil-instance-method)) is written to the cache and returned. This method supports a few additional arguments that allow to further customize how the entry is written to the cache (eg. the expiry time associated with the entry). For example: ```crystal Marten.cache.fetch("mykey", expires_in: 4.hours) do "myvalue" end ``` ### Reading from and writing to the cache It is worth mentioning that you can also explicitly read from the cache and write to the cache by leveraging the [`#read`](https://martenframework.com/docs/api/dev/Marten/Cache/Store/Base.html#read(key%3AString|Symbol%2Cversion%3AInt32|Nil%3Dnil)%3AString|Nil-instance-method) and [`#write`](https://martenframework.com/docs/api/dev/Marten/Cache/Store/Base.html#write(key%3AString|Symbol%2Cvalue%3AString%2Cexpires_at%3ATime|Nil%3Dnil%2Cexpires_in%3ATime%3A%3ASpan|Nil%3Dnil%2Cversion%3AInt32|Nil%3Dnil%2Crace_condition_ttl%3ATime%3A%3ASpan|Nil%3Dnil%2Ccompress%3ABool|Nil%3Dnil%2Ccompress_threshold%3AInt32|Nil%3Dnil)-instance-method) methods respectively. Verifying that a key exists can be done using the [`#exists?`](https://martenframework.com/docs/api/dev/Marten/Cache/Store/Base.html#exists%3F(key%3AString|Symbol%2Cversion%3AInt32|Nil%3Dnil)%3ABool-instance-method) method. For example: ```crystal # No entry in the cache yet. Marten.cache.read("foo") # => nil Marten.cache.exists?("foo") # => false # Let's add the entry to the cache. Marten.cache.write("foo", "bar", expires_in: 10.minutes) # => true # Let's read from the cache. Marten.cache.read("foo") # => "bar" Marten.cache.exists?("foo") # => true ``` ### Deleting an entry from the cache Deleting an entry from the cache is made possible through the use of the [`#delete`](https://martenframework.com/docs/api/dev/Marten/Cache/Store/Base.html#delete(key%3AString|Symbol)%3ABool-instance-method) method. This method takes the key of the entry to delete as argument and returns a boolean indicating whether an entry was actually deleted. For example: ```crystal # No entry in the cache yet. Marten.cache.delete("foo") # => false # Let's add an entry to the cache and then delete it. Marten.cache.write("foo", "bar", expires_in: 10.minutes) # => true Marten.cache.delete("foo") # => true ``` ### Incrementing and decrementing values If you need to persist integer values that are intended to be incremented or decremented, then you can leverage the [`#increment`](https://martenframework.com/docs/api/dev/Marten/Cache/Store/Base.html#increment(key%3AString%2Camount%3AInt32%3D1%2Cexpires_at%3ATime|Nil%3Dnil%2Cexpires_in%3ATime%3A%3ASpan|Nil%3Dnil%2Cversion%3AInt32|Nil%3Dnil%2Crace_condition_ttl%3ATime%3A%3ASpan|Nil%3Dnil%2Ccompress%3ABool|Nil%3Dnil%2Ccompress_threshold%3AInt32|Nil%3Dnil)%3AInt-instance-method) and [`#decrement`](https://martenframework.com/docs/api/dev/Marten/Cache/Store/Base.html#decrement(key%3AString%2Camount%3AInt32%3D1%2Cexpires_at%3ATime|Nil%3Dnil%2Cexpires_in%3ATime%3A%3ASpan|Nil%3Dnil%2Cversion%3AInt32|Nil%3Dnil%2Crace_condition_ttl%3ATime%3A%3ASpan|Nil%3Dnil%2Ccompress%3ABool|Nil%3Dnil%2Ccompress_threshold%3AInt32|Nil%3Dnil)%3AInt-instance-method) methods. The advantage of doing so is that the increment/decrement operation will be performed in an atomic fashion depending on the cache store you are using (eg. this is the case for the stores provided by the [`marten-memcached-cache`](https://github.com/martenframework/marten-memcached-cache) and [`marten-redis-cache`](https://github.com/martenframework/marten-redis-cache) shards). For example: ```crystal Marten.cache.increment("mycounter") # => 1 Marten.cache.increment("mycounter", amount: 2) # => 3 Marten.cache.decrement("mycounter") # => 2 ``` ### Clearing the cache It's possible to fully clear the content of the cache by leveraging the [`#clear`](https://martenframework.com/docs/api/dev/Marten/Cache/Store/Base.html#clear-instance-method). For example: ```crystal # Let's add an entry to the cache and then let's clear the cache. Marten.cache.write("foo", "bar", expires_in: 10.minutes) Marten.cache.clear ``` :::caution You should be extra careful when using this method because it will fully remove all the entries stored in the cache. Depending on the store implementation, only _namespaced_ entries may be removed (this is the case for the [Redis cache store](https://github.com/martenframework/marten-redis-cache) for example). ::: ## Template fragment caching You can leverage template fragment caching when you want to cache some parts of your [templates](https://martenframework.com/docs/next/templates). This capability is enabled by the use of the [`cache`](https://martenframework.com/docs/next/templates/reference/tags#cache) template tag. This template tag allows caching the content of a template fragment (enclosed within the `{% cache %}...{% endcache %}` tags) for a specific duration. This caching operation is done by leveraging the configured [global cache store](#configuration-and-cache-stores). The tag itself takes at least two arguments: the name to give to the cache fragment and a cache timeout - expressed in seconds. For example, the following snippet caches the content enclosed within the `{% cache %}...{% endcache %}` tags for a duration of 3600 seconds and associates it to the "articles" fragment name: ```html {% cache "articles" 3600 %}
    {% for article in articles %}
  • {{ article.title }}
  • {% endfor %}
{% endcache %} ``` It's worth noting that the [`cache`](https://martenframework.com/docs/next/templates/reference/tags#cache) template tag allows for the inclusion of additional arguments. These arguments, referred to as "vary on" values, play a crucial role in generating the cache key of the template fragment. Essentially, the cache is invalidated if the value of any of these arguments changes. This feature comes in handy when you need to ensure that the template fragment is cached based on other dynamic values that may impact the generation of the cached content itself. For instance, suppose the cached content is dependent on the current locale. In that case, you'd want to make sure that the current locale value is taken into account while caching the template fragment. The ability to pass additional arguments as "vary on" values enables you to achieve precisely that. For example: ```html {% cache "articles" 3600 current_locale user.id %}
    {% for article in articles %}
  • {{ article.title }}
  • {% endfor %}
{% endcache %} ``` :::tip The "key" used for the template fragment cache entry can be a template variable. The same goes for the cache timeout. For example: ```html {% cache fragment_name fragment_expiry %}
    {% for article in articles %}
  • {{ article.title }}
  • {% endfor %}
{% endcache %} ``` ::: # Create cache stores Source: https://martenframework.com/docs/next/caching/how-to/create-custom-cache-stores Marten lets you easily create custom [cache stores](https://martenframework.com/docs/next/caching/introduction#configuration-and-cache-stores) that you can then use as part of your application when it comes to perform caching operations. ## Basic store definition Defining a cache store is as simple as creating a class that inherits from the [`Marten::Caching::Store::Base`](https://martenframework.com/docs/api/dev/Marten/Cache/Store/Base.html) abstract class and that implements the following methods: * [`#clear`](https://martenframework.com/docs/api/dev/Marten/Cache/Store/Base.html#clear-instance-method) - called when clearing the cache * [`#decrement`](https://martenframework.com/docs/api/dev/Marten/Cache/Store/Base.html#decrement(key%3AString%2Camount%3AInt32%3D1%2Cexpires_at%3ATime|Nil%3Dnil%2Cexpires_in%3ATime%3A%3ASpan|Nil%3Dnil%2Cversion%3AInt32|Nil%3Dnil%2Crace_condition_ttl%3ATime%3A%3ASpan|Nil%3Dnil%2Ccompress%3ABool|Nil%3Dnil%2Ccompress_threshold%3AInt32|Nil%3Dnil)%3AInt-instance-method) - called when decrementing an integer value in the cache * [`#delete_entry`](https://martenframework.com/docs/http://localhost:3000/docs/api/dev/Marten/Cache/Store/Base.html#delete_entry%28key%3AString%29%3ABool-instance-method) - called when deleting an entry from the cache * [`#increment`](https://martenframework.com/docs/api/dev/Marten/Cache/Store/Base.html#increment(key%3AString%2Camount%3AInt32%3D1%2Cexpires_at%3ATime|Nil%3Dnil%2Cexpires_in%3ATime%3A%3ASpan|Nil%3Dnil%2Cversion%3AInt32|Nil%3Dnil%2Crace_condition_ttl%3ATime%3A%3ASpan|Nil%3Dnil%2Ccompress%3ABool|Nil%3Dnil%2Ccompress_threshold%3AInt32|Nil%3Dnil)%3AInt-instance-method) - called when incrementing an integer value in the cache * [`#read_entry`](https://martenframework.com/docs/api/dev/Marten/Cache/Store/Base.html#read_entry(key%3AString)%3AString|Nil-instance-method) - called when reading an entry in the cache * [`#write_entry`](https://martenframework.com/docs/api/dev/Marten/Cache/Store/Base.html#write_entry(key%3AString%2Cvalue%3AString%2Cexpires_in%3ATime%3A%3ASpan|Nil%3Dnil%2Crace_condition_ttl%3ATime%3A%3ASpan|Nil%3Dnil)-instance-method) - called when writing an entry to the cache For example, the following snippet implements an in-memory store that persists cache entries in a hash: ```crystal class MemoryStore < Marten::Cache::Store::Base @data = {} of String => String def initialize( @namespace : String? = nil, @expires_in : Time::Span? = nil, @version : Int32? = nil, @compress = false, @compress_threshold = DEFAULT_COMPRESS_THRESHOLD ) super end def clear : Nil @data.clear end def decrement( key : String, amount : Int32 = 1, expires_at : Time? = nil, expires_in : Time::Span? = nil, version : Int32? = nil, race_condition_ttl : Time::Span? = nil, compress : Bool? = nil, compress_threshold : Int32? = nil ) : Int apply_increment( key, amount: -amount, expires_at: expires_at, expires_in: expires_in, version: version, race_condition_ttl: race_condition_ttl, compress: compress, compress_threshold: compress_threshold ) end def increment( key : String, amount : Int32 = 1, expires_at : Time? = nil, expires_in : Time::Span? = nil, version : Int32? = nil, race_condition_ttl : Time::Span? = nil, compress : Bool? = nil, compress_threshold : Int32? = nil ) : Int apply_increment( key, amount: amount, expires_at: expires_at, expires_in: expires_in, version: version, race_condition_ttl: race_condition_ttl, compress: compress, compress_threshold: compress_threshold ) end private getter data private def apply_increment( key : String, amount : Int32 = 1, expires_at : Time? = nil, expires_in : Time::Span? = nil, version : Int32? = nil, race_condition_ttl : Time::Span? = nil, compress : Bool? = nil, compress_threshold : Int32? = nil ) normalized_key = normalize_key(key.to_s) entry = deserialize_entry(read_entry(normalized_key)) if entry.nil? || entry.expired? || entry.mismatched?(version || self.version) write( key: key, value: amount.to_s, expires_at: expires_at, expires_in: expires_in, version: version, race_condition_ttl: race_condition_ttl, compress: compress, compress_threshold: compress_threshold ) amount else new_amount = entry.value.to_i + amount entry = Entry.new(new_amount.to_s, expires_at: entry.expires_at, version: entry.version) write_entry(normalized_key, serialize_entry(entry)) new_amount end end private def delete_entry(key : String) : Bool deleted_entry = @data.delete(key) !!deleted_entry end private def read_entry(key : String) : String? data[key]? end private def write_entry( key : String, value : String, expires_in : Time::Span? = nil, race_condition_ttl : Time::Span? = nil ) data[key] = value true end end ``` ## Enabling the use of custom cache stores Custom cache store can be used by assigning an instance of the corresponding class to the [`cache_store`](https://martenframework.com/docs/next/development/reference/settings#cache_store) setting. For example: ```crystal config.cache_store = MemoryStore.new ``` # Caching stores Source: https://martenframework.com/docs/next/caching/reference/stores ## Built-in stores ### In-memory store This is the default store used as part of the [`cache_store`](https://martenframework.com/docs/next/development/reference/settings#cache_store) setting. This cache store is implemented as part of the [`Marten::Cache::Store::Memory`](https://martenframework.com/docs/api/dev/Marten/Cache/Store/Memory.html) class. This cache stores all data in memory within the same process, making it a fast and reliable option for caching in single process environments. However, it's worth noting that if you're running multiple instances of your application, the cache data will not be shared between them. For example: ```crystal Marten.configure do |config| config.cache_store = Marten::Cache::Store::Memory.new(expires_in: 24.hours) end ``` ### Null store A cache store implementation doesn't store any data. This cache store is implemented as part of the [`Marten::Cache::Store::Null`](https://martenframework.com/docs/api/dev/Marten/Cache/Store/Null.html) class. This cache store does not store any data, but provides a way to go through the caching interface. This can be useful in development and testing environments when caching is not desired. For example: ```crystal Marten.configure do |config| config.cache_store = Marten::Cache::Store::Null.new(expires_in: 24.hours) end ``` ## Other stores Additional cache stores shards are also maintained under the umbrella of the Marten project or by the community itself and can be used as part of your application depending on your specific caching requirements: * [`marten-memcached-cache`](https://github.com/martenframework/marten-memcached-cache) provides a [Memcached](https://memcached.org) cache store * [`marten-redis-cache`](https://github.com/martenframework/marten-redis-cache) provides a [Redis](https://redis.io) cache store :::info Feel free to contribute to this page and add links to your shards if you've created cache stores that are not listed here! ::: # Deployment Source: https://martenframework.com/docs/next/deployment The section explains the steps involved when it comes to deploying a Marten project. It also gives useful tips in order to secure Marten web applications in production. ## Guides - [Introduction](https://martenframework.com/docs/next/deployment/introduction) ## How-to's - [Deploy to an Ubuntu server](https://martenframework.com/docs/next/deployment/how-to/deploy-to-an-ubuntu-server) - [Deploy to Heroku](https://martenframework.com/docs/next/deployment/how-to/deploy-to-heroku) - [Deploy to Fly.io](https://martenframework.com/docs/next/deployment/how-to/deploy-to-fly-io) # Deploying Marten projects Source: https://martenframework.com/docs/next/deployment/introduction This section describes what's involved when it comes to deploying a Marten web application and highlights some important things to consider before performing deploys. ## Overview Each deployment pipeline is unique and will vary from one project to another. That being said, a few things and requirements will be commonly encountered when it comes to deploying a Marten project: 1. installing your project's dependencies 2. compiling your project's server and [management CLI](https://martenframework.com/docs/next/development/management-commands) 3. collecting your project's [assets](https://martenframework.com/docs/next/assets/serving-assets) 4. collecting your project's runtime artifacts (eg. locales and templates) 5. applying any pending migrations to your database 6. starting the compiled server Where, when, and how these steps are performed will vary from one project to another. Each of these steps is highlighted below along with some recommendations. It should also be noted that a few guides highlighting common deployment strategies can be leveraged if necessary: * [Deploying to an Ubuntu server](https://martenframework.com/docs/next/deployment/how-to/deploy-to-an-ubuntu-server) ### Installing dependencies One of the first things you need to do when deploying a Marten project is to ensure that the dependencies of the projects are available. In this light, you can leverage the `shards install` command to install your project's Crystal dependencies (assuming that Crystal is installed on your destination machine). Obviously, your project may require the installation of other types of dependencies (such as Node.js dependencies for example), which you have to take care of as well. ### Compiling your project Your project server and [management CLI](https://martenframework.com/docs/next/development/management-commands) need to be compiled to run your project's server and to execute additional deployment-related management commands (eg. to [collect assets](#collecting-assets), [collect runtime artifacts](#collecting-runtime-artifacts), or [apply migrations](#applying-migrations)). When it comes to your project server, you will usually need to compile the `src/server.cr` file (which is automatically created when generating new projects via the [`new`](https://martenframework.com/docs/next/development/reference/management-commands#new) management command). This can be achieved with the following command: ```bash crystal build src/server.cr -o bin/server --release ``` :::tip In the above example, the server binary is compiled using the `-o bin/server` option, which ensures that the compiled binary will be named `server` and stored under the related `bin` folder. You should obviously adapt this to your production environment. ::: The [management CLI](https://martenframework.com/docs/next/development/management-commands) is provided by the `manage.cr` file located at the root of your project. As usual, this file is also automatically generated for you when creating Marten projects through the use of the [`new`](https://martenframework.com/docs/next/development/reference/management-commands#new) management command. Compiling this binary can be done with the following command: ```bash crystal build manage.cr -o bin/manage --release ``` :::info The above compilation commands make use of the `--release` flag, which enables compiler optimizations. As a result, the compilation of the final binaries may take quite some time depending on your project. You can also avoid using `--release` if needed but technically performances could be impacted. See [Release builds](https://crystal-lang.org/reference/man/crystal/index.html#release-builds) for more details on this subject. ::: ### Collecting assets You need to ensure that your project and applications assets (eg. JavaScripts, CSS files, etc) are "collected" at deploy time so that they are placed at the final destination from which they will be served: this operation is made available through the use of the [`collectassets`](https://martenframework.com/docs/next/development/reference/management-commands#collectassets) management command. This "destination" depends on your deployment strategy and your configured [assets settings](https://martenframework.com/docs/next/development/reference/settings#assets-settings): it can be as simple as moving all these assets to a dedicated folder in your server (so that they can be served by your web server), or it can involve uploading these assets to an S3 or GCS bucket for example. In order to collect assets at deploy time, you will want to use the compiled `manage` binary and run the [`collectassets`](https://martenframework.com/docs/next/development/reference/management-commands#collectassets) management command (as mentioned previously) with the `--no-input` flag set in order to disable user prompts: ```bash bin/manage collectassets --no-input ``` :::info The assets handling documentation also provides a few [guidelines](https://martenframework.com/docs/next/assets/serving-assets) on how to serve asset files in production that may be worth reading. ::: ### Collecting runtime artifacts If your deployment does not ship the full project source tree, you should also collect runtime artifacts (eg. locale and template files) and ship them alongside your compiled binaries. To do so, use the [`collectartifacts`](https://martenframework.com/docs/next/development/reference/management-commands#collectartifacts) management command: ```bash bin/manage collectartifacts --no-input --dest-path artifacts ``` This will create an `artifacts` directory containing the runtime files required by Marten (including Marten built-in locales, project-level `config/locales`, and app-level `locales`/`templates`) while preserving the expected path layout. In production, you should then point the [`root_path`](https://martenframework.com/docs/next/development/reference/settings#root_path) setting to the collected directory: ```crystal Marten.configure :production do |config| config.root_path = "/path/to/artifacts" end ``` Without this setting, a compiled application will still look for runtime files under the original project path used at build time. ### Applying migrations Your projects will likely make use of models, which means that you will need to ensure that those are properly created at your configured database level by running the associated migrations. To do so, you can use the compiled `manage` binary and run the [`migrate`](https://martenframework.com/docs/next/development/reference/management-commands#migrate) management command: ```bash bin/manage migrate ``` Please refer to [Migrations](https://martenframework.com/docs/next/models-and-databases/migrations) to learn more about model migrations. ### Running the server You can run the compiled Marten server using the following command (obviously the location of the binary depends on [how the compilation was actually performed](#compiling-your-project)): ```bash bin/server ``` It's important to note that the Marten server is intended to be used behind a reverse proxy such as [Nginx](https://www.nginx.com/) or [Apache](https://httpd.apache.org/): you will usually want to configure such reverse proxy so that it targets your configured Marten server host and port. In this light, you should ensure that your Marten server is not using the HTTP port 80 (instead it could use something like 8080 or 8000 for example). Depending on your use cases, a reverse proxy will also allow you to easily serve other contents such as [assets](https://martenframework.com/docs/next/assets/serving-assets) or [uploaded files](https://martenframework.com/docs/next/files/managing-files), and to use SSL/TLS. :::tip It is possible to run multiple processes of the same server behind a reverse proxy such as Nginx. Indeed, each compiled server can accept optional parameters to override the host and/or port being used. These parameters are respectively `--bind` (or `-b`) and `--port` (or `-p`). For example: ```bash bin/server -b 127.0.0.1 bin/server -p 8080 ``` ::: ## Additional tips This section lists a few additional things to consider when deploying Marten projects. ### Secure critical setting values You should pay attention to the value of some of your settings in production environments. #### Debug mode You should ensure that the [`debug`](https://martenframework.com/docs/next/development/reference/settings#debug) setting is always set to `false` in production environments. Indeed, the debug mode can help for development purposes because it outputs useful tracebacks and site-related information. But there is a risk that all this information leaks somewhere if you enable this mode in production. #### Secret key You should ensure that the value of the [`secret_key`](https://martenframework.com/docs/next/development/reference/settings#secret_key) setting is not hardcoded in your [config files](https://martenframework.com/docs/next/development/settings). Indeed, this setting value must be kept secret and you should ensure that it's loaded dynamically instead. For example, this setting's value could be set in a dedicated environment variable (or dotenv file) and loaded as follows: ```crystal Marten.configure do |config| config.secret_key = ENV.fetch("MARTEN_SECRET_KEY") { raise "Missing MARTEN_SECRET_KEY env variable" } # [...] end ``` :::tip It is possible to generate a new secret key using the tools available. Marten provides a secret key generator which can be used to generate a random key which can then be stored in an environment variable. ```bash bin/manage gen secretkey ``` ::: ### Configuring parallelism By default, a Marten server process handles requests concurrently on a single thread (Crystal fibers share one OS thread). On Crystal 1.21 or later, you can opt into multi-threaded execution by increasing the [`parallelism`](https://martenframework.com/docs/next/development/reference/settings#parallelism) setting, which resizes Crystal's default [execution context](https://crystal-lang.org/reference/guides/parallelism.html) so request fibers can run Crystal code across multiple CPU cores. :::info `parallelism` is **not** the maximum number of concurrent HTTP requests, and it is **not** a process count. Even with `parallelism = 1`, many I/O-bound requests can progress concurrently via fibers. Raising `parallelism` only increases how many fibers can execute Crystal code at the same time. For capacity and isolation, run multiple server processes (or platform instances); use `parallelism` when a single process should utilize multiple CPU cores. ::: For example, in your production settings: ```crystal Marten.configure :production do |config| config.parallelism = 4 # [...] end ``` You can also set the initial value via the `MARTEN_PARALLELISM` environment variable (an explicit `config.parallelism` assignment always takes precedence): ```bash MARTEN_PARALLELISM=4 bin/server ``` Multi-process deployment (several `bin/server` processes behind a reverse proxy) and multi-threaded execution (`parallelism > 1`) can be combined. Multiple processes improve isolation and horizontal capacity on a host; raising `parallelism` lets a single process use more CPU cores for CPU-bound or otherwise parallelizable work. :::warning Setting `parallelism` greater than `1` enables true parallelism. Ensure your application code and dependencies are safe for concurrent access to shared mutable state. In particular, prefer a remote cache store (instead of the default in-memory cache) when running with `parallelism` greater than `1`. See the [`parallelism`](https://martenframework.com/docs/next/development/reference/settings#parallelism) setting reference for more details. ::: # Deploy to an Ubuntu server Source: https://martenframework.com/docs/next/deployment/how-to/deploy-to-an-ubuntu-server This guide covers how to deploy a Marten project to an Ubuntu server. ## Prerequisites To complete the steps in this guide, you will need: * an [Ubuntu](https://ubuntu.com) server with SSH access and `sudo` permissions * a working Marten project * a domain name targeting your server ## Install the required dependencies The first dependency we want to install on the server is Crystal itself. To do so, you can run the following command: ```bash curl -fsSL https://crystal-lang.org/install.sh | sudo bash ``` :::tip Alternatively, you can also refer to [Crystal's official installation instructions](https://crystal-lang.org/install/on_ubuntu/) for Ubuntu if the above command does not work. ::: Secondly, we should install a few additional packages that will be required later on: * `git` to clone the project's repository * `nginx` to serve the project's server behind a reverse proxy and also serve [assets](https://martenframework.com/docs/next/assets/serving-assets) and [media files](https://martenframework.com/docs/next/files/managing-files) * `postgresql` to handle our database needs This can be achieved by running the following command: ```bash sudo apt-get install git nginx postgresql ``` :::info This guide assumes the use of [PostgreSQL](https://www.postgresql.org) but can easily be adapted if your project requires another database backend. ::: ## Create a deployment user Let's now create a deployment user. This user will have access to your project's server and will be used to run the application: ```bash sudo adduser --disabled-login deploy ``` ## Create the project folders We can now create a deployment folder where we will be able to clone the project repository later on, and store collected assets or media files if necessary. While creating this folder, it is also necessary to ensure that the `deploy` user created previously has access to it: ```bash sudo mkdir /srv/ sudo chown deploy:deploy /srv/ ``` ## Create a database As mentioned previously, this guide assumes the use of [PostgreSQL](https://www.postgresql.org) for the project's database. As such, we need to create a database user and the database itself. To do so, we will need to execute the following commands: ```bash su - postgres -c 'createuser deploy' su - postgres -c 'createdb -O deploy ' ``` :::info PostgreSQL management commands are usually performed as the `postgres` user, hence the use of `su` in the above commands. ::: Obviously, you should also ensure that your Marten project is correctly configured to target this database in production. You can have a look at the [database settings](https://martenframework.com/docs/next/development/reference/settings#database-settings) to see what are the available options when it comes to configuring databases. ## Clone the project First, change into the `deploy` user you created previously: ```bash su - deploy ``` Then you can clone your repository and change into the corresponding folder using the following commands: ```bash git clone /srv//project cd /srv//project ``` ## Install the dependencies and compile the project The next step is to install your project's dependencies. To do so, you can use the [`shards`](https://crystal-lang.org/reference/man/shards/index.html) command as follows: ```bash shards install ``` We then need to compile the project binary and the [management CLI](https://martenframework.com/docs/next/development/management-commands): ```bash crystal build src/server.cr -o bin/server --release crystal build manage.cr -o bin/manage --release ``` The management CLI binary will be helpful in order to [apply migrations](https://martenframework.com/docs/next/models-and-databases/migrations) and to [collect assets](https://martenframework.com/docs/next/development/reference/management-commands#collectassets). :::info Depending on how you are handling assets as part of your projects you may have to perform additional steps. For example, you may have to install Node.js, install additional dependencies, and eventually bundle assets with Webpack if this is applicable to your project! ::: ## Collect assets You will then want to collect your [assets](https://martenframework.com/docs/next/assets/serving-assets) so that they are uploaded to their final destination. To do so you can leverage the management CLI binary you compiled previously and run the [`collectassets`](https://martenframework.com/docs/next/development/reference/management-commands#collectassets) command: ```bash bin/manage collectassets --no-input ``` This management command will "collect" all the available assets from the applications' assets directories and from the directories configured in the [`dirs`](https://martenframework.com/docs/next/development/reference/settings#dirs) setting, and ensure that they are "uploaded" to their final destination based on the [assets storage](https://martenframework.com/docs/next/assets/introduction#assets-storage) that is currently configured. ## Apply the project's migrations Then you will want to run your project's [migrations](https://martenframework.com/docs/next/models-and-databases/migrations) to ensure that your models are created at the database level. To achieve this you can leverage the management CLI binary that you compiled in a previous step and run the [`migrate`](https://martenframework.com/docs/next/development/reference/management-commands#migrate) command: ```bash bin/manage migrate ``` ## Setup a SystemD service for your application [SystemD](https://systemd.io) is a service manager for Linux that we can leverage in order to easily start or restart our deployed application. As such, we are going to create a service for our application. But first, create an empty `settings.env` file in the current shell session as the `deploy` user: ```bash touch /srv//settings.env chmod 600 /srv//settings.env ``` Exit the shell with `Ctrl-D` or by entering the `exit` command and then create a service file for your app by typing the following command: ```bash nano /etc/systemd/system/.service ``` This should open a text editor in your terminal. Copy the following content into it: ``` [Unit] Description= server After=syslog.target [Service] User=deploy ExecStart=/srv//project/bin/server Restart=always RestartSec=5s KillSignal=SIGQUIT WorkingDirectory=/srv//project Environment="MARTEN_ENV=production" EnvironmentFiles=/srv//settings.env [Install] WantedBy=multi-user.target ``` Don't forget to replace the `` placeholders with the right values and, when ready, save the file using `Ctrl-X` and `y`. As you can see in the above snippet, we are assuming that the current [Marten environment](https://martenframework.com/docs/next/development/settings#environments) is the production one by setting the `MARTEN_ENV` environment variable to `production`. You should adapt this to your deployment use case obviously. :::caution While the service file is a good place to define environment variables for your project's settings, it should not be used for secrets and sensitive information, such as the [`secret_key`](https://martenframework.com/docs/next/development/reference/settings#secret_key) setting. Edit the `settings.env` file as the `deploy` user: ```bash sudo -u deploy nano /srv//settings.env ``` Save the [`secret_key`](https://martenframework.com/docs/next/development/reference/settings#secret_key) and other sensitive settings in it: ``` MARTEN_SECRET_KEY= ``` And then load it from your application's codebase, as described in [Secure critical setting values](https://martenframework.com/docs/next/deployment/introduction#secret-key). ::: In order to ensure that SystemD takes into account the new service you just created, you can then run the following command: ```bash systemctl daemon-reload ``` And finally, you can start your server with: ```bash service start ``` Note that in subsequent deployments you will simply want to restart the SystemD service you previously defined. To do so, you can simply use the following command: ```bash service restart ``` ## Setup a Nginx reverse proxy Marten project servers are intended to be used behind a reverse proxy such as [Nginx](https://www.nginx.com/) or [Apache](https://httpd.apache.org/). Using a reverse proxy allows you to easily set up an SSL certificate for your server (for example using [Let's Encrypt](https://letsencrypt.org/)), to serve collected assets and media files if applicable, and enhance security and reliability. In our case, we will be using [Nginx](https://www.nginx.com/) and create a site configuration for our application. Let's use the following command to do so: ```bash nano /etc/nginx/sites-available/.conf ``` This should open a text editor in your terminal. Copy the following content into it: ``` server { listen 80; server_name ; include snippets/snakeoil.conf; gzip on; gzip_disable "msie6"; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_buffers 16 8k; gzip_http_version 1.1; gzip_min_length 256; gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype image/svg+xml image/x-icon; error_log /var/log/nginx/_error.log; access_log /var/log/nginx/_access.log; location /assets/ { expires 365d; alias /; } location /media/ { alias /; } location / { proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_redirect off; proxy_buffering off; proxy_pass http://localhost:; # Alternatively, if you configured a Unix socket in your Marten settings: # proxy_pass http://unix:/run//server.sock; } } ``` Don't forget to replace the ``, ``, ``, ``, and `` placeholders with the right values and, when ready, save the file using `Ctrl-X` and `y`. As you can see, the reverse proxy will serve our application on the HTTP port 80 and is configured to target our Marten server host (`localhost`) and port. Because of this, you should ensure that your Marten server is not using the HTTP port 80 (instead it could use something like 8080 or 8000 for example). Alternatively, you can configure your Marten server to listen on a Unix socket by setting the [`socket`](https://martenframework.com/docs/next/development/reference/settings#socket) setting and update the `proxy_pass` directive accordingly. You should also note that the above configuration defines two additional locations in order to serve assets (`/assets/`) and media files (`/media/`). This makes the assumption that those files are _locally_ available on the considered server. As such you should remove these lines if this is not applicable to your use case or if these files are uploaded somewhere else (eg. in a cloud bucket). You can then enable this site configuration by creating a symbolic link as follows: ```bash ln -s /etc/nginx/sites-available/.conf /etc/nginx/sites-enabled/.conf ``` And finally, you can restart the Nginx service with: ```bash sudo service nginx restart ``` # Deploy to Heroku Source: https://martenframework.com/docs/next/deployment/how-to/deploy-to-heroku This guide covers how to deploy a Marten project to [Heroku](https://heroku.com). ## Prerequisites To complete the steps in this guide, you will need: * An active account on [Heroku](https://heroku.com). * The [Heroku CLI](https://devcenter.heroku.com/articles/heroku-cli) installed and correctly configured. * A functional Marten project. ## Make your Marten project Heroku-ready Before creating the Heroku application, it is important to ensure that your project is properly configured for deployment to Heroku. This section outlines some necessary steps to ensure that your project can be deployed to Heroku without issues. ### Create a `Procfile` You should first ensure that your project defines a [`Procfile`](https://devcenter.heroku.com/articles/procfile), at the root of your project folder. A Procfile specifies the commands Heroku's dynos run, defining process types like web servers and background workers. Your Procfile should contain the following content at least: ```procfile title="Procfile" web: bin/server --port $PORT ``` :::info The `PORT` environment variable is automatically defined by Heroku. That's why we have to ensure that its value is forwarded to your server. ::: If your application requires the use of a database, you should also add a [release process](https://devcenter.heroku.com/articles/procfile#the-release-process-type) that runs the [`migrate`](https://martenframework.com/docs/next/development/reference/management-commands#migrate) management command to your Procfile: ```procfile title="Procfile" web: bin/server --port $PORT release: marten migrate ``` This will ensure that your database is properly migrated during each deployment. ### Configure the root path During deployment on Heroku, your application is prepared and compiled in a temporary directory, which is distinct from the location where the server runs your application. Specifically, the root of your application will be available under the `/app` folder on the Heroku platform. It's important to keep this in mind when setting up your application for deployment to Heroku. Marten's [application mechanism](https://martenframework.com/docs/next/development/applications) relies heavily on paths when it comes to locate things like [templates](https://martenframework.com/docs/next/templates), [translations](https://martenframework.com/docs/next/i18n), or [assets](https://martenframework.com/docs/next/assets). Because the path where your application is compiled will differ from the path where it runs, we need to ensure that you explicitly configure Marten so that it can find your project structure. To address this, we need to define a specific "root path" for your project in production. The root path specifies the actual location of the project sources in your system. This can prove helpful in scenarios where the project was compiled in a specific location different from the final destination where the project sources (and the `lib` folder) are copied, which is the case with Heroku. In this light, we can set the [`root_path`](https://martenframework.com/docs/next/development/reference/settings#root_path) setting to `/app` as follows: ```crystal title="config/settings/production.cr" Marten.configure :production do |config| config.root_path = "/app" # Other settings... end ``` As highlighted in the above example, this should be done in your "production" settings file. ### Configure key settings from environment variables When deploying to Heroku, you will have to set a few environment variables (later in this guide) that will be used to populate key settings. This should be the case for the [`secret_key`](https://martenframework.com/docs/next/development/reference/settings#secret_key) and [`allowed_hosts`](https://martenframework.com/docs/next/development/reference/settings#allowed_hosts) settings at least. As such, it is important to ensure that your project populates these settings by reading their values in corresponding environment variables. This can be achieved by updating your `config/settings/production.cr` production settings file as follows: ```crystal title="config/settings/production.cr" Marten.configure :production do |config| config.secret_key = ENV.fetch("MARTEN_SECRET_KEY") config.allowed_hosts = ENV.fetch("MARTEN_ALLOWED_HOSTS", "").split(",") # Other settings... end ``` It should be noted that if your application requires a database, you should also make sure to parse the `DATABASE_URL` environment variable and to configure your [database settings](https://martenframework.com/docs/next/development/reference/settings#database-settings) from the parsed database URL properties. The `DATABASE_URL` variable contains a URL-encoded string that specifies the connection details of your database, such as the database type, hostname, port, username, password, and database name. This can be accomplished by providing the `DATABASE_URL` environment variable value to the [`#database`](https://martenframework.com/docs/api/dev/Marten/Conf/GlobalSettings.html#database%28id%3DDB%3A%3AConnection%3A%3ADEFAULT_CONNECTION_NAME%2Curl%3AString%7CNil%3Dnil%29-instance-method) configuration method: ```crystal title="config/settings/production.cr" Marten.configure :production do |config| config.database url: ENV.fetch("DATABASE_URL") # Other settings... end ``` ### Optional: set up the asset serving middleware In order to easily serve your application's assets in Heroku, you can make use of the [`Marten::Middleware::AssetServing`](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#asset-serving-middleware) middleware. Indeed, it won't be possible to configure a web server such as [Nginx](https://nginx.org) to serve your assets directly on Heroku if you intend to use a "local file system" asset store (such as [`Marten::Core::Store::FileSystem`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/FileSystem.html)). To palliate this, you can make use of the [`Marten::Middleware::AssetServing`](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#asset-serving-middleware) middleware. Obviously, this is not necessary if you intend to leverage a cloud storage provider (like Amazon's S3 or GCS) to store and serve your collected assets (in this case, you can simply skip this section). In order to use this middleware, you can "insert" the corresponding class at the beginning of the [`middleware`](https://martenframework.com/docs/next/development/reference/settings#middleware) setting when defining production settings. For example: ```crystal Marten.configure :production do |config| config.middleware.unshift(Marten::Middleware::AssetServing) # Other settings... end ``` The middleware will serve the collected assets available under the assets root ([`assets.root`](https://martenframework.com/docs/next/development/reference/settings#root) setting). It is also important to note that the [`assets.url`](https://martenframework.com/docs/next/development/reference/settings#url) setting must align with the Marten application domain or correspond to a relative URL path (e.g., `/assets/`) for this middleware to work correctly. ## Create the Heroku app To begin, the initial action required is to generate your Heroku application itself. This can be achieved by executing the `heroku create` command as follows: ```bash heroku create ``` :::info In this guide, the `` placeholder refers to the Heroku application name that you have chosen for your project. You should replace `` with the actual name of your application in all the relevant commands and code snippets mentioned in this guide. ::: ## Set up the required buildpacks Heroku leverages [buildpacks](https://devcenter.heroku.com/articles/buildpacks) in order to "compile" web applications (which can include installing dependencies, compiling actual binaries, etc). In the context of a Marten project, it is recommended to use two buildbacks: 1. First, the [Node.js official buildback](https://github.com/heroku/heroku-buildpack-nodejs) in order to "build" your project's assets. 2. Second, the [Marten official buildback](https://github.com/martenframework/heroku-buildpack-marten) in order to (i) compile your server's binary, (ii) compile the Marten CLI, and (iii) [collect assets](https://martenframework.com/docs/next/assets/serving-assets). The sequence of buildpacks applied during the deployment process is critical: the Node.js buildpack must be the first one applied, to ensure that Heroku can initiate the necessary Node.js installations and configurations. This approach will guarantee that when the Marten buildpack is activated, the assets will have already been created and are ready to be "collected" through the [`collectassets`](https://martenframework.com/docs/next/development/reference/management-commands#collectassets) management command. You can ensure that these buildpacks are used by running the following commands: ```bash heroku buildpacks:add heroku/nodejs heroku buildpacks:add https://github.com/martenframework/heroku-buildpack-marten ``` :::tip It is important to mention that the use of the [Node.js official buildback](https://github.com/heroku/heroku-buildpack-nodejs) is completely optional: you should only use it if your project leverages Node.js to build some assets. ::: ## Set up environment variables ### `MARTEN_ENV` At least one environment variable needs to be configured in order to ensure that your Marten project operates in production mode in Heroku: the `MARTEN_ENV` variable. This variable determines the current environments (and the associated settings to apply). To set this environment variable, you can leverage the `heroku config:set` command as follows: ```bash heroku config:set MARTEN_ENV=production ``` ### `MARTEN_SECRET_KEY` It is also recommended to define the `MARTEN_SECRET_KEY` environment variable in order to populate the [`secret_key`](https://martenframework.com/docs/next/development/reference/settings#secret_key) setting, as mentioned in [Configure key settings from environment variables](#configure-key-settings-from-environment-variables). To set this environment variable, you can leverage the `heroku config:set` command as follows: ```bash heroku config:set MARTEN_SECRET_KEY=$(openssl rand -hex 16) ``` ### `MARTEN_ALLOWED_HOSTS` Finally, we want to ensure that the [`allowed_hosts`](https://martenframework.com/docs/next/development/reference/settings#allowed_hosts) setting contains the actual domain of your Heroku application, which is required as part of Marten's [HTTP Host Header Attacks Protection mechanism](https://martenframework.com/docs/next/security/introduction#http-host-header-attacks-protection). To set this environment variable, you can use the following command: ```bash heroku config:set MARTEN_ALLOWED_HOSTS=.herokuapp.com ``` ## Set up a database You'll need to provision a Heroku PostgreSQL database if your application makes use of models and migrations. To do so, you can make use of the following command: ```bash heroku addons:create heroku-postgresql:essential-0 ``` :::info You should replace `essential-0` in the above command by your desired [Postgres plan](https://devcenter.heroku.com/articles/heroku-postgres-plans). ::: ## Upload the application The final step is to upload your application's code to Heroku. This can be done by using the standard `git push` command to copy the local `main` branch to the `main` branch on Heroku: ```bash git push heroku main ``` It is worth mentioning that a few things will happen when you push your application's code to Heroku like in the above example. Indeed, Heroku will detect the type of your application and apply the buildpacks you [configured previously](#set-up-the-required-buildpacks) (ie. first the Node.js one and then the Marten one). As part of this step, your application's dependencies will be installed and your project will be compiled. If you defined a `release` process in your `Procfile` (like explained in [Create a Procfile](#create-a-procfile)), the specified command will also be executed (for example in order to run your project's migrations). A few additional things should also be noted: * The compiled server binary will be placed under the `bin/server` path. * Your project's `manage.cr` file will be compiled as well and will be available by simply calling the `marten` command. This means that you can run `marten ` if you need to call specific [management commands](https://martenframework.com/docs/next/development/management-commands). * The Marten buildpack will automatically call the [`collectassets`](https://martenframework.com/docs/next/development/reference/management-commands#collectassets) management command in order to collect your project's [assets](https://martenframework.com/docs/next/assets/serving-assets) and copy them to your configured assets storage. You can set the `DISABLE_COLLECTASSETS` environment variable to `1` if you don't want this behavior. ## Run management commands If you need to run additional [management commands](https://martenframework.com/docs/next/development/management-commands) in your provisioned application, you can use the `heroku run` command. For instance: ```bash heroku run marten listmigrations ``` # Deploy to Fly.io Source: https://martenframework.com/docs/next/deployment/how-to/deploy-to-fly-io This guide covers how to deploy a Marten project to [Fly.io](https://fly.io). ## Prerequisites To complete the steps in this guide, you will need: * An active account on [Fly.io](https://fly.io). * The Fly.io CLI [installed](https://fly.io/docs/hands-on/install-flyctl/) and correctly [configured](https://fly.io/docs/getting-started/log-in-to-fly/). * A functional Marten project. ## Make your Marten project Fly.io-ready Before creating the Fly.io application, it is important to ensure that your project is properly configured for deployment to Fly.io. This section outlines some steps to ensure that your project can be deployed to Fly.io without issues. ### Create a `Dockerfile` We will be deploying our Marten project to Fly.io by leveraging a [Dockerfile strategy](https://fly.io/docs/languages-and-frameworks/dockerfile/). A `Dockerfile` is a text file that contains a set of instructions for building a [Docker](https://www.docker.com/) image. It typically includes a base image, commands to install dependencies, and steps to configure the environment and copy files into the image. Your `Dockerfile` should be placed at the root of your project folder and should contain the following content at least: ```Dockerfile title="Dockerfile" FROM crystallang/crystal:latest WORKDIR /app COPY . . ENV MARTEN_ENV=production RUN apt-get update RUN apt-get install -y curl cmake build-essential RUN shards install RUN bin/marten collectassets --no-input RUN crystal build manage.cr -o bin/manage RUN crystal build src/server.cr -o bin/server --release CMD ["/app/bin/server"] ``` As you can see, this Dockerfile builds a Docker image based on the latest version of the Crystal programming language image. It also installs your project's Crystal dependencies, runs the [`collectassets`](https://martenframework.com/docs/next/development/reference/management-commands) management command, and compiles your server's binary. It should be noted that this Dockerfile could perform additional operations if needed. For example, some projects may require Node.js in order to install additional dependencies and build your project's assets. This could be achieved with the following additions: ```Dockerfile title="Dockerfile" FROM crystallang/crystal:latest WORKDIR /app COPY . . ENV MARTEN_ENV=production RUN apt-get update RUN apt-get install -y curl cmake build-essential // highlight-next-line RUN curl -fsSL https://deb.nodesource.com/setup_16.x | bash - // highlight-next-line RUN apt-get install -y nodejs // highlight-next-line // highlight-next-line RUN npm install // highlight-next-line RUN npm run build RUN shards install RUN bin/marten collectassets --no-input RUN crystal build manage.cr -o bin/manage RUN crystal build src/server.cr -o bin/server --release CMD ["/app/bin/server"] ``` ### Configure your production server's host and port You should ensure that your production server can be accessed from other containers, and on a specific port. To do so, it's important to set the [`host`](https://martenframework.com/docs/next/development/reference/settings#host) setting to `0.0.0.0` and the [`port`](https://martenframework.com/docs/next/development/reference/settings#port) setting to a specific value such as `8000` (which is the port we'll be using throughout this guide). This can be achieved by updating your `config/settings/production.cr` production settings file as follows: ```crystal title="config/settings/production.cr" Marten.configure :production do |config| config.host = "0.0.0.0" config.port = 8000 # Other settings... end ``` ### Configure key settings from environment variables When deploying to Fly.io, you will have to set a few environment variables (later in this guide) that will be used to populate key settings. This should be the case for the [`secret_key`](https://martenframework.com/docs/next/development/reference/settings#secret_key) and [`allowed_hosts`](https://martenframework.com/docs/next/development/reference/settings#allowed_hosts) settings at least. As such, it is important to ensure that your project populates these settings by reading their values in corresponding environment variables. This can be achieved by updating your `config/settings/production.cr` production settings file as follows: ```crystal title="config/settings/production.cr" Marten.configure :production do |config| config.secret_key = ENV.fetch("MARTEN_SECRET_KEY", "") config.allowed_hosts = ENV.fetch("MARTEN_ALLOWED_HOSTS", "").split(",") # Other settings... end ``` It should be noted that if your application requires a database, you should also make sure to parse the `DATABASE_URL` environment variable and to configure your [database settings](https://martenframework.com/docs/next/development/reference/settings#database-settings) from the parsed database URL properties. The `DATABASE_URL` variable contains a URL-encoded string that specifies the connection details of your database, such as the database type, hostname, port, username, password, and database name. This can be accomplished as follows for a PostgreSQL database: ```crystal title="config/settings/production.cr" Marten.configure :production do |config| if ENV.has_key?("DATABASE_URL") # Note: DATABASE_URL isn't available at build time... config.database url: ENV.fetch("DATABASE_URL") do |db| # Fly.io's Postgres works over an internal & encrypted network which does not support SSL. # Hence, SSL must be disabled. db.options = {"sslmode" => "disable"} end end # Other settings... end ``` ### Optional: set up the asset serving middleware In order to easily serve your application's assets in Fly.io, you can make use of the [`Marten::Middleware::AssetServing`](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#asset-serving-middleware) middleware. Indeed, it won't be possible to configure a web server such as [Nginx](https://nginx.org) to serve your assets directly on Fly.io if you intend to use a "local file system" asset store (such as [`Marten::Core::Store::FileSystem`](https://martenframework.com/docs/api/dev/Marten/Core/Storage/FileSystem.html)). To palliate this, you can make use of the [`Marten::Middleware::AssetServing`](https://martenframework.com/docs/next/handlers-and-http/reference/middlewares#asset-serving-middleware) middleware. Obviously, this is not necessary if you intend to leverage a cloud storage provider (like Amazon's S3 or GCS) to store and serve your collected assets (in this case, you can simply skip this section). In order to use this middleware, you can "insert" the corresponding class at the beginning of the [`middleware`](https://martenframework.com/docs/next/development/reference/settings#middleware) setting when defining production settings. For example: ```crystal Marten.configure :production do |config| config.middleware.unshift(Marten::Middleware::AssetServing) # Other settings... end ``` The middleware will serve the collected assets available under the assets root ([`assets.root`](https://martenframework.com/docs/next/development/reference/settings#root) setting). It is also important to note that the [`assets.url`](https://martenframework.com/docs/next/development/reference/settings#url) setting must align with the Marten application domain or correspond to a relative URL path (e.g., `/assets/`) for this middleware to work correctly. ## Create the Fly.io app To begin, the initial action required is to generate your Fly.io application itself. This can be achieved by executing the `fly launch` command as follows: ```bash fly launch --no-deploy --no-cache --internal-port 8000 --name --env MARTEN_ALLOWED_HOSTS=.fly.dev ``` The above command creates a Fly.io application whose internal port is set to `8000` while also ensuring that the `MARTEN_ALLOWED_HOSTS` environment variable is set to your future app domain. The command will ask you to choose a specific [region](https://fly.io/docs/reference/regions/) for your application and will create a `fly.toml` file whose content should look like this: ```toml title="fly.toml" app = "" primary_region = "" [env] MARTEN_ALLOWED_HOSTS = ".fly.dev" [http_service] internal_port = 8000 force_https = true auto_stop_machines = true auto_start_machines = true ``` The `fly.toml` is a configuration file used by Fly.io to know how to deploy your application to the Fly.io platform. :::info In this guide, the `` placeholder refers to the Fly.io application name that you have chosen for your project. You should replace `` with the actual name of your application in all the relevant commands and code snippets mentioned in this guide. ::: ## Set up environment secrets It is recommended to define the `MARTEN_SECRET_KEY` environment variable order to populate the [`secret_key`](https://martenframework.com/docs/next/development/reference/settings#secret_key) setting, as mentioned in [Configure key settings from environment variables](#configure-key-settings-from-environment-variables). Fly.io gives the ability to define such sensitive setting values using [runtime secrets](https://fly.io/docs/reference/secrets/). In this light, we can create a `MARTEN_SECRET_KEY` secret by using the `fly secrets` command as follows: ```bash fly secrets set MARTEN_SECRET_KEY=$(openssl rand -hex 16) ``` ## Set up a database You'll need to provision a Fly.io PostgreSQL database if your application makes use of models and migrations (otherwise you can skip this step!). In this light, you first need to create a PostgreSQL cluster with the following command: ```bash fly pg create --name -db ``` Then you will need to "attach" the PostgreSQL cluster you just created with your actual application. This can be achieved with the following command: ```bash fly postgres attach -db --app ``` Additionally, you will want to ensure that migrations are automatically applied every time your project is deployed. To do so, you can update the `fly.toml` file that was generated previously and add the following section to it: ```toml title="fly.toml" app = "" primary_region = "" [env] MARTEN_ALLOWED_HOSTS = ".fly.dev" [http_service] internal_port = 8000 force_https = true auto_stop_machines = true auto_start_machines = true // highlight-next-line [deploy] // highlight-next-line release_command = "bin/manage migrate" ``` ## Deploy the application The final step is to upload your application's code to Fly.io. This can be done by using the following command: ```bash fly deploy ``` It is worth mentioning that a few things will happen when you push your application's code to Fly.io like in the above example. Indeed, Fly.io will build a Docker image of your application based on the `Dockerfile` you defined [previously](#create-a-dockerfile) and then push it to the Fly.io registry (a private Docker registry maintained by Fly.io). Once this is done, it will launch a Docker container by using the obtained Docker image, and then route incoming traffic to the running container. # The Marten project Source: https://martenframework.com/docs/next/the-marten-project This section provides general information about the Marten project itself and details how to get involved and contribute to the framework. ## Guides - [Why Marten?](https://martenframework.com/docs/next/the-marten-project/why-marten) - [Design philosophies](https://martenframework.com/docs/next/the-marten-project/design-philosophies) - [Contributing](https://martenframework.com/docs/next/the-marten-project/contributing) - [Acknowledgments](https://martenframework.com/docs/next/the-marten-project/acknowledgments) - [Release notes](https://martenframework.com/docs/next/the-marten-project/release-notes) # Why Marten? Source: https://martenframework.com/docs/next/the-marten-project/why-marten Marten is a batteries-included web framework for [Crystal](https://crystal-lang.org/). It is designed to provide a consistent and extensible foundation for building complete web applications while taking advantage of Crystal's expressive syntax, static type system, native compilation, and performance. Rather than requiring applications to assemble and integrate many independent libraries for common web development needs, Marten provides these capabilities as parts of the framework itself. ## Batteries included Marten follows the "batteries included" philosophy. Features commonly required by web applications are available out of the box, including an [ORM](https://martenframework.com/docs/next/models-and-databases/introduction) and [migrations](https://martenframework.com/docs/next/models-and-databases/migrations), [schemas](https://martenframework.com/docs/next/schemas/introduction) and [validation](https://martenframework.com/docs/next/schemas/validations), [templates](https://martenframework.com/docs/next/templates/introduction), [sessions](https://martenframework.com/docs/next/handlers-and-http/sessions), [authentication](https://martenframework.com/docs/next/authentication/introduction), [internationalization](https://martenframework.com/docs/next/i18n/introduction), [emailing](https://martenframework.com/docs/next/emailing/introduction), [caching](https://martenframework.com/docs/next/caching/introduction), and more. The goal is not to eliminate choice, but to provide a solid foundation for common needs so that applications don't have to reinvent them. ## Consistent by design Having many features built into a framework is most useful when those features feel like parts of the same system. Marten aims to provide consistent conventions and predictable APIs across its different components. As applications grow and make use of more of the framework, the same concepts and patterns remain familiar instead of requiring entirely different approaches for each new concern. This consistency is an important part of Marten's [design philosophies](https://martenframework.com/docs/next/the-marten-project/design-philosophies): the framework is intended to be understood as a whole rather than as a collection of unrelated libraries. ## Extensible when needed Batteries included does not mean closed or inflexible. Marten provides extension points throughout the framework so that built-in behavior can be complemented or adapted to specific needs. [Custom model fields](https://martenframework.com/docs/next/models-and-databases/how-to/create-custom-model-fields), [route parameter types](https://martenframework.com/docs/next/handlers-and-http/how-to/create-custom-route-parameters), [session stores](https://martenframework.com/docs/next/handlers-and-http/sessions#session-stores), [template engines](https://martenframework.com/docs/next/templates/introduction), and other components can be implemented and registered with the framework. This allows Marten to provide useful defaults for common cases without preventing applications from going beyond them. ## Applications as building blocks Marten projects can be divided into logical [apps](https://martenframework.com/docs/next/development/applications). Each app can encapsulate its own [models](https://martenframework.com/docs/next/models-and-databases/introduction), [migrations](https://martenframework.com/docs/next/models-and-databases/migrations), [handlers](https://martenframework.com/docs/next/handlers-and-http/introduction), [routes](https://martenframework.com/docs/next/handlers-and-http/routing), [templates](https://martenframework.com/docs/next/templates/introduction), and other functionality. Apps are useful for organizing larger projects, but they can also be extracted and distributed as Crystal shards to provide reusable functionality to other Marten projects. As a result, the same mechanism used to structure an application also provides a foundation for extending Marten and building reusable components around it. ## The benefits of Crystal, with a full-featured framework [Crystal](https://crystal-lang.org/) provides an expressive, Ruby-inspired syntax together with a static type system, native compilation, and strong runtime performance. Marten builds on these characteristics while providing the higher-level abstractions and built-in functionality expected from a full-featured web framework. Its goal is to make it possible to build complete web applications with Crystal without having to assemble the fundamental pieces of the web stack yourself. ## Backend-oriented by choice Marten is intentionally backend-oriented and avoids making unnecessary assumptions about how frontend code should be structured or built. Applications are free to use [server-rendered templates](https://martenframework.com/docs/next/templates/introduction), dedicated frontend applications, JavaScript bundlers, asset pipelines, or other approaches depending on their needs. Marten provides the mechanisms necessary to [work with](https://martenframework.com/docs/next/assets/introduction) and [deploy](https://martenframework.com/docs/next/assets/serving-assets) assets without requiring a specific frontend toolchain. This keeps the framework focused on providing a strong foundation for the backend while leaving frontend architecture in the hands of each application. ## Familiar ideas, designed for Crystal Marten draws inspiration from established frameworks such as [Django](https://www.djangoproject.com/) and [Ruby on Rails](https://rubyonrails.org/), but it is not intended to be a port of either. Concepts such as [models](https://martenframework.com/docs/next/models-and-databases/introduction), [migrations](https://martenframework.com/docs/next/models-and-databases/migrations), [handlers](https://martenframework.com/docs/next/handlers-and-http/introduction), [templates](https://martenframework.com/docs/next/templates/introduction), [applications](https://martenframework.com/docs/next/development/applications), and convention-oriented development have been adapted and designed around Crystal and Marten's own architecture. Developers familiar with batteries-included frameworks should therefore encounter many recognizable ideas while still working with APIs and patterns designed specifically for Crystal. ## How does Marten compare to other Crystal frameworks? Crystal offers several frameworks for building web applications, but they make significantly different architectural choices. Marten is designed for those who want a complete web framework whose components form a consistent and extensible whole. ### Kemal [Kemal](https://kemalcr.com/) intentionally provides a lightweight foundation centered around [routing](https://martenframework.com/docs/next/handlers-and-http/routing), request handling, [middleware](https://martenframework.com/docs/next/handlers-and-http/middlewares), and HTTP responses. This makes it an excellent choice for small services or applications where assembling the rest of the stack independently is desirable. Marten takes the opposite approach. [Models](https://martenframework.com/docs/next/models-and-databases/introduction), [migrations](https://martenframework.com/docs/next/models-and-databases/migrations), [schemas](https://martenframework.com/docs/next/schemas/introduction), [templates](https://martenframework.com/docs/next/templates/introduction), [sessions](https://martenframework.com/docs/next/handlers-and-http/sessions), [authentication](https://martenframework.com/docs/next/authentication/introduction), [emailing](https://martenframework.com/docs/next/emailing/introduction), [internationalization](https://martenframework.com/docs/next/i18n/introduction), [caching](https://martenframework.com/docs/next/caching/introduction), and other common needs are part of the framework and are designed to work together. For complete web applications, this means fewer architectural and integration decisions have to be made before application-specific work can begin. If you want the framework to provide a coherent application architecture rather than primarily an HTTP layer, Marten provides a stronger foundation. ### Lucky [Lucky](https://luckyframework.org/) is the closest alternative to Marten in terms of scope. It is also a full-featured framework and makes extensive use of Crystal's type system to catch errors at compile time. The two frameworks differ significantly in how they approach application design. Lucky emphasizes specialized, explicit abstractions and compile-time guarantees across the stack. Marten favors a smaller set of familiar concepts and consistent conventions that recur throughout the framework. Marten's [models](https://martenframework.com/docs/next/models-and-databases/introduction), [query sets](https://martenframework.com/docs/next/models-and-databases/queries), [schemas](https://martenframework.com/docs/next/schemas/introduction), [handlers](https://martenframework.com/docs/next/handlers-and-http/introduction), [templates](https://martenframework.com/docs/next/templates/introduction), [routes](https://martenframework.com/docs/next/handlers-and-http/routing), [applications](https://martenframework.com/docs/next/development/applications), and other components are designed to feel like parts of the same system. The goal is to keep the framework predictable as its surface area grows, without requiring every concern to introduce an entirely different way of working. For those who value a cohesive batteries-included architecture and straightforward, familiar APIs over maximizing the amount of application behavior encoded through compile-time abstractions, Marten offers a simpler and more consistent approach. ### Amber [Amber](https://amberframework.org/) provides a full-stack, MVC-oriented framework with conventions, [generators](https://martenframework.com/docs/next/development/generators), and tooling covering both application development and the surrounding development workflow. Marten deliberately focuses more narrowly on providing a strong backend framework. It does not prescribe how frontend assets should be authored, bundled, or structured, allowing applications to use [server-rendered templates](https://martenframework.com/docs/next/templates/introduction), dedicated frontend applications, or whichever frontend toolchain best fits their needs. Marten also places reusable [applications](https://martenframework.com/docs/next/development/applications) at the center of its architecture. The same app mechanism used to organize a project can be used to package [models](https://martenframework.com/docs/next/models-and-databases/introduction), [migrations](https://martenframework.com/docs/next/models-and-databases/migrations), [handlers](https://martenframework.com/docs/next/handlers-and-http/introduction), [routes](https://martenframework.com/docs/next/handlers-and-http/routing), [templates](https://martenframework.com/docs/next/templates/introduction), and other functionality for reuse in other projects. For applications where a cohesive backend architecture, frontend independence, and reusable application components are more important than a conventional full-stack MVC workflow, Marten provides a more flexible foundation. These differences reflect deliberate architectural choices. If you want a minimal HTTP framework, [Kemal](https://kemalcr.com/) may be the better tool. If you specifically prefer [Lucky](https://luckyframework.org/)'s emphasis on compile-time guarantees and explicit abstractions, Lucky may suit you better. If you prefer [Amber](https://amberframework.org/)'s full-stack MVC approach, Amber may be the natural choice. But if you are looking for a comprehensive, consistent, extensible, and backend-oriented foundation for building complete web applications in Crystal, Marten is designed to provide exactly that. ## When is Marten a good fit? Marten may be a good fit when: * You want to build a complete web application with Crystal rather than assemble the framework layer yourself. * You value a batteries-included approach with common web development functionality available out of the box. * You prefer a framework whose different components follow consistent conventions and are designed to work together. * You want useful defaults while retaining the ability to extend or replace framework behavior when necessary. * You want to organize functionality into reusable [applications](https://martenframework.com/docs/next/development/applications). * You want the benefits of Crystal without giving up the conveniences of a full-featured web framework. * You prefer to keep control over your frontend architecture instead of having the backend framework prescribe one. Marten may be less appropriate when all that is needed is a minimal HTTP layer, when an application depends heavily on integrations available only in a larger ecosystem, or when a framework is expected to prescribe the entire frontend toolchain as well as the backend. ## In short Marten's proposition is not based on any single feature. It comes from the combination of a batteries-included approach, consistent conventions, extensibility, reusable applications, backend orientation, and the characteristics of the Crystal programming language. If that combination matches the way you want to build web applications, Marten provides a foundation designed around it from the start. # Design philosophies Source: https://martenframework.com/docs/next/the-marten-project/design-philosophies This document goes over the fundamental design philosophies that influenced the creation of the Marten web framework. It seeks to provide insight into the past and serve as a reference for the future. ## Simple and easy to use Marten tries to ensure that everything it enables is as simple as possible and that the syntax provided for dealing with the framework's components remains obvious and easy to remember (and certainly not complex or obscure). The framework makes it as easy as possible to leverage its capabilities and perform CRUD operations. ## Full-featured Marten adheres to the "batteries included" philosophy. Out of the box, it provides the tools and features that are commonly required by web applications: [ORM](https://martenframework.com/docs/next/models-and-databases/introduction), [migrations](https://martenframework.com/docs/next/models-and-databases/migrations), [schemas](https://martenframework.com/docs/next/schemas/introduction) and [validation](https://martenframework.com/docs/next/schemas/validations), [translations](https://martenframework.com/docs/next/i18n/introduction), [templating engine](https://martenframework.com/docs/next/templates/introduction), [sessions](https://martenframework.com/docs/next/handlers-and-http/sessions), [emailing](https://martenframework.com/docs/next/emailing/introduction), [authentication](https://martenframework.com/docs/next/authentication/introduction), and [caching](https://martenframework.com/docs/next/caching/introduction). ## Consistent Marten aims to provide consistent conventions and predictable APIs across its different components. As applications grow and make use of more of the framework, the same concepts and patterns should remain familiar instead of requiring entirely different approaches for each new concern. The framework is intended to be understood as a whole rather than as a collection of unrelated libraries. ## Extensible Marten gives developers the ability to contribute extra functionalities to the framework easily. Things like [custom model field implementations](https://martenframework.com/docs/next/models-and-databases/how-to/create-custom-model-fields), [new route parameter types](https://martenframework.com/docs/next/handlers-and-http/how-to/create-custom-route-parameters), [session stores](https://martenframework.com/docs/next/handlers-and-http/sessions#session-stores), etc... can all be registered to the framework easily. ## DB-Neutral The framework's ORM is and should remain usable with multiple database backends (including MariaDB, MySQL, PostgreSQL, and SQLite). ## App-oriented Marten allows separating projects into a set of logical "[apps](https://martenframework.com/docs/next/development/applications)", which helps improve code organization and makes it easy for multiple developers to work on different components. Each app can contribute specific abstractions and features to a project like models and migrations, templates, HTTP handlers and routes, etc. These apps can also be extracted in Crystal shards in order to contribute features and behaviors to other Marten projects. The goal behind this capability is to allow the creation of a powerful apps ecosystem over time and to encourage "reusability" and "pluggability". :::tip In this light, the [Awesome Marten](https://github.com/martenframework/awesome-marten) repository lists applications that you can leverage in your projects. ::: ## Backend-oriented The framework is intentionally very "backend-oriented" because the idea is to not make too many assumptions regarding how the frontend code and assets should be structured, packaged or bundled together. The framework can't account for all the ways assets can be packaged and/or bundled together and does not advocate for specific solutions in this area. Some projects might require a webpack strategy to bundle assets, some might require a fingerprinting step on top of that, and others might need something entirely different. How these toolchains are configured or set up is left to the discretion of web application developers, and the framework simply makes it easy to [reference these assets](https://martenframework.com/docs/next/assets/introduction) and [collect them](https://martenframework.com/docs/next/assets/serving-assets) at deploy time to upload them to their final destination. # Contributing to the Marten project Source: https://martenframework.com/docs/next/the-marten-project/contributing Marten is a big project that will keep evolving over time. If you want to, there are many ways to get involved! ## First things first... The Marten project adheres to the [Contributor Covenant Code of Conduct](https://github.com/martenframework/marten/blob/main/CODE_OF_CONDUCT.md). Everyone contributing to the Marten project is expected to follow this code. ## Reporting issues You should use the [project's issue tracker](https://github.com/martenframework/marten/issues) that is hosted on GitHub if you've found a bug or if you want to propose a new feature. ### About bug reports If you've found a bug related to the Marten web framework **that is not a security issue**, then you should (i) search the [existing issues](https://github.com/martenframework/marten/issues) to verify that it hasn't been reported yet and (ii) [create a new issue](https://github.com/martenframework/marten/issues/new) if that's not the case. Don't forget to include as many details as possible in your tickets: an explanatory description of the issue at hand and how to reproduce it, snippets and/or tracebacks if this is appropriate, etc. ### About security issues If you've found a security issue please **do not open a GitHub issue**. Instead, send an email to `security@martenframework.com`. We'll then investigate together to resolve the problem so we can make an announcement about a solution along with the vulnerability. ## Contributing code The preferred way to contribute to the Marten framework is to submit pull requests to the project's [GitHub repository](https://github.com/martenframework/marten). If you don't know where to start and would like to start contributing code to the Marten framework, you can have a look at the [Good first issues](https://github.com/martenframework/marten/issues?q=is%3Aissue+is%3Aopen+label%3A%22Good+first+issue%22). Below are provided some general tips regarding contributing code: development environments, running tests, etc. ### Development environment :::info The following steps assume that you have at least [git](https://git-scm.com/), [Crystal](https://crystal-lang.org/), [Node.js](https://nodejs.org), and [libvips](https://www.libvips.org/) (required to compile the spec suite) installed on your system. See the [release notes](https://martenframework.com/docs/next/the-marten-project/release-notes) of the version currently under development for the list of supported Crystal versions. ::: First, you should [fork](https://github.com/martenframework/marten/fork) the Marten git repository. Then you can get a local copy of the project using the following command: ```bash git clone git@github.com:/marten.git ``` Once this is done you should change into the `marten` repository and install the framework dependencies by running the following command: ```bash make ``` This will install a bunch of Crystal shards and some Node.js dependencies (which are required to work on the [Docusaurus](https://docusaurus.io/)-powered documentation). ### Setting up a test project with Marten This section dives into creating and configuring a test project using the Marten development environment. This allows you to experiment and develop features in isolation, ensuring everything works smoothly before committing changes to the main codebase. #### Creating a new test project Start by building the Marten CLI from your local checkout: ```bash crystal build src/marten_cli.cr -o bin/marten ``` Then create a new test project: ```bash ./bin/marten new project test-project [options] ``` Replace `test-project` with your desired project name. After creating the project, change into its directory. #### Configuring the Test Environment To use the development marten project instead of the one provided by `shard.yml`, you need to create a `shard.override.yml`. ```yaml name: test-project version: 0.1.0 dependencies: marten: path: /path/to/development/marten ``` Run `shards install`. Now, your test project is configured to use your local Marten development environment. ### Coding style Overall, Marten tries to comply with Crystal's [style guide](https://crystal-lang.org/reference/conventions/coding_style.html) and you should ensure that your changes comply with it as well if you are contributing code to the project. In addition to that, Marten's codebase is checked using [ameba](https://github.com/crystal-ameba/ameba), the standard [`crystal tool format`](https://crystal-lang.org/reference/man/crystal/index.html#crystal-tool-format) command, and [typos](https://github.com/crate-ci/typos). Every pull request opened on [Marten's GitHub repository](https://github.com/martenframework/marten) will be checked using these tools automatically. If needed, you can verify that these checks are passing locally by running the following commands: ```bash make qa # Run ameba, Crystal formatting, and spelling checks make lint # Run ameba checks only make format_checks # Run Crystal formatting checks only make typos # Run spelling checks only ``` The spelling checks require the [typos](https://github.com/crate-ci/typos) CLI to be installed on your system. Additionally, you can also apply Crystal's default formatting to the codebase by running: ```bash make format ``` ### Tests You should not submit pull requests without providing tests. Marten uses the standard [spec module](https://crystal-lang.org/reference/guides/testing.html) and comes with an extensive spec suite. Specs must be defined in the `spec` folder, at the root of the project's repository. You can run the whole spec suite by using the following command (which is equivalent to running `crystal spec`): ```bash make tests ``` When iterating on a change, you can also run a subset of the spec suite by passing specific files or directories to `crystal spec`: ```bash crystal spec spec/marten/template/tag_spec.cr crystal spec spec/marten/db/ ``` By default, specs will be executed using an in-memory SQLite database. If you wish to, you can configure additional databases by updating the `.spec.env.json` file that should've been automatically generated by the `make` command earlier (cf. [Development environment](#development-environment)). This file defines a bunch of "environment" setting values that are automatically leveraged to configure the test project that is used when running specs. It looks something like this: ```json title=.spec.env.json { "MARIADB_DEFAULT_DB_NAME": "example", "MARIADB_OTHER_DB_NAME": "other_example", "MARIADB_DB_USER": "example", "MARIADB_DB_PASSWORD": "", "MARIADB_DB_HOST": "", "MYSQL_DEFAULT_DB_NAME": "example", "MYSQL_OTHER_DB_NAME": "other_example", "MYSQL_DB_USER": "example", "MYSQL_DB_PASSWORD": "", "MYSQL_DB_HOST": "", "POSTGRESQL_DEFAULT_DB_NAME": "example", "POSTGRESQL_OTHER_DB_NAME": "other_example", "POSTGRESQL_DB_USER": "example", "POSTGRESQL_DB_PASSWORD": "", "POSTGRESQL_DB_HOST": "" } ``` As you can see, you have to specify two databases for each database backend (MariaDB, MySQL, and PostgreSQL). This is mandatory because Marten's specs are also testing cases where multiple databases are configured and used simultaneously for the same project. Specs are always executed using a _single_ database backend. As mentioned previously this database backend is the SQLite one by default, but you can specify the one to use when running specs by setting the `MARTEN_SPEC_DB_CONNECTION` environment variable. For example: ```bash MARTEN_SPEC_DB_CONNECTION=mariadb make tests # Will run specs using the MariaDB DB backend MARTEN_SPEC_DB_CONNECTION=mysql make tests # Will run specs using the MySQL DB backend MARTEN_SPEC_DB_CONNECTION=postgresql make tests # Will run specs using the PostgreSQL DB backend ``` Compiling the full spec suite in a single process can require a lot of memory. If that happens, or if you want to run specs the same way CI does, you can run them in batches: ```bash scripts/run_batched_specs ``` This splits spec files into several batches, runs `crystal spec` on each of them, and prints an aggregated summary at the end. The `MARTEN_SPEC_DB_CONNECTION` environment variable can be used with this script as well. ### Documentation Marten's documentation is written using Markdown. It is powered by [Docusaurus](https://docusaurus.io/) and lives under the `docs` folder. To run the documentation live server locally, you can change into `docs` and make use of the following command: ```bash npm run start ``` This will start the Docusaurus server at [http://localhost:3000/docs/](http://localhost:3000/docs/) and you will be able to easily see and test the changes you are making to the documentation source files. If you are contributing a new feature or a user-facing change, please update the relevant documentation guides and the [release notes](https://martenframework.com/docs/next/the-marten-project/release-notes) of the version currently under development. # Acknowledgements Source: https://martenframework.com/docs/next/the-marten-project/acknowledgments This section lists and acknowledges the various projects that inspired the Marten web framework, as well as notable contributions. ## Inspirations The Marten web framework implements a set of ideas and APIs that are inspired by the awesome work that was put into two particular frameworks: [Django](https://www.djangoproject.com/) and [Ruby on Rails](https://rubyonrails.org/). It can be easy to take for granted what these frameworks provide, and we should not forget to give credit where credit is due. ### Django The Marten web framework takes a lot from [Django](https://www.djangoproject.com/) - its biggest source of inspiration: * The [Model](https://martenframework.com/docs/next/models-and-databases)-[Handler](https://martenframework.com/docs/next/handlers-and-http)-[Template](https://martenframework.com/docs/next/templates) triptych is Marten's vision of the Model-View-Template (MVT) pattern provided by Django * The [auto-generated migrations](https://martenframework.com/docs/next/models-and-databases/migrations) mechanism is inspired by a similar mechanism within Django * [Generic handlers](https://martenframework.com/docs/next/handlers-and-http/generic-handlers) are inspired by Django's generic class-based views * The template syntax is inspired by Django's templating language * The concept of [apps](https://martenframework.com/docs/next/development/applications) and projects is inherited from Django as well Needless to say that this is a non-exhaustive list. ### Ruby on Rails The Marten web framework is also inspired by [Ruby on Rails](https://rubyonrails.org/) in some aspects. Among those we can mention: * The [generic validation DSL](https://martenframework.com/docs/next/models-and-databases/validations) * Most [model callbacks](https://martenframework.com/docs/next/models-and-databases/callbacks) * The idea of [message encryptors](https://martenframework.com/docs/api/dev/Marten/Core/Encryptor.html) and [message signers](https://martenframework.com/docs/api/dev/Marten/Core/Signer.html) ### But also... * The exception page displayed while in [debug](https://martenframework.com/docs/next/development/reference/settings#debug) mode is inspired by the [Exception Page](https://github.com/crystal-loot/exception_page) shard * The way to [handle custom objects](https://martenframework.com/docs/next/templates/introduction#using-custom-objects-in-contexts) in Marten templates is inspired by a similar mechanism within [Crinja](https://github.com/straight-shoota/crinja) * The idea of class-based [email definitions](https://martenframework.com/docs/next/emailing/introduction) is borrowed from [Carbon](https://github.com/luckyframework/carbon) ## Contributors Thanks to all the [contributors](https://github.com/martenframework/marten/contributors) of the project! # Release notes Source: https://martenframework.com/docs/next/the-marten-project/release-notes Here are listed the release notes for each version of the Marten web framework. ## Marten 1.0 * [Marten 1.0 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/1.0) _(Under development)_ ## Marten 0.7 * [Marten 0.7.2 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.7.2) _(Under development)_ * [Marten 0.7.1 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.7.1) * [Marten 0.7 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.7) ## Marten 0.6 * [Marten 0.6.4 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.6.4) * [Marten 0.6.3 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.6.3) * [Marten 0.6.2 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.6.2) * [Marten 0.6.1 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.6.1) * [Marten 0.6 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.6) ## Marten 0.5 * [Marten 0.5.7 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.5.7) * [Marten 0.5.6 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.5.6) * [Marten 0.5.5 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.5.5) * [Marten 0.5.4 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.5.4) * [Marten 0.5.3 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.5.3) * [Marten 0.5.2 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.5.2) * [Marten 0.5.1 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.5.1) * [Marten 0.5 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.5) ## Marten 0.4 * [Marten 0.4.5 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.4.5) * [Marten 0.4.4 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.4.4) * [Marten 0.4.3 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.4.3) * [Marten 0.4.2 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.4.2) * [Marten 0.4.1 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.4.1) * [Marten 0.4 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.4) ## Marten 0.3 * [Marten 0.3.4 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.3.4) * [Marten 0.3.3 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.3.3) * [Marten 0.3.2 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.3.2) * [Marten 0.3.1 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.3.1) * [Marten 0.3 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.3) ## Marten 0.2 * [Marten 0.2.4 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.2.4) * [Marten 0.2.3 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.2.3) * [Marten 0.2.2 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.2.2) * [Marten 0.2.1 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.2.1) * [Marten 0.2 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.2) ## Marten 0.1 * [Marten 0.1.5 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.1.5) * [Marten 0.1.4 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.1.4) * [Marten 0.1.3 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.1.3) * [Marten 0.1.2 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.1.2) * [Marten 0.1.1 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.1.1) * [Marten 0.1 release notes](https://martenframework.com/docs/next/the-marten-project/release-notes/0.1) # Marten 0.7.2 release notes Source: https://martenframework.com/docs/next/the-marten-project/release-notes/0.7.2 _Under development._ ## Bug fixes * Fix the debug logger raising unexpectedly when request data cannot be parsed and [debug mode](https://martenframework.com/docs/next/development/reference/settings#debug) is enabled. * Fix request data parsing for malformed `application/json` bodies. A body that is not valid JSON now raises a bad request (`Marten::HTTP::Errors::InvalidRequestParameters`) instead of `JSON::ParseException`. # Marten 1.0.0 release notes Source: https://martenframework.com/docs/next/the-marten-project/release-notes/1.0 _Under development._ ## Requirements and compatibility * **Crystal:** 1.20, 1.21, and 1.22. * **Databases:** * MariaDB 10.11 and higher. * MySQL 8.4 and higher. * PostgreSQL 15 and higher. * SQLite 3.37.0 and higher. ## New features ### Minor features #### Models and databases * Query sets now provide a [`#each_batch`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#each_batch) method, allowing to iterate over large query sets in batches without loading all the matching records into memory at once. Records are fetched in batches using a primary key cursor and are always processed in ascending primary key order. * Models and query sets now support pessimistic row locking via `SELECT ... FOR UPDATE`. Query sets provide a [`#lock`](https://martenframework.com/docs/next/models-and-databases/reference/query-set#lock) method, while model records provide [`#lock!`](https://martenframework.com/docs/api/dev/Marten/DB/Model/Persistence.html#lock!(lock%3ABool%7CString%3Dtrue%2Cusing%3ANil%7CString%7CSymbol%3Dnil)-instance-method) and [`#with_lock`](https://martenframework.com/docs/api/dev/Marten/DB/Model/Persistence.html#with_lock(lock%3ABool%7CString%3Dtrue%2Cusing%3ANil%7CString%7CSymbol%3Dnil%2C%26block)-instance-method). See [Pessimistic locking](https://martenframework.com/docs/next/models-and-databases/transactions#pessimistic-locking) for more details. * Multi-database projects can now define pluggable [database routers](https://martenframework.com/docs/next/models-and-databases/multiple-databases#database-routers) via the [`database_routers`](https://martenframework.com/docs/next/development/reference/settings#database_routers) setting. Routers resolve which database to use for reads and writes, gate cross-database relations, and control which migrations apply to a given database. Model instances also remember the database they were loaded from or saved to when an explicit `#using` selection is used. #### Handlers and HTTP * Handlers now support the [`QUERY`](https://martenframework.com/docs/next/handlers-and-http/introduction#writing-handlers) HTTP method through [`#query`](https://martenframework.com/docs/api/dev/Marten/Handlers/Base.html#query-instance-method). `QUERY` is safe and idempotent, and its request body is available through the request's `#data` and `#body` methods. CSRF protection treats `QUERY` as a safe method. The test client also provides [`#query`](https://martenframework.com/docs/api/dev/Marten/Spec/Client.html#query(path%3AString%2Cdata%3AHash|NamedTuple|Nil|String%3Dnil%2Cquery_params%3AHash|NamedTuple|Nil%3Dnil%2Ccontent_type%3AString|Nil%3Dnil%2Cheaders%3AHash|NamedTuple|Nil%3Dnil%2Csecure%3Dfalse)%3AMarten%3A%3AHTTP%3A%3AResponse-instance-method) to issue these requests. #### Schemas * [`Marten::Core::Validation::Error`](https://martenframework.com/docs/api/dev/Marten/Core/Validation/Error.html) and [`Marten::Core::Validation::ErrorSet`](https://martenframework.com/docs/api/dev/Marten/Core/Validation/ErrorSet.html) can now be serialized to JSON. An error set becomes a list of objects with `field`, `type`, and `message`, and `field` is `null` for global errors. Schema and model validation errors can therefore be returned from a JSON response through the [`#json`](https://martenframework.com/docs/next/handlers-and-http/introduction#json) handler helper. See [Serializing errors as JSON](https://martenframework.com/docs/next/schemas/validations#serializing-errors-as-json). #### Development * The [`serve`](https://martenframework.com/docs/next/development/reference/management-commands#serve) management command now displays how long project compilation took after each successful build. * The [`new`](https://martenframework.com/docs/next/development/reference/management-commands#new) command now writes an `AGENTS.md` file when creating a project. The file records the Marten version, links to the matching guides and API, and describes the project layout, generators, requires, migrations, CSRF, and specs, so coding agents can work in the generated project. Projects created with `--edge` link to the in-development guides. * The in-development guides are published as a single file at [`/docs/llms-full.txt`](https://martenframework.com/docs/llms-full.txt), next to the guide index at [`/docs/llms.txt`](https://martenframework.com/docs/llms.txt). * The [`new`](https://martenframework.com/docs/next/development/reference/management-commands#new) command prints its usage and exits with status 1 when `type` or `name` is omitted and stdin is not a terminal, instead of waiting for prompts. Passing both arguments still runs without prompts. ## Backward incompatible changes ### Handlers and HTTP * The default value of the [`trailing_slash`](https://martenframework.com/docs/next/development/reference/settings#trailing_slash) setting is now `:remove`, so unresolved URLs ending with a trailing slash are permanently redirected to their slashless version by default. Applications that want to keep the previous behavior should explicitly set `config.trailing_slash = :do_nothing`. * [`#query`](https://martenframework.com/docs/api/dev/Marten/Handlers/Base.html#query-instance-method) is now the handler method for the `QUERY` HTTP method, and `QUERY` is allowed by default. A handler that already defines `#query` for another purpose will have that method invoked for incoming `QUERY` requests. Rename that method if it is not meant to handle the HTTP verb. CSRF protection also treats `QUERY` as a safe method.