Search is not available for this dataset
text
stringlengths
75
104k
def perform(self, store, count): """ Upgrade C{store} performing C{count} upgrades per transaction. Also, catch any exceptions and print out something useful. """ self.count = count try: self.upgradeStore(store) print 'Upgrade complete' e...
def runcode(self, code): """ Override L{code.InteractiveConsole.runcode} to run the code in a transaction unless the local C{autocommit} is currently set to a true value. """ if not self.locals.get('autocommit', None): return self.locals['db'].transact(code.In...
def namespace(self): """ Return a dictionary representing the namespace which should be available to the user. """ self._ns = { 'db': self.store, 'store': store, 'autocommit': False, } return self._ns
def addAccount(self, siteStore, username, domain, password): """ Create a new account in the given store. @param siteStore: A site Store to which login credentials will be added. @param username: Local part of the username for the credentials to add. @param domain: Domai...
def itemTypeWithSomeAttributes(attributeTypes): """ Create a new L{Item} subclass with L{numAttributes} integers in its schema. """ class SomeItem(Item): typeName = 'someitem_' + str(typeNameCounter()) for i, attributeType in enumerate(attributeTypes): locals()['attr_' + ...
def createSomeItems(store, itemType, values, counter): """ Create some instances of a particular type in a store. """ for i in counter: itemType(store=store, **values)
def save(self, commit=True): """save the instance or create a new one..""" # walk through the document fields for field_name, field in iter_valid_fields(self._meta): setattr(self.instance, field_name, self.cleaned_data.get(field_name)) if commit: self.instance.s...
def transacted(func): """ Return a callable which will invoke C{func} in a transaction using the C{store} attribute of the first parameter passed to it. Typically this is used to create Item methods which are automatically run in a transaction. The attributes of the returned callable will resemble...
def dependentItems(store, tableClass, comparisonFactory): """ Collect all the items that should be deleted when an item or items of a particular item type are deleted. @param tableClass: An L{Item} subclass. @param comparison: A one-argument callable taking an attribute and returning an L{iaxi...
def allowDeletion(store, tableClass, comparisonFactory): """ Returns a C{bool} indicating whether deletion of an item or items of a particular item type should be allowed to proceed. @param tableClass: An L{Item} subclass. @param comparison: A one-argument callable taking an attribute and retu...
def declareLegacyItem(typeName, schemaVersion, attributes, dummyBases=()): """ Generate a dummy subclass of Item that will have the given attributes, and the base Item methods, but no methods of its own. This is for use with upgrading. @param typeName: a string, the Axiom TypeName to have attribut...
def empowerment(iface, priority=0): """ Class decorator for indicating a powerup's powerup interfaces. The class will also be declared as implementing the interface. @type iface: L{zope.interface.Interface} @param iface: The powerup interface. @type priority: int @param priority: The prio...
def powerUp(self, powerup, interface=None, priority=0): """ Installs a powerup (e.g. plugin) on an item or store. Powerups will be returned in an iterator when queried for using the 'powerupsFor' method. Normally they will be returned in order of installation [this may change i...
def powerDown(self, powerup, interface=None): """ Remove a powerup. If no interface is specified, and the type of the object being installed has a "powerupInterfaces" attribute (containing either a sequence of interfaces, or a sequence of (interface, priority) tuples), t...
def powerupsFor(self, interface): """ Returns powerups installed using C{powerUp}, in order of descending priority. Powerups found to have been deleted, either during the course of this powerupsFor iteration, during an upgrader, or previously, will not be returned. ...
def interfacesFor(self, powerup): """ Return an iterator of the interfaces for which the given powerup is installed on this object. This is not implemented for in-memory powerups. It will probably fail in an unpredictable, implementation-dependent way if used on one. ""...
def _getPowerupInterfaces(self): """ Collect powerup interfaces this object declares that it can be installed on. """ powerupInterfaces = getattr(self.__class__, "powerupInterfaces", ()) pifs = [] for x in powerupInterfaces: if isinstance(x, type(Inter...
def _currentlyValidAsReferentFor(self, store): """ Is this object currently valid as a reference? Objects which will be deleted in this transaction, or objects which are not in the same store are not valid. See attributes.reference.__get__. """ if store is None: ...
def _schemaPrepareInsert(self, store): """ Prepare each attribute in my schema for insertion into a given store, either by upgrade or by creation. This makes sure all references point to this store and all relative paths point to this store's files directory. """ ...
def existingInStore(cls, store, storeID, attrs): """Create and return a new instance from a row from the store.""" self = cls.__new__(cls) self.__justCreated = False self.__subinit__(__store=store, storeID=storeID, __everInserted=True) ...
def getSchema(cls): """ return all persistent class attributes """ schema = [] for name, atr in cls.__attributes__: atr = atr.__get__(None, cls) if isinstance(atr, SQLAttribute): schema.append((name, atr)) cls.getSchema = staticmeth...
def persistentValues(self): """ Return a dictionary of all attributes which will be/have been/are being stored in the database. """ return dict((k, getattr(self, k)) for (k, attr) in self.getSchema())
def committed(self): """ Called after the database is brought into a consistent state with this object. """ if self.__deleting: self.deleted() if not self.__legacy__: self.store.objectCache.uncache(self.storeID, self) self._...
def checkpoint(self): """ Update the database to reflect in-memory changes made to this item; for example, to make it show up in store.query() calls where it is now valid, but was not the last time it was persisted to the database. This is called automatically when in 'autocommi...
def registerUpgrader(upgrader, typeName, oldVersion, newVersion): """ Register a callable which can perform a schema upgrade between two particular versions. @param upgrader: A one-argument callable which will upgrade an object. It is invoked with an instance of the old version of the object. ...
def registerAttributeCopyingUpgrader(itemType, fromVersion, toVersion, postCopy=None): """ Register an upgrader for C{itemType}, from C{fromVersion} to C{toVersion}, which will copy all attributes from the legacy item to the new item. If postCopy is provided, it will be called with the new item after u...
def registerDeletionUpgrader(itemType, fromVersion, toVersion): """ Register an upgrader for C{itemType}, from C{fromVersion} to C{toVersion}, which will delete the item from the database. @param itemType: L{axiom.item.Item} subclass @return: None """ # XXX This should actually do something...
def _hasExplicitOid(store, table): """ Does the given table have an explicit oid column? """ return any(info[1] == 'oid' for info in store.querySchemaSQL( 'PRAGMA *DATABASE*.table_info({})'.format(table)))
def _upgradeTableOid(store, table, createTable, postCreate=lambda: None): """ Upgrade a table to have an explicit oid. Must be called in a transaction to avoid corrupting the database. """ if _hasExplicitOid(store, table): return store.executeSchemaSQL( 'ALTER TABLE *DATABASE*.{...
def upgradeSystemOid(store): """ Upgrade the system tables to use explicit oid columns. """ store.transact( _upgradeTableOid, store, 'axiom_types', lambda: store.executeSchemaSQL(CREATE_TYPES)) store.transact( _upgradeTableOid, store, 'axiom_objects', lambda: store.ex...
def upgradeExplicitOid(store): """ Upgrade a store to use explicit oid columns. This allows VACUUMing the database without corrupting it. This requires copying all of axiom_objects and axiom_types, as well as all item tables that have not yet been upgraded. Consider VACUUMing the database...
def checkUpgradePaths(self): """ Check that all of the accumulated old Item types have a way to get from their current version to the latest version. @raise axiom.errors.NoUpgradePathAvailable: for any, and all, Items that do not have a valid upgrade path """ ...
def queueTypeUpgrade(self, oldtype): """ Queue a type upgrade for C{oldtype}. """ if oldtype not in self._oldTypesRemaining: self._oldTypesRemaining.append(oldtype)
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 UpgraderRecursio...
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...
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._...
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(...
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._...
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.clos...
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...
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() ...
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: ...
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 th...
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 h...
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 interf...
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 ...
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__) ...
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, ...
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): ...
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: ...
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-exis...
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) memo...
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) _mkdi...
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 h...
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 sto...
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 ...
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 depr...
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...
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 th...
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 spe...
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.c...
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 = se...
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...
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.s...
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 ...
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('...
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'...
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. ...
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, type...
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 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: i...
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 ma...
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 whic...
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 f...
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...
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()...
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, ...
def batchInsert(self, itemType, itemAttributes, dataRows): """ Create multiple items in the store without loading corresponding Python objects into memory. the items' C{stored} callback will not be called. Example:: myData = [(37, u"Fred", u"Wichita"), ...
def changed(self, item): """ An item in this store was changed. Add it to the current transaction's list of changed items, if a transaction is currently underway, or raise an exception if this L{Store} is currently in a state which does not allow changes. """ if ...
def transact(self, f, *a, **k): """ Execute C{f(*a, **k)} in the context of a database transaction. Any changes made to this L{Store} by C{f} will be committed when C{f} returns. If C{f} raises an exception, those changes will be reverted instead. If a transaction is a...
def _indexNameOf(self, tableClass, attrname): """ Return the unqualified (ie, no database name) name of the given attribute of the given table. @type tableClass: L{MetaItem} @param tableClass: The Python class associated with a table in the database. @param ...
def getTableName(self, tableClass): """ Retrieve the fully qualified name of the table holding items of a particular class in this store. If the table does not exist in the database, it will be created as a side-effect. @param tableClass: an Item subclass @raises axiom...
def getColumnName(self, attribute): """ Retreive the fully qualified column name for a particular attribute in this store. The attribute must be bound to an Item subclass (its type must be valid). If the underlying table does not exist in the database, it will be created as a ...
def getTypeID(self, tableClass): """ Retrieve the typeID associated with a particular table in the in-database schema for this Store. A typeID is an opaque integer representing the Item subclass, and the associated table in this Store's SQLite database. @param tableClas...
def _justCreateTable(self, tableClass): """ Execute the table creation DDL for an Item subclass. Indexes are *not* created. @type tableClass: type @param tableClass: an Item subclass """ sqlstr = [] sqlarg = [] # needs to be calculated including...
def _maybeCreateTable(self, tableClass, key): """ A type ID has been requested for an Item subclass whose table was not present when this Store was opened. Attempt to create the table, and if that fails because another Store object (perhaps in another process) has created the ta...
def _createIndexesFor(self, tableClass, extantIndexes): """ Create any indexes which don't exist and are required by the schema defined by C{tableClass}. @param tableClass: A L{MetaItem} instance which may define a schema which includes indexes. @param extantIndexes...
def getItemByID(self, storeID, default=_noItem, autoUpgrade=True): """ Retrieve an item by its storeID, and return it. Note: most of the failure modes of this method are catastrophic and should not be handled by application code. The only one that application programmers should...
def querySQL(self, sql, args=()): """For use with SELECT (or SELECT-like PRAGMA) statements. """ if self.debug: result = timeinto(self.queryTimes, self._queryandfetch, sql, args) else: result = self._queryandfetch(sql, args) return result
def createSQL(self, sql, args=()): """ For use with auto-committing statements such as CREATE TABLE or CREATE INDEX. """ before = time.time() self._execSQL(sql, args) after = time.time() if after - before > 2.0: log.msg('Extremely long CREATE: ...
def executeSQL(self, sql, args=()): """ For use with UPDATE or INSERT statements. """ sql = self._execSQL(sql, args) result = self.cursor.lastRowID() if self.executedThisTransaction is not None: self.executedThisTransaction.append((result, sql, args)) ...
def updateVersion(fname): """ given a filename to a file containing a __counter__ variable, open it, read the count, add one, rewrite the file. This: __counter__=123 Becomes: __counter__=124 """ fname=os.path.abspath(fname) if not os.path.exists(fname): print("c...