<?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 Kenneth Geisshirt on Medium]]></title>
        <description><![CDATA[Stories by Kenneth Geisshirt on Medium]]></description>
        <link>https://medium.com/@geisshirt?source=rss-955272aa9eb0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*3_6VkKZelwJ6oz1k2eZ_Yg.png</url>
            <title>Stories by Kenneth Geisshirt on Medium</title>
            <link>https://medium.com/@geisshirt?source=rss-955272aa9eb0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 01:19:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@geisshirt/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[Realm JavaScript v12: complete rewrite without surprises]]></title>
            <link>https://medium.com/realm/realm-javascript-v12-complete-rewrite-without-surprises-62eea2a2e8ae?source=rss-955272aa9eb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/62eea2a2e8ae</guid>
            <category><![CDATA[realm]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Kenneth Geisshirt]]></dc:creator>
            <pubDate>Thu, 17 Aug 2023 08:47:31 GMT</pubDate>
            <atom:updated>2023-08-25T12:47:02.850Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fjax54MjVULD3eNvK43wNg.jpeg" /></figure><p>The first commit in the Realm JavaScript repository is from May 2015. With 100+ contributors and 5.3k Github stars, the team, product priorities, JavaScript engines, and frameworks like React Native have evolved in those last eight years. The architecture worked great in the early years, while it has become increasingly difficult keeping up with the thriving React Native community, addingnew features, and supporting the increasing number of JavaScript engines and runtime environments.</p><p>About one year ago, the team began a complete rewrite to leverage the things we have learned and to accommodate the changes to the supported platforms.</p><p>The goal of the project has been to move to a totally new architecture without bringing any major surprises (aka breaking changes) for our users.</p><p>In the last months, we have released a couple of prereleases of the rewrite in order to learn from our users. Luckily, many users have tried these prereleases and reported back issues. We appreciate the time you have spent trying it out, and it has been motivating to engage with dedicated users.</p><h3>Changes to the existing API</h3><p>The goal of the rewrite is to keep the public API as it is and change the internal implementation. To ensure that we are keeping the API mostly untouched, we are either reusing or rewriting the tests we have written over the years.</p><p>We are changing our collection classes a bit. Today, they derive from a common Collection class that is modelled over ReadonlyArray. It is problematic for Realm. Dictionary as there is no natural ordering. Furthermore, we’ve contemplated deprecating our namespaced API since we find it out of touch with modern TypeScript and JavaScript development. However, to keep the breakage to a minimum, we’ll leave the namespaced API as-is for the 12.0.0 release. We are deprecating support for Altas push notifications (they have been <a href="https://www.mongodb.com/docs/atlas/app-services/reference/push-notifications/?utm_campaign=devrel&amp;utm_source=community&amp;utm_medium=cta&amp;utm_content=Blogpost%20for%20Realm%20JS%2012&amp;utm_term=kenneth.geisshirt">deprecated some time ago</a>).</p><p>How to define schemas has been cleaned up. In the last four years, we have been adding new data and collection types, and it has increased the complexity of our schema parser. You might experience a breaking change as our new schema parser is providing a much better and consistent schema syntax. Mixing object style and short-hand style is not possible. In the code snippet “Bad” is what is no longer possible, and “Good” is what you should write instead.</p><pre>const TaskSchema = {<br>  name: &quot;Task&quot;,<br>  properties: {<br>    description: /* property schema (shorthand or object form) */,<br>  },<br>};<br><br>// Explicitness<br>&quot;[]&quot;          // Bad (previously parsed as implicit &quot;mixed&quot;)<br>&quot;mixed[]&quot;     // Good<br><br>{ type: &quot;list&quot; }                              // Bad<br>{ type: &quot;list&quot;, objectType: &quot;mixed&quot; }         // Good<br><br>// Mixing shorthand and object form<br>{ type: &quot;int[]&quot; }                             // Bad<br>&quot;int[]&quot;                                       // Good<br>{ type: &quot;list&quot;, objectType: &quot;int&quot; }           // Good<br><br>{ type: &quot;int?&quot; }                              // Bad<br>&quot;int?&quot;                                        // Good<br>{ type: &quot;int&quot;, optional: true }               // Good<br><br>// Specifying object types<br>{ type: &quot;SomeType&quot; }                          // Bad<br>&quot;SomeType&quot;                                    // Good<br>{ type: &quot;object&quot;, objectType: &quot;SomeType&quot; }    // Good<br><br>{ type: &quot;object[]&quot;, objectType: &quot;SomeType&quot; }  // Bad<br>&quot;SomeType[]&quot;                                  // Good<br>{ type: &quot;list&quot;, objectType: &quot;SomeType&quot; }      // Good<br><br>{ type: &quot;linkingObjects&quot;, objectType: &quot;SomeType&quot;, property: &quot;someProperty&quot; } // Good</pre><p>Moreover, we discourage mixing class-based models and schemas defined by JavaScript objects when developing in TypeScript. You will likely get an error if you do <strong>realm.objects&lt;Person&gt;(“person”)</strong>. If you use class-based models, consider using <strong>realm.objects&lt;Person&gt;(Person)</strong> instead.</p><h3>Our new architecture</h3><p>Realm JavaScript builds on <a href="https://github.com/realm/realm-core">Realm Core</a>, which is composed of a storage engine, query engine, and sync client <a href="https://www.mongodb.com/docs/atlas/app-services/sync/?utm_campaign=devrel&amp;utm_source=community&amp;utm_medium=cta&amp;utm_content=Blogpost%20for%20Realm%20JS%2012&amp;utm_term=kenneth.geisshirt">connecting your client device with MongoDB Atlas</a>. Realm Core is a C++ library, and the vast majority of Realm JavaScript’s C++ code in our old architecture calls into Realm Core. Another large portion of our old C++ code is interfacing with the different JavaScript engines we are supporting (currently using <a href="https://nodejs.org/api/n-api.html">NAPI</a> (Node.js and Electron) and JSI (JavaScriptCore and Hermes on React Native)).</p><p>Our rewrite creates two separated layers: i) a handcrafted SDK layer and ii) a generated binding layer. The binding layer is interfacing with the JavaScript engines and Realm Core. It is generated code, and our code generator (aka binding generator) will read a specification of the Realm Core API and generate C++ code and TypeScript definitions. The generated C++ code can be called from our SDK, which is written in TypeScript.</p><p>On top of the binding layer, we implement a hand-crafted SDK layer. It is an implementation of the Realm JavaScript API as you know it. It is implemented using classes and methods in the binding layer as building blocks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4AgYNLo6ghMyhDfiteeBfw.png" /></figure><p>We see a number of benefits from this rewrite:</p><p><strong>Deliver new features faster</strong></p><p>First, our hypothesis is that we are able to deliver new functionality faster. We don’t have to write so much C++ boilerplate code as we have done in the past.</p><p><strong>Provide a TypeScript-first experience</strong></p><p>Second, we are implementing the SDK in TypeScript, which guarantees that the TypeScript definitions will be accurate and consistent with the implementation. If you are a TypeScript developer, this is for you. Likely, your editor will guide you through integrating with Realm, and it will be possible to do static type checking and analysis before deploying your app in production. We are also moving from JSDoc to TSDoc so the API documentation will coexist with the SDK implementation. Again, it will help you and your editor in your day-to-day work, as well as eliminate the previously seen inconsistencies between the API documentation and TypeScripts definitions.</p><p><strong>Facilitate community contributions</strong></p><p>Third, we are lowering the bar for you to contribute. In the past, you likely had to have a good understanding of C++ to open a pull request with either a bug fix or a new feature. Many features can now be implemented in TypeScript alone by using the building blocks found in the binding layer. We are looking forward to seeing <a href="https://www.mongodb.com/community/forums/tags/c/atlas-app-services-realm/realm/58/react-js?utm_campaign=devrel&amp;utm_source=community&amp;utm_medium=cta&amp;utm_content=Blogpost%20for%20Realm%20JS%2012&amp;utm_term=kenneth.geisshirt">contributions from you</a>.</p><p><strong>Generate more optimal code</strong></p><p>Last but not least, we hope to be able to generate more optimal code for the supported JavaScript engines. In the past, we had to write C++ code which was working across multiple JavaScript engines. Our early measurements indicate that many parts of the API will be a little faster, and in a few places, it will be much faster.</p><h3>New features</h3><p>As the number of our tests passing increased during the rewrite, our confidence that the rewrite is the right approach, we stopped developing new features for series 11 of Realm JavaScript. A hard decision was made: all new features will only be introduced in version 12, and let us briefly introduce some highlights.</p><p>First, a new unified logging mechanism has been introduced. It means that you can get more insights into what the storage engine, query engine, and sync client are doing. The goal is to make it easier for you to debug. You provide a callback function to the global logger, and log messages will be captured by calling your function.</p><pre>type Log = {<br>  message: string;<br>  level: string;<br>};<br>let logs: Log[] = [];<br><br>Realm.setLogger((level, message) =&gt; {<br>  logs.push({ level, message });<br>});<br><br>Realm.setLogLevel(&quot;all&quot;);</pre><p>Second, the full-text search will be supported. You can mark a string property to be indexed for full-text search, and Realm Query Language allows you to query your Realm. Currently, the feature is limited to Latin alphabets. Advanced functionality like stemming and spanning across properties will be added later.</p><pre>interface IStory {<br>  title?: string;<br>  content?: string;<br>}<br> <br>class Story extends Realm.Object&lt;Story&gt; implements IStory {<br>  title?: string;<br>  content?: string;<br> <br>  static schema: ObjectSchema = {<br>    name: &quot;Story&quot;,<br>    properties: {<br>      title: { type: &quot;string&quot; },<br>      content: { type: &quot;string&quot;, indexed: &quot;full-text&quot; },<br>    },<br>    primaryKey: &quot;title&quot;,<br>  };<br>}<br><br>// ... initialize your app and open your Realm<br><br>let amazingStories = realm.objects(Story).filtered(&quot;content TEXT &#39;amazing&#39;&quot;);</pre><p>We are introducing our first version of geospatial queries. The Realm Query Language has been expanded with a new operator <strong>geoWithin</strong>. In order for your geodata to work with Realm you must transform the data into certain shapes (it will be carefully documented how to do it). In the future, we might add more operators and special types for geodata.</p><pre>// Example of a user-defined point class that can be queried using geospatial queries<br>class MyGeoPoint extends Realm.Object implements CanonicalGeoPoint {<br>    coordinates!: GeoPosition;<br>    type = &quot;Point&quot; as const;<br> <br> <br>    static schema: ObjectSchema = {<br>        name: &quot;MyGeoPoint&quot;,<br>        embedded: true,<br>        properties: {<br>            type: &quot;string&quot;,<br>            coordinates: &quot;double[]&quot;,<br>        },<br>    };<br> }<br> <br> <br> class PointOfInterest extends Realm.Object {<br>    name!: string;<br>    location!: MyGeoPoint;<br> <br> <br>    static schema: ObjectSchema = {<br>        name: &quot;PointOfInterest&quot;,<br>        properties: {<br>            name: &quot;string&quot;,<br>            location: &quot;MyGeoPoint&quot;,<br>        },<br>    };<br> }<br> <br> <br> realm.write(() =&gt; {<br>    realm.create(PointOfInterest, {<br>        name: &quot;Copenhagen&quot;,<br>        location: {<br>            coordinates: [12.558892784045568, 55.66717839648401],<br>            type: &quot;Point&quot;,<br>        } as MyGeoPoint<br>    });<br>    realm.create(PointOfInterest, {<br>        name: &quot;New York&quot;,<br>        location: {<br>            coordinates: [-73.92474936213434, 40.700090994927415],<br>            type: &quot;Point&quot;,<br>        } as MyGeoPoint<br>    });<br> });<br> <br> <br> const berlinCoordinates: GeoPoint = [13.397255909303222, 52.51174463251085];<br> const radius = kmToRadians(500); // 500 km = 0.0783932519 rad<br> <br> <br> // Circle with a radius of 500 kms centered in Berlin<br> const circleShape: GeoCircle = {<br>    center: berlinCoordinates,<br>    distance: radius,<br> };<br> <br> <br> // All points of interest in a 500 kms radius from Berlin<br> let result = realm.objects(PointOfInterest)<br>                .filtered(&quot;location geoWithin $0&quot;, circleShape);</pre><p>Last, a new experimental subscription API for flexible sync has been added. The aim is to make it easier to subscribe and unsubscribe by providing <strong>subscribe()</strong> and <strong>unsubscribe()</strong> methods directly on the query result.</p><pre>const peopleOver20 = await realm<br> .objects(&quot;Person&quot;)<br> .filtered(&quot;age &gt; 20&quot;)<br> .subscribe({<br>   name: &quot;peopleOver20&quot;,<br>   behavior: WaitForSync.FirstTime, // Default<br>   timeout: 2000,<br> });<br><br><br>// …<br><br>peopleOver20.unsubscribe();</pre><h3>A better place</h3><p>While Realm JavaScript version 12 does not bring major changes for you as a developer, we believe that the code base is now at a better place. The code base is easier to work with, and it is an open invitation for you to contribute.</p><p>If you are using React Native, we encourage you to try out <a href="https://www.mongodb.com/docs/realm/sdk/react-native/install/#install-the--realm-react-library?utm_campaign=devrel&amp;utm_source=community&amp;utm_medium=cta&amp;utm_content=Blogpost%20for%20Realm%20JS%2012&amp;utm_term=kenneth.geisshirt">@realm/react</a> together with Realm JavaScript. It will save you from writing a lot of boilerplate code, and you will be able to get the most out of your Realm database as possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62eea2a2e8ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/realm/realm-javascript-v12-complete-rewrite-without-surprises-62eea2a2e8ae">Realm JavaScript v12: complete rewrite without surprises</a> was originally published in <a href="https://medium.com/realm">Realm Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data modeling: comparing Realm and SQLite]]></title>
            <link>https://medium.com/realm/data-modeling-comparing-realm-and-sqlite-2c07750991e8?source=rss-955272aa9eb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c07750991e8</guid>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[realm]]></category>
            <category><![CDATA[data-modeling]]></category>
            <dc:creator><![CDATA[Kenneth Geisshirt]]></dc:creator>
            <pubDate>Fri, 30 Jun 2023 11:51:01 GMT</pubDate>
            <atom:updated>2023-06-30T17:50:38.784Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b4FpStOAcBeIm5u86SgKPw.png" /></figure><h3>Data modelling: comparing Realm and SQLite</h3><h3>Introduction</h3><p>In this blog post, we will compare data modelling of two popular databases used for mobile applications: <a href="https://sqlite.org/index.html">SQLite</a> and <a href="https://www.mongodb.com/docs/realm/">Realm</a>.</p><p>SQLite is preinstalled on any Android and iOS device, while Realm requires a deliberate decision by the app developer to include it. We will use SQLite in its raw form i.e., without any programming language other than SQL. It means that the <a href="https://en.wikipedia.org/wiki/Object%E2%80%93relational_impedance_mismatch">object-relational impedance mismatch</a> is not considered. For SQLite, many Object-Relational Mappers exist with <a href="https://developer.android.com/training/data-storage/room">ROOM</a> (Android) and <a href="https://developer.apple.com/documentation/coredata">Core Data</a> (iOS) as highly popular examples. For Realm, the <a href="https://github.com/realm/realm-js">JavaScript SDK </a>is selected, as it will make it possible for you to run the examples on your computer without going through setting up a mobile app.</p><p>We will model a group of people and their life as they get married, have children, are divorced and die. The source code for both SQLite and Realm is found at <a href="https://github.com/kneth/data-model-compare">https://github.com/kneth/data-model-compare</a>.</p><p>The group of people we model are called <strong>Parent</strong> objects (or rows). They can be married to another <strong>Parent</strong> object, and they can have zero, one or more children. The children are modelled as a <strong>Child</strong> object (or row).</p><h3>Two data models</h3><p>In SQL, both the <strong>Parent</strong> and <strong>Child</strong> can be modelled using tables which are straightforward.</p><pre>CREATE TABLE Parent (<br>    name VARCHAR PRIMARY KEY NOT NULL,<br>    city VARCHAR NOT NULL,<br>    marriedTo VARCHAR REFERENCES Parent(name) NULL<br>);<br><br>CREATE TABLE Child (<br>    name VARCHAR PRIMARY KEY NOT NULL,<br>    age INTEGER NOT NULL<br>);</pre><p>The most advanced part is the self-referential column in <strong>Parent</strong>. The tricky part is the modelling of the relationship between <strong>Parent</strong> and <strong>Child</strong>. We will need to introduce an auxiliary table, <strong>Parent_Child</strong>, to capture who is the parent to which child. Such a <a href="https://en.wikipedia.org/wiki/Associative_entity">join-table</a> is common in SQL, and by using foreign keys we can link the two tables together.</p><pre>CREATE TABLE Parent_Child (<br>    parent_name VARCHAR NOT NULL,<br>    child_name VARCHAR NOT NULL,<br>    CONSTRAINT fk_parent<br>        FOREIGN KEY (parent_name)<br>        REFERENCES Parent(name)<br>        ON DELETE CASCADE,<br>    CONSTRAINT fk_child<br>        FOREIGN KEY (child_name)<br>        REFERENCES Child(name)<br>        ON DELETE CASCADE,<br>    UNIQUE (parent_name, child_name)<br>);</pre><p>On the other hand, Realm is an object database and objects can be tied together by links or references. Moreover, it is possible to have a list of links which we can use to model a <strong>Parent</strong> having multiple <strong>Child</strong> objects.</p><pre>const Parent = {<br>    name: &quot;Parent&quot;,<br>    primaryKey: &quot;name&quot;,<br>    properties: {<br>        name: &quot;string&quot;,<br>        city: &quot;string&quot;,<br>        children: &quot;Child[]&quot;,<br>        marriedTo: &quot;Parent&quot;,<br>    }<br>};<br><br>const Child = {<br>    name: &quot;Child&quot;,<br>    properties: {<br>        name: &quot;string&quot;,<br>        age: &quot;int&quot;,<br>        parents: { <br>            type: &quot;linkingObjects&quot;, <br>            objectType: &quot;Parent&quot;, <br>            property: &quot;children&quot; <br>        },<br>    }<br>};</pre><p>Links in Realm are directional, and you can think of your Realm database as a set of directed graphs where the nodes are objects. In order to be able to query a link in the opposite direction, Realm introduces the notion of <strong>linkingObjects</strong>. As you can see, an auxiliary table is not required as Realm’s native storage is based on objects. It is important to note that <strong>linkingObjects</strong> properties are updated automatically by the Realm database.</p><p>A short-coming of both data models is that it is technically possible for a child to have more than two parents. To ensure that a child only has one or two parents will be left to the application’s logic.</p><h3>Getting married</h3><p>A database is only interesting if it contains some data. Initially, we will add four persons and they form two married couples. First, we have to create the rows or objects and thereafter update who is married to whom. Neither data model can handle the constraint that marriage is a symmetric property, and we leave it to the application developer to ensure that data is consistent.</p><p>For SQL, we insert new rows and update the relevant column.</p><pre>BEGIN TRANSACTION;<br><br>/* Alice and Bob are married */<br>INSERT INTO Parent (&quot;name&quot;, &quot;city&quot;) VALUES (&quot;Alice&quot;, &quot;Stockholm&quot;);<br>INSERT INTO Parent (&quot;name&quot;, &quot;city&quot;) VALUES (&quot;Bob&quot;, &quot;Stockholm&quot;);<br>UPDATE Parent SET marriedTo = &quot;Bob&quot; WHERE name = &quot;Alice&quot;;<br>UPDATE Parent SET marriedTo = &quot;Alice&quot; WHERE name = &quot;Bob&quot;;<br><br>/* Charlie and Dorothy are married */<br>INSERT INTO Parent (&quot;name&quot;, &quot;city&quot;) VALUES (&quot;Charlie&quot;, &quot;Helsinki&quot;);<br>INSERT INTO Parent (&quot;name&quot;, &quot;city&quot;) VALUES (&quot;Dorothy&quot;, &quot;Helsinki&quot;);<br>UPDATE Parent SET marriedTo = &quot;Dorothy&quot; WHERE name = &quot;Charlie&quot;;<br>UPDATE Parent SET marriedTo = &quot;Charlie&quot; WHERE name = &quot;Dorothy&quot;;<br><br>COMMIT TRANSACTION;</pre><p>Similar operations are needed for Realm.</p><pre>realm.write(() =&gt; {<br>    // Alice and Bob are married<br>    const alice = realm.create(Parent.name, { name: &quot;Alice&quot;, city: &quot;Stockholm&quot; });<br>    const bob = realm.create(Parent.name, { name: &quot;Bob&quot;, city: &quot;Stockholm &quot;});<br>    alice.marriedTo = bob;<br>    bob.marriedTo = alice;<br><br>    // Charlie and Dorothy are married<br>    const charlie = realm.create(Parent.name, { name: &quot;Charlie&quot;, city: &quot;Helsinki&quot; });<br>    const dorothy = realm.create(Parent.name, { name: &quot;Dorothy&quot;, city: &quot;Helsinki &quot;});<br>    charlie.marriedTo = dorothy;<br>    dorothy.marriedTo = charlie;<br>});</pre><p>One major difference between SQL and Realm is that Realm operates with managed objects. For example, the object <strong>alice</strong> is a representation of data in the database, and the object behaves as a JavaScript object (if you are using another Realm SDK, the managed object will behave like a native object for the specific programming language). When you change the object, the database is changed. Later we will see that the implication is that you do not have to populate JavaScript objects from query results.</p><h3>Kids arrive</h3><p>The two couples continue their lives, and children are born. In database terminology, birth means that rows or objects are created. While creating new rows is almost trivial, keeping track of parenthood is not trivial in SQL. We need to update the join-table in order to record the relationship between parents and children. Until we insert rows into the join-table, we have orphaned children (the <a href="https://en.wikipedia.org/wiki/Atomicity_(database_systems)">atomicity</a> of the transaction will prevent it from happening).</p><pre>BEGIN TRANSACTION;<br><br>/* Alice and Bob */<br>INSERT INTO Child (name, age) VALUES (&quot;Alma&quot;, 14);<br>INSERT INTO Child (name, age) VALUES (&quot;Bill&quot;, 12);<br>INSERT INTO Parent_Child (parent_name, child_name) VALUES (&quot;Alice&quot;, &quot;Alma&quot;);<br>INSERT INTO Parent_Child (parent_name, child_name) VALUES (&quot;Alice&quot;, &quot;Bill&quot;);<br>INSERT INTO Parent_Child (parent_name, child_name) VALUES (&quot;Bob&quot;, &quot;Alma&quot;);<br>INSERT INTO Parent_Child (parent_name, child_name) VALUES (&quot;Bob&quot;, &quot;Bill&quot;);<br><br>/* Charlie and Dorothy */<br>INSERT INTO Child (name, age) VALUES (&quot;Charlotte&quot;, 5);<br>INSERT INTO Child (name, age) VALUES (&quot;Dillon&quot;, 8);<br>INSERT INTO Child (name, age) VALUES (&quot;Chuck&quot;, 11);<br>INSERT INTO Parent_Child (parent_name, child_name) VALUES (&quot;Charlotte&quot;, &quot;Charlie&quot;);<br>INSERT INTO Parent_Child (parent_name, child_name) VALUES (&quot;Dillon&quot;, &quot;Charlie&quot;);<br>INSERT INTO Parent_Child (parent_name, child_name) VALUES (&quot;Chuck&quot;, &quot;Charlie&quot;);<br>INSERT INTO Parent_Child (parent_name, child_name) VALUES (&quot;Charlotte&quot;, &quot;Dorothy&quot;);<br>INSERT INTO Parent_Child (parent_name, child_name) VALUES (&quot;Dillon&quot;, &quot;Dorothy&quot;);<br>INSERT INTO Parent_Child (parent_name, child_name) VALUES (&quot;Chuck&quot;, &quot;Dorothy&quot;);<br><br>COMMIT TRANSACTION;</pre><p>For Realm, the children are modelled as a list of links (or an array of references). With managed objects, we can simply append (in JavaScript, <strong>Array#push()</strong> appends a new object to an array and Realm tries to be as idiomatic as possible) references to the <strong>children</strong> property. The managed objects for the parents are found in the database by a look up by primary key (<strong>Realm#objectForPrimaryKey()</strong>). Realm will automatically update the links in the opposite direction i.e., the <strong>parents</strong> property does not need to be handled by the application.</p><pre>realm.write(() =&gt; {<br>    // Alice and Bob<br>    const alice = realm.objectForPrimaryKey(Parent.name, &quot;Alice&quot;);<br>    const bob = realm.objectForPrimaryKey(Parent.name, &quot;Bob&quot;);<br><br>    const alma = realm.create(Child.name, { name: &quot;Alma&quot;, age: 14 });<br>    const bill = realm.create(Child.name, { name: &quot;Bill&quot;, age: 12 });<br>    [alma, bill].forEach(c =&gt; {<br>        alice.children.push(c);<br>        bob.children.push(c);<br>    });<br><br>    // Charlie and Dorothy<br>    const charlie = realm.objectForPrimaryKey(Parent.name, &quot;Charlie&quot;);<br>    const dorothy = realm.objectForPrimaryKey(Parent.name, &quot;Dorothy&quot;);<br><br>    const charlotte = realm.create(Child.name, { name: &quot;Charlotte&quot;, age: 5 });<br>    const dillon = realm.create(Child.name, { name: &quot;Dillon&quot;, age: 8 });<br>    const chuck = realm.create(Child.name, { name: &quot;Chuck&quot;, age: 11 });<br>    [charlotte, dillon, chuck].forEach(c =&gt; {<br>        charlie.children.push(c);<br>        dorothy.children.push(c);<br>    });<br>});</pre><h3>Splitting up</h3><p>In the history of our two families, Alice and Bob decided to split up and divorce. For both SQL and Realm, this means that the <strong>marriedTo</strong> column/property has to be updated.</p><pre>BEGIN TRANSACTION;<br><br>UPDATE Parent SET marriedTo = NULL WHERE name = &quot;Alice&quot;;<br>UPDATE Parent SET marriedTo = NULL WHERE name = &quot;Bob&quot;;<br><br>COMMIT TRANSACTION;</pre><p>For Realm, we first find the object, and then update it.</p><pre>realm.write(() =&gt; {<br>    const alice = realm.objectForPrimaryKey(Parent.name, &quot;Alice&quot;);<br>    const bob = realm.objectForPrimaryKey(Parent.name, &quot;Bob&quot;);<br><br>    alice.marriedTo = null;<br>    bob.marriedTo = null;<br>});</pre><h3>Meeting a new partner</h3><p>Eventually, Alice will meet a new partner, Eric, and get married. At the same time, Alice moves to Eric’s hometown. Moreover, together they have a child. In SQL, the marriage and the move can be done in a single operation, <strong>UPDATE</strong>.</p><pre>BEGIN TRANSACTION;<br><br>INSERT INTO Parent (name, city, marriedTo) VALUES (&quot;Eric&quot;, &quot;Oslo&quot;, &quot;Alice&quot;);<br>UPDATE Parent SET city = &quot;Oslo&quot;, marriedTo = &quot;Eric&quot; WHERE name = &quot;Alice&quot;;<br><br>INSERT INTO Child (name, age) VALUES (&quot;Ellen&quot;, 1);<br>INSERT INTO Parent_Child (parent_name, child_name) VALUES (&quot;Alice&quot;, &quot;Ellen&quot;);<br>INSERT INTO Parent_Child (parent_name, child_name) VALUES (&quot;Eric&quot;, &quot;Ellen&quot;);<br><br>COMMIT TRANSACTION;</pre><p>Alice’s move requires two updates in Realm, but otherwise it is not much different from SQL.</p><pre>realm.write(() =&gt; {<br>    const alice = realm.objectForPrimaryKey(Parent.name, &quot;Alice&quot;);<br><br>    const eric = realm.create(Parent.name, { name: &quot;Eric&quot;, city: &quot;Oslo&quot;, marriedTo: alice });<br>    alice.marriedTo = eric;<br>    alice.city = &quot;Oslo&quot;;<br><br>    const ellen = realm.create(Child.name, { name: &quot;Ellen&quot;, age: 1 });<br>    alice.children.push(ellen);<br>    eric.children.push(ellen);<br>});</pre><h3>As time goes by</h3><p>In our data model we track the age of the children. As time goes by, we need to update it. Adding 15 years to the age is simple in SQL.</p><pre>BEGIN TRANSACTION;<br><br>UPDATE Child SET age = age + 15;<br><br>COMMIT TRANSACTION;</pre><p>With Realm, we will query the database for all Child objects, and iterate through them. Fortunately, Realm is lazy-loaded so we will only load the objects we access (in this case we access them all).</p><pre>realm.write(() =&gt; {<br>    realm.objects(Child.name).forEach(c =&gt; c.age += 15 );<br>});</pre><h3>We don’t live forever</h3><p>In our data model, death is modeled by deleting rows or objects. In our family history, a sad moment is when Alice dies. In SQL, our model does not guarantee integrity of the database, and we need to update Eric is no longer married.</p><pre>BEGIN TRANSACTION;<br><br>DELETE FROM Parent WHERE name = &quot;Alice&quot;;<br>UPDATE Parent SET marriedTo = NULL WHERE marriedTo = &quot;Alice&quot;;<br>DELETE FROM Parent_Child WHERE parent_name = &quot;Alice&quot;; /* enforce foreign key constraints is off by default */<br><br>COMMIT TRANSACTION;</pre><p>Deleting an object in Realm will lead to an update of links where the object is associated with. The implication is that we only have to delete the object representing Alice, and the <strong>marriedTo</strong> property of the object representing Eric will be set to <strong>null</strong>.</p><pre>realm.write(() =&gt; {<br>    realm.delete(realm.objectForPrimaryKey(Parent.name, &quot;Alice&quot;));<br>});</pre><h3>Children with one parent</h3><p>To end our story, we would like to know who has only one living parent. It turns out that it is complicated to query SQL. Our way is to combine a subselect and a join to find the three children (Alma, Bill, and Ellen).</p><pre>SELECT Child.name, age<br>FROM Child<br>JOIN Parent_Child<br>ON Child.name = child_name<br>WHERE parent_name IN<br>    (SELECT parent_name<br>     FROM Parent_Child<br>     GROUP BY child_name<br>     HAVING COUNT(parent_name) = 1);</pre><p>On the other hand, Realm can directly query it using the <strong>linkingObjects</strong> property in the data model.</p><pre>realm.objects(Child.name)<br>    .filtered(&quot;parents.@count = 1&quot;);<br>    .forEach(c =&gt; console.log(`${c.name} (${c.age})`));</pre><h3>Conclusion</h3><p>All databases have advantages and disadvantages. SQL’s major advantage is that it is governed by an ISO standard, and you can leverage your knowledge from one application to the next. If you have used Microsoft SQL Server, you can apply many of the same tricks to your mobile app’s SQLite database. What makes SQL hard to work with is that you need to <a href="https://en.wikipedia.org/wiki/Database_normalization">normalize</a> your database in order to take full advantage of it.</p><p>In the example above, we have not considered how you populate JavaScript objects from SQL queries. You can automate it by using an ORM, but many ORMs will require that you specify SQL queries or annotate classes to access the links.</p><p>Realm is an object database, and the major advantage is that it is closer to your programming language. Modern software development — also for mobile applications — is based on object-oriented programming, and working with objects makes it easier to get started.</p><p>Objects in Realm are lazy-loaded, and they are direct representations of data in the database. It often gives you lower memory consumption and faster access. Furthermore, the <a href="https://www.mongodb.com/docs/realm/realm-query-language/">Realm Query Language</a> is optimized for querying objects, as the last example clearly shows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c07750991e8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/realm/data-modeling-comparing-realm-and-sqlite-2c07750991e8">Data modeling: comparing Realm and SQLite</a> was originally published in <a href="https://medium.com/realm">Realm Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>