Skip to content

Loading…

Initial try at implementing text_counter #3

Merged
merged 1 commit into from

2 participants

@kaoru

Warning: this code written by somebody has never used SQLite so it's
probably horrific. Somebody come along and tidy up after me please :-)

Specifically I'm sure there must be a less crappy way to do the "update count and get count back" in a single query...?

Time to go get some lunch! #ye2013 ;)

@kaoru kaoru 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 :-)
5edea73
@davorg davorg merged commit 0508e98 into davorg:master
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Aug 13, 2013
  1. @kaoru

    Initial try at implementing text_counter

    kaoru committed
    Warning: this code written by somebody has never used SQLite so it's
    probably horrific. Somebody come along and tidy up after me please :-)
Showing with 64 additions and 0 deletions.
  1. +64 −0 text_counter/counter.psgi
View
64 text_counter/counter.psgi
@@ -0,0 +1,64 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+use 5.010;
+
+use Dancer;
+use DBI;
+use File::Spec;
+use FindBin;
+use Data::Dumper;
+
+my $dbh = init_db_connection();
+
+get '/' => sub {
+ my $count = increment_and_get_count($dbh);
+ return $count;
+};
+
+dance;
+
+#######################################
+
+sub init_db_connection {
+ # connect to the SQLite database
+ my $counter_db_file = File::Spec->catfile($FindBin::Bin, 'counter.db');
+ my $dbh = DBI->connect(
+ "dbi:SQLite:dbname=${counter_db_file}", # data source
+ "", # username
+ "", # password
+ { RaiseError => 1 }, # throw exceptions on failure
+ ) or die "Failed to connect to SQLite DB: $DBI::errstr";
+
+ # maybe initialize
+ maybe_initialize_db($dbh);
+
+ return $dbh;
+}
+
+sub maybe_initialize_db {
+ my $dbh = shift;
+
+ $dbh->do("CREATE TABLE IF NOT EXISTS Count(count INT DEFAULT 0);");
+
+ my $sth = $dbh->prepare("SELECT count FROM Count;");
+ $sth->execute();
+ if (!$sth->fetchrow()) {
+ $dbh->do("INSERT INTO Count VALUES(0)");
+ }
+
+ return;
+}
+
+sub increment_and_get_count {
+ my $dbh = shift;
+
+ $dbh->do("UPDATE Count SET count = count + 1;");
+
+ my $sth = $dbh->prepare("SELECT count FROM Count;");
+ $sth->execute();
+ my ($count) = $sth->fetchrow();
+
+ return $count;
+}
Something went wrong with that request. Please try again.