
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.core.context_processors import csrf
from django.conf import settings

from json import dumps as to_json
from uuid import UUID

import cql
from cql.results import ResultSet
 
import threading

__local = threading.local()

def __get_cursor():
    return cql.connect(settings.CASSANDRA_HOST,
                       settings.CASSANDRA_PORT).cursor()

def __execute(query, keyspace=None):
    # Lazily assign a cursor instance to a thread-local variable
    if not hasattr(__local, "cursor") or not getattr(__local, "cursor"):
        __local.cursor = __get_cursor()
    if keyspace:
        __local.cursor.execute("USE " + keyspace)
        
    __local.cursor.execute(query)
    return __local.cursor

def __serialize(cursor):
    def marshal(value):
        if isinstance(value, UUID):
            return str(value)
        return value
        
    if isinstance(cursor.result, ResultSet):
        rows = {}
        for row in cursor.result.rows:
            rows[row.key] = []
            for col in row.columns:
                rows[row.key].append(
                    {"name": marshal(col.name), "value": marshal(col.value)})
        return to_json({"rows": rows})
    else:
        return to_json({"void": "Success"})

# View methods
def index(request):
    return render_to_response("index.html", csrf(request))

def query(request):
    query_string = request.POST['post_data']
    try:
        if query_string.upper().startswith("USE"):
            __execute(query_string)
            keyspace = query_string.split()[1].strip(";")

            # Giving people access to the system keyspace would be Bad
            if keyspace == "system":
                raise cql.DatabaseError("No. Not as stupid as I look.");

            request.session["current_keyspace"] = keyspace
            json = to_json({"void": "Using keyspace %s" % keyspace})
        elif query_string.split()[1].upper().startswith("COUNT"):
            current_keyspace = request.session.get("current_keyspace", None)
            cursor = __execute(query_string, current_keyspace)
            json = to_json({"int": cursor.result[0][0]})
        else:
            current_keyspace = request.session.get("current_keyspace", None)
            cursor = __execute(query_string, current_keyspace)
            json = __serialize(cursor)
    except cql.DatabaseError, error:
        json = to_json({"exception": str(error)})
    return HttpResponse(json, mimetype="application/json")
    
def describe_keyspaces(request):
    schema = __get_cursor().decoder.schema    # you gotta keep 'em violated
    del schema["system"]
    return HttpResponse(to_json(schema), mimetype="application/json")



@@ -336,22 +336,103 @@
 ():%0A    
-return
+if not hasattr(__local, %22conn%22) or not getattr(__local, %22conn%22):%0A        __local.conn =
  cql.con
@@ -484,16 +484,28 @@
         
+   
+         
 settings
@@ -520,16 +520,40 @@
 RA_PORT)
+%0A    return __local.conn
 .cursor(
@@ -665,93 +665,8 @@
     
-if not hasattr(__local, %22cursor%22) or not getattr(__local, %22cursor%22):%0A        __local.
 curs
@@ -706,32 +706,24 @@
 ce:%0A        
-__local.
 cursor.execu
@@ -757,24 +757,16 @@
    %0A    
-__local.
 cursor.e
@@ -790,24 +790,16 @@
  return 
-__local.
 cursor%0A%0A
@@ -876,20 +876,27 @@
 (value, 
+(
 UUID
+,long)
 ):%0A     
@@ -1029,23 +1029,27 @@
 for 
-row
+x
  in 
+range(
 cursor.r
 esul
@@ -1048,19 +1048,51 @@
 or.r
-esult.rows:
+owcount):%0A            r = cursor.fetchone()
 %0A   
@@ -1106,22 +1106,19 @@
   rows%5Br
-ow.key
+%5B0%5D
 %5D = %5B%5D%0A 
@@ -1136,86 +1136,138 @@
 for 
-col in row.columns:%0A                rows%5Brow.key%5D.append(%0A                    
+(j, column_value) in enumerate(r%5B1:%5D):%0A                column_name = cursor.description%5Bj+1%5D%5B0%5D%0A                rows%5Br%5B0%5D%5D.append(
 %7B%22na
@@ -1286,15 +1286,38 @@
 (col
-.
+umn_
 name),
+%0A                   
  %22va
@@ -1333,17 +1333,20 @@
 shal(col
-.
+umn_
 value)%7D)

fix buggy usage of dbapi2 interface