summaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
authorMike Bayer <mike_mp@zzzcomputing.com>2010-11-14 17:54:47 -0500
committerMike Bayer <mike_mp@zzzcomputing.com>2010-11-14 17:54:47 -0500
commitf252af2b21c5bafeaa30aabcf65dfed9b5c01093 (patch)
treedd5bf4f56ac68d78edfcb37a9c0c3c380c8ef6a8 /examples
parent9d7158a2c3869ad7a1ab07d3a41e831f6806a68c (diff)
parent06bf218ed37ca780bc4de2ceb47769c84de70ba1 (diff)
downloadsqlalchemy-f252af2b21c5bafeaa30aabcf65dfed9b5c01093.tar.gz
merge tip
Diffstat (limited to 'examples')
-rw-r--r--examples/association/basic_association.py10
-rw-r--r--examples/association/proxied_association.py10
-rw-r--r--examples/custom_attributes/custom_management.py60
-rw-r--r--examples/elementtree/__init__.py17
-rw-r--r--examples/elementtree/adjacency_list.py15
-rw-r--r--examples/elementtree/optimized_al.py38
-rw-r--r--examples/elementtree/pickle.py15
-rw-r--r--examples/sharding/attribute_shard.py4
-rw-r--r--examples/vertical/dictlike-polymorphic.py11
-rw-r--r--examples/vertical/dictlike.py11
10 files changed, 97 insertions, 94 deletions
diff --git a/examples/association/basic_association.py b/examples/association/basic_association.py
index 9c280d7ea..d3d764167 100644
--- a/examples/association/basic_association.py
+++ b/examples/association/basic_association.py
@@ -14,7 +14,7 @@ from datetime import datetime
from sqlalchemy import (create_engine, MetaData, Table, Column, Integer,
String, DateTime, Numeric, ForeignKey, and_)
-from sqlalchemy.orm import mapper, relationship, create_session
+from sqlalchemy.orm import mapper, relationship, Session
# Uncomment these to watch database activity.
#import logging
@@ -70,14 +70,14 @@ mapper(OrderItem, orderitems, properties={
'item': relationship(Item, lazy='joined')
})
-session = create_session()
+session = Session()
# create our catalog
session.add(Item('SA T-Shirt', 10.99))
session.add(Item('SA Mug', 6.50))
session.add(Item('SA Hat', 8.99))
session.add(Item('MySQL Crowbar', 16.99))
-session.flush()
+session.commit()
# function to return items from the DB
def item(name):
@@ -91,9 +91,7 @@ order.order_items.append(OrderItem(item('SA Mug')))
order.order_items.append(OrderItem(item('MySQL Crowbar'), 10.99))
order.order_items.append(OrderItem(item('SA Hat')))
session.add(order)
-session.flush()
-
-session.expunge_all()
+session.commit()
# query the order, print items
order = session.query(Order).filter_by(customer_name='john smith').one()
diff --git a/examples/association/proxied_association.py b/examples/association/proxied_association.py
index ac258121e..fa41f21c3 100644
--- a/examples/association/proxied_association.py
+++ b/examples/association/proxied_association.py
@@ -4,7 +4,7 @@ the usage of the associationproxy extension."""
from datetime import datetime
from sqlalchemy import (create_engine, MetaData, Table, Column, Integer,
String, DateTime, Float, ForeignKey, and_)
-from sqlalchemy.orm import mapper, relationship, create_session
+from sqlalchemy.orm import mapper, relationship, Session
from sqlalchemy.ext.associationproxy import AssociationProxy
engine = create_engine('sqlite://')
@@ -55,14 +55,14 @@ mapper(OrderItem, orderitems, properties={
'item':relationship(Item, lazy='joined')
})
-session = create_session()
+session = Session()
# create our catalog
session.add_all([Item('SA T-Shirt', 10.99),
Item('SA Mug', 6.50),
Item('SA Hat', 8.99),
Item('MySQL Crowbar', 16.99)])
-session.flush()
+session.commit()
# function to return items
def item(name):
@@ -81,9 +81,7 @@ order.items.append(item('SA Mug'))
order.items.append(item('SA Hat'))
session.add(order)
-session.flush()
-
-session.expunge_all()
+session.commit()
# query the order, print items
order = session.query(Order).filter_by(customer_name='john smith').one()
diff --git a/examples/custom_attributes/custom_management.py b/examples/custom_attributes/custom_management.py
index 4d135edcd..34481b623 100644
--- a/examples/custom_attributes/custom_management.py
+++ b/examples/custom_attributes/custom_management.py
@@ -1,20 +1,24 @@
-"""this example illustrates how to replace SQLAlchemy's class descriptors with a user-defined system.
+"""this example illustrates how to replace SQLAlchemy's class descriptors with
+a user-defined system.
-This sort of thing is appropriate for integration with frameworks that redefine class behaviors
-in their own way, such that SQLA's default instrumentation is not compatible.
+This sort of thing is appropriate for integration with frameworks that
+redefine class behaviors in their own way, such that SQLA's default
+instrumentation is not compatible.
-The example illustrates redefinition of instrumentation at the class level as well as the collection
-level, and redefines the storage of the class to store state within "instance._goofy_dict" instead
-of "instance.__dict__". Note that the default collection implementations can be used
-with a custom attribute system as well.
+The example illustrates redefinition of instrumentation at the class level as
+well as the collection level, and redefines the storage of the class to store
+state within "instance._goofy_dict" instead of "instance.__dict__". Note that
+the default collection implementations can be used with a custom attribute
+system as well.
"""
-from sqlalchemy import (create_engine, MetaData, Table, Column, Integer, Text,
- ForeignKey)
-from sqlalchemy.orm import (mapper, relationship, create_session,
- InstrumentationManager)
+from sqlalchemy import create_engine, MetaData, Table, Column, Integer, Text,\
+ ForeignKey
+from sqlalchemy.orm import mapper, relationship, Session,\
+ InstrumentationManager
-from sqlalchemy.orm.attributes import set_attribute, get_attribute, del_attribute, is_instrumented
+from sqlalchemy.orm.attributes import set_attribute, get_attribute, \
+ del_attribute, is_instrumented
from sqlalchemy.orm.collections import collection_adapter
@@ -118,17 +122,20 @@ class MyCollectionAdapter(object):
def fire_append_event(self, item, initiator=None):
if initiator is not False and item is not None:
- self.state.get_impl(self.key).fire_append_event(self.state, self.state.dict, item,
- initiator)
+ self.state.get_impl(self.key).\
+ fire_append_event(self.state, self.state.dict, item,
+ initiator)
def fire_remove_event(self, item, initiator=None):
if initiator is not False and item is not None:
- self.state.get_impl(self.key).fire_remove_event(self.state, self.state.dict, item,
- initiator)
+ self.state.get_impl(self.key).\
+ fire_remove_event(self.state, self.state.dict, item,
+ initiator)
def fire_pre_remove_event(self, initiator=None):
- self.state.get_impl(self.key).fire_pre_remove_event(self.state, self.state.dict,
- initiator)
+ self.state.get_impl(self.key).\
+ fire_pre_remove_event(self.state, self.state.dict,
+ initiator)
class MyCollection(object):
def __init__(self):
@@ -150,8 +157,13 @@ class MyCollection(object):
if __name__ == '__main__':
meta = MetaData(create_engine('sqlite://'))
- table1 = Table('table1', meta, Column('id', Integer, primary_key=True), Column('name', Text))
- table2 = Table('table2', meta, Column('id', Integer, primary_key=True), Column('name', Text), Column('t1id', Integer, ForeignKey('table1.id')))
+ table1 = Table('table1', meta,
+ Column('id', Integer, primary_key=True),
+ Column('name', Text))
+ table2 = Table('table2', meta,
+ Column('id', Integer, primary_key=True),
+ Column('name', Text),
+ Column('t1id', Integer, ForeignKey('table1.id')))
meta.create_all()
class A(MyClass):
@@ -172,11 +184,10 @@ if __name__ == '__main__':
assert a1.bs[0].name == 'b1'
assert isinstance(a1.bs, MyCollection)
- sess = create_session()
+ sess = Session()
sess.add(a1)
- sess.flush()
- sess.expunge_all()
+ sess.commit()
a1 = sess.query(A).get(a1.id)
@@ -186,8 +197,7 @@ if __name__ == '__main__':
a1.bs.remove(a1.bs[0])
- sess.flush()
- sess.expunge_all()
+ sess.commit()
a1 = sess.query(A).get(a1.id)
assert len(a1.bs) == 1
diff --git a/examples/elementtree/__init__.py b/examples/elementtree/__init__.py
index 70554f5c9..33805c0cb 100644
--- a/examples/elementtree/__init__.py
+++ b/examples/elementtree/__init__.py
@@ -1,6 +1,11 @@
"""
-Illustrates three strategies for persisting and querying XML documents as represented by
-ElementTree in a relational database. The techniques do not apply any mappings to the ElementTree objects directly, so are compatible with the native cElementTree as well as lxml, and can be adapted to suit any kind of DOM representation system. Querying along xpath-like strings is illustrated as well.
+Illustrates three strategies for persisting and querying XML
+documents as represented by ElementTree in a relational
+database. The techniques do not apply any mappings to the
+ElementTree objects directly, so are compatible with the
+native cElementTree as well as lxml, and can be adapted to
+suit any kind of DOM representation system. Querying along
+xpath-like strings is illustrated as well.
In order of complexity:
@@ -10,10 +15,10 @@ In order of complexity:
represented in a separate table. The nodes are associated in a hierarchy using an adjacency list
structure. A query function is introduced which can search for nodes along any path with a given
structure of attributes, basically a (very narrow) subset of xpath.
-* ``optimized_al.py`` - Uses the same strategy as ``adjacency_list.py``, but adds a
- :class:`~sqlalchemy.orm.interfaces.MapperExtension` which optimizes how the hierarchical structure
- is loaded, such that the full set of DOM nodes are loaded within a single table result set, and
- are organized hierarchically as they are received during a load.
+* ``optimized_al.py`` - Uses the same strategy as ``adjacency_list.py``, but associates each
+ DOM row with its owning document row, so that a full document of DOM nodes can be
+ loaded using O(1) queries - the construction of the "hierarchy" is performed after
+ the load in a non-recursive fashion and is much more efficient.
E.g.::
diff --git a/examples/elementtree/adjacency_list.py b/examples/elementtree/adjacency_list.py
index 78d71f3fe..3b9e4c523 100644
--- a/examples/elementtree/adjacency_list.py
+++ b/examples/elementtree/adjacency_list.py
@@ -8,15 +8,15 @@ styles of persistence are identical, as is the structure of the main Document cl
################################# PART I - Imports/Coniguration ####################################
from sqlalchemy import (MetaData, Table, Column, Integer, String, ForeignKey,
- Unicode, and_)
-from sqlalchemy.orm import mapper, relationship, create_session, lazyload
+ Unicode, and_, create_engine)
+from sqlalchemy.orm import mapper, relationship, Session, lazyload
import sys, os, StringIO, re
from xml.etree import ElementTree
+e = create_engine('sqlite://')
meta = MetaData()
-meta.bind = 'sqlite://'
################################# PART II - Table Metadata #########################################
@@ -44,7 +44,7 @@ attributes = Table('attributes', meta,
Column('name', Unicode(100), nullable=False, primary_key=True),
Column('value', Unicode(255)))
-meta.create_all()
+meta.create_all(e)
#################################### PART III - Model #############################################
@@ -142,7 +142,7 @@ Document.element = ElementTreeMarshal()
line = "\n--------------------------------------------------------"
# save to DB
-session = create_session()
+session = Session(e)
# get ElementTree documents
for file in ('test.xml', 'test2.xml', 'test3.xml'):
@@ -151,12 +151,9 @@ for file in ('test.xml', 'test2.xml', 'test3.xml'):
session.add(Document(file, doc))
print "\nSaving three documents...", line
-session.flush()
+session.commit()
print "Done."
-# clear session (to illustrate a full load), restore
-session.expunge_all()
-
print "\nFull text of document 'text.xml':", line
document = session.query(Document).filter_by(filename="test.xml").first()
diff --git a/examples/elementtree/optimized_al.py b/examples/elementtree/optimized_al.py
index 98c4e1129..d6110a132 100644
--- a/examples/elementtree/optimized_al.py
+++ b/examples/elementtree/optimized_al.py
@@ -5,19 +5,19 @@ which joins on only three tables.
"""
-################################# PART I - Imports/Configuration ###########################################
+##################### PART I - Imports/Configuration #########################
from sqlalchemy import (MetaData, Table, Column, Integer, String, ForeignKey,
- Unicode, and_)
-from sqlalchemy.orm import mapper, relationship, create_session, lazyload
+ Unicode, and_, create_engine)
+from sqlalchemy.orm import mapper, relationship, Session, lazyload
import sys, os, StringIO, re
from xml.etree import ElementTree
+e = create_engine('sqlite://', echo=True)
meta = MetaData()
-meta.bind = 'sqlite://'
-################################# PART II - Table Metadata ###########################################
+####################### PART II - Table Metadata #############################
# stores a top level record of an XML document.
documents = Table('documents', meta,
@@ -43,9 +43,9 @@ attributes = Table('attributes', meta,
Column('name', Unicode(100), nullable=False, primary_key=True),
Column('value', Unicode(255)))
-meta.create_all()
+meta.create_all(e)
-#################################### PART III - Model #############################################
+########################### PART III - Model #################################
# our document class. contains a string name,
# and the ElementTree root element.
@@ -59,7 +59,7 @@ class Document(object):
self.element.write(buf)
return buf.getvalue()
-#################################### PART IV - Persistence Mapping ###################################
+########################## PART IV - Persistence Mapping #####################
# Node class. a non-public class which will represent
# the DB-persisted Element/SubElement object. We cannot create mappers for
@@ -145,12 +145,12 @@ class ElementTreeMarshal(object):
# override Document's "element" attribute with the marshaller.
Document.element = ElementTreeMarshal()
-########################################### PART V - Basic Persistence Example ############################
+###################### PART V - Basic Persistence Example ####################
line = "\n--------------------------------------------------------"
# save to DB
-session = create_session()
+session = Session(e)
# get ElementTree documents
for file in ('test.xml', 'test2.xml', 'test3.xml'):
@@ -159,25 +159,25 @@ for file in ('test.xml', 'test2.xml', 'test3.xml'):
session.add(Document(file, doc))
print "\nSaving three documents...", line
-session.flush()
+session.commit()
print "Done."
-# clear session (to illustrate a full load), restore
-session.expunge_all()
-
print "\nFull text of document 'text.xml':", line
document = session.query(Document).filter_by(filename="test.xml").first()
print document
-############################################ PART VI - Searching for Paths #######################################
+######################## PART VI - Searching for Paths #######################
# manually search for a document which contains "/somefile/header/field1:hi"
print "\nManual search for /somefile/header/field1=='hi':", line
-d = session.query(Document).join('_nodes', aliased=True).filter(and_(_Node.parent_id==None, _Node.tag==u'somefile')).\
- join('children', aliased=True, from_joinpoint=True).filter(_Node.tag==u'header').\
- join('children', aliased=True, from_joinpoint=True).filter(and_(_Node.tag==u'field1', _Node.text==u'hi')).\
- one()
+d = session.query(Document).join('_nodes', aliased=True).\
+ filter(and_(_Node.parent_id==None, _Node.tag==u'somefile')).\
+ join('children', aliased=True, from_joinpoint=True).\
+ filter(_Node.tag==u'header').\
+ join('children', aliased=True, from_joinpoint=True).\
+ filter(and_(_Node.tag==u'field1', _Node.text==u'hi')).\
+ one()
print d
# generalize the above approach into an extremely impoverished xpath function:
diff --git a/examples/elementtree/pickle.py b/examples/elementtree/pickle.py
index 4eaaa2f8d..5e53e6798 100644
--- a/examples/elementtree/pickle.py
+++ b/examples/elementtree/pickle.py
@@ -8,14 +8,14 @@ styles of persistence are identical, as is the structure of the main Document cl
from sqlalchemy import (create_engine, MetaData, Table, Column, Integer, String,
PickleType)
-from sqlalchemy.orm import mapper, create_session
+from sqlalchemy.orm import mapper, Session
import sys, os
from xml.etree import ElementTree
-engine = create_engine('sqlite://')
-meta = MetaData(engine)
+e = create_engine('sqlite://')
+meta = MetaData()
# setup a comparator for the PickleType since it's a mutable
# element.
@@ -30,7 +30,7 @@ documents = Table('documents', meta,
Column('element', PickleType(comparator=are_elements_equal))
)
-meta.create_all()
+meta.create_all(e)
# our document class. contains a string name,
# and the ElementTree root element.
@@ -49,12 +49,11 @@ filename = os.path.join(os.path.dirname(__file__), "test.xml")
doc = ElementTree.parse(filename)
# save to DB
-session = create_session()
+session = Session(e)
session.add(Document("test.xml", doc))
-session.flush()
+session.commit()
-# clear session (to illustrate a full load), restore
-session.expunge_all()
+# restore
document = session.query(Document).filter_by(filename="test.xml").first()
# print
diff --git a/examples/sharding/attribute_shard.py b/examples/sharding/attribute_shard.py
index 1a39f5de3..fd1fa50ae 100644
--- a/examples/sharding/attribute_shard.py
+++ b/examples/sharding/attribute_shard.py
@@ -248,9 +248,7 @@ quito.reports.append(Report(85))
sess = create_session()
for c in [tokyo, newyork, toronto, london, dublin, brasilia, quito]:
sess.add(c)
-sess.flush()
-
-sess.expunge_all()
+sess.commit()
t = sess.query(WeatherLocation).get(tokyo.id)
assert t.city == tokyo.city
diff --git a/examples/vertical/dictlike-polymorphic.py b/examples/vertical/dictlike-polymorphic.py
index e4046b3ad..1acb6aee5 100644
--- a/examples/vertical/dictlike-polymorphic.py
+++ b/examples/vertical/dictlike-polymorphic.py
@@ -132,7 +132,7 @@ if __name__ == '__main__':
from sqlalchemy import (MetaData, Table, Column, Integer, Unicode,
ForeignKey, UnicodeText, and_, not_, or_, String, Boolean, cast, text,
null, case)
- from sqlalchemy.orm import mapper, relationship, create_session
+ from sqlalchemy.orm import mapper, relationship, Session
from sqlalchemy.orm.collections import attribute_mapped_collection
metadata = MetaData()
@@ -191,7 +191,7 @@ if __name__ == '__main__':
metadata.bind = 'sqlite:///'
metadata.create_all()
- session = create_session()
+ session = Session()
stoat = Animal(u'stoat')
stoat[u'color'] = u'red'
@@ -199,8 +199,7 @@ if __name__ == '__main__':
stoat[u'weasel-like'] = True
session.add(stoat)
- session.flush()
- session.expunge_all()
+ session.commit()
critter = session.query(Animal).filter(Animal.name == u'stoat').one()
print critter[u'color']
@@ -210,7 +209,7 @@ if __name__ == '__main__':
critter[u'cuteness'] = u'very cute'
metadata.bind.echo = True
- session.flush()
+ session.commit()
metadata.bind.echo = False
marten = Animal(u'marten')
@@ -225,7 +224,7 @@ if __name__ == '__main__':
shrew[u'poisonous'] = True
session.add(shrew)
- session.flush()
+ session.commit()
q = (session.query(Animal).
filter(Animal.facts.any(
diff --git a/examples/vertical/dictlike.py b/examples/vertical/dictlike.py
index ce76b3140..e288d70ba 100644
--- a/examples/vertical/dictlike.py
+++ b/examples/vertical/dictlike.py
@@ -125,7 +125,7 @@ class VerticalPropertyDictMixin(object):
if __name__ == '__main__':
from sqlalchemy import (MetaData, Table, Column, Integer, Unicode,
ForeignKey, UnicodeText, and_, not_)
- from sqlalchemy.orm import mapper, relationship, create_session
+ from sqlalchemy.orm import mapper, relationship, Session
from sqlalchemy.orm.collections import attribute_mapped_collection
metadata = MetaData()
@@ -175,7 +175,7 @@ if __name__ == '__main__':
metadata.bind = 'sqlite:///'
metadata.create_all()
- session = create_session()
+ session = Session()
stoat = Animal(u'stoat')
stoat[u'color'] = u'reddish'
@@ -186,8 +186,7 @@ if __name__ == '__main__':
print stoat.facts[u'color']
session.add(stoat)
- session.flush()
- session.expunge_all()
+ session.commit()
critter = session.query(Animal).filter(Animal.name == u'stoat').one()
print critter[u'color']
@@ -197,7 +196,7 @@ if __name__ == '__main__':
print 'changing cuteness:'
metadata.bind.echo = True
- session.flush()
+ session.commit()
metadata.bind.echo = False
marten = Animal(u'marten')
@@ -214,7 +213,7 @@ if __name__ == '__main__':
loris[u'cuteness'] = u'fairly'
loris[u'poisonous-part'] = u'elbows'
session.add(loris)
- session.flush()
+ session.commit()
q = (session.query(Animal).
filter(Animal.facts.any(