code
stringlengths
1
18.2k
def upgradeItem(self, thisItem): """ Upgrade a legacy item. @raise axiom.errors.UpgraderRecursion: If the given item is already in the process of being upgraded. """ sid = thisItem.storeID if sid in self._currentlyUpgrading: raise UpgraderRecursion() self._currentlyUpgrading[sid] = thisItem try: return upgradeAllTheWay...
def upgradeBatch(self, n): """ Upgrade the entire store in batches, yielding after each batch. @param n: Number of upgrades to perform per transaction @type n: C{int} @raise axiom.errors.ItemUpgradeError: if an item upgrade failed @return: A generator that yields after each batch upgrade. This needs to be consumed for ...
in store.query(itemType, limit=n): upgradedAnything = True try: self.upgradeItem(theItem) except: f = Failure() raise ItemUpgradeError( f, theItem.storeID, itemType, _typeNameToMostRecentClass[itemType.typeName]) return upgradedAnything if self.upgradesPending: didAny = False while self._oldTypesRemaining: t0 = self._o...
completely upgraded." % (store.dbdir.path,))
def open(self): """ Obtains the lvm, vg_t and lv_t handle. Usually you would never need to use this method unless you are doing operations using the ctypes function wrappers in conversion.py *Raises:* * HandleError """ self.vg.open() self.__lvh = lvm_lv_from_uuid(self.vg.handle, self.uuid) if not bool(self.__lvh): rais...
def name(self): """ Returns the logical volume name. """ self.open() name = lvm_lv_get_name(self.__lvh) self.close() return name
def is_active(self): """ Returns True if the logical volume is active, False otherwise. """ self.open() active = lvm_lv_is_active(self.__lvh) self.close() return bool(active)
def is_suspended(self): """ Returns True if the logical volume is suspended, False otherwise. """ self.open() susp = lvm_lv_is_suspended(self.__lvh) self.close() return bool(susp)
def size(self, units="MiB"): """ Returns the logical volume size in the given units. Default units are MiB. *Args:* * units (str): Unit label ('MiB', 'GiB', etc...). Default is MiB. """ self.open() size = lvm_lv_get_size(self.__lvh) self.close() return size_convert(size, units)
def activate(self): """ Activates the logical volume. *Raises:* * HandleError """ self.open() a = lvm_lv_activate(self.handle) self.close() if a != 0: raise CommitError("Failed to activate LV.")
def deactivate(self): """ Deactivates the logical volume. *Raises:* * HandleError """ self.open() d = lvm_lv_deactivate(self.handle) self.close() if d != 0: raise CommitError("Failed to deactivate LV.")
def open(self): """ Obtains the lvm, vg_t and pv_t handle. Usually you would never need to use this method unless you are doing operations using the ctypes function wrappers in conversion.py *Raises:* * HandleError """ self.vg.open() self.__pvh = lvm_pv_from_uuid(self.vg.handle, self.uuid) if not bool(self.__pvh): rais...
def name(self): """ Returns the physical volume device path. """ self.open() name = lvm_pv_get_name(self.handle) self.close() return name
def mda_count(self): """ Returns the physical volume mda count. """ self.open() mda = lvm_pv_get_mda_count(self.handle) self.close() return mda
def size(self, units="MiB"): """ Returns the physical volume size in the given units. Default units are MiB. *Args:* * units (str): Unit label ('MiB', 'GiB', etc...). Default is MiB. """ self.open() size = lvm_pv_get_size(self.handle) self.close() return size_convert(size, units)
def dev_size(self, units="MiB"): """ Returns the device size in the given units. Default units are MiB. *Args:* * units (str): Unit label ('MiB', 'GiB', etc...). Default is MiB. """ self.open() size = lvm_pv_get_dev_size(self.handle) self.close() return size_convert(size, units)
def free(self, units="MiB"): """ Returns the free size in the given units. Default units are MiB. *Args:* * units (str): Unit label ('MiB', 'GiB', etc...). Default is MiB. """ self.open() size = lvm_pv_get_free(self.handle) self.close() return size_convert(size, units)
def mongoengine_validate_wrapper(old_clean, new_clean): """ A wrapper function to validate formdata against mongoengine-field validator and raise a proper django.forms ValidationError if there are any problems. """ def inner_validate(value): value = old_clean(value) try: new_clean(value) return value except ValidationE...
def iter_valid_fields(meta): """walk through the available valid fields..""" # fetch field configuration and always add the id_field as exclude meta_fields = getattr(meta, 'fields', ()) meta_exclude = getattr(meta, 'exclude', ()) meta_exclude += (meta.document._meta.get('id_field'),) # walk through meta_fields or throu...
for field_name, field in meta.document._fields.iteritems(): # skip excluded fields if field_name not in meta_exclude: yield (field_name, field)
def dependsOn(itemType, itemCustomizer=None, doc='', indexed=True, whenDeleted=reference.NULLIFY): """ This function behaves like L{axiom.attributes.reference} but with an extra behaviour: when this item is installed (via L{axiom.dependency.installOn} on a target item, the type named here will be instantiated and insta...
@param itemCustomizer: A callable that accepts the item installed as a dependency as its first argument. It will be called only if an item is created to satisfy this dependency. @return: An L{axiom.attributes.reference} instance. """ frame = sys._getframe(1) locals = frame.f_locals # Try to make sure we were called fro...
can be used only from a class definition.") ref = reference(reftype=itemType, doc=doc, indexed=indexed, allowNone=True, whenDeleted=whenDeleted) if "__dependsOn_advice_data__" not in locals: addClassAdvisor(_dependsOn_advice) locals.setdefault('__dependsOn_advice_data__', []).append( (itemType, itemCustomizer, ref)) re...
def uninstallFrom(self, target): """ Remove this object from the target, as well as any dependencies that it automatically installed which were not explicitly "pinned" by calling "install", and raising an exception if anything still depends on this. """ #did this class powerup on any interfaces? powerdown if so. target...
uninstallFrom(item, target) callback = getattr(self, "uninstalled", None) if callback is not None: callback()
def installedOn(self): """ If this item is installed on another item, return the install target. Otherwise return None. """ try: return self.store.findUnique(_DependencyConnector, _DependencyConnector.installee == self ).target except ItemNotFound: return None
def installedDependents(self, target): """ Return an iterable of things installed on the target that require this item. """ for dc in self.store.query(_DependencyConnector, _DependencyConnector.target == target): depends = dependentsOf(dc.installee.__class__) if self.__class__ in depends: yield dc.installee
def installedUniqueRequirements(self, target): """ Return an iterable of things installed on the target that this item requires and are not required by anything else. """ myDepends = dependentsOf(self.__class__) #XXX optimize? for dc in self.store.query(_DependencyConnector, _DependencyConnector.target==target): if dc....
still depends on it" % (self, target, dc.installee)) for cls in myDepends[:]: #If one of my dependencies is required by somebody #else, leave it alone if cls in depends: myDepends.remove(cls) for dc in self.store.query(_DependencyConnector, _DependencyConnector.target==target): if (dc.installee.__class__ in myDepends a...
def installedRequirements(self, target): """ Return an iterable of things installed on the target that this item requires. """ myDepends = dependentsOf(self.__class__) for dc in self.store.query(_DependencyConnector, _DependencyConnector.target == target): if dc.installee.__class__ in myDepends: yield dc.installee
def storeServiceSpecialCase(st, pups): """ Adapt a store to L{IServiceCollection}. @param st: The L{Store} to adapt. @param pups: A list of L{IServiceCollection} powerups on C{st}. @return: An L{IServiceCollection} which has all of C{pups} as children. """ if st.parent is not None: # If for some bizarre reason we're st...
# risk starting the upgrader run twice. (XXX: it *IS* possible to # figure out whether we need to or not, I just doubt this will ever # even happen in practice -- fix here if it does) return serviceSpecialCase(st, pups) if st._axiom_service is not None: # not new, don't add twice. return st._axiom_service collection = ...
from axiom import batch batcher = batch.BatchProcessingControllerService(st) batcher.setServiceParent(collection) scheduler = iaxiom.IScheduler(st) # If it's an old database, we might get a SubScheduler instance. It has no # setServiceParent method. setServiceParent = getattr(scheduler, 'setServiceParent', None) if set...
def _schedulerServiceSpecialCase(empowered, pups): """ This function creates (or returns a previously created) L{IScheduler} powerup. If L{IScheduler} powerups were found on C{empowered}, the first of those is given priority. Otherwise, a site L{Store} or a user L{Store} will have any pre-existing L{IScheduler} powerup...
import _SiteScheduler, _UserScheduler # Give precedence to anything found in the store for pup in pups: return pup # If the empowered is a store, construct a scheduler for it. if isinstance(empowered, Store): if getattr(empowered, '_schedulerService', None) is None: if empowered.parent is None: sched = _SiteScheduler(e...
def _diffSchema(diskSchema, memorySchema): """ Format a schema mismatch for human consumption. @param diskSchema: The on-disk schema. @param memorySchema: The in-memory schema. @rtype: L{bytes} @return: A description of the schema differences. """ diskSchema = set(diskSchema) memorySchema = set(memorySchema) diskOnly =...
return '\n'.join(diff)
def close(self): """ Close this file and commit it to its permanent location. @return: a Deferred which fires when the file has been moved (and backed up to tertiary storage, if necessary). """ now = time.time() try: file.close(self) _mkdirIfNotExists(self._destpath.dirname()) self.finalpath = self._destpath os.rename(...
def explain(self): """ A debugging API, exposing SQLite's I{EXPLAIN} statement. While this is not a private method, you also probably don't have any use for it unless you understand U{SQLite opcodes<http://www.sqlite.org/opcode.html>} very well. Once you do, it can be handy to call this interactively to get a sense of ...
L{str} (the SQL statement which will be run), and the remainder of which is 3-tuples resulting from the I{EXPLAIN} of that statement. """ return ([self._sqlAndArgs('SELECT', self._queryTarget)[0]] + self._runQuery('EXPLAIN SELECT', self._queryTarget))
def _computeFromClause(self, tables): """ Generate the SQL string which follows the "FROM" string and before the "WHERE" string in the final SQL statement. """ tableAliases = [] self.fromClauseParts = [] for table in tables: # The indirect calls to store.getTableName() will create the tables # if needed. (XXX That's ba...
table.getTableName(self.store) tableAlias = table.getTableAlias(self.store, tuple(tableAliases)) if tableAlias is None: self.fromClauseParts.append(tableName) else: tableAliases.append(tableAlias) self.fromClauseParts.append('%s AS %s' % (tableName, tableAlias)) self.sortClauseParts = [] for attr, direction in self.sor...
def _selectStuff(self, verb='SELECT'): """ Return a generator which yields the massaged results of this query with a particular SQL verb. For an attribute query, massaged results are of the type of that attribute. For an item query, they are items of the type the query is supposed to return. @param verb: a str containi...
variant of 'SELECT', the only two currently implemented being 'SELECT' and 'SELECT DISTINCT'. """ sqlResults = self._runQuery(verb, self._queryTarget) for row in sqlResults: yield self._massageData(row)
def next(self): """ This method is deprecated, a holdover from when queries were iterators, rather than iterables. @return: one element of massaged data. """ if self._selfiter is None: warnings.warn( "Calling 'next' directly on a query is deprecated. " "Perhaps you want to use iter(query).next(), or something " "more e...
def paginate(self, pagesize=20): """ Split up the work of gathering a result set into multiple smaller 'pages', allowing very large queries to be iterated without blocking for long periods of time. While simply iterating C{paginate()} is very similar to iterating a query directly, using this method allows the work to o...
@param pagesize: the number of results gather in each chunk of work. (This is mostly for testing paginate's implementation.) @type pagesize: L{int} @return: an iterable which yields all the results of this query. """ sort = self.sort oc = list(sort.orderColumns()) if not oc: # You can't have an unsorted pagination. sor...
supported yet with paginate" %(len(oc),)) sortColumn = oc[0][0] if oc[0][1] == 'ASC': sortOp = operator.gt else: sortOp = operator.lt if _isColumnUnique(sortColumn): # This is the easy case. There is never a tie to be broken, so we # can just remember our last value and yield from there. Right now # this only happens w...
the future we will have more of this. tiebreaker = None else: tiebreaker = self.tableClass.storeID tied = lambda a, b: (sortColumn.__get__(a) == sortColumn.__get__(b)) def _AND(a, b): if a is None: return b return attributes.AND(a, b) results = list(self.store.query(self.tableClass, self.comparison, sort=sort, limit=pa...
1, there's no next result to test for a tie with, so we # must be at the end, and we should just yield the result and finish. yield results[0] return for resultidx in range(len(results) - 1): # check for a tie. result = results[resultidx] nextResult = results[resultidx + 1] if tied(result, nextResult): # Yield any ties...
tiebreaker.__get__(result) # Note that this query is _NOT_ limited: currently large ties # will generate arbitrarily large amounts of work. trq = self.store.query( self.tableClass, _AND(self.comparison, sortColumn == sortColumn.__get__(result))) tiedResults = list(trq) tiedResults.sort(key=lambda rslt: (sortColumn.__ge...
sortColumn.__get__(result) # hooray namespace pollution results = list(self.store.query( self.tableClass, _AND(self.comparison, sortOp(sortColumn, sortColumn.__get__(result))), sort=sort, limit=pagesize + 1))
def _massageData(self, row): """ Convert a row into an Item instance by loading cached items or creating new ones based on query results. @param row: an n-tuple, where n is the number of columns specified by my item type. @return: an instance of the type specified by this query. """ result = self.store._loadedItem(self...
store" % (result,) return result
def getColumn(self, attributeName, raw=False): """ Get an L{iaxiom.IQuery} whose results will be values of a single attribute rather than an Item. @param attributeName: a L{str}, the name of a Python attribute, that describes a column on the Item subclass that this query was specified for. @return: an L{AttributeQuery}...
results will be instances of. """ # XXX: 'raw' is undocumented because I think it's completely unused, # and it's definitely untested. It should probably be removed when # someone has the time. -glyph # Quotient POP3 server uses it. Not that it shouldn't be removed. # ;) -exarkun attr = getattr(self.tableClass, attribu...
def deleteFromStore(self): """ Delete all the Items which are found by this query. """ if (self.limit is None and not isinstance(self.sort, attributes.UnspecifiedOrdering)): # The ORDER BY is pointless here, and SQLite complains about it. return self.cloneQuery(sort=None).deleteFromStore() #We can do this the fast way ...
to do it the slow way. deletedOverridden = ( self.tableClass.deleted.im_func is not item.Item.deleted.im_func) deleteFromStoreOverridden = ( self.tableClass.deleteFromStore.im_func is not item.Item.deleteFromStore.im_func) if deletedOverridden or deleteFromStoreOverridden: for it in self: it.deleteFromStore() else: # F...
not item.allowDeletion(self.store, self.tableClass, itemsToDelete): raise errors.DeletionDisallowed( 'Cannot delete item; ' 'has referents with whenDeleted == reference.DISALLOW') for it in item.dependentItems(self.store, self.tableClass, itemsToDelete): it.deleteFromStore() # actually run the DELETE for the items in t...
def _involvedTables(self): """ Return a list of tables involved in this query, first checking that no required tables (those in the query target) have been omitted from the comparison. """ # SQL and arguments if self.comparison is not None: tables = self.comparison.getInvolvedTables() self.args = self.comparison.getArg...
omits required reference to result type %s" % tableClass.typeName) return tables
def _massageData(self, row): """ Convert a row into a tuple of Item instances, by slicing it according to the number of columns for each instance, and then proceeding as for ItemQuery._massageData. @param row: an n-tuple, where n is the total number of columns specified by all the item types in this query. @return: a t...
""" offset = 0 resultBits = [] for i, tableClass in enumerate(self.tableClass): numAttrs = self.schemaLengths[i] result = self.store._loadedItem(self.tableClass[i], row[offset], row[offset+1:offset+numAttrs]) assert result.store is not None, "result %r has funky store" % (result,) resultBits.append(result) offset += nu...
def cloneQuery(self, limit=_noItem, sort=_noItem): """ Clone the original query which this distinct query wraps, and return a new wrapper around that clone. """ newq = self.query.cloneQuery(limit=limit, sort=sort) return self.__class__(newq)
def count(self): """ Count the number of distinct results of the wrapped query. @return: an L{int} representing the number of distinct results. """ if not self.query.store.autocommit: self.query.store.checkpoint() target = ', '.join([ tableClass.storeID.getColumnName(self.query.store) for tableClass in self.query.table...
one result: %r' % (result,) return result[0][0] or 0
def _massageData(self, row): """ Convert a raw database row to the type described by an attribute. For example, convert a database integer into an L{extime.Time} instance for an L{attributes.timestamp} attribute. @param row: a 1-tuple, containing the in-database value from my attribute. @return: a value of the type des...
def sum(self): """ Return the sum of all the values returned by this query. If no results are specified, return None. Note: for non-numeric column types the result of this method will be nonsensical. @return: a number or None. """ res = self._runQuery('SELECT', 'SUM(%s)' % (self._queryTarget,)) or [(0,)] assert len(res...
return self.attribute.outfilter(dbval, _FakeItemForFilter(self.store))
def average(self): """ Return the average value (as defined by the AVG implementation in the database) of the values specified by this query. Note: for non-numeric column types the result of this method will be nonsensical. @return: a L{float} representing the 'average' value of this column. """ rslt = self._runQuery('...
% (rslt,) return rslt[0][0]
def _attachChild(self, child): "attach a child database, returning an identifier for it" self._childCounter += 1 databaseName = 'child_db_%d' % (self._childCounter,) self._attachedChildren[databaseName] = child # ATTACH DATABASE statements can't use bind paramaters, blech. self.executeSQL("ATTACH DATABASE '%s' AS %s" %...
def _startup(self): """ Called during __init__. Check consistency of schema in database with classes in memory. Load all Python modules for stored items, and load version information for upgrader service to run later. """ typesToCheck = [] for oid, module, typename, version in self.querySchemaSQL(_schema.ALL_TYPES): if...
raise ImportError('cannot find module ' + module, str(err)) self.typenameAndVersionToID[typename, version] = oid # Can't call this until typenameAndVersionToID is populated, since this # depends on building a reverse map of that. persistedSchema = self._loadTypeSchema() # Now that we have persistedSchema, loop over eve...
version != cls.schemaVersion: typesToCheck.append( self._prepareOldVersionOf( typename, version, persistedSchema)) else: typesToCheck.append(cls) for cls in typesToCheck: self._checkTypeSchemaConsistency(cls, persistedSchema) # Schema is consistent! Now, if I forgot to create any indexes last # time I saw this table, d...
def findOrCreate(self, userItemClass, __ifnew=None, **attrs): """ Usage:: s.findOrCreate(userItemClass [, function] [, x=1, y=2, ...]) Example:: class YourItemType(Item): a = integer() b = text() c = integer() def f(x): print x, \"-- it's new!\" s.findOrCreate(YourItemType, f, a=1, b=u'2') Search for an item with colum...
with the given attributes if not. Takes an optional positional argument function to call on the new item if it is new. """ andargs = [] for k, v in attrs.iteritems(): col = getattr(userItemClass, k) andargs.append(col == v) if len(andargs) == 0: cond = [] elif len(andargs) == 1: cond = [andargs[0]] else: cond = [attrib...
= userItemClass(store=self, **attrs) if __ifnew is not None: __ifnew(newItem) return newItem
def newFile(self, *path): """ Open a new file somewhere in this Store's file area. @param path: a sequence of path segments. @return: an L{AtomicFile}. """ assert len(path) > 0, "newFile requires a nonzero number of segments" if self.dbdir is None: if self.filesdir is None: raise RuntimeError("This in-memory store has ...
".tmp") return AtomicFile(tmpname.path, self.newFilePath(*path))
def _loadTypeSchema(self): """ Load all of the stored schema information for all types known by this store. It's important to load everything all at once (rather than loading the schema for each type separately as it is needed) to keep store opening fast. A single query with many results is much faster than many querie...
two-tuples of item type name and schema version as keys and lists of five-tuples of attribute schema information for that type. The elements of the five-tuple are:: - a string giving the name of the Python attribute - a string giving the SQL type - a boolean indicating whether the attribute is indexed - the Python attr...
giving documentation for the attribute """ # Oops, need an index going the other way. This only happens once per # store open, and it's based on data queried from the store, so there # doesn't seem to be any broader way to cache and re-use the result. # However, if we keyed the resulting dict on the database typeID rat...
schemaVersion), we wouldn't need the information this # dict gives us. That would mean changing the callers of this function # to use typeID instead of that tuple, which may be possible. Probably # only represents a very tiny possible speedup. typeIDToNameAndVersion = {} for key, value in self.typenameAndVersionToID.it...
from the schema and the sorted() here doesn't seem to be any faster # than doing this. persistedSchema = sorted(self.querySchemaSQL( "SELECT attribute, type_id, sqltype, indexed, " "pythontype, docstring FROM *DATABASE*.axiom_attributes ")) # This is trivially (but measurably!) faster than getattr(attributes, # pythont...
result: result[key] = [] result[key].append(( attribute, sqltype, indexed, getAttribute(pythontype), docstring)) return result
def _checkTypeSchemaConsistency(self, actualType, onDiskSchema): """ Called for all known types at database startup: make sure that what we know (in memory) about this type agrees with what is stored about this type in the database. @param actualType: A L{MetaItem} instance which is associated with a table in this stor...
database to ensure they agree. @param onDiskSchema: A mapping from L{MetaItem} instances (such as C{actualType}) to the schema known in the database and associated with C{actualType}. @raise RuntimeError: if the schema defined by C{actualType} does not match the database-present schema given in C{onDiskSchema} or if C{...
both the runtime and the database both know about this # type; if they don't both know, we can't check that their views are # consistent try: inMemorySchema = _inMemorySchemaCache[actualType] except KeyError: inMemorySchema = _inMemorySchemaCache[actualType] = [ (storedAttribute.attrname, storedAttribute.sqltype) for (...
on already-loaded %r <%r> object version %d:\n%s" % (actualType, actualType.typeName, actualType.schemaVersion, _diffSchema(persistedSchema, inMemorySchema))) if actualType.__legacy__: return if (key[0], key[1] + 1) in onDiskSchema: raise RuntimeError( "Memory version of %r is %d; database has newer" % ( actualType.typ...
def _prepareOldVersionOf(self, typename, version, persistedSchema): """ Note that this database contains old versions of a particular type. Create the appropriate dummy item subclass and queue the type to be upgraded. @param typename: The I{typeName} associated with the schema for which to create a dummy item class. @p...
class. @param persistedSchema: A mapping giving information about all schemas stored in the database, used to create the attributes of the dummy item class. """ appropriateSchema = persistedSchema[typename, version] # create actual attribute objects dummyAttributes = {} for (attribute, sqlType, indexed, pythontype, doc...
oldType
def findUnique(self, tableClass, comparison=None, default=_noItem): """ Find an Item in the database which should be unique. If it is found, return it. If it is not found, return 'default' if it was passed, otherwise raise L{errors.ItemNotFound}. If more than one item is found, raise L{errors.DuplicateUniqueItem}. @par...
list(self.query(tableClass, comparison, limit=2)) lr = len(results) if lr == 0: if default is _noItem: raise errors.ItemNotFound(comparison) else: return default elif lr == 2: raise errors.DuplicateUniqueItem(comparison, results) elif lr == 1: return results[0] else: raise AssertionError("limit=2 database query returne...
def findFirst(self, tableClass, comparison=None, offset=None, sort=None, default=None): """ Usage:: s.findFirst(tableClass [, query arguments except 'limit']) Example:: class YourItemType(Item): a = integer() b = text() c = integer() ... it = s.findFirst(YourItemType, AND(YourItemType.a == 1, YourItemType.b == u'2'), s...
the passed default (None if none is passed) if one is not found. """ limit = 1 for item in self.query(tableClass, comparison, limit, offset, sort): return item return default
def query(self, tableClass, comparison=None, limit=None, offset=None, sort=None): """ Return a generator of instances of C{tableClass}, or tuples of instances if C{tableClass} is a tuple of classes. Examples:: fastCars = s.query(Vehicle, axiom.attributes.AND( Vehicle.wheels == 4, Vehicle.maxKPH > 200), limit=100, sort=...
look for instances of, or a tuple of subclasses. @param comparison: a provider of L{IComparison}, or None, to match all items available in the store. If tableClass is a tuple, then the comparison must refer to all Item subclasses in that tuple, and specify the relationships between them. @param limit: an int to limit t...
available results. @param offset: an int to specify a starting point within the available results, or None to start at 0. @param sort: an L{ISort}, something that comes from an SQLAttribute's 'ascending' or 'descending' attribute. @return: an L{ItemQuery} object, which is an iterable of Items or tuples of Items, accord...