<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kristóf Liliom on Medium]]></title>
        <description><![CDATA[Stories by Kristóf Liliom on Medium]]></description>
        <link>https://medium.com/@kristofliliom?source=rss-9beca28c8f67------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*j7sIX5AODdAKjgdy</url>
            <title>Stories by Kristóf Liliom on Medium</title>
            <link>https://medium.com/@kristofliliom?source=rss-9beca28c8f67------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 02:30:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kristofliliom/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[RelationalSwift: SQLite ORM with Modern Swift]]></title>
            <link>https://medium.com/supercharges-mobile-product-guide/relationalswift-sqlite-orm-with-modern-swift-91f9cc14662c?source=rss-9beca28c8f67------2</link>
            <guid isPermaLink="false">https://medium.com/p/91f9cc14662c</guid>
            <dc:creator><![CDATA[Kristóf Liliom]]></dc:creator>
            <pubDate>Wed, 27 Nov 2024 14:17:36 GMT</pubDate>
            <atom:updated>2024-11-27T14:17:36.413Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7-QaEIOWiGPY4YL--bcB_A.jpeg" /></figure><h3><strong>What is RelationalSwift?</strong></h3><p>A streamlined, Swift-exclusive ORM designed to operate on top of SQLite. Built with modern Swift in mind, it simplifies data persistence, making database interactions in Swift more intuitive and less error-prone.</p><p>Most applications need to store data that persists between app launches. This is where an ORM, or Object-Relational Mapping, comes in handy. ORMs provide a bridge between databases and entity models, allowing developers to read and write data more easily while reducing the potential for programming errors. RelationalSwift offers a type-safe interface to handle common database operations, ensuring consistency and reliability.</p><p>RelationalSwift was developed to explore and experiment with new Swift features, offering a fresh approach to building an ORM. By focusing on cutting-edge Swift 6 capabilities like actors, async/await, and parameter packs, the library aims to explore how these modern language tools can enhance type safety and performance in database interactions. It takes a distinct approach than existing ORMs, providing a straightforward, thin layer over SQLite rather than adding heavy abstraction. Additionally, the project is designed with flexibility in mind, allowing for potential expansion to non-Apple platforms in the future.</p><p>RelationalSwift is a convenience layer above SQLite, providing a type-safe, concurrency-safe interface for common database tasks while leaving room for advanced users to access SQLite’s full power directly. This balance offers both simplicity and flexibility, catering to various developer needs.</p><h3><strong>Design Goals</strong></h3><p>RelationalSwift is built with a few core principles in mind:</p><ul><li><strong>Modern Swift Compatibility</strong>: RelationalSwift requires Swift 6 as a minimum to leverage the latest language features.</li><li><strong>Concurrency-Safety</strong>: Using Swift’s actors, async/await, and non-copyable structures, RelationalSwift ensures that database access is limited to a single task at a time through a dedicated global actor. Non-copyable structures benefit the lifecycle management of specific objects, such as SQLite statement handles.</li><li><strong>Performance and Usability</strong>: Parameter packs are utilized in various user-facing functions to enhance usability and performance by enabling more optimizations at compile-time.</li><li><strong>Minimal Abstraction</strong>: RelationalSwift provides a relatively thin layer over SQLite, avoiding “magic” abstractions. While knowledge of SQLite is helpful for using RelationalSwift, it is not mandatory. The library only operates within the capabilities of SQLite, without introducing additional complexities.</li><li><strong>Macro Usage</strong>: RelationalSwift employs macros to automatically generate SQLite helper functions for common operations (e.g., SELECT, INSERT, UPDATE, DELETE).</li><li><strong>Comprehensive Functionality</strong>: RelationalSwift aims to support the most common operations required by typical applications, making it a versatile choice for developers.</li></ul><h3>Example App</h3><p>To demonstrate the basic capabilities of the library, let’s create a simple iOS app for managing contacts.</p><p>After creating an Xcode project for an iOS app, we must add the dependency to our project (<a href="https://github.com/kliliom/RelationalSwift">GitHub</a>). <strong><em>TableMacros</em></strong> will need to be approved before it can be used, if the build fails, go to the build log in Xcode and enable the macro.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*O8lpBFpSIjNa2YA4gyWykg.gif" /><figcaption>Trust macro in Xcode</figcaption></figure><p>Now we can define our models. We want to manage multiple contacts, and each contact can have multiple properties (multiple email addresses, phone numbers, addresses). To implement this, we will have a <strong>Contact</strong> model which contains a name, and a <strong>ContactProperty</strong> model which will be responsible for storing key-value pairs.</p><p>To define the <strong>Contact</strong> model, we need to use the <strong>Table</strong> macro. This macro will tell RelationalSwift to generate supporting code for the annotated type:</p><pre>import Foundation<br>import RelationalSwift<br><br>@Table struct Contact {<br>    @Column(primaryKey: true) var id: UUID<br>    @Column var name: String<br>}</pre><p>This code will:</p><ul><li>generate code for a table named <strong>Contact</strong></li><li>tell that the table has a column named <strong>id</strong> which is a UUID and is the primary key</li><li>and has another column named <strong>name</strong> which is a String</li></ul><p>This code will not create the table itself in the database, we’ll handle that later, but first, let’s take a look at the <strong>ContactProperty</strong> model:</p><pre>import Foundation<br>import RelationalSwift<br><br>@Table struct ContactProperty {<br>    @Column(primaryKey: true) var id: UUID<br>    @Column var contactID: UUID<br>    @Column var key: ContactPropertyKey<br>    @Column var value: String<br>}<br><br>enum ContactPropertyKey: String, Bindable {<br>    case phoneNumber<br>    case email<br>    case address<br>}</pre><p>This code will:</p><ul><li>generate code for a table named <strong>ContactProperty</strong></li><li>tell that the table has a column named <strong>id</strong> which is a UUID and is the primary key</li><li>has a column named <strong>contactID</strong> which we will use to reference rows from the <strong>Contact</strong> table</li><li>has a column named <strong>key</strong>, which will be the type of information</li><li>and the last column named <strong>value</strong> which is a String</li></ul><p>The neat part is that RelationalSwift can use custom types (like <strong>ContactPropertyKey</strong>). They just need to conform to the <strong>Bindable</strong> protocol. Types conforming to <strong>Codable</strong> or <strong>RawRepresentable</strong> (where the raw type is <strong>Bindable</strong>) already have supporting code and only the <strong>Bindable</strong> conformance needs to be added.</p><p>So far so good, now we need to create the database:</p><pre>let url = // An URL to a SQLite database file.<br><br>// Check for the file&#39;s existance<br>let exists = FileManager.default<br>    .fileExists(atPath: url.path(percentEncoded: false))<br><br>// Create or open database<br>let database = try await Database.open(url: url)<br><br>// Create tables if the database was newly created<br>if !exists {<br>    try await database.createTable(for: Contact.self)<br>    try await database.createTable(for: ContactProperty.self)<br>}</pre><p>This code implements a simple database initialization. Before we open the database, we check whether the file exists or not. If it didn’t, we need to create the tables, because the database is empty. The <strong>createTable(for:)</strong> function executes the SQL statement to create the specified table. The library has migration support, but for this demo that would be unnecessarily complex.</p><p>Now that we have a connection to the database, we can create the repositories. Let’s start with <strong>ContactRepository</strong>:</p><pre>protocol ContactRepository: Sendable {<br>    var database: Database { get }<br>    @DatabaseActor func getAll() throws -&gt; [Contact]<br>    @DatabaseActor func get(byID: UUID) throws -&gt; Contact<br>    @DatabaseActor func insert(_ contact: Contact) throws<br>    @DatabaseActor func update(_ contact: Contact) throws<br>    @DatabaseActor func delete(byID id: UUID) throws<br>}<br><br>final class DefaultContactRepository: ContactRepository {<br>    let database: Database<br><br>    init(database: Database) {<br>        self.database = database<br>    }<br><br>    ...<br>}</pre><p>Most functions are annotated with <strong>@DatabaseActor</strong>, this tells Swift when/where the code can be executed. This global actor is used to guarantee that only one database operation is running at a time. Now let’s implement these methods.</p><p>To select all items from a table we use the database’s <strong>from(_:)</strong> method and pass the table’s type <strong>Contact.self</strong> and then call the <strong>select()<em> </em></strong>method:</p><pre>func getAll() throws -&gt; [Contact] {<br>    try database.from(Contact.self)<br>        .select()<br>}</pre><p>To get an item by ID, we can use the <strong>where {…}</strong> method to add conditions to the selection before calling <strong>select()</strong>. Because <strong><em>id</em></strong> is the primary key, we can assume that there can only be one result in this <strong>select()</strong> and throw an error if there is none:</p><pre>func get(byID: UUID) throws -&gt; Contact {<br>    let contacts = try database.from(Contact.self)<br>        .where { $0.id == byID }<br>        .select()<br><br>    guard let contact = contacts.first else {<br>        throw AppError.contactNotFound<br>    }<br>    return contact<br>}</pre><p>Creating and updating rows are simple and the database’s <strong>insert(_:)</strong> and <strong>update(_:)</strong> methods solve that:</p><pre>func insert(_ contact: Contact) throws {<br>    try database.insert(contact)<br>}<br><br>func update(_ contact: Contact) throws {<br>    try database.update(contact)<br>}</pre><p>And finally, deletion can be done by using the primary key:</p><pre>func delete(byID id: UUID) throws {<br>    try database.delete(from: Contact.self, byKey: id)<br>}</pre><p>That’s all! <strong>ContactPropertyRepository</strong> can be created similarly. The only code I would show here is how we can select properties for a specific <strong>Contact<em>.</em></strong> All column fields of the type can be accessed in a type-safe manner:</p><pre>func getAll(for contact: Contact) throws -&gt; [ContactProperty] {<br>    try database.from(ContactProperty.self)<br>        .where { $0.contactID == contact.id }<br>        .select()<br>}</pre><p>In this article, we focused on database related code. The complete source can be found on <a href="https://github.com/kliliom/RelationalSwift-ContactsDemo">GitHub</a> and includes everything mentioned here, along with a simple SwiftUI interface.</p><p>RelationalSwift supports much more complex operations and setups than shown in this article, so I hope you liked this intro and give it a try.</p><p>Happy coding!</p><p><em>At Supercharge, we create smart product strategies, design delightful interfaces, and build robust, AI-driven software to turn some of our partners’ most challenging digital initiatives into success stories. If you liked this article, check out some of Supercharge’s other articles on our </em><a href="https://medium.com/supercharges-mobile-product-guide"><em>blog</em></a><em>. If you’re interested in open positions, </em><a href="https://supercharge.io/careers/positions"><em>follow this link.</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91f9cc14662c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/supercharges-mobile-product-guide/relationalswift-sqlite-orm-with-modern-swift-91f9cc14662c">RelationalSwift: SQLite ORM with Modern Swift</a> was originally published in <a href="https://medium.com/supercharges-mobile-product-guide">Supercharge&#39;s Digital Product Guide</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>