diff database.rb @ 0:1eef88068f9f tip

initial commit of maze game source
author ferencd
date Sun, 15 Sep 2019 11:46:47 +0200
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/database.rb	Sun Sep 15 11:46:47 2019 +0200
@@ -0,0 +1,96 @@
+require 'utils'
+require 'gs_logger'
+
+#
+# This class is responsible for handling all database related requests
+#
+
+class Database
+
+  private_class_method :new
+
+  def Database.initialize
+
+    @@conn = PG::Connection.new(:dbname => 'mazedb', :user => 'mazedb', :password => 's321851gper')
+
+    @@conn.prepare('ins_prep_stmt', 'insert into games (level_id, level_number,level_type) values ($1,$2,$3)')
+    @@conn.prepare('sel_for_game_id_prep_stmt', 'select * from games where level_id=$1')
+    @@conn.prepare('sel_level_no_prep_stmt', 'select level_number from games where level_id=$1')
+    @@conn.prepare('upd_prep_stmt', 'update games set level_number=$1 where level_id=$2')
+
+    $LOG.info 'Database initialized'
+  rescue => ex
+    $LOG.fatal "Exception caught while preparing the statements: #{ex.class.to_s}\n"
+    exit 1
+  end
+
+  #
+  # Inserts a game ID into the database
+  #
+  def Database.insert_game_id_to_db(game_id, lev_no, gam_type)
+    @@conn.exec_prepared 'ins_prep_stmt', ["#{game_id}", lev_no, gam_type]
+  rescue => ex
+    $LOG.error "Exception caught: #{ex.class.to_s}\n"
+    raise
+  end
+
+  #
+  # Creates a valid game ID by assuring no duplicates in the database
+  #
+  def Database.create_valid_game_id (game_type)
+    game_id = game_type + Utils.random_string(8)
+    # Create a unique ID for the current level
+    loop do
+      begin
+        res = @@conn.exec_prepared 'sel_for_game_id_prep_stmt', ["#{game_id}"]
+      rescue => ex
+        $LOG.error "Exception caught: #{ex.class.to_s}\n"
+        raise
+      end
+
+      break if res.cmd_tuples == 0
+      res.clear
+      game_id = 'S' + Utils.random_string(8)
+
+    end
+    game_id
+  end
+
+  #
+  # Returns the level to which this gid is associated
+  #
+  def Database.get_db_level_for_gid(gid)
+    level_no = 1
+    loop do
+      begin
+        res = @@conn.exec_prepared 'sel_level_no_prep_stmt', ["#{gid}"]
+      rescue => ex
+        $LOG.error "Exception caught: #{ex.class.to_s}\n"
+        raise
+      end
+      return -1 if res.cmd_tuples == 0
+      level_no = res[0]
+      res.clear
+      break
+    end
+    level_no['level_number'].to_i
+  end
+
+  #
+  # Updates the level number for the given game ID to reflect th current state
+  #
+  def Database.update_level_number_for_gid(level_number, gid)
+    loop do
+      begin
+        res = @@conn.exec_prepared 'upd_prep_stmt', [level_number, "#{gid}"]
+      rescue => ex
+        $LOG.error "Exception caught: #{ex.class.to_s}\n"
+        raise
+      end
+      break if res.cmd_tuples == 0
+      res.clear
+      break
+    end
+  end
+
+end