def __get__(self, instance, owner): '''If there is no keyspace defined, we simply use the default keyspace''' value = super(KeyspaceProperty, self).__get__(instance, owner) if not value: try: return settings()["keyspace"] except KeyError: raise ConfigurationError("No default keyspace has been defined for homer")
def tearDown(self): '''Release resources that have been allocated''' try: print "Closing all open Cassandra resources." query = "DROP KEYSPACE IF EXISTS %s;" % settings()["keyspace"] CqlQuery(query=query).execute() Schema.clear() except Exception as e: print e
def query(self, **keywords): """Allows you to query for Model's that have specific properties""" assert keywords, "You must pass in keywords to the query function" limit = settings().get("limit", LIMIT) try: query = AutoCqlQuery(self.model).where(**keywords).limit(limit) return query except Exception as e: logging.exception(e) raise e
def build(self): '''Builds the final query from the internal fragments of this object''' if not self.__distinct_used and not self.__count_used: # IF DISTINCT AND COUNT ISN'T USED, THEN SELECT * self.__all = "*" else: self.__all = "" if not self.__limit_used: # IF NO LIMIT IS SPECIFIED, USE HOMER'S DEFAULT. self.limit(settings().get("limit", LIMIT)) instance = self.clasz() query = self.template.format( distinct=self.__distinct, count=self.__count, keyspace=instance.keyspace, kind=instance.kind(), all=self.__all, where=self.__where, orderby=self.__orderby, limit=self.__limit, filter=self.__filter ) self.query = query return self
def setUp(self): '''Create the Pool''' print "Creating a Pool with the default connections" self.pool = RoundRobinPool(settings())
def create(self): '''Creates the Keyspace and Model for self.keyspace and Model''' from homer.core.models import CqlProperty if Schema.contains(self.model): print("{model} has already been created before".format(model=self.model)) return # MAKE THE KEYSPACE q = """CREATE KEYSPACE IF NOT EXISTS {keyspace} WITH REPLICATION = {replication} AND DURABLE_WRITES = {durable};""" config = settings() replication = config.get("strategy", None) durable = config.get("durable", True) if not replication: raise ConfigurationError("No replication strategy specified.") replication = '{' + ', '.join([quote(k) + ':' + quote(v) for k,v in replication.items()]) + '}' print("GOT REPLICATION CONFIGURATION: " + replication) keyspace = self.model.keyspace durable = str(durable).lower() q = q.format(keyspace=keyspace, replication=replication, durable=durable) try: print("Creating keyspace: {0}".format(q)) CqlQuery(query=q).execute() except Exception as e: logging.exception(e) # raise e # FIND ALL THE CQLPROPERTY DESCRIPTORS FROM THIS MODEL. properties = fields(self.model, CqlProperty) # BUILD THE CQL3 QUERY FOR MAKING THE TABLE. id, type = False, None columns = [] keys = [] for name, property in properties.items(): if name == "id": id = True type = property.ctype else: fragment = "{0} {1}".format(name, property.ctype) columns.append(fragment) if property.key: keys.append(name) # CONSTRUCT THE QUERY STRING FOR CREATING TABLES. q = """ CREATE TABLE IF NOT EXISTS {keyspace}.{kind} ( {key} {columns} {keys} ); """ assert id, "Every Model must have an id property" if keys: keys = sorted(keys) keys.insert(0, "id") columns.append("{0} {1}".format("id", type)) keys = ", PRIMARY KEY(" + ",".join(keys) + ")" key = "" else: keys = "" key = "id {type} PRIMARY KEY,".format(type=type) values = {"columns" : ",".join(sorted(columns))} values["key"] = key values["keys"] = keys values["kind"] = self.model.kind() values["keyspace"] = self.model.keyspace values["type"] = type query = q.format(**values) try: print("Creating Table for Model with Query: " + query) CqlQuery(query=query).execute() except Exception as e: logging.exception(e) raise e # BUILD INDEXES, FOR EACH INDEXABLE PROPERTY. q = "CREATE INDEX IF NOT EXISTS {name} ON {keyspace}.{kind}({name});" for name, property in properties.items(): if name == "id": continue if property.indexed() and not property.key: query = q.format(name=name, keyspace=self.model.keyspace, kind=self.model.kind()) try: CqlQuery(query=query).execute() except Exception as e: logging.exception(e) raise e # If everything goes well, mark this model as created by adding it to the global schema cache. Schema.add(self.model)
def setUp(self): self.pool = RoundRobinPool(settings())