Acme-CPANModulesBundle-Import-MojoliciousAdvent-2017
view release on metacpan or search on metacpan
devdata/https_mojolicious.io_blog_2017_12_18_day-18-the-wishlist-model view on Meta::CPAN
where items.user_id=user.id
)
) as items
from users user
where user.name=?
<span class="hljs-keyword"> SQL</span>
<span class="hljs-keyword">return</span> <span class="hljs-type">$self</span><span class="hljs-type">
</span> ->sqlite
->db
->query(<span class="hljs-type">$sql</span>, <span class="hljs-type">$name</span>)
->expand(json => '<span class="hljs-string">items</span>')
->hash;
}
<span class="hljs-keyword">sub </span><span class="hljs-function">list_user_names</span> {
<span class="hljs-keyword">my</span> <span class="hljs-type">$self</span> = <span class="hljs-function">shift</span>;
<span class="hljs-keyword">return</span> <span class="hljs-type">$self</span><span class="hljs-type">
</span> ->sqlite
->db
-><span class="hljs-function">select</span>(
'<span class="hljs-string">users</span>' => ['<span class="hljs-string">name</span>'],
devdata/https_mojolicious.io_blog_2017_12_18_day-18-the-wishlist-model view on Meta::CPAN
<p>This class define the ways that the application can alter the data in the database.
Rather than the familiar DBI methods like <code>selectrow_arrayref</code>, Mojo-Flavored DBI make a query and then ask for the result shape they want returned.
The user can ask for a row as a hash or an array.
They can also ask for and array of all thr rows, again as a hash or an array.
Sometimes there are other data you want rather than the actual results, like the <code>last_insert_id</code> or the number of <code>rows</code> affected.</p>
<p>Most of the methods are simple enough to employ the SQL::Abstract forms: add, update, remove, even listing the users.
However for getting a user we want to make a more complex <code>query</code> by hand.
It looks up the user row by name, and aggregates the items that user is wishing for as JSON.</p>
<p>Before fetching the results we tell Mojo::SQLite that we would like to expand the JSON back into Perl data transparently.
This <a href="https://metacpan.org/pod/Mojo::SQLite::Results#expand"><code>expand</code></a> method differs slightly from the other flavors since SQLite doesn't have metadata to give Mojo::SQLite hints about which column to expand.
Once setup, when we call <code>hash</code> we get a nice Perl structure as a result.</p>
<h2>The Application Class</h2>
<p>The application class might look quite different but its behavior is very similar to yesterday.
Don't fret over every line, I will only cover the important things for our purposes.</p>
<pre><code class="hljs"><span class="hljs-keyword">package</span> Wishlist;
<span class="hljs-keyword">use</span> <span class="hljs-function">Mojo::Base</span> '<span class="hljs-string">Mojolicious</span>';
( run in 0.646 second using v1.01-cache-2.11-cpan-5b529ec07f3 )