<?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 Kirk Lewis on Medium]]></title>
        <description><![CDATA[Stories by Kirk Lewis on Medium]]></description>
        <link>https://medium.com/@kirklewis?source=rss-c886c30782f9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*82lyNTSSdRKT9bqlMQatbQ.jpeg</url>
            <title>Stories by Kirk Lewis on Medium</title>
            <link>https://medium.com/@kirklewis?source=rss-c886c30782f9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:39:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kirklewis/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[Perl 5 XML Validation with DTD and XSD]]></title>
            <link>https://medium.com/cultured-perl/perl-5-xml-validation-with-dtd-and-xsd-ec2d90f7c434?source=rss-c886c30782f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec2d90f7c434</guid>
            <category><![CDATA[perl]]></category>
            <category><![CDATA[xml]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kirk Lewis]]></dc:creator>
            <pubDate>Mon, 15 Jan 2018 22:19:55 GMT</pubDate>
            <atom:updated>2020-07-19T20:46:50.493Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4swXekT7LDNE49TXPbE2qA@2x.jpeg" /><figcaption>source: <a href="https://www.flickr.com/photos/kirklewis/50131042077/">https://www.flickr.com/photos/kirklewis/50131042077</a></figcaption></figure><p>This post is a brief but practical demonstration of validating an XML Document against <a href="https://en.wikipedia.org/wiki/Document_type_definition">Document Type Definition</a> (DTD) and <a href="https://en.wikipedia.org/wiki/XML_Schema_(W3C)">XML Schema Definition</a> (XSD) files. Such validation is necessary to ensure that XML sent between both the client, and the server hosting an XML based Web Service, is received as expected. Both DTD and XSD allow you to define the elements and attributes, an XML document should contain. XSD has the advantage of being written in XML itself, making it easier to read. XSD also allows more information to be defined about an element — such as their data type, namespace and restrictions for values. There are a few modules for validating XML in Perl 5 but I will be using two from the <a href="https://metacpan.org/pod/XML::LibXML#DESCRIPTION">Lib::XML</a> namespace.</p><h3>Project Setup</h3><h4>Project Files</h4><p>I’ll be using the following files contained in a directory named perl5-xml-validation to demonstrate both DTD and XSD validation.</p><pre>perl5-xml-validation/<br>.<br>├── bin<br>│   ├── dtd_validation.pl<br>│   └── xsd_validation.pl<br>├── cpanfile<br>└── xml<br>    ├── book.xml<br>    └── schemas<br>        ├── book.dtd<br>        └── book.xsd</pre><p>Once you’ve created the directory, be sure to enter it using cd perl5-xml-validation.</p><h4>Dependencies</h4><p>Open the file cpanfile and list the following modules:</p><pre>requires &#39;XML::LibXML&#39;;<br>requires &#39;Try::Tiny&#39;;</pre><p>Run cpanm -L local --installdeps . to install the modules. I will explain the other files as we start using them.</p><h4>The XML</h4><p>The XML document used for this demonstration simply contains book details within the file ./xml/book.xml as follows:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;<br>&lt;book&gt;<br>    &lt;title&gt;XML Validation&lt;/title&gt;<br>    &lt;numPages&gt;-200&lt;/numPages&gt;<br>&lt;/book&gt;</pre><p><em>The value ‘-200’ for the numPages element has been set deliberately. The reason should be clear later.</em></p><h3>Validating the XML with DTD</h3><h4>The DTD File</h4><p>The file ./xml/schemas/book.dtd contains the following definitions:</p><pre>&lt;!ELEMENT book (title,author,numPages?)&gt;<br>&lt;!ELEMENT title (#PCDATA)&gt;<br>&lt;!ELEMENT author (#PCDATA)&gt;<br>&lt;!ELEMENT numPages (#PCDATA)&gt;</pre><p>For any XML document associated with this DTD to be valid, it must contain the elements <em>book</em>, <em>title</em>, <em>author</em>, and optionally <em>numPages</em>. As you will notice, the <em>author</em> element is missing from the XML we defined earlier — we’ll correct this later.</p><p>Now let’s validate the XML. The file ./bin/dtd_validation.pl contains the following code, which I explain below it.</p><p><strong>The Code</strong></p><pre>#!/usr/bin/env perl</pre><pre>use v5.18;<br>use warnings;<br><br>use XML::LibXML;<br>use Try::Tiny qw(try catch);</pre><pre>my $xml_doc = XML::LibXML-&gt;load_xml(location =&gt; &#39;./xml/book.xml&#39;);<br>my $dtd_doc = XML::LibXML::Dtd-&gt;new(&#39;&#39;, &#39;./xml/schemas/book.dtd&#39;);</pre><pre>my $is_xml_valid = try {<br>    $xml_doc-&gt;validate($dtd_doc)<br>}<br>catch {<br>    say &#39;==&gt; &#39; . $_;<br>    return 0;<br>};<br>say $is_xml_valid ? &#39;Valid&#39; : &#39;Invalid&#39;;</pre><p>Regarding validation, the code above does the following:</p><ul><li>Loads the XML file using load_xml, which returns a XML::LibXML::Document object which is assigned to $xml_doc.</li><li>Then the DTD file book.dtd is loaded as part of <a href="https://metacpan.org/pod/XML::LibXML::Dtd#DESCRIPTION">XML::LibXML::Dtd</a> instance construction.</li><li>Finally, the validation itself is done using the validate method.</li></ul><p>So that the ternary expression to the bottom of the code is executed, we use the functions try and catch which are exported by <a href="https://metacpan.org/pod/Try::Tiny#SYNOPSIS">Try::Tiny</a>. These two functions will handle any errors thrown by the validate method. Not handling any errors which occur during the call to validate will cause the script to halt execution, so the ternary operation would not be executed.</p><p><strong>Validation Errors</strong></p><p>Now if you run perl ./bin/dtd_validation.pl and have not corrected the XML prior to this point, you will notice similar output in your shell as seen below:</p><pre>==&gt; ./xml/book.xml:0: validity error : Element book content does not follow the DTD, expecting (title , author , numPages?), got (title numPages )</pre><pre>Invalid</pre><p>The output message is indicating that the book element’s children are not as expected. The validation expected title, author and optionally numPages (in that order) but instead it just got title and numPages.</p><p><strong>Fixing the Error</strong></p><p>Just adding the element author just after the <em>title</em> element and assigning it a value, <em>for example:</em> &lt;author&gt;Johny Bravo&lt;/author&gt;, will ensure validation is successful next time the script is run. As such, Valid will be printed.</p><h3>Validating XML with XSD</h3><h4>The XSD File</h4><p>The file ./xml/schemas/book.xsd defines the structure which the ./xml/book.xml document should adhere to as follows:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;xs:schema xmlns:xs=&quot;http://www.w3.org/2001/XMLSchema&quot;<br>    elementFormDefault=&quot;qualified&quot;<br>    attributeFormDefault=&quot;unqualified&quot;&gt;</pre><pre>    &lt;xs:element name=&quot;book&quot;&gt;<br>        &lt;xs:complexType&gt;<br>            &lt;xs:sequence&gt;<br>                &lt;xs:element name = &quot;title&quot; type = &quot;xs:string&quot;/&gt;<br>                &lt;xs:element name = &quot;author&quot; type = &quot;xs:string&quot;/&gt;<br>                &lt;xs:element name = &quot;numPages&quot; type = &quot;xs:positiveInteger&quot; minOccurs=&quot;0&quot;/&gt;<br>            &lt;/xs:sequence&gt;<br>        &lt;/xs:complexType&gt;<br>    &lt;/xs:element&gt;</pre><pre>&lt;/xs:schema&gt;</pre><p>Similarly to the DTD defined earlier, the elements <em>title</em> and <em>author</em> are mandatory, and the other, <em>numPages</em> is optional (indicated by minOccurs=&quot;0&quot;). You should also note that the value of numPages is expected to be of type positiveInteger. XSD lets you define many different data types, using a richer syntax while DTD does not.</p><p><strong>The Code</strong></p><p>The file ./bin/xsd_validation.pl contains the following code, which I explain below it:</p><pre>#!/usr/bin/env perl</pre><pre>use v5.18;<br>use warnings;<br><br>use XML::LibXML;<br>use Try::Tiny qw(try catch);</pre><pre>my $xml_doc = XML::LibXML-&gt;load_xml(location =&gt; &#39;./xml/book.xml&#39;);<br>my $xsd_doc = XML::LibXML::Schema-&gt;new(location =&gt; &#39;./xml/schemas/book.xsd&#39;);</pre><pre>my $is_xml_valid = try {<br>    not $xsd_doc-&gt;validate($xml_doc);<br>}<br>catch {<br>    say &#39;==&gt; &#39; . $_;<br>    return 0;<br>};<br>say $is_xml_valid ? &#39;Valid&#39; : &#39;Invalid&#39;;</pre><p>The code above is the same overall process as the DTD validation code seen earlier. The only two implementation differences are:</p><p>1) The module <a href="https://metacpan.org/pod/XML::LibXML::Schema#NAME">XML::LibXML::Schema</a> is used to both load and validate the XML file.</p><p>2) The XML::LibXML::Schema method validate actually returns a 0 when validation is successful. As such, I precede the call to ...validate($xml) with the not keyword, to make its false return value true.</p><p><strong>Validation Errors</strong></p><p>Run the XSD validation using perl ./bin/xsd_validation.pl.</p><pre>==&gt; ./xml/book.xml:0: Schemas validity error : Element &#39;numPages&#39;: &#39;-200&#39; is not a valid value of the atomic type &#39;xs:positiveInteger&#39;.</pre><pre>Invalid</pre><p>Running the script should give the output seen above. The error indicates that the XSD expects a positive integer value for numPages but in fact the XML contains a negative integer, in this case ‘-200’.</p><p><strong>Fixing the Error</strong></p><p>You’ve probably beat me to it, but just changing the numPages value from -200 to 200 and running the script again should output Valid.</p><h3>Conclusion</h3><p>Validating the XML document using the two <em>XML::LibXML</em> modules discussed only required two objects, a call to the <em>validate </em>method, and the use of <em>try</em> and <em>catch</em>, to handle any errors that may be thrown.</p><p>If you are interested in seeing the validation done using Perl tests, click <a href="https://github.com/kirklewis/perl5-xml-validation">here</a> for the Github repository containing the code for this article.</p><p>Thank you for reading this article! Feel free to leave a clap👏 and also recommend this article to others.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec2d90f7c434" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cultured-perl/perl-5-xml-validation-with-dtd-and-xsd-ec2d90f7c434">Perl 5 XML Validation with DTD and XSD</a> was originally published in <a href="https://medium.com/cultured-perl">Cultured Perl</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn ORM in Perl with DBIx::Class - Part 2]]></title>
            <link>https://medium.com/cultured-perl/learn-orm-in-perl-with-dbix-class-part-2-d339095e353?source=rss-c886c30782f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d339095e353</guid>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[perl]]></category>
            <category><![CDATA[object-relational-mapping]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kirk Lewis]]></dc:creator>
            <pubDate>Sat, 04 Feb 2017 16:28:23 GMT</pubDate>
            <atom:updated>2017-03-31T05:28:50.473Z</atom:updated>
            <content:encoded><![CDATA[<h4>Generating the schema classes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*9G_thWvzpXaTixih.jpg" /><figcaption>source: <a href="https://www.flickr.com/photos/kirklewis/32579951031/">https://www.flickr.com/photos/kirklewis/32579951031/</a></figcaption></figure><p>In <a href="https://medium.com/@kirklewis/learn-orm-in-perl-with-dbix-class-part-1-7305957e1d8b">part 1</a> we laid the foundation for our project, and in this part we will focus on the database and class schema creation. The ‘class schema’ refers to the classes which are based on the database and its tables.</p><p>After we generate the classes, we will then create an accessor to return data in a special way, and then a method to perform a custom search. After each stage we can run the tests to check what is both missing and working.</p><h3>Generating the Schema</h3><p>We’ll now use the function <em>make_schema_at</em> which is exported by the DBIx::Class::Schema::Loader, to generate the schema classes. The <em>make_schema_at </em>simply reads a RDBMS schema, in our case <em>app.db, </em>and creates the classes based on its tables.</p><h4><strong>Make Schema Script</strong></h4><p>Open the file <em>scripts/make_schema.pl</em> and enter the following lines.</p><pre>#!/usr/bin/env perl</pre><pre>use strict;<br>use warnings;</pre><pre>use DBIx::Class::Schema::Loader qw(make_schema_at);</pre><pre>my <a href="http://twitter.com/dsn">@dsn</a>     = &#39;dbi:SQLite:dbname=app.db&#39;;<br>my %options = (<br>    dump_directory =&gt; &#39;./lib&#39;<br>);</pre><pre>make_schema_at(&#39;App::Schema&#39; =&gt; \%options, \<a href="http://twitter.com/dsn">@dsn</a>);</pre><p>A quick explanation of this file - <em>@dsn</em> defines how a database connection is established, and <em>%options</em> contains information which can be used to help create the classes. In this case, <em>dump_directory </em>indicates what directory the classes will be created in. Finally <a href="https://metacpan.org/pod/DBIx::Class::Schema::Loader#make_schema_at">make_schema_at</a> is called to generate the classes under the namespace <em>App::Schema</em>.</p><p>Now run our generation script:</p><pre>perl scripts/make_schema.pl</pre><p>The contents of the <em>lib </em>directory should now look like this:</p><pre>lib/<br>└── App<br>    ├── Schema<br>    │   └── Result<br>    │       └── User.pm<br>    └── Schema.pm</pre><p>Run the test with <em>prove -lv t/basic.t</em> and the output should be similar to the following.</p><pre>ok 1 — use App::Schema;<br>not ok 2 — App::Schema::Result::User-&gt;can(&#39;fullname&#39;)<br>…</pre><p>The first test should pass since App::Schema now exists. However the other four will fail because neither the accessor <em>fullname </em>nor the method <em>age_less_than</em> have yet been implemented. This is covered in the next sections.</p><h3>Custom Fields and Searches</h3><p>Okay, now that the class schema is generated it’s time to add some custom functionality to it. We will start by defining a custom accessor to return the full name of a user. This is a shorter way than having to manually concatenate the first and last name wherever a user’s full name is required.</p><h4>Adding the fullname accessor</h4><p>Open the file <em>lib/App/Schema/Result/User.pm</em> and add the following method.</p><pre>sub fullname {<br>    my $self = shift;<br>    return $self-&gt;firstname . &#39; &#39; . $self-&gt;lastname;<br>}</pre><p><strong><em>Note</em></strong><em>: The above sub-routine must be defined below the line that reads as follows:</em></p><pre># Created by DBIx::Class::Schema::Loader v0.07045 @ 2016–08–07 10:02:31<br># DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:</pre><p>If you make changes to your database such as add a new column to the users table, running the <em>make_schema.pl</em> again will update the <em>User.pm</em> module to reflect the changes. However, it does not remove any code written below the line mentioned. Making any changes above this line can cause the class schema generation to fail.</p><h4><strong>Test the Accessor</strong></h4><p>Run the test again and the results should look like this:</p><pre>ok 1 — use App::Schema;<br>ok 2 — App::Schema::Result::User-&gt;can(&#39;fullname&#39;)<br>ok 3 — Should read from set using a custom accessor<br>not ok 4 — App::Schema::ResultSet::User-&gt;can(&#39;age_less_than&#39;)</pre><p>The second and third tests now pass since <em>fullname </em>has been defined and is functioning correctly.</p><p>As you can see the <em>fullname</em> accessor acts like a <a href="https://en.m.wikipedia.org/wiki/Virtual_column">Virtual Column</a> in SQL. The <em>fullname</em> field is considered virtual because it is not a column of the users table but it appears that way. Instead the full name is computed using the firstname and lastname fields.</p><h4>Define the Custom Search Method</h4><p>Now we will define a method to perform a custom search on the users. This method will be defined on a <a href="https://metacpan.org/pod/DBIx::Class::ResultSet#NAME">ResultSet</a> class which can be created as follows:</p><pre>mkdir -p lib/App/Schema/ResultSet &amp;&amp; \<br>touch lib/App/Schema/ResultSet/User.pm</pre><p>Now open the file <em>lib/App/Schema/ResultSet/User.pm</em> and enter the following code:</p><pre>package App::Schema::ResultSet::User;</pre><pre>use base &#39;DBIx::Class::ResultSet&#39;;</pre><pre>sub age_less_than {<br>   my $self = shift;<br>   my $age  = shift;</pre><pre>   return $self-&gt;find({ age =&gt; { &#39;&lt;&#39; =&gt; $age }});<br>}</pre><pre>1;</pre><h4>Test the Custom Method</h4><p>Run the test again and the output should be as follows.</p><pre>t/basic.t ..<br>ok 1 — use App::Schema;<br>ok 2 — App::Schema::Result::User-&gt;can(&#39;fullname&#39;)<br>ok 3 — should read from set using a custom accessor<br>ok 4 — App::Schema::ResultSet::User-&gt;can(&#39;age_less_than&#39;)<br>ok 5 — should perform search using a custom method<br>1..5<br>ok<br>All tests successful.</pre><p>The output above indicates that everything is working as we intended. That is, we’re able get the full name of a user using a custom accessor, and we’re able to find all users less than a specified age.</p><h3>Summary</h3><p>This post wraps up this brief two part introduction to ORM in Perl with <em>DBIx::Class</em>. Generating the class schema was achieved using a single call to <em>make_schema_at</em>. Adding a custom accessor and method just required adding a sub-routine to both the <em>Result::User</em> and <em>ResultSet::User</em> modules respectively. We also proved our functionality with Test Driven Development.</p><p>Thank you for reading and you can recommend this series of posts using the 💚 button.</p><p>The code for both parts of this article can be found <a href="https://github.com/kirklewis/learn-orm-perl-with-dbix/releases">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d339095e353" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cultured-perl/learn-orm-in-perl-with-dbix-class-part-2-d339095e353">Learn ORM in Perl with DBIx::Class - Part 2</a> was originally published in <a href="https://medium.com/cultured-perl">Cultured Perl</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn ORM in Perl with DBIx::Class - Part 1]]></title>
            <link>https://medium.com/cultured-perl/learn-orm-in-perl-with-dbix-class-part-1-7305957e1d8b?source=rss-c886c30782f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7305957e1d8b</guid>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[perl]]></category>
            <category><![CDATA[object-relational-mapping]]></category>
            <dc:creator><![CDATA[Kirk Lewis]]></dc:creator>
            <pubDate>Sat, 04 Feb 2017 16:26:35 GMT</pubDate>
            <atom:updated>2017-04-26T19:10:04.264Z</atom:updated>
            <content:encoded><![CDATA[<h4>Wrap your database with OO abstraction</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9G_thWvzpXaTixih.jpg" /><figcaption>source: <a href="https://www.flickr.com/photos/kirklewis/32579951031/">https://www.flickr.com/photos/kirklewis/32579951031/</a></figcaption></figure><p>This post will provide a breif hands-on introduction to <a href="https://en.wikipedia.org/wiki/Object-relational_mapping">ORM</a> in Perl using a few <a href="https://metacpan.org/pod/DBIx::Class">DBIx::Class</a> sub classes.</p><p>In detail, this means we will generate <a href="https://metacpan.org/pod/DBIx::Class::Schema#DESCRIPTION">Schema</a>, <a href="https://metacpan.org/pod/distribution/DBIx-Class/lib/DBIx/Class/Manual/ResultClass.pod">Result </a>and <a href="https://metacpan.org/pod/DBIx::Class::ResultSet#NAME">ResultSet</a> classes (Perl modules) which will be used to interface with a SQLite database. The database will contain a single users table. Once the database has been created, we will implement functionality to both return the full name of a user, and find all users under a given age. To ensure the functionality of the schema, this code will be implemented using <a href="https://en.wikipedia.org/wiki/Test-driven_development">Test Driven Development</a> (TDD), where the tests will be written first, then made to pass as we add new functionality.</p><p>This article is divided into two parts. The first part is doing the groundwork — installing Perl modules, setting up the directory structure, the database to test against, and a unit test against which we can measure our progress. In the second part we will create a database and use <em>DBIx::Class</em><strong><em> </em></strong>modules to make the tests pass.</p><h3>Prerequisites</h3><ul><li>Understanding of Object Relational Mapping (ORM)</li><li>Basic knowledge of Perl — including sub-routines, references, packages and of course, writing tests.</li><li><a href="https://sqlite.org/about.html">SQLite</a> will be used to generate the database.</li><li><a href="https://metacpan.org/pod/App::cpanminus#INSTALLATION">cpanm</a> a CLI tool for downloading, building and installing Perl modules.</li><li><a href="https://perlbrew.pl/">Perlbrew</a> is optional but recommended as it’s good for managing module dependencies independently per project.</li></ul><h3>Getting Started</h3><p>Start by creating a project directory and empty files where you’ll put your code. The simplest way to do this is to copy and paste the lines below into your terminal and then press enter.</p><pre>mkdir -p dbix-proj/<strong>{</strong>lib,scripts,t<strong>} &amp;&amp; </strong>\<br>touch dbix-proj/<strong>{</strong>cpanfile,t/basic.t,scripts/<strong>{</strong>schema.sql,make_schema.pl<strong>}}</strong></pre><p>This gives you a directory structure and files which looks like this:</p><pre>dbix-proj<br>├── cpanfile<br>├── lib<br>├── scripts<br>│   ├── make_schema.pl<br>│   └── schema.sql<br>└── t<br>    └── basic.t</pre><h3>Project Dependencies</h3><p>The modules required for the tests and generating the class schema need to be added to the <em>cpanfile</em> and then installed.</p><p>Open the <em>cpanfile</em> and add the following modules.</p><pre>requires &#39;DBIx::Class&#39;;<br>requires &#39;DBIx::Class::Schema::Loader&#39;;<br>requires &#39;Test::More&#39;;</pre><h4><strong>Install Modules</strong></h4><p>From within the <em>dbix-proj</em> directory install the modules using the cpanm command.</p><pre>cd dbix-proj<br>cpanm --installdeps .</pre><p>The modules should now be installed.</p><p><strong>Note:</strong> Depending on what you already have installed (and your bandwidth) this can take a few minutes minutes. This is because <em>cpanm </em>will run the tests which ship with each module. Scan ahead or go and make a coffee — you’ll see it’s well worth the wait!</p><p>To make sure these packages are found by Perl (if not using perlbrew) run this:</p><pre>perl -e &#39;use DBIx::Class&#39;</pre><p>If you get an error message like:</p><pre>Can&#39;t locate DBIx/Class.pm in @INC <strong>(</strong>you may need to install<br>the DBIx::Class module<strong>)</strong> <strong>(</strong>@INC contains:...</pre><p>then you need to update <em>@INC</em> to include the directory where the packages were installed:</p><pre>export PERL5LIB<strong>=</strong>~/perl5/lib/perl5/</pre><h3>The Database</h3><p>Here we will create a database schema and later use it to create our class schema in part 2.</p><h4><strong>Writing the SQL</strong></h4><p>Open the file <em>scripts/schema.sql</em> and enter the following SQL statements.</p><pre><strong>DROP</strong> <strong>TABLE</strong> <strong>IF</strong> <strong>EXISTS</strong> users;</pre><pre><strong>CREATE</strong> <strong>TABLE</strong> users (<br>    id          INTEGER <strong>PRIMARY</strong> <strong>KEY</strong>,<br>    age         INTEGER <strong>NOT</strong> <strong>NULL</strong>,<br>    firstname   TEXT    <strong>NOT</strong> <strong>NULL</strong>,<br>    lastname    TEXT    <strong>NOT</strong> <strong>NULL</strong><br>);</pre><pre><strong>INSERT</strong> <strong>INTO</strong> users <strong>VALUES</strong> (<strong>NULL</strong>, 55, &#39;Bob&#39;, &#39;Doe&#39;);<br><strong>INSERT</strong> <strong>INTO</strong> users <strong>VALUES</strong> (<strong>NULL</strong>, 30, &#39;Sarah&#39;, &#39;Connor&#39;);</pre><h4><strong>Create the Database</strong></h4><p>Now lets create the database and its tables, and populate it with data in one go using SQLite. In the root directory enter the following command in your terminal.</p><pre>sqlite3 app.db &lt; scripts/schema.sql</pre><h4><strong>Verify the Database</strong></h4><p>To verify the database schema has been created, open the <em>app.db</em> database as follows.</p><pre>sqlite3 app.db</pre><p>Now select all the users in the <em>users</em> table.</p><pre>select * from users;</pre><p>The results should read as follows</p><pre>1|55|Bob|Doe<br>2|30|Sarah|Connor</pre><h3>Writing a Test</h3><p>Now some basic tests will be written to check whether our class schema exists and the modules within its namespace ‘work as intended’.</p><h4><strong>t/basic.t</strong></h4><p>Open the file <em>t/basic.t</em> and write the following:</p><pre>#!/usr/bin/env perl</pre><pre><strong>use</strong> strict;<br><strong>use</strong> warnings;</pre><pre><strong>use</strong> Test::More;<br></pre><pre><em># Check the schema exists</em><br>use_ok(&#39;App::Schema&#39;);</pre><pre><strong>my</strong> $schema  <strong>=</strong> App::Schema<strong>-&gt;</strong>connect(&#39;dbi:SQLite:app.db&#39;);<br><strong>my</strong> $user_rs <strong>=</strong> $schema<strong>-&gt;</strong>resultset(&#39;User&#39;);</pre><pre><em># Check custom accessors are defined</em><br>can_ok($user_rs<strong>-&gt;</strong>result_class, qw(fullname));</pre><pre>is($user_rs<strong>-&gt;</strong>find(1)<strong>-&gt;</strong>fullname,<br>  &#39;Bob Doe&#39;, &#39;Should read from set using custom accessor&#39;);</pre><pre><em># Check custom methods are defined</em><br>can_ok($user_rs, qw(age_less_than));</pre><pre>is($user_rs<strong>-&gt;</strong>age_less_than(50)<strong>-&gt;</strong>fullname,<br>  &#39;Sarah Connor&#39;, &#39;Should perform search using custom method&#39;);</pre><pre>done_testing;</pre><p>And that’s our test. Although commented I will briefly explain the entire file.</p><p>First <a href="https://metacpan.org/pod/Test::More#NAME">Test::More</a> is imported so we can use its functions <a href="https://metacpan.org/pod/Test::More#use_ok">use_ok</a>, <a href="https://metacpan.org/pod/Test::More#can_ok">can_ok</a> and <a href="https://metacpan.org/pod/Test::More#is">is</a> which it exports. Each of these functions is used to prove a test case.</p><ul><li>Next, our soon to be generated ‘App::Schema’ module is imported. Since it is not yet implemented the <em>use_ok</em> just below it will fail.</li><li>The next part is connecting to the database and creating a ResultSet instance for the User source. This is how we will interface with the user table in the second part of this article.</li><li>Finally the tests which follow use <em>can_ok</em> and <em>is</em>, to check whether a custom accessor <em>fullname</em> or method <em>age_less_than</em> have been defined first, before trying to use them.</li></ul><h4><strong>Run the Test</strong></h4><p>Now let’s run the test using prove and the flags <em>-l</em> which means check the <em>lib </em>directory for modules, and <em>-v</em> to provide verbose output.</p><pre>prove -lv t/basic.t</pre><p>The test should fail and the output should look similar to this:</p><pre>t/basic.t .. Can’t locate App/Schema.pm in @INC <strong>(</strong>you may need to install the App::Schema module<strong>)<br>...<br></strong>Result: FAIL</pre><p>The failure occurred because there is no App::Schema defined since it has not been generated yet. This will be done in <a href="https://medium.com/@kirklewis/learn-orm-in-perl-with-dbix-class-part-2-d339095e353">part 2</a>.</p><h3>Summary</h3><p>The sections above focused on getting the project set up, so that in the next part we can just focus on generating the class schema. One important file that was created here is <em>t/basic.t</em>, our test file. This will be used throughout the <a href="https://medium.com/@kirklewis/learn-orm-in-perl-with-dbix-class-part-2-d339095e353">second part</a> to check whether everything is working as intended.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7305957e1d8b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cultured-perl/learn-orm-in-perl-with-dbix-class-part-1-7305957e1d8b">Learn ORM in Perl with DBIx::Class - Part 1</a> was originally published in <a href="https://medium.com/cultured-perl">Cultured Perl</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>