Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Initial try at implementing text_counter

Warning: this code written by somebody has never used SQLite so it's
probably horrific. Somebody come along and tidy up after me please :-)
  • Loading branch information...
commit ffa884c25ca950b6750847e72d11608966bc4dc4 1 parent 6ec638e
Alex Balhatchet authored August 13, 2013

Showing 1 changed file with 64 additions and 0 deletions. Show diff stats Hide diff stats

  1. 64  text_counter/counter.psgi
64  text_counter/counter.psgi
... ...
@@ -0,0 +1,64 @@
  1
+#!/usr/bin/perl
  2
+
  3
+use strict;
  4
+use warnings;
  5
+use 5.010;
  6
+
  7
+use Dancer;
  8
+use DBI;
  9
+use File::Spec;
  10
+use FindBin;
  11
+use Data::Dumper;
  12
+
  13
+my $dbh = init_db_connection();
  14
+
  15
+get '/' => sub {
  16
+    my $count = increment_and_get_count($dbh);
  17
+    return $count;
  18
+};
  19
+
  20
+dance;
  21
+
  22
+#######################################
  23
+
  24
+sub init_db_connection {
  25
+    # connect to the SQLite database
  26
+    my $counter_db_file = File::Spec->catfile($FindBin::Bin, 'counter.db');
  27
+    my $dbh = DBI->connect(
  28
+        "dbi:SQLite:dbname=${counter_db_file}", # data source
  29
+        "",                                     # username
  30
+        "",                                     # password
  31
+        { RaiseError => 1 },                    # throw exceptions on failure
  32
+    ) or die "Failed to connect to SQLite DB: $DBI::errstr";
  33
+
  34
+    # maybe initialize
  35
+    maybe_initialize_db($dbh);
  36
+
  37
+    return $dbh;
  38
+}
  39
+
  40
+sub maybe_initialize_db {
  41
+    my $dbh = shift;
  42
+
  43
+    $dbh->do("CREATE TABLE IF NOT EXISTS Count(count INT DEFAULT 0);");
  44
+
  45
+    my $sth = $dbh->prepare("SELECT count FROM Count;");
  46
+    $sth->execute();
  47
+    if (!$sth->fetchrow()) {
  48
+        $dbh->do("INSERT INTO Count VALUES(0)");
  49
+    }
  50
+
  51
+    return;
  52
+}
  53
+
  54
+sub increment_and_get_count {
  55
+    my $dbh = shift;
  56
+
  57
+    $dbh->do("UPDATE Count SET count = count + 1;");
  58
+
  59
+    my $sth = $dbh->prepare("SELECT count FROM Count;");
  60
+    $sth->execute();
  61
+    my ($count) = $sth->fetchrow();
  62
+
  63
+    return $count;
  64
+}

0 notes on commit ffa884c

Please sign in to comment.
Something went wrong with that request. Please try again.